#!/bin/bash
#
# RMM Agent Linux Installer
# Unterstuetzt: Debian, Ubuntu, Proxmox VE
#
# Verwendung nach ZIP-Download:
#   unzip rmm-linux-*.zip
#   bash install.sh
#

set -e

BASEDIR="$(cd "$(dirname "$0")" && pwd)"
AGENT_BIN="${BASEDIR}/rmm-agent-linux"
UPDATER_BIN="${BASEDIR}/rmm-updater-linux"
INSTALL_DIR="/usr/local/bin"
CONFIG_DIR="/etc/rmm"
CONFIG_FILE="${CONFIG_DIR}/config.yaml"
AGENT_ID_FILE="${CONFIG_DIR}/agent_id"

echo "========================================"
echo " RMM Agent Linux Installer"
echo "========================================"

# Root-Check
if [ "$(id -u)" -ne 0 ]; then
    echo "FEHLER: Bitte als root ausfuehren (sudo bash install.sh)"
    exit 1
fi

# Binaries pruefen
if [ ! -f "${AGENT_BIN}" ]; then
    echo "FEHLER: ${AGENT_BIN} nicht gefunden"
    echo "ZIP-Inhalt muss 'rmm-agent-linux' enthalten"
    exit 1
fi

# Alte Dienste stoppen
echo "[1/5] Alte Dienste stoppen..."
systemctl stop rmm-agent 2>/dev/null || true
systemctl stop rmm-updater 2>/dev/null || true

# Binaries installieren
echo "[2/5] Binaries installieren..."
cp "${AGENT_BIN}" "${INSTALL_DIR}/rmm-agent"
chmod +x "${INSTALL_DIR}/rmm-agent"
echo "  rmm-agent -> ${INSTALL_DIR}/rmm-agent"

if [ -f "${UPDATER_BIN}" ]; then
    cp "${UPDATER_BIN}" "${INSTALL_DIR}/rmm-updater"
    chmod +x "${INSTALL_DIR}/rmm-updater"
    echo "  rmm-updater -> ${INSTALL_DIR}/rmm-updater"
fi

# Config anlegen (wenn noch nicht vorhanden)
echo "[3/5] Konfiguration anlegen..."
mkdir -p "${CONFIG_DIR}"

# Agent-ID immer loeschen — jede Neuinstallation bekommt eine neue UUID
if [ -f "${AGENT_ID_FILE}" ]; then
    rm -f "${AGENT_ID_FILE}"
    echo "  Alte Agent-ID geloescht (neue wird beim Start generiert)"
fi

if [ ! -f "${CONFIG_FILE}" ]; then
    cat > "${CONFIG_FILE}" << 'CFGEOF'
backend_url: "https://BACKEND_IP:8443"
api_key: "DEIN_API_KEY"
interval_seconds: 60
agent_name: ""
insecure: true
CFGEOF
    echo "  Config erstellt: ${CONFIG_FILE}"
    echo "  WICHTIG: Bitte Backend-URL und API-Key eintragen!"
else
    echo "  Config bereits vorhanden — unveraendert"
fi

# Systemd Services
echo "[4/5] Systemd Services installieren..."

cat > /etc/systemd/system/rmm-agent.service << 'SVCEOF'
[Unit]
Description=RMM Agent
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
ExecStart=/usr/local/bin/rmm-agent -config /etc/rmm/config.yaml
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal
SyslogIdentifier=rmm-agent

[Install]
WantedBy=multi-user.target
SVCEOF

if [ -f "${INSTALL_DIR}/rmm-updater" ]; then
    cat > /etc/systemd/system/rmm-updater.service << 'SVCEOF'
[Unit]
Description=RMM Agent Updater
After=network-online.target rmm-agent.service
Wants=network-online.target

[Service]
Type=simple
ExecStart=/usr/local/bin/rmm-updater
Restart=always
RestartSec=30
StandardOutput=journal
StandardError=journal
SyslogIdentifier=rmm-updater

[Install]
WantedBy=multi-user.target
SVCEOF
fi

systemctl daemon-reload
systemctl enable rmm-agent
[ -f "${INSTALL_DIR}/rmm-updater" ] && systemctl enable rmm-updater || true

echo "  Systemd Services registriert"

# Start (nur wenn Config bereits ausgefuellt)
echo "[5/5] Dienste starten..."
if grep -q "BACKEND_IP\|DEIN_API_KEY" "${CONFIG_FILE}" 2>/dev/null; then
    echo ""
    echo "  Config noch nicht angepasst — Agent wird NICHT gestartet."
    echo ""
    echo "  Bitte Config bearbeiten und dann starten:"
    echo "    nano ${CONFIG_FILE}"
    echo "    systemctl start rmm-agent"
    [ -f "${INSTALL_DIR}/rmm-updater" ] && echo "    systemctl start rmm-updater" || true
else
    systemctl start rmm-agent
    [ -f "${INSTALL_DIR}/rmm-updater" ] && systemctl start rmm-updater || true
    echo "  Dienste gestartet"
fi

echo ""
echo "========================================"
echo " RMM Agent Linux installiert!"
echo ""
echo " Config:  ${CONFIG_FILE}"
echo " Logs:    journalctl -u rmm-agent -f"
echo " Status:  systemctl status rmm-agent"
echo "========================================"
