#!/usr/bin/env bash

# Usage:
#   $0 PACKAGE_NAME VERSION
#
# Before calling this script, run the commands to update the dependency. If
# there dependency shouldn't update then the script must not modify the repo.
#
# When the repo is in the updated state, run this script. It will commit
# everything and create a PR.
#
# The PR title is `Update ${PACKAGE_NAME} to ${VERSION}` the script checks for
# this string and only creates a new PR if the string isn't the title of an
# existing PR.
#
# PACKAGE_NAME is an identifier of the package, no spaces. Doesn't need to be
#              the exact name of the dependency.
#
# VERSION an identifier of the next version of the package, no spaces. This
#         variable must be the same if the version if the same and different if
#         the version is different. However, it doesn't have to be a `x.y.z` it
#         could be a Git SHA, or something else.

set -eu

PACKAGE_NAME=$1
VERSION=$2
BRANCH=update-${PACKAGE_NAME}-${VERSION}
COMMIT_MESSAGE="Update ${PACKAGE_NAME} to ${VERSION}"

if [[ -z "${PACKAGE_NAME}" ]]
then
    echo "Empty PACKAGE_NAME."
    exit -1
fi

if [[ -z "${VERSION}" ]]
then
    echo "Empty VERSION."
    exit -1
fi


# NOTE: In a later runs of CI we will search for PR with this exact
#       title. Only if no such PR exists will the script create a
#       new PR.
PR_TITLE="Update ${PACKAGE_NAME} to ${VERSION}"

if [[ -z "$(git status --porcelain)" ]]
then
    echo "No differences detected: ${PACKAGE_NAME} is up-to-date."
    exit 0
fi

if [[ -z "$(gh pr list --state all --search "${PR_TITLE}")" ]]
then

    git checkout -b $BRANCH
    git config user.name github-actions
    git config user.email github-actions@github.com
    git commit -a -m "${COMMIT_MESSAGE}"

    git push -u origin ${BRANCH}
    gh pr create \
        --title "${PR_TITLE}" \
        --body "This PR was generated by a Github Actions workflow."

else
    echo "Old PR detected: didn't create a new one."
fi
