#!/bin/bash
#
# SPDX-FileCopyrightText: The LineageOS Project
#
# SPDX-License-Identifier: Apache-2.0
#

usage() {
    echo "Usage ${0} [-t topic] <remote> <merge_sha> <branch>"
}

# Parse CLI args
while getopts "t:" opt; do
    case $opt in
        t)
            EXTRA+=",topic=${OPTARG}"
            ;;
        \?)
            exit 1
            ;;
    esac
done

shift $((OPTIND - 1))

# Verify argument count
if [ "${#}" -ne 3 ]; then
    usage
    exit 1
fi

REMOTE="${1}"
MERGE_SHA="${2}"
BRANCH="${3}"
FIRST_SHA="$(git show -s --pretty=%P ${MERGE_SHA} | cut -d ' ' -f 1)"
SECOND_SHA="$(git show -s --pretty=%P ${MERGE_SHA} | cut -d ' ' -f 2)"

git push "${REMOTE}" "${MERGE_SHA}":refs/for/"${BRANCH}"%base="${FIRST_SHA}",base="${SECOND_SHA}${EXTRA}"
