#!/bin/bash

# script from: https://python-semantic-release.readthedocs.io/en/stable/configuration/automatic-releases/github-actions.html#common-workflow-example

set +o pipefail

UPSTREAM_BRANCH_NAME="$(git status -sb | head -n 1 | awk -F '\\.\\.\\.' '{print $2}' | cut -d ' ' -f1)"
printf '%s\n' "Upstream branch name: $UPSTREAM_BRANCH_NAME"

set -o pipefail

if [ -z "$UPSTREAM_BRANCH_NAME" ]; then
    printf >&2 '%s\n' "::error::Unable to determine upstream branch name!"
    exit 1
fi

git fetch "${UPSTREAM_BRANCH_NAME%%/*}"

if ! UPSTREAM_SHA="$(git rev-parse "$UPSTREAM_BRANCH_NAME")"; then
    printf >&2 '%s\n' "::error::Unable to determine upstream branch sha!"
    exit 1
fi

HEAD_SHA="$(git rev-parse HEAD)"

if [ "$HEAD_SHA" != "$UPSTREAM_SHA" ]; then
    printf >&2 '%s\n' "[HEAD SHA] $HEAD_SHA != $UPSTREAM_SHA [UPSTREAM SHA]"
    printf >&2 '%s\n' "::error::Upstream has changed, aborting release..."
    exit 1
fi

printf '%s\n' "Verified upstream branch has not changed, continuing with release..."