#!/bin/bash -eu
#
# Rebase onto upstream
#

function out()
{
	local rc=${?}

	trap - EXIT INT TERM HUP
	if [ ${rc} -ne 0 ] ; then
		echo "Error: Script failed" >&2
	fi

	exit "${rc}"
}

function usage()
{
	cat <<EOF
Usage: $(basename "${0}") [-h]

Rebase onto latest upstream linux-firmware. If not present, adds a new remote
'upstream', fetches form it, rebases onto upstream/main and adds a rebase
commit.

Option arguments:
  -h, --help  Show this help text and exit.
EOF
}

while [ ${#} -gt 0 ] ; do
	case "${1}" in
		-h|--help)
			usage
			exit
			;;
		*)
			echo "Invalid argument: ${1}" >&2
			exit 2
			;;
	esac
	shift
done

version=$(dpkg-parsechangelog -SVersion)
if echo "${version}" | grep -qE '\.[0-9]$' ; then
	echo "Current package version (${version}) looks like an SRU version." \
		 "Not rebasing." >&2
	exit 1
fi

trap out EXIT INT TERM HUP

# Add an upstream remote and fetch it
upstream_git=git://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git
if ! git remote | grep -qxF upstream ; then
	git remote add upstream "${upstream_git}"
fi
git fetch upstream

# Current upstream commit and version
. debian/upstream

# New upstream commit and version
new_commit=$(git rev-parse upstream/main)
new_version=$(date --utc +%Y%m%d).git${new_commit::8}

# Rebase onto upstream/main
git rebase "${new_commit}"

# Create the rebase commit
{
	echo "COMMIT=${new_commit}"
	echo "VERSION=${new_version}"
} > debian/upstream
git add debian/upstream
git commit -s -m "UBUNTU: Rebase to upstream commit ${new_commit}

Rebase against ${upstream_git}
${new_commit}
$(git log --no-merges --reverse --format='- %s' "${COMMIT}".."${new_commit}")"
