#!/bin/bash

. "$(dirname "$0")/init-functions"

BRANCH_COMMIT=HEAD

usage() {
	echo -e "$(basename "$0") [OPTION]... upstream-commit-id"
	echo
	echo -e "  -h, --help\t\t\tshow this help info"
	echo -e "  -q, --quiet\t\t\tdo not print tips"
	echo -e "  -b, --branch\t\t\ttest commit in [branch]"
	echo
}

commit_in_tree() {
	local commit="$1"
	local fullhash
	local subj
	local stable_maj_ver
	local stable_min_ver
	local cursubj
	local i

	# Validate input
	if [[ -z "$commit" ]]; then
		echo -e "${YELLOW}Warning: No commit specified${NC}" >&2
		return 0
	fi

	# Get full hash of the commit
	if ! fullhash=$(git rev-parse "$commit" 2>/dev/null); then
		# This might happen if someone pointed to a commit that doesn't exist in our tree
		return 0
	fi

	# Hope for the best, same commit is/isn't in the current branch
	if git merge-base --is-ancestor "$fullhash" "$BRANCH_COMMIT" 2>/dev/null; then
		return 1
	fi

	# Grab the subject, since commit sha1 is different between branches we
	# have to look it up based on subject
	if ! subj=$(git log -1 --pretty="%s" "$commit" 2>/dev/null); then
		return 0
	fi

	# Use version information from init-functions
	if [[ -z "$STABLE_MAJ_VER" ]] || [[ -z "$STABLE_MIN_VER" ]]; then
		echo -e "${YELLOW}Warning: Could not determine version information${NC}" >&2
		return 0
	fi

	stable_maj_ver="$STABLE_MAJ_VER"
	stable_min_ver="$STABLE_MIN_VER"

	# Try and find if there's a commit with given subject the hard way
	while IFS= read -r i; do
		if [[ -n "$i" ]]; then
			if cursubj=$(git log -1 --format="%s" "$i" 2>/dev/null); then
				if [[ "$cursubj" == "$subj" ]]; then
					return 1
				fi
			fi
		fi
	done < <(git log --pretty="%H" -F --grep "$subj" "v${stable_maj_ver}.${stable_min_ver}..${BRANCH_COMMIT}" 2>/dev/null)

	return 0
}

# Parse command line arguments
if ! ARGS=$(getopt -o hqb: -a --long help,quiet,branch: -- "$@"); then
	echo "Terminating..." >&2
	usage
	exit 1
fi

eval set -- "${ARGS}"

while true; do
	case "$1" in
		-h|--help)
			usage
			exit 0
			;;
		-b|--branch)
			BRANCH_COMMIT="$2"
			shift 2
			;;
		-q|--quiet)
			QUIET_TIPS=true
			shift
			;;
		--)
			shift
			break
			;;
		*)
			echo -e "${YELLOW}Unknown option: $1${NC}" >&2
			usage
			exit 1
			;;
	esac
done

# Check arguments
if [[ $# -lt 1 ]]; then
	echo -e "${YELLOW}Error: Missing upstream-commit-id argument${NC}" >&2
	usage
	exit 1
fi

# Main logic
commit_in_tree "$1"
result=$?

if [[ $result -eq 1 ]]; then
	[[ "$QUIET_TIPS" != "true" ]] && echo -e "${GREEN}Found.${NC}"
	exit 0
else
	[[ "$QUIET_TIPS" != "true" ]] && echo -e "${BLUE}Not Found.${NC}"
	exit 1
fi
