#!/bin/bash

set -e
set -u

OLD_PWD=$(pwd)
TAILS_REPO_PATH="$1"

trap cleanup exit

#cd $TAILS_REPO_PATH && git fetch || exit 1
cd $TAILS_REPO_PATH || exit 1

TAILS_BASE_BRANCHES="master devel testing"
LAST_RELEASE=$(git log -1 --format=%ct 1.2.3)

cleanup() {
  cd "$OLD_PWD"
}

# Takes a base branch
# Return a list of all branches not merged in this one
list_unmerged_feature_and_bugfix_branches() {
  local base="$1"
  git branch -r --no-merged "origin/${base}" | \
  egrep 'origin/feature|origin/bugfix' | grep -v "feature/jessie"
}

# Takes a datetime in seconds since 1970-01-01 00:00:00 UTC
#   and a branch
# Return 0 if last commit in branch is newer than datetime, 1
#  otherwise
branch_last_commit_newer_than() {
  local datetime="$1"
  local branch="$2"
  branch_last_commit_date=$(git show --format="%ct" $branch | head -n1)
  [ $branch_last_commit_date -gt $datetime ] || return 1
}

# Takes a datetime in seconds since 1970-01-01 00:00:00 UTC
# Returns a list of unmerged branches in master, stable and devel since then
list_unmerged_branches_since () {
  local date="$1"
  local keepers=""
  for base_branch in $TAILS_BASE_BRANCHES; do
    for unmerged_branch in $(list_unmerged_feature_and_bugfix_branches $base_branch); do
        if ! echo $keepers | grep -qs $unmerged_branch; then
          if $(branch_last_commit_newer_than $date $unmerged_branch); then
            keepers="$keepers $unmerged_branch"
        fi
      fi
    done
  done
  echo "$keepers"
}

BRANCHES=$(list_unmerged_branches_since $LAST_RELEASE)
for branch in $BRANCHES; do
    branch_last_commit_human_date=$(LC_ALL="C" git show --format="%ci %cr" $branch | head -n1)
    echo "$branch_last_commit_human_date	$branch"
done | sort
