#! /usr/bin/env bash

# Check git repository for various things:
#
# master    - check the current branch is master
# clean     - check for untracked files/uncommitted changes
# synced    - check that local and origin are in sync (push/pull)
# submodule - check submodules are synced
#
# Usage: check [--master] [--clean] [--synced] [--submodule] [<dir>]
#
usage="usage: $0 [--master] [--clean] [--synced] [--submodule] [<dir>]"

trap 'exit 1' ERR

function info () { echo "$*" 1>&2; }
function error () { info "$*"; exit 1; }

dir=.
master=n
submod=n
clean=n
synced=n

while [ $# -gt 0 ]; do
  case $1 in
    --master)
      master=y
      shift
      ;;
    --submodule)
      submod=y
      shift
      ;;
    --clean)
      clean=y
      shift
      ;;
    --synced)
      synced=y
      shift
      ;;
    *)
      dir=$1
      break
      ;;
  esac
done

function branch () # <dir>
{
  git -C $1 rev-parse --symbolic-full-name --abbrev-ref HEAD
}

function synced () # <dir> <branch>
{
  git -C $1 fetch

  local r=`git -C $1 rev-parse --verify $2`
  local or=`git -C $1 rev-parse --verify origin/$2`

  if [ "$r" != "$or" ]; then
    return 1
  fi
}

r=0

if [ "$master" = "y" ]; then
  br=`branch $dir`

  if [ "$br" != "master" ]; then
    info "current branch in $dir is $br, not master"
    r=1
  fi
fi

function submod () # <dir>
{
  # The --recursive option doesn't produce the complete path so we will
  # have to recurse ourselves.
  #
  local sms=`git -C $1 submodule foreach --quiet 'echo -n "$path "'`

  #info "checking '$sms' in $1..."

  local sm=
  for sm in $sms; do
    local smd=$1/$sm

    #info "sumbodule '$sm' in '$smd'"

    local br=`branch $smd`

    if ! synced $smd $br; then
      info "submodule $smd is not updated"
      return 1
    fi

    if ! submod $smd; then
      return 1
    fi
  done
}

if [ "$submod" = "y" ]; then
  if ! submod $dir; then
    r=1
  fi
fi

if [ "$clean" = "y" ]; then
  if git -C $dir status --porcelain | grep -q "^?? "; then
    info "untracked files in $dir"
    r=1
  fi

  if git -C $dir status --porcelain | grep -q "^ M "; then
    info "unstaged changes in $dir"
    r=1
  fi

  if git -C $dir status --porcelain | grep -q "^M "; then
    info "staged changes in $dir"
    r=1
  fi
fi

if [ "$synced" = "y" ]; then
  br=`branch $dir`

  if ! synced $dir $br; then
    info "$br and origin/$br in $dir differ, not synced"
    r=1
  fi
fi

exit $r