#!/bin/bash
# Accept either positional arguments or environment variables
SERIAL=${1:-$SERIAL}
EMAIL=${2:-$EMAIL}
PASSWORD=${3:-$PASSWORD}
COMMAND=${4:-$COMMAND}
UNITY_BUILDER=${5:-$UNITY_BUILDER}

# Best-effort cleanup for any Docker lock created by the composite action.
if [[ -n "$LOCK_NAME" ]]; then
    echo "Removing Docker lock '$LOCK_NAME'..."
    docker rmi "$LOCK_NAME" >/dev/null 2>&1 || true
fi

DEFAULT_ARGS="-quit -logFile -"

rm -rf $HOME/.config/unity3d
rm -rf /home/unity/.config/unity3d

#Add ssh key information for resolving packages.
bash /scripts/add_ssh_keys.sh

if [[ "$SERIAL" != "activated" ]]; then
    echo "::group::Activating Unity License"
    bash /scripts/activate_license.sh "$SERIAL" "$EMAIL" "$PASSWORD"
    echo "::endgroup::"
fi

echo "::group::Running Unity Command"
#Run the command.
if [[ -n "$UNITY_BUILDER" && "$UNITY_BUILDER" != "false" ]]; then
    echo "Using UnityBuilder to run the command:"
    echo "    UnityBuilder $COMMAND"
    UnityBuilder $COMMAND
else
    echo "Using unity-editor to run the command:"
    echo "    unity-editor $DEFAULT_ARGS $COMMAND"
    unity-editor $DEFAULT_ARGS $COMMAND
fi
RESULT=$?
echo "Unity command exited with code: $RESULT"
echo "::endgroup::"

# Uncomment if movingback to a docker action.
#echo "exitCode=$RESULT" >> "$GITHUB_OUTPUT"

if [[ "$CATCH_ERRORS" != "true" ]]; then
    exit $RESULT
fi
