#!/bin/bash
SERIAL=$1; USERNAME=$2; PASSWORD=$3;

function check_path
{
    local SECRET_PATH="/run/secrets"
    local ENV_NAME="$1"
    local ENV_VALUE="${!ENV_NAME}"

    local FILE_PATH="$SECRET_PATH/$ENV_NAME"
    if [[ -z "$ENV_VALUE" && -f "$FILE_PATH" ]]; then
        export $ENV_NAME=$(cat "$FILE_PATH")
    fi
}

check_path SERIAL
check_path USERNAME
check_path PASSWORD

if [[ -z "$SERIAL" || -z "$USERNAME" || -z "$PASSWORD" ]]; then
    echo "Warning: License activation skipped - missing credentials"
    exit 0
fi

#Activate Unity
if [[ "$SERIAL" == "personal" ]]; then
    echo "Obtaining personal license for Unity..."
    UnityBuilder activate -i /usr/bin/unity-editor -u $USERNAME -p $PASSWORD
    ACTIVATION_RESULT=$?
else
    echo "Activating Unity License with serial number."
    unity-editor $DEFAULT_ARGS -serial $SERIAL -username $USERNAME -password $PASSWORD
    ACTIVATION_RESULT=$?
fi

if [[ $ACTIVATION_RESULT -ne 0 ]]; then
    echo "ERROR: Unity license activation failed with exit code $ACTIVATION_RESULT"
    exit $ACTIVATION_RESULT
fi

echo "Unity license activated successfully"