#!/bin/sh
#
# gitex - git extensions; useful for making git aliases that dont suck
# optionally, use !/usr/bin/env dash to really test POSIX
#
# usage: gitex <subcommand>

gitex_usage() {
  printf %s "\
$(basename "$0") is a simple wrapper around git - for making git aliases that dont suck

commands:
  help              - Display gitex help comments.
  branch-cleanup    - Remove branches no longer on remote.
  branch-main       - Get the name of the default branch for a repo(main,master,trunk,etc).
  branch-name       - Get the current branch name.
  browse            - Open web browser to git remote URL.
  checkout-branches - Checkout and track all branches.
  is-clean          - Is the git repo clean.
  is-dirty          - Is the git repo dirty.
  lg                - Print my preferred git log view.
  log-pretty        - Print a pretty log.
  pushup            - Push a new branch to the remote.
  repodir           - Print my preferred root repo directory.
  sha               - Print the 7-char short git SHA, with a * indicating dirty.
  whoami            - Print my config's username and email.

flags:
  -h, --help        - Display this message.
"
  exit 0
}

# for testing...
gitex_foo() {
  echo "foo called with $# params: $*"
}

# POSIX test for function existence.
is_function() {
  [ "$#" -eq 1 ] || return 1
  type "$1" | sed "s/$1//" | grep -qwi function
}

##? help: Display gitex help comments
gitex_help() {
  # echo "$0"
  grep "^##?" "$0" | cut -c 5-
}

##? branch-cleanup: Remove branches no longer on remote
gitex_branch_cleanup() {
  # source: https://ao.bloat.cat/questions/7726949/remove-tracking-branches-no-longer-on-remote
  defbranch="$(gitex_branch_main 2>/dev/null)"
  git checkout "${defbranch:-main}" >/dev/null 2>/dev/null \
    && git fetch --prune \
    && git branch -vv \
    | awk '/: gone]/{ print $1 }' | xargs git branch -d
}

##? branch-main: Get the name of the default branch for a repo (main, master, trunk, etc)
gitex_branch_main() {
  # source: https://ao.bloat.cat/questions/28666357/git-how-to-get-default-branch
  git symbolic-ref --short refs/remotes/origin/HEAD | sed 's|^origin/||'
}

##? branch-name: Get the current branch name
gitex_branch_name() {
  git branch --show-current
}

##? browse: Open web browser to git remote URL
gitex_browse() {
  url=$(
    git config "remote.${1:-origin}.url" \
      | sed -e 's|^.*@|https://|' -e 's|.git$||' -e 's|:|/|2'
  )
  git web--browse "${url}"
}

##? checkout-branches: Checkout and track all branches
gitex_checkout_branches() {
  # source: https://ao.bloat.cat/questions/67699/how-to-clone-all-remote-branches-in-git
  git branch --all | sed -n "/\\/HEAD /d; /\\/main$/d; /\\/master$/d; /remotes/p;" \
    | xargs -L1 git checkout --track
}

##? is-clean: Is the git repo clean
gitex_is_clean() {
  # shellcheck disable=SC2312
  test -z "$(git status --porcelain 2>/dev/null)"
}

##? is-dirty: Is the git repo dirty
gitex_is_dirty() {
  # shellcheck disable=SC2312
  test -n "$(git status --porcelain 2>/dev/null)"
}

##? lg: Print my preferred git log view.
gitex_lg() {
  git log --all --decorate --oneline --graph
}

##? log-pretty: Print a pretty log.
gitex_log_pretty() {
  git log --graph --abbrev-commit --decorate --format=format:'%C(bold blue)%h%C(reset) - %C(bold green)(%ar)%C(reset) %C(white)%s%C(reset) %C(dim white)- %an%C(reset)%C(auto)%d%C(reset)' --all
}

##? pushup: Push a new branch to the remote
gitex_pushup() {
  # Quick way to resolve the annoying error:
  #  'fatal: The current branch foo has no upstream branch.'
  # Or, you could just set `push.autoSetupRemote = true` in gitconfig...
  # shellcheck disable=SC2312
  git push --set-upstream "${1:-origin}" "$(git rev-parse --abbrev-ref HEAD)"
}

##? repodir: Print my preferred root repo directory.
gitex_repodir() {
  # shellcheck disable=SC2250
  (git config gitex.repodir || echo "${HOME}/src") | sed -e "s|^~|$HOME|"
}

##? sha: Print the 7-char short git SHA, with a * indicating dirty.
gitex_sha() {
  # shellcheck disable=SC2312
  printf '%s' "$(git rev-parse --short HEAD)"
  gitex_is_dirty && echo '*' || echo
}

##? whoami: Print my config's username and email.
gitex_whoami() {
  git config user.name && git config user.email
}

# main gitex command
gitex() {
  if [ "$#" -eq 0 ]; then
    printf '%s\n' "$(basename "$0"): expecting a subcommand. [-h|h] for help."
    return 1
  fi

  subcmd="$1"

  # if [ "${subcmd}" = "-h" ] || [ "${subcmd}" = "--help" ]; then
  #   # Support -h/--help flags
  #   subcmd="help"
  # else
  #   # Make kebab-case-subcommands work.
  #   subcmd=$(printf '%s' "${subcmd}" | tr '-' '_')
  # fi

  case "${subcmd}" in
    -h | --help)
      subcmd="usage"
      ;;
    h | help)
      subcmd="usage"
      ;;
    *)
      subcmd=$(printf '%s' "${subcmd}" | tr '-' '_')
      ;;
  esac

  # call the subcommand if it exists.
  if is_function "gitex_${subcmd}"; then
    shift
    "gitex_${subcmd}" "$@"
  else
    echo >&2 "gitex: subcommand not found '${subcmd}'."
    return 1
  fi
}

gitex "$@"
