#!/bin/bash

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

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

$(dirname $0)/../stable-tools/stable commit-in-tree $1
[ $? == 1 ] && echo -e "${green}In-tree, not need.${NC}" && exit 0;

# 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^)
	echo $1 >> $_commitlisttmpfile

	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)
_commitlisttmpfile=$(mktemp)

for ((level=0; level < max_level; level++))
do
	need_print_level="true"

	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

		grep -rn "$commit" $_commitlisttmpfile &> /dev/null
		# Not search before
		if [ $? = 1 ];
		then
			if [ x"$need_print_level" == x"true" ]; then
				# Insert empty line
				[ $level != 0 ] && echo
				echo -e "${blue}Level $level:${NC}"
				need_print_level="false";
			fi
			commit-deps $commit
			[ $? = 0 ] && echo -e "$commit : ${green}done.${NC}"
		fi
	done

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

	# clean
	[ -f $_patchlisttmpfile ] && rm -f $_patchlisttmpfile
done

[ -f $_commitlisttmpfile ] && rm -f $_commitlisttmpfile

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