#!/bin/bash

set -euo pipefail

SCRIPT_DIR=$(dirname -- "${BASH_SOURCE[0]}")
SCRIPT_DIR=$(cd "$SCRIPT_DIR" && pwd)
OUTPUT_PATH=${1:-"$SCRIPT_DIR/bootstrap-standalone.sh"}
TMP_PATH=$(mktemp "${OUTPUT_PATH}.XXXXXX")
BASH_TMP_PATH=$(mktemp "${OUTPUT_PATH}.bash.XXXXXX")

cleanup() {
    rm -f "$TMP_PATH"
    rm -f "$BASH_TMP_PATH"
}
trap cleanup EXIT

append_module() {
    local module_path=$1

    awk -v module_path="$module_path" '
        skip_self_run && /^[[:space:]]*fi[[:space:]]*$/ { skip_self_run=0; next }
        skip_self_run { next }
        skip_function_depth > 0 {
            if ($0 ~ /\{/) skip_function_depth++
            if ($0 ~ /\}/) skip_function_depth--
            next
        }
        NR == 1 && /^#!/ { next }
        /^set -euo pipefail$/ { next }
        /SCRIPT_DIR/ { next }
        /BASH_SOURCE/ { skip_self_run=1; next }
        module_path ~ /main[.]sh$/ && /^print_modular_usage\(\)/ { skip_function_depth=1; next }
        module_path ~ /main[.]sh$/ && /^print_usage\(\)/ {
            print "print_usage() {"
            print "    print_standalone_usage"
            print "}"
            skip_function_depth=1
            next
        }
        module_path ~ /main[.]sh$/ && /^execute_modular_action\(\)/ { skip_function_depth=1; next }
        module_path ~ /main[.]sh$/ && /^execute_action\(\)/ {
            print "execute_action() {"
            print "    execute_standalone_action"
            print "}"
            skip_function_depth=1
            next
        }
        { print }
    ' "$module_path"
}

{
    cat <<'HEADER'
#!/bin/bash

set -euo pipefail

MANTICORE_STANDALONE=1
HEADER

    echo ""
    echo "# ---- constants.sh ----"
    append_module "$SCRIPT_DIR/constants.sh"

    cat <<'LOGGING'

# ---- standalone logging ----
DEFAULT_INSTALL_LOG="/var/log/manticore_install.log"
if [[ -n "${MANTICORE_INSTALL_LOG:-}" ]]; then
    INSTALL_LOG="$MANTICORE_INSTALL_LOG"
elif [[ -w /var/log || ( -e "$DEFAULT_INSTALL_LOG" && -w "$DEFAULT_INSTALL_LOG" ) ]]; then
    INSTALL_LOG="$DEFAULT_INSTALL_LOG"
else
    INSTALL_LOG="${TMPDIR:-/tmp}/manticore_installer.log"
fi

COLOR_STRIP_REGEX='s/\x1b\[[0-9;]*m//g'
: > "$INSTALL_LOG"

if [[ -t 1 ]]; then
    export MANTICORE_COLOR_TTY=true
    exec > >(tee /dev/tty | sed "$COLOR_STRIP_REGEX" >> "$INSTALL_LOG") 2>&1
else
    export MANTICORE_COLOR_TTY=false
    exec > >(tee -a "$INSTALL_LOG") 2>&1
fi

print_log() {
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1"
}
LOGGING

    for module in ui.sh upgrade.sh install.sh uninstall.sh detect.sh main.sh; do
        echo ""
        echo "# ---- ${module} ----"
        append_module "$SCRIPT_DIR/$module"
    done
} > "$BASH_TMP_PATH"

bash -n "$BASH_TMP_PATH"

{
    cat <<'SH_WRAPPER'
#!/bin/sh
set -eu

if ! command -v bash >/dev/null 2>&1; then
    echo "[ERROR] bash is required to run this installer." >&2
    exit 1
fi

payload_path=$(mktemp "${TMPDIR:-/tmp}/manticore-standalone.XXXXXX.sh")

cleanup_payload() {
    rm -f "$payload_path"
}
trap cleanup_payload EXIT HUP INT TERM

cat > "$payload_path" <<'MANTICORE_STANDALONE_BASH_PAYLOAD'
SH_WRAPPER

    cat "$BASH_TMP_PATH"

    cat <<'SH_WRAPPER'
MANTICORE_STANDALONE_BASH_PAYLOAD

bash "$payload_path" "$@"
SH_WRAPPER
} > "$TMP_PATH"

chmod +x "$TMP_PATH"
sh -n "$TMP_PATH"
mv "$TMP_PATH" "$OUTPUT_PATH"
trap - EXIT
rm -f "$TMP_PATH" "$BASH_TMP_PATH"
echo "Built $OUTPUT_PATH"
