#!/bin/zsh
#function mockgit {
  # handle these commands:
  # - `git -C "$dir" config remote.origin.url`
  # - `git -C "$dir" pull --quiet --ff --rebase --autostash`
  # - `git -C "$dir" rev-parse --short HEAD`
  # - `git clone --quiet --depth 1 --recurse-submodules --shallow-submodules --branch branch $url $dir`
  # - `git --version`
  emulate -L zsh; setopt local_options extended_glob
  local MATCH MBEGIN MEND; local -a match mbegin mend  # appease 'warn_create_global'
  0=${(%):-%x}
  local prjdir="${0:A:h:h:h}"
  local args=("$@[@]")
  local o_path o_quiet o_ff o_rebase o_autostash o_short
  local o_depth o_recurse_submodules o_shallow_submodules o_branch
  local o_init o_recursive
  zparseopts -D -E --      \
    C:=o_path              \
    -short=o_short         \
    -quiet=o_quiet         \
    -ff=o_ff               \
    -rebase=o_rebase       \
    -autostash=o_autostash \
    -recurse-submodules=o_recurse_submodules \
    -shallow-submodules=o_shallow_submodules \
    -depth:=o_depth                          \
    -branch:=o_branch                        \
    -init=o_init                             \
    -recursive=o_recursive                  ||
    return 1

  if [[ "$@" = "--version" ]]; then
    echo "mockgit version 0.0.0"
  elif [[ "$1" = "clone" ]]; then
    local giturl="$2"
    local repo="${giturl:h:t}/${${giturl:t}%.git}"
    local bundledir="${3:-.}"
    local gitsite_repodir="$prjdir/tests/fakegitsite.com/${repo}"
    if [[ -d "$gitsite_repodir" ]]; then
      [[ -d "${bundledir:A}" ]] || mkdir -p "${bundledir:A}"
      cp -r -- "$gitsite_repodir" "${bundledir:A}"
    elif ! (( $#o_quiet )); then
      echo "MOCKGIT: Cloning into '${repo:t}'..."
      echo "MOCKGIT: Repository not found."
      echo "MOCKGIT: repository '$giturl' not found"
    fi
  elif [[ "$@" = "config remote.origin.url" ]]; then
    if [[ -e $bundledir/.git/config/remote.origin.url ]]; then
      cat $bundledir/.git/config/remote.origin.url
    else
      # un-sanitize dir into URL
      local url=$o_path[-1]
      url=${url:t}
      url=${url:gs/-AT-/\@}
      url=${url:gs/-COLON-/\:}
      url=${url:gs/-SLASH-/\/}
      echo "$url"
    fi
  elif [[ "$@" = "pull" ]]; then
    (( $#o_quiet )) || echo "MOCKGIT: Already up to date."
  elif [[ "$@" = "rev-parse HEAD" ]]; then
    if (( $#o_short )); then
      echo "abcd123"
    else
      echo "abcd1230abcd1230abcd1230abcd1230abcd1230"
    fi
  elif [[ "$1" == (submodule|fetch) ]]; then
    # nothing to do
  else
    echo >&2 "mocking not implemented for git command: git $@"
    return 1
  fi
#}
