#!/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 -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/5] 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: Unload launchd service ───────────────────────────────────────────
echo "[2/5] Removing launchd service..."
if [ -f "${PLIST_PATH}" ]; then
    run_as_user launchctl unload "${PLIST_PATH}" 2>/dev/null \
        && echo "  Unloaded: ${PLIST_PATH}" \
        || echo "  Note: launchctl unload returned non-zero (service may not have been running)"
    rm -f "${PLIST_PATH}" && echo "  Removed plist: ${PLIST_PATH}" || true
else
    echo "  No plist found at ${PLIST_PATH}"
fi
echo ""

# ── Step 3: Remove protocol handler app bundle ───────────────────────────────
echo "[3/5] Removing protocol handler app bundle..."
if [ -d "${HANDLER_APP}" ]; then
    rm -rf "${HANDLER_APP}" && echo "  Removed: ${HANDLER_APP}" || echo "  WARNING: Could not remove ${HANDLER_APP}"
else
    echo "  Not found: ${HANDLER_APP}"
fi
# Also check the system-level location used by the .pkg installer
SYSTEM_HANDLER="/Applications/XPyCode/XPyCodeHandler.app"
if [ -d "${SYSTEM_HANDLER}" ]; then
    rm -rf "${SYSTEM_HANDLER}" && echo "  Removed: ${SYSTEM_HANDLER}" || true
fi
echo ""

# ── Step 4: Remove desktop shortcut ──────────────────────────────────────────
echo "[4/5] Removing desktop shortcut..."
if [ -f "${DESKTOP_SHORTCUT}" ]; then
    rm -f "${DESKTOP_SHORTCUT}" && echo "  Removed: ${DESKTOP_SHORTCUT}" || true
else
    echo "  Not found: ${DESKTOP_SHORTCUT}"
fi
echo ""

# ── Step 5: Remove existing installation directory ───────────────────────────
echo "[5/5] 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
