#!/bin/zsh

Prog=$(basename "$0")

Usage="$Prog <project name> [<directory>]"
case $Prog in
    chtc-hubclone) Upstream=CHTC ;;
    condor-hubclone) Upstream=htcondor ;;
    osg1-hubclone) Upstream=opensciencegrid ;;
    osg2-hubclone) Upstream=osg-htc ;;
    pelican-hubclone) Upstream=PelicanPlatform ;;
    hubclone)
        Usage="$Prog <upstream> <project name> [<directory>]"
        Upstream=${1?"Usage: $Usage"}
        shift
        ;;
    *)
        echo >&2 "Unknown executable name. Bailing."
        exit 2
        ;;
esac

Project=${1?"Usage: $Usage"}
Directory=${2:-${Project%.git}}

set -e


thisbranch () {
    git rev-parse --abbrev-ref HEAD
}


ask_yn () {
    echo >&2 "$@"
    while read -r; do
        case $REPLY in
            [Yy]*) return 0;;
            [Nn]*) return 1;;
            *) echo >&2 "Enter yes or no";;
        esac
    done
    return 2  # EOF
}


git clone "git@github.com:matyasselmeci/$Project" "$Directory"
echo
cd "$Directory"
git remote add -f upstream "https://github.com/${Upstream?}/$Project"
git branch -u "upstream/$(thisbranch)" "$(thisbranch)"
git config remote.pushDefault origin
git config --add remotes.github "upstream origin"
git config --add remote.origin.push '+refs/heads/wip/*:refs/heads/wip/*'
git config --add remote.origin.push 'refs/heads/*:refs/heads/*'
git config --local user.name 'Matyas Selmeci'
git config --local user.email 'mselmeci@wisc.edu'
if which gh &>/dev/null; then
    gh repo set-default "${Upstream?}/${Project}"
fi
echo
if which mr &>/dev/null; then
    if ask_yn "Register in mr? "; then
        mr register .
    fi
    echo
fi
echo "Done"
