#!/bin/bash


# Runs legacy cluster-init scripts:
# - the script is run in its directory
# - the script is run with a umask of 0022
# - the script is only run once (if it has already run successfully, it is skipped)
# - the script's output is logged to a project-specific log directory
function main() {
    local SpecName=$1
    local ScriptFilename=$2
    local LogFile
    local OldUmask
    local ScriptName
    local ScriptPath
    local OptRunDir

    if [[ -z "$CYCLECLOUD_PROJECT_PATH" ]]; then
        echo "This script can only be run inside a cluster-init stage."
        exit 1
    fi

    if [[ -z "$ScriptFilename" ]]; then
        echo "Usage: $0 <spec-name> <script-filename>"
        exit 1
    fi

    ScriptName="$SpecName/scripts/$ScriptFilename"
    ScriptPath="$CYCLECLOUD_PROJECT_PATH/$ScriptName"

    if [[ ! -f "$ScriptPath" ]]; then
        echo "Error: File '$ScriptFilename' does not exist in the 'scripts' directory for the '$SpecName' spec"
        exit 1
    fi

    if [[ "$SpecName" != @($CYCLECLOUD_SPEC_MATCH) ]]; then
        exit 0
    fi

    OptRunDir="$CYCLECLOUD_HOME/run/cluster-init/.run"
    RunFile="$OptRunDir/$CYCLECLOUD_PROJECT_NAME/${ScriptName}.run"
    if [[ -f "$RunFile" ]]; then
        echo "Script $ScriptName has already run successfully, skipping"
        return 0
    fi

    export CYCLECLOUD_SPEC_NAME="$SpecName"
    export CYCLECLOUD_SPEC_PATH="$CYCLECLOUD_PROJECT_PATH/$SpecName"

    pushd "$CYCLECLOUD_PROJECT_PATH/$SpecName/scripts" > /dev/null || exit 1

    OldUmask=$(umask) || exit 1
    umask 0022 || exit 1
    chmod u+x "$ScriptPath" || exit 1

    LogFile="$CYCLECLOUD_HOME/logs/cluster-init/$CYCLECLOUD_PROJECT_NAME/${ScriptName}.out"
    mkdir -p "$(dirname "$LogFile")" || exit 1

    echo "Executing cluster-init script: $ScriptPath, output written to $LogFile"

    "$ScriptPath" > "$LogFile" 2>&1
    local ScriptExitCode=$?
    if [[ $ScriptExitCode -ne 0 && "$CYCLECLOUD_FAIL_ON_ERROR" == "true" ]]; then
        cat "$LogFile" 2>&1
        exit $ScriptExitCode
    fi

    echo "Cluster-init script $ScriptPath ran successfully"

    mkdir -p "$(dirname "$RunFile")" || exit 1
    touch "$RunFile" || exit 1

    # Prior to CycleCloud 8.9.1, run files were stored under /mnt/cluster-init/.run, which is
    # wiped on deallocate. Symlink the legacy path to the new location for backward compatibility.
    # On the next converge:
    #   - If an individual run file was removed via the symlink, that script re-runs.
    #   - If the symlink itself disappeared (e.g. /mnt wiped on deallocate), nothing re-runs
    local LegacyRunDir="/mnt/cluster-init/.run"
    if [[ ! -e "$LegacyRunDir" || -L "$LegacyRunDir" ]]; then
        mkdir -p /mnt/cluster-init || exit 1
        ln -sfn "$OptRunDir" "$LegacyRunDir" || exit 1
    fi

    popd > /dev/null || exit 1
    umask "$OldUmask" || exit 1
}

main "$@"
