#! /bin/bash
set -e

log=$(realpath "$0.log")

#--- Get repository name -----------------------------------------------------#

src_dir=$1
if [ -f "$src_dir" ]
then
    src_dir=$(dirname "$1")
fi
echo "src_dir:   $src_dir" > "$log"

cd "$src_dir"
git_root=$(git rev-parse --show-superproject-working-tree)
git_sub=$(git rev-parse --show-toplevel)
if [ -z "$git_root" ]
then
    git_root=$git_sub
fi
echo "git_root:  $git_root" >> "$log"
echo "git_sub:   $git_sub"  >> "$log"

repos_yml="$HOME/.config/smartgit/25.1/repository-grouping.yml"
comma=',\s+'
repo_name=$(grep -Pzo "(?<={name: )[^}]+(?=${comma}path: [^}]+${comma}path.absolute: ${git_root}[},])" "$repos_yml" | tr -d '\0')
echo "repo_name: $repo_name" >> "$log"

#--- Find or start SmartGit --------------------------------------------------#

pid=$(ps ax -o pid=,args= | awk '{if ($2 == "/usr/local/bin/smartgit/jre/bin/java") print $1}')
if [ -z "$pid" ]
then
    /usr/local/bin/smartgit/bin/smartgit.sh ?
    pid=$!
fi
echo "pid:       $pid" >> "$log"

wid=$(wmctrl -lp | awk "{if (\$3 == $pid) print \$1}")
echo "wid:       $wid" >> "$log"

#--- Activate SmartGit and select repository ---------------------------------#

select_smartgit_item() {
    xdotool type --delay 140 "$1"
    xdotool key  --delay 140 'Return' 'Return'
}

xdotool windowactivate $wid key 'ctrl+shift+1' 'Home'
select_smartgit_item "$repo_name"

#--- Select branch if required -----------------------------------------------#

branch=$2
if [ -n "$branch" ]
then
    echo "branch:    $branch" >> "$log"
    xdotool key 'ctrl+shift+2' 'Home'
    select_smartgit_item "$branch"
fi

#--- Select submodule if required --------------------------------------------#

if [ "$git_root" != "$git_sub" ]
then
    submodule_name=$(basename "$git_sub")
    xdotool key 'ctrl+shift+1' 'Down'
    select_smartgit_item "$submodule_name"
fi
