#!/bin/sh
set -eu

DEFAULT_SINCE='3.weeks.ago'
since=$DEFAULT_SINCE

usage () {
    cat <<EOF
usage: git active-branches [-s|-a <date>]

Options:
-s      show branches active since <date> (as in 'git log --since')
-a      (an alias for '-s')
<date>  any date format recognized by 'git log'

Unless specified, <date> defaults to "$DEFAULT_SINCE". For examples see:
https://git-scm.com/book/en/v2/Git-Basics-Viewing-the-Commit-History
EOF
}

while [ $# -gt 0 ]; do
    if ! getopts a:s:h flag; then usage >&2; exit 2; fi
    case "$flag" in
        a|s) since=$OPTARG; shift ;;
        \?)  usage >&2; exit 2 ;;  # argument missing its option
        h)   usage; exit 0 ;;
    esac
    shift
done

git local-branches | while read branch; do
    # '--no-patch' = suppress diff output (long form of '-s')
    maybebranch=$(
        git log -1 --since="$since" --no-patch "refs/heads/$branch" --
    )
    if [ -n "$maybebranch" ]; then
        echo "$branch"
    fi
done

git remote-branches | while read branch; do
    # '--no-patch' = suppress diff output (long form of '-s')
    maybebranch=$(
        git log -1 --since="$since" --no-patch "$branch" --
    )
    if [ -n "$maybebranch" ]; then
        echo "$branch"
    fi
done
