#!/bin/bash

################################################################################
# Wrapper script for Server Toolkit (Beta)
################################################################################
# Safely runs toolkit with history isolation and reliable cleanup
################################################################################

set -o pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CLEANUP_FLAG="/tmp/.cleanup_requested"

# Save original history setting to restore even if interrupted
HISTORY_SETTING=$(set +o | grep history)
RESTORE_HISTORY=false

# Cleanup function: restore history even on error/interrupt
cleanup_on_exit() {
    if [ "$RESTORE_HISTORY" = true ]; then
        eval "$HISTORY_SETTING" 2>/dev/null || true
    fi
}

# Register cleanup to run on exit, interrupt, or error
trap cleanup_on_exit EXIT
trap 'cleanup_on_exit; return 130' INT TERM

# Validate script can be sourced
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    echo "ERROR: This script must be sourced, not executed."
    echo ""
    echo "Run it like this:"
    echo "  source $0"
    echo "  or"
    echo "  . $0"
    return 1
fi

# Validate launcher exists
if [ ! -f "$SCRIPT_DIR/launcher.sh" ]; then
    echo "ERROR: launcher.sh not found in $SCRIPT_DIR"
    return 1
fi

# Validate and fix HISTFILE if needed (prevents crashes)
if [ -n "$HISTFILE" ]; then
    HISTFILE_DIR="$(dirname "$HISTFILE" 2>/dev/null)"
    if [ ! -d "$HISTFILE_DIR" ] 2>/dev/null; then
        export HISTFILE="$HOME/.bash_history"
    fi
fi

# Disable history recording (toolkit runs invisibly)
set +o history
RESTORE_HISTORY=true

# Run the launcher in current shell
source "$SCRIPT_DIR/launcher.sh"
LAUNCHER_EXIT=$?

# Re-enable history (trap will also do this)
eval "$HISTORY_SETTING" 2>/dev/null || true
RESTORE_HISTORY=false

# Handle cleanup request (if user selected "Clean and remove traces")
if [ -f "$CLEANUP_FLAG" ]; then
    rm -f "$CLEANUP_FLAG"

    # Attempt cleanup in subshell (safe, isolated)
    # Wait a moment for file descriptors to close
    sleep 0.5

    if (
        cd /root 2>/dev/null || exit 1
        rm -rf "$SCRIPT_DIR" 2>/dev/null
    ) 2>/dev/null; then
        # Cleanup succeeded - return cleanly
        clear
        echo ""
        echo "✓ Toolkit removed successfully"
        echo ""
        sleep 0.5  # Brief delay before returning to let system release resources
        return 0   # Return success (not $LAUNCHER_EXIT) after cleanup
    else
        # Cleanup failed - inform user but still return cleanly
        clear
        echo ""
        echo "⚠ Toolkit removal incomplete (may need manual cleanup)"
        echo "  Command: rm -rf '$SCRIPT_DIR'"
        echo ""
        return 0   # Return success to avoid shell confusion
    fi
fi

# Normal exit (no cleanup) - return launcher's exit status
return $LAUNCHER_EXIT
