#!/bin/bash

red='\e[033[31m'
yellow='\e[0;33m'
green='\033[32m'
blue='\033[34m'
NC='\e[0m'

function usage()
{
	echo -e "Usage: `basename $0` upstream-comit-id"
}

[ $# -lt 1 ] && usage && exit -1

STABLE_MAJ_VER=$(grep VERSION Makefile | head -n1 | awk {'print $3'})
STABLE_MIN_VER=$(grep PATCHLEVEL Makefile | head -n1 | awk {'print $3'})

# LTS 4.4 is gone, fixup to 4.9
if [ "$STABLE_MAJ_VER.$STABLE_MIN_VER" = "4.4" ]; then
	STABLE_MIN_VER="9"
fi

latest_branch_tag=$(git tag --list "v$STABLE_MAJ_VER.$STABLE_MIN_VER.*" --sort="-taggerdate" | head -n 1)

# Grab the subject, since commit sha1 is different between branches we
# have to look it up based on subject.
subj=$(git log -1 --pretty="%s" $1)
if [ $? -gt 0 ]; then
        exit 0
fi

# Try and find if there's a commit with given subject the hard way
for i in $(git log --pretty="%H" -F --grep "$subj" v$STABLE_MAJ_VER.$STABLE_MIN_VER..$latest_branch_tag);
do
	cursubj=$(git log -1 --format="%s" $i)
	if [ "$cursubj" = "$subj" ]; then
		tags=$(git tag --sort=taggerdate --contains $i | head -n 1)
		echo -e "$tags -> $i"
		echo -e "${green}Successed.${NC}"
		exit 0;
	fi
done

echo -e "${yellow}Not found${NC}"
