#!/bin/bash
FILE_PATH=$(readlink -f "$BASH_SOURCE")
FILE_DIR=$(dirname "$FILE_PATH")
source "$FILE_DIR/compare_versions.sh"

EVENT_NAME="$1"
HEAD="$2"
BASE="$3"
PR_NUMBER="$4"
LATEST_MMP_VERSION="$5" # Latest major.minor.patch version.
LATEST_REVISION="${6:-0}"

if [[ ! -f "$GITHUB_OUTPUT" ]]; then
    # Write to stdout if the output file doesn't exist.
    GITHUB_OUTPUT="/dev/fd/1"
fi

BASE_VERSION=$(echo "$BASE" | cut -d '/' -sf 2 | xargs)
# Remove the first v in the version if it has onem as well as invalid characters.
BASE_VERSION="${BASE_VERSION#v}"
# Convert the base to a valid semver version. Anything not alphanumeric or a - or ..
BASE_VERSION="${BASE_VERSION//[^a-z0-9\-\.]/-}"

if [[ -z "$BASE_VERSION" ]]; then
    # Just use the latest version as a base if the release branch has no possible versions.
    BASE_VERSION="$LATEST_MMP_VERSION"
fi

echo "majorMinorPatchVersion=$BASE_VERSION" >> "$GITHUB_OUTPUT"

# Convert the head to a valid semver patch version. Anything not alphanumeric or a -.
HEAD="${HEAD//[^a-z0-9\-]/-}"

compare_versions "$BASE_VERSION" "$LATEST_MMP_VERSION"
if [[ $? == 1 ]]; then
    # If the base version is greater than the latest version, then set the increment mode to 'patch'
    LATEST_REVISION=0
fi

if [[ "$EVENT_NAME" == "pull_request" ]]; then
    # Use the branch name as a prerelease version and increment the revision.
    BASE_VERSION="$BASE_VERSION-$PR_NUMBER.$HEAD"
    CURRENT_VERSION="$BASE_VERSION.$LATEST_REVISION"
elif [[ "$EVENT_NAME" != "push" && "$EVENT_NAME" != "workflow_dispatch" ]]; then
    echo "Invalid event name to attempt to push a package on: $EVENT_NAME"
    exit 1
fi

CURRENT_VERSION="$BASE_VERSION.$LATEST_REVISION"

echo "baseVersion=$BASE_VERSION" >> "$GITHUB_OUTPUT"
echo "currentVersion=$CURRENT_VERSION" >> "$GITHUB_OUTPUT"
