#!/usr/bin/env bash

# git-my v0.1
#
# Lists (stale) (branches|tags) in the remote named (origin) (where you were
# the last committer)
#
# Copyright (c) 2015 David O'Trakoun <me@davidosomething.com>
#
# Usage:
#   git my
#
# Options:
#   @todo NOT IMPLEMENTED
#   -U|--username="gitconfig user.name"
#   -R|--remote=origin
#   -T|--tags
#   -B|--branches
#   -F|--filter=mine,stale
#

_check_in_repository() {
  git rev-parse --git-dir > /dev/null 2>&1
}

_filter_mine() {
  local git_user=$(git config --get user.name)

  # use eval to not parse the fmt string
  local my_remotes=$(echo "$1" | grep -i "^$git_user")
  echo "$my_remotes" | awk -F'\t' '{ print $2 }'
}

# @TODO
_filter_stales() {
  local raw_stales=$(git remote prune --dry-run origin)
  echo "$raw_stales"
}

_main() {
  if ! _check_in_repository ; then
    echo "This is not a git repository."
    exit 1
  fi

  # user.name<TAB>branch.name
  # the TAB is used as a delimiter to awk with
  local fmt='
    a=%(authorname)
    r=%(refname)
    b=${r#refs/remotes/origin/}
    printf "%s\t%s\n" "$a" "$b"
  '

  local cmd_everyones_remotes=$(
    git for-each-ref --shell --format="$fmt" refs/remotes/origin
  )
  local everyones_remotes=$(eval "$cmd_everyones_remotes")

  _filter_mine "$everyones_remotes"
}

_main

