#!/bin/bash

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

comment=$(git show --stat $1)
if [ $? != 0 ]; then
	echo "Not found commit"
	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
		# commit 4bf584a03eec674975ee9fe36c8583d9d470dab1 upstream.
		mainline_commit=$(echo $string | awk '{print $2}')
	else
		# [ Upstream commit d518691cbd3be3dae218e05cca3f3fc9b2f1aa77 ]
		mainline_commit=$(echo $string | awk '{print $4}')
	fi
else
	mainline_commit=$1
fi

# Now get the mainline commit
tag=$(git tag --sort=taggerdate --contains $mainline_commit| head -n 1)
msg=$(git log -1 --format="%s%n%nMainline: $mainline_commit%nFrom: $tag%nCategory: Bugfix%nCVE: NA%nKABI: NA%n%n%b" $1)
if [ x"$2" != x"insert-head-only" ]; then
	git cherry-pick $1 -s
fi
if [ $? == 0 ]; then
	git commit -s --amend -m "$msg"
fi
