#!/usr/bin/env bash
# DeathOps Agent Universal Linux Installer
# Usage:
#   curl -sSL https://deathops.example.com/install.sh | sudo bash -s -- --api-key sec_agent_xxx
#
set -euo pipefail

PREFILLED_KEY=""
DEFAULT_BACKEND="http://deathops.muc.cloud"

API_KEY="${PREFILLED_KEY}"
BACKEND_URL="${DEFAULT_BACKEND}"
CONFIG_FILE="/etc/deathops/agent.conf"

# Parse CLI arguments
while [[ $# -gt 0 ]]; do
    case "$1" in
        -k|--key|--api-key)
            API_KEY="$2"
            shift 2
            ;;
        -b|--backend|--backend-url)
            BACKEND_URL="${2%/}"
            shift 2
            ;;
        -h|--help)
            echo "Usage: sudo ./install.sh [options]"
            echo "Options:"
            echo "  -k, --api-key <key>       DeathOps Agent API Key (required)"
            echo "  -b, --backend <url>       DeathOps Backend URL (default: ${DEFAULT_BACKEND})"
            exit 0
            ;;
        *)
            shift
            ;;
    esac
done

echo "================================================================="
echo "        💀 DeathOps Host Security & Telemetry Agent             "
echo "================================================================="

if [ "$(id -u)" -ne 0 ]; then
    echo "[!] Error: This installer must be run as root (use sudo)."
    exit 1
fi

if [ -z "${API_KEY}" ]; then
    echo -n "Enter your DeathOps API Key: "
    read -r API_KEY
    if [ -z "${API_KEY}" ]; then
        echo "[!] Error: An API Key is required to register this host."
        exit 1
    fi
fi

echo "[*] Backend URL: ${BACKEND_URL}"
echo "[*] API Key:     ${API_KEY:0:15}..."

# Export for package postinst
mkdir -p /etc/deathops
echo "INSTALL_API_KEY='${API_KEY}'" > /tmp/.deathops_install_env
echo "INSTALL_BACKEND_URL='${BACKEND_URL}'" >> /tmp/.deathops_install_env
chmod 600 /tmp/.deathops_install_env

# Detect package system
TMP_DIR=$(mktemp -d)
trap 'rm -rf "${TMP_DIR}"' EXIT

INSTALLED=0

# 1. Debian / Ubuntu (.deb)
if command -v dpkg >/dev/null 2>&1; then
    echo "[*] Debian/Ubuntu system detected. Fetching .deb package..."
    DEB_URL="${BACKEND_URL}/packages/deathops-agent.deb"
    DEB_PATH="${TMP_DIR}/deathops-agent.deb"
    
    if curl -sSL -f "${DEB_URL}" -o "${DEB_PATH}"; then
        echo "[*] Installing .deb package via dpkg..."
        if ! dpkg -i "${DEB_PATH}"; then
            echo "[*] Resolving dependencies via apt-get..."
            apt-get update -qq || true
            apt-get install -f -y
        fi
        INSTALLED=1
    else
        echo "[!] Could not fetch .deb package from ${DEB_URL}. Falling back to standalone script install."
    fi
fi

# 2. RHEL / Rocky / Alma / Fedora / CentOS (.rpm)
if [ "${INSTALLED}" -eq 0 ] && command -v rpm >/dev/null 2>&1; then
    echo "[*] RPM-based system detected. Fetching .rpm package..."
    RPM_URL="${BACKEND_URL}/packages/deathops-agent.rpm"
    RPM_PATH="${TMP_DIR}/deathops-agent.rpm"

    if curl -sSL -f "${RPM_URL}" -o "${RPM_PATH}"; then
        echo "[*] Installing .rpm package via rpm..."
        rpm -Uvh --replacepkgs "${RPM_PATH}" || true
        INSTALLED=1
    else
        echo "[!] Could not fetch .rpm package from ${RPM_URL}. Falling back to standalone script install."
    fi
fi

# 3. Fallback direct install if package download failed
if [ "${INSTALLED}" -eq 0 ]; then
    echo "[*] Installing standalone deathops-agent binary and service..."
    mkdir -p /etc/deathops /usr/bin /lib/systemd/system /var/log/deathops
    
    # Download agent directly
    curl -sSL -f "${BACKEND_URL}/agent/deathops-agent" -o /usr/bin/deathops-agent 2>/dev/null || \
    cp "$(dirname "$0")/../agent/deathops-agent" /usr/bin/deathops-agent 2>/dev/null || true
    chmod 755 /usr/bin/deathops-agent

    # Download service unit
    curl -sSL -f "${BACKEND_URL}/agent/deathops-agent.service" -o /lib/systemd/system/deathops-agent.service 2>/dev/null || \
    cp "$(dirname "$0")/../agent/deathops-agent.service" /lib/systemd/system/deathops-agent.service 2>/dev/null || true
fi

# Ensure configuration file is written
if [ ! -f "${CONFIG_FILE}" ] || [ -f "${CONFIG_FILE}.example" ]; then
    cat <<EOF > "${CONFIG_FILE}"
[agent]
api_key = ${API_KEY}
backend_url = ${BACKEND_URL}
interval_seconds = 300
verify_ssl = true
collect_packages = true
log_level = INFO
EOF
else
    # Update existing config with new key & backend
    sed -i "s|^api_key = .*|api_key = ${API_KEY}|" "${CONFIG_FILE}"
    sed -i "s|^backend_url = .*|backend_url = ${BACKEND_URL}|" "${CONFIG_FILE}"
fi
chmod 600 "${CONFIG_FILE}"

# Reload systemd and start service
if command -v systemctl >/dev/null 2>&1; then
    echo "[*] Reloading systemd and starting deathops-agent..."
    systemctl daemon-reload
    systemctl enable deathops-agent.service
    systemctl restart deathops-agent.service
fi

echo "[*] Performing initial telemetry test..."
if /usr/bin/deathops-agent --run-once; then
    echo ""
    echo "================================================================="
    echo " [✓] DeathOps Agent successfully installed and reporting!        "
    echo "================================================================="
    echo " Service:  sudo systemctl status deathops-agent"
    echo " Logs:     sudo journalctl -u deathops-agent -f"
    echo " Config:   /etc/deathops/agent.conf"
    echo " Dashboard:${BACKEND_URL}"
    echo "================================================================="
else
    echo "[!] Warning: Initial report failed. Check /var/log/deathops/agent.log or journalctl -u deathops-agent"
fi
