#!/usr/bin/env bash

echoerr() { printf "%s\n" "$*" >&2; }

echo Commandline:
echo
echo "$0" "$@"
echo
echo ---------------------------------------------------------------------------
echo Attachment:
if [ -f "$1" ]; then
    echo "File $1 exists."
    ls -la "$1"
else
    echo "File $1 does not exist."
fi
echo

# MultiFlexi injects real secrets (DB password, ENCRYPTION_MASTER_KEY, credential
# fields) into every job's environment. Since this probe persists its full env
# dump into RESULT_FILE/stdout, which MultiFlexi stores permanently in the job
# table, names matching this pattern are redacted by default. Set
# PROBE_SHOW_SECRETS=true to get the raw, unredacted dump for local debugging.
secret_name_pattern='(^|_)(PASSWORD|SECRET|TOKEN|CREDENTIAL)($|_)|^ENCRYPTION_MASTER_KEY$|^MULTIFLEXI_MASTER_KEY$|_KEY$'

envirnonment_variables=$(
    while IFS= read -r line; do
        key="${line%%=*}"
        value="${line#*=}"

        if [ "${PROBE_SHOW_SECRETS:-false}" != "true" ] && [[ "$key" =~ $secret_name_pattern ]]; then
            value="***REDACTED***"
        fi

        printf '%s=%s\n' "$key" "$value"
    done < <(env) | jq -R 'split("=") | {(.[0]): (.[1:] | join("="))}' | jq -s add
)

if [ -n "$RESULT_FILE" ]; then
    echo "$envirnonment_variables"     > "$RESULT_FILE"
fi

echo "$envirnonment_variables"

echoerr "StdErr Output example"

echo "Mount Info"
cat /proc/self/mountinfo 

if [[ -n "$PROBE_SLEEP" && "$PROBE_SLEEP" =~ ^[0-9]+$ && "$PROBE_SLEEP" -gt 0 ]]; then
    echo "Sleeping for ${PROBE_SLEEP}s to simulate a long-running job..."
    elapsed=0
    while [[ $elapsed -lt $PROBE_SLEEP ]]; do
        sleep 1
        elapsed=$((elapsed + 1))
        if (( elapsed % 60 == 0 )); then
            echo
        elif (( elapsed % 10 == 0 )); then
            printf '.'
        fi
    done
    echo
fi

if [[ -n "$FORCE_EXITCODE" && "$FORCE_EXITCODE" =~ ^[0-9]+$ ]]; then
    exit "$FORCE_EXITCODE"
fi
