#!/bin/bash
MAJOR="$1"
MINOR="$2"
PATCH="$3"
REVISION="$4"
SUFFIX="$5"
METADATA="$6"
INCREMENT_MODE="${7:-default}"
GIT_SHA_METADATA="$8"

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

NEXT_MAJOR=$((MAJOR + 1))
NEXT_MINOR=$((MINOR + 1))
NEXT_PATCH=$((PATCH + 1))
NEXT_REVISION=$((REVISION + 1))
NEXT_SUFFIX="$SUFFIX"
NEXT_METADATA="$METADATA"
if [[ "$GIT_SHA_METADATA" == "true" ]]; then
    NEXT_METADATA="$GITHUB_SHA"
fi

echo "nextMajor=$NEXT_MAJOR" >> "$GITHUB_OUTPUT"
echo "nextMinor=$NEXT_MINOR" >> "$GITHUB_OUTPUT"
echo "nextPatch=$NEXT_PATCH" >> "$GITHUB_OUTPUT"
echo "nextRevision=$NEXT_REVISION" >> "$GITHUB_OUTPUT"
echo "nextSuffix=$NEXT_SUFFIX" >> "$GITHUB_OUTPUT"
echo "nextMetadata=$NEXT_METADATA" >> "$GITHUB_OUTPUT"


# This script assumes that thre version numbers is the desired default format.
NEXT_VERSION="${MAJOR:-0}.${MINOR:-0}"
if [[ "$INCREMENT_MODE" == "default" ]]; then
    if [[ -n "$REVISION" ]]; then
        NEXT_VERSION="$NEXT_VERSION.${PATCH:-0}.$NEXT_REVISION"
    elif [[ -n "$PATCH" ]]; then
        NEXT_VERSION="$NEXT_VERSION.$NEXT_PATCH"
    elif [[ -n "$MINOR" ]]; then
        NEXT_VERSION="${MAJOR:-0}.$NEXT_MINOR.0"
    else
        NEXT_VERSION="$NEXT_MAJOR.0.0"
    fi
elif [[ "$INCREMENT_MODE" == "major" ]]; then
    NEXT_VERSION="$NEXT_MAJOR.0.0"
elif [[ "$INCREMENT_MODE" == "minor" ]]; then
    NEXT_VERSION="${MAJOR:-0}.$NEXT_MINOR.0"
elif [[ "$INCREMENT_MODE" == "patch" ]]; then
    NEXT_VERSION="${MAJOR:-0}.${MINOR:-0}.$NEXT_PATCH"
elif [[ "$INCREMENT_MODE" == "revision" ]]; then
    NEXT_VERSION="${MAJOR:-0}.${MINOR:-0}.${PATCH:-0}.$NEXT_REVISION"
else
    echo "Invalid increment mode: $INCREMENT_MODE"
    exit 1
fi

if [[ -n "$NEXT_SUFFIX" ]]; then
    NEXT_VERSION="$NEXT_VERSION-$NEXT_SUFFIX"
fi

if [[ -n "$NEXT_METADATA" ]]; then
    NEXT_VERSION="$NEXT_VERSION+$NEXT_METADATA"
fi

echo "nextVersion=$NEXT_VERSION" >> "$GITHUB_OUTPUT"
