#!/bin/bash
# ============================================
# LXC Docker Creator - Proxmox
# Erstellt einen gehaerteten Debian 12 LXC
# Container mit Docker vorinstalliert
# ============================================
# Aufruf:  bash lxc-docker-creator.sh [CT_ID] [HOSTNAME] [IP]
# Beispiel: bash lxc-docker-creator.sh 130 my-app 192.168.1.130
# Quelle:  sgit.space/downloads
# ============================================

set -euo pipefail

# --- Defaults (anpassen!) ---
DEFAULT_STORAGE="local-lvm"
DEFAULT_TEMPLATE="local:vztmpl/debian-12-standard_12.7-1_amd64.tar.zst"
DEFAULT_GATEWAY="192.168.1.1"
DEFAULT_DNS="192.168.1.1"
DEFAULT_CORES=2
DEFAULT_RAM=1024      # MB
DEFAULT_SWAP=512      # MB
DEFAULT_DISK=8        # GB
DEFAULT_BRIDGE="vmbr0"
SSH_KEY_FILE="$HOME/.ssh/id_rsa.pub"

# --- Farben ---
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m'

# Nur auf PVE Host
if ! command -v pct &> /dev/null; then
    echo -e "${RED}Fehler: Dieses Script muss auf dem Proxmox VE Host laufen.${NC}"
    exit 1
fi

# Parameter
CT_ID="${1:-}"
HOSTNAME="${2:-}"
IP="${3:-}"

if [ -z "$CT_ID" ] || [ -z "$HOSTNAME" ] || [ -z "$IP" ]; then
    echo "Verwendung: $0 <CT_ID> <HOSTNAME> <IP>"
    echo "Beispiel:   $0 130 my-app 192.168.1.130"
    echo ""
    echo "Verfuegbare Templates:"
    pveam list local 2>/dev/null | grep debian || echo "  Keine gefunden. 'pveam download local debian-12-standard_12.7-1_amd64.tar.zst'"
    echo ""
    echo "Naechste freie CT-ID: $(pvesh get /cluster/nextid 2>/dev/null || echo '?')"
    exit 1
fi

# Pruefen ob CT-ID schon existiert
if pct status "$CT_ID" &>/dev/null; then
    echo -e "${RED}Fehler: CT $CT_ID existiert bereits!${NC}"
    exit 1
fi

echo -e "${GREEN}===== LXC Docker Creator =====${NC}"
echo "CT-ID:    $CT_ID"
echo "Hostname: $HOSTNAME"
echo "IP:       $IP/24"
echo "Gateway:  $DEFAULT_GATEWAY"
echo "Cores:    $DEFAULT_CORES"
echo "RAM:      ${DEFAULT_RAM}MB"
echo "Disk:     ${DEFAULT_DISK}GB"
echo ""
read -p "Container erstellen? (j/N) " -n 1 -r
echo
[[ ! $REPLY =~ ^[Jj]$ ]] && exit 0

# === 1. Container erstellen ===
echo -e "\n${GREEN}[1/6]${NC} Erstelle Container..."
pct create "$CT_ID" "$DEFAULT_TEMPLATE" \
    --hostname "$HOSTNAME" \
    --storage "$DEFAULT_STORAGE" \
    --rootfs "${DEFAULT_STORAGE}:${DEFAULT_DISK}" \
    --cores "$DEFAULT_CORES" \
    --memory "$DEFAULT_RAM" \
    --swap "$DEFAULT_SWAP" \
    --net0 "name=eth0,bridge=${DEFAULT_BRIDGE},ip=${IP}/24,gw=${DEFAULT_GATEWAY}" \
    --nameserver "$DEFAULT_DNS" \
    --unprivileged 1 \
    --features nesting=1,keyctl=1 \
    --onboot 1 \
    --start 0

echo "Container $CT_ID erstellt."

# === 2. Starten ===
echo -e "${GREEN}[2/6]${NC} Starte Container..."
pct start "$CT_ID"
sleep 3

# Warten bis Netzwerk da ist
for i in {1..10}; do
    if pct exec "$CT_ID" -- ping -c1 -W2 8.8.8.8 &>/dev/null; then
        break
    fi
    sleep 2
done

# === 3. System aktualisieren ===
echo -e "${GREEN}[3/6]${NC} System aktualisieren..."
pct exec "$CT_ID" -- bash -c "
    export DEBIAN_FRONTEND=noninteractive
    apt-get update -qq
    apt-get upgrade -y -qq
    apt-get install -y -qq curl wget gnupg lsb-release ca-certificates apt-transport-https sudo htop
"

# === 4. Docker installieren ===
echo -e "${GREEN}[4/6]${NC} Docker installieren..."
pct exec "$CT_ID" -- bash -c "
    curl -fsSL https://download.docker.com/linux/debian/gpg | gpg --dearmor -o /usr/share/keyrings/docker.gpg
    echo 'deb [arch=amd64 signed-by=/usr/share/keyrings/docker.gpg] https://download.docker.com/linux/debian bookworm stable' > /etc/apt/sources.list.d/docker.list
    apt-get update -qq
    apt-get install -y -qq docker-ce docker-ce-cli containerd.io docker-compose-plugin
    systemctl enable docker
"

# === 5. SSH haerten ===
echo -e "${GREEN}[5/6]${NC} SSH haerten..."

# SSH Key kopieren (falls vorhanden)
if [ -f "$SSH_KEY_FILE" ]; then
    pct exec "$CT_ID" -- mkdir -p /root/.ssh
    pct push "$CT_ID" "$SSH_KEY_FILE" /root/.ssh/authorized_keys
    pct exec "$CT_ID" -- chmod 700 /root/.ssh
    pct exec "$CT_ID" -- chmod 600 /root/.ssh/authorized_keys
fi

pct exec "$CT_ID" -- bash -c "
    # SSH haerten
    sed -i 's/#PermitRootLogin.*/PermitRootLogin prohibit-password/' /etc/ssh/sshd_config
    sed -i 's/#PasswordAuthentication.*/PasswordAuthentication no/' /etc/ssh/sshd_config
    sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config
    sed -i 's/#MaxAuthTries.*/MaxAuthTries 3/' /etc/ssh/sshd_config
    sed -i 's/#LoginGraceTime.*/LoginGraceTime 30/' /etc/ssh/sshd_config
    systemctl restart sshd
"

# === 6. fail2ban + unattended-upgrades ===
echo -e "${GREEN}[6/6]${NC} Sicherheit konfigurieren..."
pct exec "$CT_ID" -- bash -c "
    export DEBIAN_FRONTEND=noninteractive
    apt-get install -y -qq fail2ban unattended-upgrades

    # fail2ban: sshd Jail
    cat > /etc/fail2ban/jail.local << 'JAIL'
[sshd]
enabled = true
port = ssh
filter = sshd
backend = systemd
maxretry = 3
bantime = 3600
findtime = 600
JAIL
    systemctl enable fail2ban
    systemctl restart fail2ban

    # Unattended Upgrades: nur Security
    cat > /etc/apt/apt.conf.d/50unattended-upgrades << 'UU'
Unattended-Upgrade::Origins-Pattern {
    \"origin=Debian,codename=\${distro_codename}-security,label=Debian-Security\";
};
Unattended-Upgrade::Remove-Unused-Dependencies \"true\";
Unattended-Upgrade::Automatic-Reboot \"false\";
UU
    cat > /etc/apt/apt.conf.d/20auto-upgrades << 'AU'
APT::Periodic::Update-Package-Lists \"1\";
APT::Periodic::Unattended-Upgrade \"1\";
APT::Periodic::AutocleanInterval \"7\";
AU
    systemctl enable unattended-upgrades
"

# === Zusammenfassung ===
DOCKER_V=$(pct exec "$CT_ID" -- docker --version 2>/dev/null | awk '{print $3}' | tr -d ',')
echo ""
echo -e "${GREEN}===== Container $CT_ID fertig! =====${NC}"
echo ""
echo "  Hostname:   $HOSTNAME"
echo "  IP:         $IP"
echo "  Docker:     $DOCKER_V"
echo "  SSH:        Password-Auth deaktiviert"
echo "  fail2ban:   sshd-Jail aktiv"
echo "  Updates:    unattended-upgrades aktiv"
echo ""
echo "  Naechste Schritte:"
echo "    1. docker-compose.yml nach /opt/$HOSTNAME/ kopieren"
echo "    2. docker compose up -d"
echo "    3. Reverse Proxy (NPM) einrichten"
echo "    4. Backup-Job hinzufuegen"
echo ""
