#!/bin/bash

. $(dirname $0)/init-functions

# Cleanup function for temporary files
cleanup() {
	[ -f "$_patchlisttmpfile" ] && rm -f "$_patchlisttmpfile"
	[ -f "$_commitlisttmpfile" ] && rm -f "$_commitlisttmpfile"
}

# Set trap to ensure cleanup on exit
trap cleanup EXIT

function usage()
{
	echo -e "Usage: $(basename $0) [OPTION] <commit sha1>";
	echo -e "       -f | --force\tForce check commit.";
	echo -e "       -l | --level\tSet maximum dependency level (default: 5).";
	echo
	echo -e "./$(basename $0) [-f] [-l level] upstream-commit-id"
}

# Validate commit ID
validate_commit() {
	local commit="$1"
	if test -z "$(git log -1 --pretty=%s "$commit" 2>/dev/null)"; then
		echo -e "${YELLOW}Skipping: Bad commit ID: ${commit}${NC}"
		return 1
	fi
	return 0
}

# Default values
FORCE=false
max_level=5

# Parse command line arguments
ARGS=`getopt -o hfl: -a --long help,force,level: -- "$@"`
[ $? != 0 ] && echo "Terminating..." && usage && exit -1

eval set -- "${ARGS}"

while true; do
	case $1 in
		-h|--help)
			usage
			exit 0
			;;
		-f|--force)
			FORCE=true
			shift
			;;
		-l|--level)
			if [[ "$2" =~ ^[0-9]+$ ]] && [ "$2" -gt 0 ]; then
				max_level="$2"
				shift 2
			else
				echo "Error: -l/--level requires a positive integer" >&2
				usage
				exit 1
			fi
			;;
		--)
			shift
			break
			;;
	esac
done

# check args
[ $# -lt 1 ] && usage && exit -1;

# save commits
commits="$@"

# sanity check commitid
if ! validate_commit "$1"; then
	exit -2
fi
# test in tree ?
$(dirname $0)/test-commit-in-tree -q $1
if [ $? == 0 -a x"$FORCE" != x"true" ]; then
	echo -e "${GREEN}In-tree, not need.${NC}" && exit 0;
fi

# Need git-deps
if ! command -v git-deps >/dev/null 2>&1; then
	echo -e "${RED}Error: git-deps not found, run 'pip install git-deps' first${NC}"
	exit 1
fi

# Process commit dependencies
# Args: $1 => commit hash
# Returns: 0 if no dependencies found, 1 if dependencies found
process_commit_deps() {
	local commit="$1"
	local deps_found=0

	# Get dependencies for this commit
	local commit_deps=$(git deps "$commit"..."$commit"^)
	echo "$commit" >> "$_commitlisttmpfile"

	for dep_commit in $commit_deps; do
		# Check if dependency is already in tree
		if ! "$(dirname $0)/test-commit-in-tree" -q "$dep_commit"; then
			local tag=$(gdct "$dep_commit")
			# Save for next level processing
			echo "$commit : $dep_commit : $tag" >> "$_patchlisttmpfile"
			# Display dependency
			echo "$commit : $dep_commit : $tag"
			deps_found=1
		fi
	done

	[ $deps_found -eq 1 ] && return 1
	return 0
}

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

for ((level=0; level < max_level; level++)); do
	level_printed=false

	for commit in $commits; do
		# Validate commit ID
		if ! validate_commit "$commit"; then
			continue
		fi

		# Skip if already processed
		if ! grep -q "$commit" "$_commitlisttmpfile" 2>/dev/null; then
			# Print level header if needed
			if [ "$level_printed" = false ]; then
				[ $level -ne 0 ] && echo
				echo -e "${BLUE}Level $level:${NC}"
				level_printed=true
			fi

			# Process dependencies
			if process_commit_deps "$commit"; then
				echo -e "$commit : ${GREEN}done.${NC}"
			fi
		fi
	done

	# Check for next level dependencies
	if [ -f "$_patchlisttmpfile" ] && [ -s "$_patchlisttmpfile" ]; then
		commits=$(awk -F':' '{print $2}' "$_patchlisttmpfile" | sort -u)
		[ -z "$commits" ] && break
		# Clean up for next iteration
		rm -f "$_patchlisttmpfile"
	else
		break
	fi
done

# Check if maximum level reached
if [ $level -eq $max_level ]; then
	echo -e "${YELLOW}Warning: Dependency level exceeds $max_level. Consider splitting the search"
	echo -e "or using -l/--level option to increase the max level.${NC}"
fi
