#!/bin/bash

mydir=$(dirname $0)
max_level=3
commits="$@"
yellow='\e[0;33m'
green='\033[32m'
blue='\033[34m'
NC='\e[0m'

[ $# -lt 1 ] && echo "Usage: $(basename $0) <commit sha1>" && exit -1;

# Need git-deps
command -v git-deps >/dev/null 2>&1 || echo "git-deps not found, run 'pip install git-deps' first"

# args:
#   $1 => commit
#   $2 => level file
function commit-deps () {
	single_commit_deps=$(git deps $1...$1^)

	local inner_found=0
	for l_commit in $single_commit_deps
	do
		$mydir/../stable-tools/stable commit-in-tree $l_commit
		if [[ $? != 1 ]]; then
			tag=$(git tag --sort=taggerdate --contains $l_commit | head -n 1)
			# for next level
			echo "$1 : $l_commit : $tag" >> $_patchlisttmpfile
			# print
			echo "$1 : $l_commit : $tag"
			inner_found=1
		fi
	done

	[ $inner_found = 1 ] && return 1
	return 0
}

# temp file for depend founding
_patchlisttmpfile=$(mktemp)

for ((level=0; level < max_level; level++))
do
	echo -e "${blue}Level $level:${NC}"
	for commit in $commits
	do
		# sanity check commitid
		if test -z "$(git log -1 --pretty=%s $commit 2> /dev/null)"
		then
		        echo -e "${yellow}Skipping: Bad commit ID: ${commit}${NC}"
		        continue
		fi

		commit-deps $commit
		if [ $? = 0 ]; then
			echo -e "$commit : ${green}done.${NC}"
		fi
	done

	# have next level?
	if [ -f $_patchlisttmpfile ]; then
		commits=$(cat $_patchlisttmpfile | awk -F':' '{print $2}' | uniq)
		if [ x"$commits" = x"" ]; then
			break;
		fi
	else
		break;
	fi

	# clean
	[ -f $_patchlisttmpfile ] && rm -f $_patchlisttmpfile
	# insert empty line
	echo ""
done

if [ $level = $max_level ]; then
	echo -e "${yellow}The dependency level exceeds 3, I suggest you to split the search,"
	echo -e "or change the max_level value of this script.${NC}"
fi
