#!/usr/bin/env bash
set -euo pipefail

# --- Überprüfen, ob ASSIGNMENT gesetzt ist ---
if [[ -z "${ASSIGNMENT:-}" ]]; then
  echo "Fehler: Die Umgebungsvariable ASSIGNMENT ist nicht gesetzt."
  echo "Beispiel: export ASSIGNMENT='{\"Mandant\":\"...\",\"Retailer\":\"...\",\"Customer\":\"...\"}'"
  exit 1
fi

# --- Distribution und Codename ermitteln ---
if command -v lsb_release >/dev/null 2>&1; then
  DIST_ID=$(lsb_release -is | tr '[:upper:]' '[:lower:]')
  DIST_CODENAME=$(lsb_release -cs)
else
  # Fallback über /etc/os-release
  source /etc/os-release
  DIST_ID=$(echo "$ID" | tr '[:upper:]' '[:lower:]')
  DIST_CODENAME=$VERSION_CODENAME
fi

echo "[*] Gefundene Distribution: $DIST_ID ($DIST_CODENAME)"

# --- .NET 9 installieren ---
echo "[*] Installiere .NET 9..."
wget -qO- https://repo.manage4all.de/install-dotnet.sh | bash

# --- manage4all Repository hinzufügen ---
echo "[*] Richte manage4all Repository ein..."
sudo mkdir -p /etc/apt/trusted.gpg.d
echo "deb [signed-by=/etc/apt/trusted.gpg.d/manage4all.asc] https://repo.manage4all.de/${DIST_ID} ${DIST_CODENAME} main" \
  | sudo tee /etc/apt/sources.list.d/manage4all.list > /dev/null

# Wichtig: Schlüssel passend zur Distribution holen
sudo wget -O /etc/apt/trusted.gpg.d/manage4all.asc https://repo.manage4all.de/${DIST_ID}/public-key.asc

sudo apt-get update
sudo apt-get install -y manage4all-agent

# --- Assignment setzen ---
echo "[*] Schreibe Assignment nach /etc/manage4all/ServiceSecurity/SC_Assignments_NoReg.json..."
sudo mkdir -p /etc/manage4all/ServiceSecurity
echo "$ASSIGNMENT" | sudo tee /etc/manage4all/ServiceSecurity/SC_Assignments_NoReg.json > /dev/null

# --- Agent neu starten ---
echo "[*] Starte manage4all-agent neu..."
sudo systemctl restart m4A-agent
sudo systemctl enable m4A-agent

echo "[✓] Installation und Konfiguration abgeschlossen."
