#!/bin/bash
# XPyCode macOS .pkg Pre-Install Script
# Runs as root before the payload is laid down.
# Detects and removes any existing XPyCode installation.

set -uo pipefail

INSTALL_DIR="/Applications/XPyCode"
PLIST_LABEL="com.xpycode.master"

# Resolve the real user (not root) who launched the installer
if [ -n "${USER:-}" ] && [ "${USER}" != "root" ]; then
    REAL_USER="${USER}"
elif [ -n "${SUDO_USER:-}" ]; then
    REAL_USER="${SUDO_USER}"
else
    # Ask the window server for the console user (macOS-specific)
    REAL_USER=$(stat -f "%Su" /dev/console 2>/dev/null || echo "")
fi

echo "=== XPyCode Pre-Install ==="
echo "Install dir : ${INSTALL_DIR}"
echo "Real user   : ${REAL_USER:-<unknown>}"
echo ""

# ── Helper: run as real user ─────────────────────────────────────────────────
run_as_user() {
    if [ -n "${REAL_USER}" ] && [ "${REAL_USER}" != "root" ]; then
        sudo -H -u "${REAL_USER}" "$@"
    else
        "$@"
    fi
}

user_home() {
    if [ -n "${REAL_USER}" ] && [ "${REAL_USER}" != "root" ]; then
        eval echo "~${REAL_USER}"
    else
        echo "${HOME:-/var/root}"
    fi
}

USER_HOME=$(user_home)
PLIST_PATH="${USER_HOME}/Library/LaunchAgents/${PLIST_LABEL}.plist"
HANDLER_APP="${USER_HOME}/Applications/XPyCodeHandler.app"
DESKTOP_SHORTCUT="${USER_HOME}/Desktop/XPyCode.command"

if [ ! -d "${INSTALL_DIR}" ]; then
    echo "No existing installation found. Fresh install."
    exit 0
fi

echo "Existing installation detected at ${INSTALL_DIR}"
echo ""

# ── Step 1: Kill running XPyCode processes ───────────────────────────────────
echo "[1/3] Stopping any running XPyCode processes..."
pkill -f "xpycode_master" 2>/dev/null && echo "  Sent SIGTERM to xpycode_master processes" || echo "  No running xpycode_master processes found"
sleep 1
pkill -9 -f "xpycode_master" 2>/dev/null || true
echo ""

# ── Step 2: Teardown existing configuration ───────────────────────────────────
# Delegates to xpycode_master --teardown which handles: unregister manifest,
# clear SSL certificates, remove autostart (launchd plist), remove desktop
# shortcut, and remove protocol handler.
echo "[2/3] Tearing down existing configuration..."
PYTHON_EXE="${INSTALL_DIR}/python/bin/python3"
if [ -x "${PYTHON_EXE}" ]; then
    run_as_user "${PYTHON_EXE}" -m xpycode_master --teardown \
        && echo "  Configuration torn down successfully" \
        || echo "  WARNING: Teardown failed (will continue with cleanup)"
else
    echo "  Python not found, skipping teardown (manual cleanup will follow)"
fi
echo ""

# ── Step 3: Remove existing installation directory ───────────────────────────
echo "[3/3] Removing existing installation directory..."
if [ -d "${INSTALL_DIR}" ]; then
    rm -rf "${INSTALL_DIR}" && echo "  Removed: ${INSTALL_DIR}" || echo "  WARNING: Could not fully remove ${INSTALL_DIR}"
else
    echo "  Not found: ${INSTALL_DIR}"
fi
echo ""

echo "=== Pre-Install complete ==="
exit 0
