#!/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

    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

    RunFile="/mnt/cluster-init/.run/$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

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

main "$@"
