#!/bin/bash
VERSION="$1"

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

IS_PRERELEASE=$(echo "$VERSION" | grep -c '-')
if [[ "$IS_PRERELEASE" == 0 ]]; then
    IS_PRERELEASE=false
else
    IS_PRERELEASE=true
fi
echo "isPrerelease=$IS_PRERELEASE" >> "$GITHUB_OUTPUT"

MAJOR=$(echo "$VERSION" | cut -d '.' -f 1 | cut -d '+' -f 1 | xargs printf %d 2> /dev/null)
MINOR=$(echo "$VERSION" | cut -d '.' -f 2 | cut -d '+' -f 1 | xargs printf %d 2> /dev/null)
PATCH=$(echo "$VERSION" | cut -d '.' -f 3 | cut -d '-' -f 1 | xargs | cut -d '+' -f 1 | xargs printf %d 2> /dev/null)
REVISION=$(echo "$VERSION" | cut -d '.' -f 4 | cut -d '-' -f 1 | cut -d '+' -f 1 | xargs printf %d 2> /dev/null)
SUFFIX=$(echo "$VERSION" | sed "s|^$MAJOR.$MINOR.$PATCH||" | sed "s|^.$REVISION||" | sed "s|^-||" | cut -d '+' -f 1 | xargs)
METADATA=$(echo "$VERSION" | cut -d '+' -sf 2 | xargs) # Empty if no delimeter '+' present.

echo "version=$VERSION" >> "$GITHUB_OUTPUT"
echo "major=$MAJOR" >> "$GITHUB_OUTPUT"
echo "minor=$MINOR" >> "$GITHUB_OUTPUT"
echo "patch=$PATCH" >> "$GITHUB_OUTPUT"
echo "revision=$REVISION" >> "$GITHUB_OUTPUT"
echo "suffix=$SUFFIX" >> "$GITHUB_OUTPUT"
echo "metadata=$METADATA" >> "$GITHUB_OUTPUT"
