#!/usr/bin/zsh -feu

# Tool to setup a mirror of git repositories in an identical dir-hierarchy (on 2 hosts).
# This is only about SSH-based git. not git:// urls!
# Add as a `git remote host' maruskadell, with the path same as this one.

# die ... maybe git-functions should source it?
source /usr/share/mmc-shell/mmc-functions.sh
source /usr/share/mmc-shell/git-functions.sh
check_getopt

# asume USER is set!
unsetopt FUNCTION_ARGZERO
usage()
{
    cat <<EOF
usage: ${0##*/} [+-h] [-n URL] [-d]
-d --dry
-v --verbose
-n --name  ex. ${GIT_REMOTE_NAME-}
-u --url  ex ${GIT_URL-}
-U --user {name}  ssh as that user.
-c --clone
EOF
}

#possible wrapped into echo(1). for a dry run.
CMD=
clone=n

remote_path=$(get_remote_path)

override=n
verbose=n

# this splits, reorders,
cmd_options=$(getopt --name $0 --shell bash \
                     --longoptions clone,verbose,url:,name:,dry,user:,help \
                     --options hcdfn:u:U:v -- "$@") || { usage && exit 1 }
# setopt KSH_ARRAYS
eval set -- "$cmd_options"

while (( $# > 0 )) do
      echo $1 >&2
      case $1 in
          -c)
              clone=y
              ;;
          -f)
              override=y
              ;;
          -d | --dry )
              # run_dry=y
              CMD=echo
              ;;
          -h | --help)
              usage
              exit 0
              ;;
          -n| --name)
              GIT_REMOTE_NAME=$2
              shift
              ;;
          -u | --url)
              GIT_URL=$2
              shift
              ;;
          -U | --user)
              USER=$2
              shift
              ;;
          -v | --verbose )
              verbose=y
              ;;
          --)
              shift
              break
              ;;
          *)
              usage >&2
              exit 2
              ;;
      esac
      shift
done

if [ $# -gt 0 ]; then
    GIT_REMOTE_NAME=$1
fi

# set_remote_name

if [[ -n $GIT_REMOTE_NAME ]]; then
    if [[ -z ${GIT_URL-} ]];then
        GIT_URL=$USER@$GIT_REMOTE_NAME:$(get_remote_path)
    fi
else
    guess_twin
fi


if [[ $clone = "y" ]];
then
    $CMD git clone $GIT_URL:$remote_path
else

    if [ $override = y ]; then
        $CMD git remote set-url $GIT_REMOTE_NAME $GIT_URL:$remote_path
    else
        $CMD git remote add $GIT_REMOTE_NAME $GIT_URL
    fi

    git fetch $GIT_REMOTE_NAME
fi
