#!/usr/bin/env bash
# reset environment variables that could interfere with normal usage
unset -v GREP_OPTIONS
# put all utility functions here

# make a temporary file
git_extra_mktemp() {
    mktemp -t "$(basename "$0")".XXXXXXX
}

git_extra_default_branch() {
    local extras_default_branch init_default_branch
    extras_default_branch=$(git config --get git-extras.default-branch)
    init_default_branch=$(git config --get init.defaultBranch)
    if [ -n "$extras_default_branch" ]; then
        echo "$extras_default_branch"
    elif [ -n "$init_default_branch" ]; then
        echo "$init_default_branch"
    else
        echo "main"
    fi
}
#
# check whether current directory is inside a git repository
#

is_git_repo() {
  git rev-parse --show-toplevel > /dev/null 2>&1
  result=$?
  if test $result != 0; then
    >&2 echo 'Not a git repo!'
    exit $result
  fi
}

is_git_repo

GREEN="$(tput setaf 2)"
NORMAL="$(tput sgr0)"
if [ "$1" = "--color" ] || [ "$2" = "--color" ] || \
     [ "$1" = "-c" ] || [ "$2" = "-c" ] ; then
  COLOR_TITLE="$GREEN"
else
  COLOR_TITLE="$NORMAL"
fi

HIDE_CONFIG=
if [ "$1" != "--no-config" ] && [ "$2" != "--no-config" ]; then
  HIDE_CONFIG=1
fi

get_config() {
  cmd_get_config="$(git config --get-all git-extras.info.config-grep)"
  if [ -z "$cmd_get_config" ]; then
    git config --list
  else
    eval "$cmd_get_config"
  fi
}

most_recent_commit() {
  cmd_get_log="$(git config --get-all git-extras.info.log)"
  if [ -z "$cmd_get_log" ]; then
    git log --max-count=1 --pretty=short
  else
    eval "$cmd_get_log"
  fi
}

submodules() {
  # short sha1
  git submodule status | sed 's/\([^abcdef0-9]\{0,2\}\)\([abcdef0-9]\{7\}\)\([abcdef0-9]\{33\}\)\(.*\)/\1\2\4/'
}

local_branches() {
  git branch
}

remote_branches() {
  git branch -r
}

remote_urls() {
  git remote -v
}

echon() {
  echo "$@"
  echo
}

echo
echon "${COLOR_TITLE}## Remote URLs:${NORMAL}"
echon "$(remote_urls)"

echon "${COLOR_TITLE}## Remote Branches:${NORMAL}"
echon "$(remote_branches)"

echon "${COLOR_TITLE}## Local Branches:${NORMAL}"
echon "$(local_branches)"

SUBMODULES_LOG=$(submodules)
if [ -n "$SUBMODULES_LOG" ]; then
  echon "${COLOR_TITLE}## Submodule(s):${NORMAL}"
  echon "$SUBMODULES_LOG"
fi

echon "${COLOR_TITLE}## Most Recent Commit:${NORMAL}"
echon "$(most_recent_commit)"

if [ -n "$HIDE_CONFIG" ]; then
  echon "${COLOR_TITLE}## Configuration (.git/config):${NORMAL}"
  echon "$(get_config)"
fi
