#!/usr/bin/zsh

ROOT_PREFIX="${REPO_ROOT_DIR:-$HOME/repo}"
GIT_USER="${REPO_GIT_USER:-git}"

clean_path()
{
stripped=$1
prefix="http://"
stripped="${stripped#"$prefix"}"
prefix="https://"
stripped="${stripped#"$prefix"}"
prefix="git@"
stripped="${stripped#"$prefix"}"
suffix=".git"
stripped="${stripped%"$suffix"}"
stripped=$(echo "$stripped" | sed -e "s/:/\//1")
echo $stripped
}

show_help()
{
  printf "Usage: repo <get|goto> <repo>\n"
}

do_get()
{
  cleaned=$(clean_path $1)
  output_path="$ROOT_PREFIX/$cleaned"
  mkdir -p $output_path
  if [ ! -d $output_path/.git ]; then
    repourl=$(echo "$GIT_USER@$cleaned" | sed -e "s/\//:/1")
    git clone $repourl $output_path
  fi
  cd $output_path
}

do_goto()
{
cleaned=$(clean_path $1)
output_path="$ROOT_PREFIX/$cleaned"
cd $output_path
}


case "$1" in
  'get' )
    do_get $2
    do_goto $2
  ;;
  'go' | "goto")
    do_goto $2
  ;;
  'help' | "-h"| "-help" | "--help")
    show_help
esac