#!/bin/bash

if [ "$#" -eq 0 ] || [ "$#" -gt 2 ]; then
        echo "Usage: sync-stable <stable or mainline commit sha1> <insert-head-only>"
        exit -1
fi

ret=0

do_exit()
{
	if [ $ret == 0 ];then
		echo -e "\033[32mSucessed.\033[0m"
	else
		echo -e "\033[34mSomething wrong, please check it.\033[0m"
	fi
	exit $1
}

comment=$(git show --stat $1)
if [ $? != 0 ]; then
	echo "Not found commit"
	ret=-2
	do_exit -1;
fi

# Commit from stable tree ?
string=$(git show --stat $1 | grep -i upstream)
if [ $? == 0 ]; then
	result=$(echo $string | grep "\[ Upstream")
	if [[ "$result" != "" ]]
	then
		# [ Upstream commit d518691cbd3be3dae218e05cca3f3fc9b2f1aa77 ]
		mainline_commit=$(echo $string | awk '{print $4}')
	else
		# commit 4bf584a03eec674975ee9fe36c8583d9d470dab1 upstream.
		for sha in $(echo $string | awk '{print $2}')
		do
			if [ 40 == `echo $sha | wc -L` ]; then
				mainline_commit=$sha
			fi
		done

		if [ x"$mainline_commit" == x"" ]; then
			mainline_commit=$1
			echo "find fake upstream commit, use your commit."
		fi
	fi
else
	mainline_commit=$1
fi

# Now get the mainline commit
tag=$(git tag --sort=taggerdate --contains $mainline_commit| head -n 1)
if [ x"$tag" == x"" ];then
	echo -e "\033[31mNot found tag, please note.\033[0m"
	ret=-2
fi
if [ x"$2" != x"insert-head-only" -a x"$2" != x"iho" ]; then
	git cherry-pick -x $1
	if [ $? != 0 ]; then
		ret=-1
		COMMIT_ID=$1
	else
		COMMIT_ID=`git rev-parse HEAD`
	fi
else
	COMMIT_ID=$1
fi
if [ $ret == 0 ] || [ $ret == -2 ]; then
	msg=$(git log -1 --format="%s%n%nMainline: $mainline_commit%nFrom: $tag%nCategory: Bugfix%n%n%b%nK2CI-Arch: All%nCc: ky2022-next" ${COMMIT_ID})
	git commit -s --amend -m "$msg"
fi

do_exit
