#!/bin/bash
# M.Blakeney, Oct 2018.

PROG="$(basename $0)"
PROGDIR="$(dirname $0)"
SUMPROG="md5sum"
MAINPROG="libinput-gestures"

usage() {
    echo "Usage: $PROG [-options] [hashsum]"
    echo "Development utility to list version and hash sums, and flag those that"
    echo "match given hash sum. Must be run from the $MAINPROG git repo dir."
    echo "Options:"
    echo "-o (use old hash calc)"
    exit 1
}

# Process command line options
OLDCALC=0
while getopts o\? c; do
    case $c in
    o) OLDCALC=1;;
    \?) usage;;
    esac
done

shift $((OPTIND - 1))

if [[ $# -eq 1 ]]; then
    HASHSUM="$1"
elif [[ $# -ne 0 ]]; then
    usage
else
    HASHSUM=""
fi

output() {
    local tag=$1
    local hashsum=${2/ */}

    if [[ -n $HASHSUM && $HASHSUM == $hashsum ]]; then
	found=" *"
    else
	found=""
    fi

    printf "%-24s %s%s\n" $tag $hashsum "$found"
}

cd ${PROGDIR:-.} || exit 1

# Iterate through all tags and output the md5 hash for each version
tag=""
while read hashc; do
    tag=$(git describe --tags --always $hashc)

    filelist="$hashc:$MAINPROG"
    if [[ $OLDCALC -eq 0 ]]; then
	filelist="$filelist $hashc:$MAINPROG-setup"
    fi

    output $tag "$(git show $filelist 2>/dev/null | $SUMPROG)"
done <<< "$(git rev-list --all --reverse)"

# Output a version for the working tree as well
tagw=$(git describe --tags --always --dirty)
if [[ $tagw != $tag ]]; then
    if [[ $OLDCALC -eq 0 ]]; then
	output $tagw "$(cat $MAINPROG $MAINPROG-setup | $SUMPROG)"
    else
	output $tagw "$($SUMPROG <$MAINPROG)"
    fi
fi
