#!/bin/bash
# A wrapper for system git that prevents commands such as `clone` or `fetch` to be
# executed in testing. It logs commands to "~/.history" so afterwards it can be
# asserted that they ran.
set -e

command="$1"
case "$command" in
  "config" ) ;;
  "web--browse" )
    echo git web--browse PATH/$(basename "$2") >> "$HOME"/.history
    ;;
  * )
    echo git "$@" >> "$HOME"/.history
    ;;
esac

case "$command" in
  "--list-cmds="* )
    echo add
    echo branch
    echo commit
    ;;
  "fetch" )
    [[ $2 != -* && $3 == *:* && $3 != -* ]] || exit 0
    refspec="$3"
    dest="${refspec#*:}"
    head="$(git rev-parse --verify -q HEAD || true)"
    if [ -z "$head" ]; then
      git commit --allow-empty -m "auto-commit"
      head="$(git rev-parse --verify -q HEAD)"
    fi
    if [[ $dest == refs/remotes/* ]]; then
      mkdir -p ".git/${dest%/*}"
      cat >".git/${dest}" <<<"$head"
      cat >".git/FETCH_HEAD" <<<"$head"
    else
      "$HUB_SYSTEM_GIT" checkout -b "${dest#refs/heads/}" HEAD
      cat >".git/FETCH_HEAD" <<<"$head"
    fi
    exit 0
    ;;
  "clone" | "pull" | "push" | "web--browse" )
    # don't actually execute these commands
    exit 0
    ;;
  * )
    # note: `submodule add` also initiates a clone, but we work around it
    if [ "$command $2 $3" = "remote add -f" ]; then
      subcommand=$2
      shift 3
      exec "$HUB_SYSTEM_GIT" $command $subcommand "$@"
    else
      exec "$HUB_SYSTEM_GIT" "$@"
    fi
    ;;
  esac
