#!/bin/sh
#
# git-manage - git manager with fzf
# dependencies: fzf

current_branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)

if [ -z "${current_branch}" ]; then
  exit 1
fi

usage() {
  cat <<EOF
$(basename "$0")

commands:
  go-branch-interactive             - Checkout branch with fzf.
  go-remote                         - Checkout branch, submodule init. Default: remotes
  go-remote-interactive
  go-main|go-master|abandon-remote  - Abandon a branch checkedout by go-remote. Default: main
  prune
  update                            - Pull and update submodules.
EOF
}

case "$1" in
  go-branch-interactive)
    shift
    res=$(git branch | grep -v '^\*' | fzf | sed -E 's/^ +//')
    [ -n "${res}" ] && git checkout "${res}"
    ;;
  go-remote)
    if [ -n "$2" ] && [ "$2" != "--all" ] && [ "$2" != "-a" ]; then
      # "git-manage go-remote origin/new-super-feature"
      git checkout -b "${2#*/}" "$2"
      git submodule init
      git submodule update
    else
      if [ "$2" = "--all" ] || [ "$2" = "-a" ] \
        || [ -z "${GIT_MANAGE_REMOTE_FILTER}" ]; then
        git branch --remotes
      else
        git branch --remotes | grep "${GIT_MANAGE_REMOTE_FILTER}"
      fi
    fi
    ;;
  go-remote-interactive)
    shift
    res=$($0 go-remote "$@" | fzf | sed -E 's/^ +//')
    [ -n "${res}" ] && $0 go-remote "${res}"
    ;;
  go-main | go-master | abandon-remote)
    # abandon a branch checked out by "go-remote".
    # prefer "main" if it exists.
    if [ -n "$2" ]; then
      to=$2
    elif git rev-parse main >/dev/null 2>&1; then
      to=main
    else
      to=master
    fi
    if [ "${current_branch}" != "${to}" ]; then
      git checkout "${to}"
      git branch --delete "${current_branch}"
      git submodule init
      git submodule update
    fi
    ;;
  prune)
    if [ -n "$2" ]; then
      git remote prune "$2"
    else
      for i in $(git remote); do
        git remote prune "${i}"
      done
    fi
    ;;
  update)
    git pull
    git submodule init
    git submodule update
    ;;
  -h | --help)
    usage
    exit 0
    ;;
  *)
    usage
    exit 1
    ;;
esac
