#!/bin/bash

# --- Configuration & Paths ---
INSTALL="no"; UNINSTALL="no"
PRC_KEY=""; PRC_USER=""; TMP_DIR=""
INSTALL_DIR="/usr/bin"
CONF_DIR="/etc/pandorarc"
OLD_CONF_DIR="/etc/ehorus"
NEW_SHARE_DIR="/usr/share/pandorarc"
OLD_SHARE_DIR="/usr/share/ehorus"
SERVICE_DIR="/etc/systemd/system"
LOCK_FILE="/var/run/pandorarc_install.lock"
ARCH=$(uname -m)

export PERL_JSON_BACKEND=0

# -------------------------------------------------
# 1. ENVIRONMENT & ARCH CHECK
# -------------------------------------------------
[ "$EUID" -ne 0 ] && { echo "Error: This script must be run as root (sudo)."; exit 1; }
[ "$ARCH" != "aarch64" ] && [[ ! "$ARCH" =~ arm ]] && { echo "Error: Compatible with ARM systems only."; exit 1; }

exec 200>"$LOCK_FILE"
flock -n 200 || { echo "Error: Another instance of this installer is already running."; exit 1; }

# -------------------------------------------------
# 2. ARGUMENT PARSING
# -------------------------------------------------
while [ "$1" != "" ]; do
    case "$1" in
        --install)   INSTALL="yes" ;;
        --uninstall) UNINSTALL="yes" ;;
        --prc_key)   PRC_KEY=$2; shift ;;
        --prc_user)  PRC_USER=$2; shift ;;
        --tmp_dir)   TMP_DIR=$2; shift ;;
        --help)      INSTALL="help"; break ;;
    esac
    shift
done

# =================================================
# INSTALLATION / UPGRADE / MIGRATION
# =================================================
if [ "$INSTALL" = "yes" ]; then
    echo "> Starting Installation..."

    # PHASE 1: Cleanup (Using the industrial-grade PID loop)
    systemctl stop ehorus_agent_daemon 2>/dev/null || true
    systemctl stop pandorarc_agent_daemon 2>/dev/null || true
    pkill -9 -f "ehorus" 2>/dev/null || true
    
    RAW_PIDS=$(pgrep -f "pandorarc")
    PIDS_TO_KILL=""
    for p in $RAW_PIDS; do
        if [ "$p" != "$$" ] && [ "$p" != "$PPID" ]; then PIDS_TO_KILL="$PIDS_TO_KILL $p"; fi
    done
    [ -n "$PIDS_TO_KILL" ] && kill -9 $PIDS_TO_KILL 2>/dev/null || true

    sync && sleep 1 
    rm -rf /tmp/par-726f6f74 /tmp/par-70616e646f72617263 /tmp/par-65686f727573 2>/dev/null || true
    rm -f /tmp/.X11-unix/X* /tmp/.X*-lock 2>/dev/null || true

    # Remove legacy service files from all common paths
    for P in /etc/systemd/system /lib/systemd/system /usr/lib/systemd/system; do
        rm -f "$P/ehorus_agent_daemon.service" 2>/dev/null
    done
    rm -f /etc/init.d/ehorus_agent_daemon 2>/dev/null || true

    # PHASE 2: Binary & Script Deployment
    mkdir -p "$CONF_DIR" "$NEW_SHARE_DIR" "/var/log" || exit 1
    
    cp -f pandorarc_agent "$INSTALL_DIR/pandorarc_agent"
    chmod 755 "$INSTALL_DIR/pandorarc_agent"
    rm -f "$INSTALL_DIR/ehorus_agent" 2>/dev/null || true

    cp -f pandorarc_agent_daemon /etc/init.d/pandorarc_agent_daemon
    chmod 755 /etc/init.d/pandorarc_agent_daemon

    # PHASE 3: Migration
    NEW_CONF_FILE="$CONF_DIR/pandorarc_agent.conf"
    NEW_CONF_NEW="$CONF_DIR/pandorarc_agent.conf.new"
    OLD_CONF_FILE="$OLD_CONF_DIR/ehorus_agent.conf"

    if [ -f "$OLD_CONF_FILE" ]; then
        echo "> Legacy eHorus detected. Migrating configuration..."
        [ -d "$OLD_SHARE_DIR" ] && cp -rp "$OLD_SHARE_DIR/." "$NEW_SHARE_DIR/" 2>/dev/null && rm -rf "$OLD_SHARE_DIR" 2>/dev/null
        sed -e "s/eh_/prc_/g" -e "s/ehorus/pandorarc/g" "$OLD_CONF_FILE" > "$NEW_CONF_FILE" || exit 4
        cp -f pandorarc_agent.conf "$NEW_CONF_NEW"
        rm -rf "$OLD_CONF_DIR" 2>/dev/null
    elif [ ! -f "$NEW_CONF_FILE" ]; then
        cp -f pandorarc_agent.conf "$NEW_CONF_FILE"
        cp -f pandorarc_agent.conf "$NEW_CONF_NEW"
    else
        cp -f pandorarc_agent.conf "$NEW_CONF_NEW"
    fi

    chown root:root "$NEW_CONF_FILE" "$NEW_CONF_NEW" 2>/dev/null || true
    chmod 600 "$NEW_CONF_FILE" "$NEW_CONF_NEW" 2>/dev/null || true

    # PHASE 4: Service Setup
    [ -n "$PRC_KEY" ] && sed -i "s|^prc_key.*|prc_key $PRC_KEY|g" "$NEW_CONF_FILE"
    [ -n "$PRC_USER" ] && sed -i "s|^prc_user.*|prc_user $PRC_USER|g" "$NEW_CONF_FILE"

    cp -f pandorarc_agent_daemon.service "$SERVICE_DIR/pandorarc_agent_daemon.service"
    
    # Idempotent Environment injection
    sed -i '/Environment="PERL_JSON_BACKEND=/d' "$SERVICE_DIR/pandorarc_agent_daemon.service"
    sed -i '/Environment="PAR_GLOBAL_TMPDIR=/d' "$SERVICE_DIR/pandorarc_agent_daemon.service"
    sed -i "/\[Service\]/a Environment=\"PERL_JSON_BACKEND=0\"" "$SERVICE_DIR/pandorarc_agent_daemon.service"

    if [ -n "$TMP_DIR" ]; then
        mkdir -p "$TMP_DIR"
        sed -i "/\[Service\]/a Environment=\"PAR_GLOBAL_TMPDIR=$TMP_DIR\"" "$SERVICE_DIR/pandorarc_agent_daemon.service"
    fi

    # PHASE 5: Activation
    systemctl daemon-reload >/dev/null 2>&1 || true
    systemctl enable pandorarc_agent_daemon.service >/dev/null 2>&1 || true

    [ -d /etc/logrotate.d ] && cp -f pandorarc_agent_logrotate /etc/logrotate.d/pandorarc_agent.conf 2>/dev/null || true
    cp -f LICENSES.README "$CONF_DIR/"

    echo ""
    echo "> Pandora RC Agent installed successfully."
    echo "> IMPORTANT: To start the agent and apply the configuration, please run manually:"
    echo "> sudo systemctl restart pandorarc_agent_daemon.service"
    echo ""

elif [ "$UNINSTALL" = "yes" ]; then
    echo "> Cleaning system..."
    systemctl stop pandorarc_agent_daemon 2>/dev/null || true
    systemctl disable pandorarc_agent_daemon 2>/dev/null || true
    
    # Clean processes safely
    RAW_PIDS=$(pgrep -f "pandorarc")
    PIDS_TO_KILL=""
    for p in $RAW_PIDS; do
        if [ "$p" != "$$" ] && [ "$p" != "$PPID" ]; then PIDS_TO_KILL="$PIDS_TO_KILL $p"; fi
    done
    [ -n "$PIDS_TO_KILL" ] && kill -9 $PIDS_TO_KILL 2>/dev/null || true

    rm -f "$INSTALL_DIR/pandorarc_agent" "$SERVICE_DIR/pandorarc_agent_daemon.service" /etc/init.d/pandorarc_agent_daemon
    rm -rf "$CONF_DIR" "$NEW_SHARE_DIR" /etc/logrotate.d/pandorarc_agent.conf
    systemctl daemon-reload >/dev/null 2>&1 || true
    echo "> Uninstallation complete."

else
    echo "Usage: $0 [--install|--uninstall] [--prc_user PRC_USER] [--prc_key PRC_KEY] [--tmp_dir TMP_DIR]"
    echo "  --install   To install Pandora RC agent on this system (you must be root)"
    echo "  --uninstall To uninstall and remove Pandora RC agent on this System"
    echo " "
    echo " Optional parameters:"
    echo " "
    echo " --prc_user   PRC_USER to manually set the prc_user on Pandora RC agent"
    echo " --prc_key    PRC_KEY to manually set a prc_key on Pandora RC agent"
    echo " --tmp_dir    TMP_DIR to manually set a custom TMP directory for the agent"
    rm -f "$LOCK_FILE"
    exit 0
fi

rm -f "$LOCK_FILE"
