#!/bin/bash
# =============================================================================
# Nextcloud-Snap Installationsskript für Ubuntu
# =============================================================================
# Getestet auf: Ubuntu 22.04 LTS / 24.04 LTS
# Ausführung:   sudo bash nextcloud.sh [-dryrun] [-domain <fqdn>] [-email <adresse>] [-help]
# =============================================================================

set -euo pipefail

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

# ── Konfiguration ─────────────────────────────────────────────────────────────
HTTP_PORT=80
HTTPS_PORT=443
SNAP_DATA_DIR="/var/snap/nextcloud/common/nextcloud/data"
ADMIN_USER="admin"
ROOT_PASS=""
DOMAIN=""
LETSENCRYPT_EMAIL=""
PHP_MEMORY_LIMIT="1024M"
UPLOAD_CHUNK_SIZE=20971520

# ── Hilfsfunktionen ───────────────────────────────────────────────────────────
info()    { echo -e "${BLUE}[INFO]${NC}  $*"; }
success() { echo -e "${GREEN}[OK]${NC}    $*"; }
warn()    { echo -e "${YELLOW}[WARN]${NC}  $*"; }
error()   { echo -e "${RED}[FEHLER]${NC} $*" >&2; exit 1; }

run() {
    if $dry_run
    then
        echo -e "${YELLOW}[DRYRUN]${NC} $*"
    else
        eval "$@"
    fi
}

show_help() {
    echo ""
    echo "Verwendung: sudo bash $0 [OPTIONEN]"
    echo ""
    echo "Optionen:"
    echo "  -dryrun            Befehle nur anzeigen, nicht ausführen"
    echo "  -domain <fqdn>     Domain für Let's Encrypt (sonst selbstsigniertes Zertifikat)"
    echo "  -email <adresse>   Kontakt-E-Mail für Let's Encrypt (Default: admin@<domain>)"
    echo "  -rootpass <pw>     Nextcloud-Admin-Passwort = dieses Passwort (sonst zufällig generiert)"
    echo "  -help              Diese Hilfe anzeigen"
    echo ""
    echo "Beispiele:"
    echo "  sudo bash $0"
    echo "  sudo bash $0 -domain cloud.example.com -email admin@example.com -rootpass 'MeinPasswort'"
    echo "  sudo bash $0 -dryrun"
    echo ""
}

# =============================================================================
# options – Argumente parsen
# =============================================================================
options() {
    dry_run=false

    while test $# -gt 0
    do
        case "$1" in
            -dryrun)
                shift
                dry_run=true
                ;;
            -domain)
                shift
                DOMAIN="${1:-}"
                shift
                ;;
            -email)
                shift
                LETSENCRYPT_EMAIL="${1:-}"
                shift
                ;;
            -rootpass)
                shift
                ROOT_PASS="${1:-}"
                shift
                ;;
            -help)
                show_help
                exit 0
                ;;
            *)
                echo "$1 ist kein bekanntes Flag!"
                show_help
                exit 1
                ;;
        esac
    done

    main
}

# =============================================================================
# main – Ablaufsteuerung
# =============================================================================
main() {
    echo ""
    echo "============================================================"
    echo "   Nextcloud-Snap – Installationsskript"
    if $dry_run
    then
        echo -e "   ${YELLOW}[DRY-RUN MODUS – keine Änderungen werden vorgenommen]${NC}"
    fi
    echo "============================================================"
    echo ""

    # Root-Prüfung
    if [[ $EUID -ne 0 ]]
    then
        error "Dieses Skript muss als root ausgeführt werden. Benutze: sudo bash $0"
    fi

    # Ubuntu-Prüfung
    if ! grep -qi '^ID=ubuntu' /etc/os-release 2>/dev/null
    then
        error "Dieses Skript unterstützt nur Ubuntu. Erkanntes System: $(grep -oP '(?<=^PRETTY_NAME=").*(?=")' /etc/os-release 2>/dev/null || echo unbekannt)"
    fi

    system_update
    snap_install
    check_ports
    setup_data_disk
    configure_nextcloud
    tune_nextcloud
    setup_fail2ban
    print_summary
}

# =============================================================================
# system_update – System aktualisieren
# =============================================================================
system_update() {
    info "Schritt 1/7: Systemaktualisierung …"

    run apt-get update -y
    run apt-get dist-upgrade -y
    run apt-get install -y snapd parted e2fsprogs
    run apt-get autoremove -y

    success "System aktualisiert."
}

# =============================================================================
# snap_install – Nextcloud-Snap installieren
# =============================================================================
snap_install() {
    info "Schritt 2/7: Nextcloud-Snap installieren …"

    if snap list nextcloud &>/dev/null
    then
        warn "Nextcloud-Snap ist bereits installiert: $(snap list nextcloud 2>/dev/null | tail -n1)"
        warn "Überspringe Installation."
    else
        run snap install core
        run snap install nextcloud
        success "Nextcloud-Snap erfolgreich installiert."
    fi
}

# =============================================================================
# check_ports – Portbelegung prüfen
# =============================================================================
check_ports() {
    info "Schritt 3/7: Portbelegung prüfen …"

    for port in "$HTTP_PORT" "$HTTPS_PORT"
    do
        if ss -tlnp | grep -q ":${port} "
        then
            warn "Port ${port} ist bereits belegt! Nextcloud-Snap benötigt diesen Port – bitte freigeben."
        else
            success "Port ${port} ist frei."
        fi
    done
}

# =============================================================================
# setup_data_disk – Zweite Festplatte erkennen, partitionieren und als
#                    Nextcloud-Datenverzeichnis einhängen
# =============================================================================
setup_data_disk() {
    info "Schritt 4/7: Zweite Festplatte für Nextcloud-Daten prüfen …"

    if mountpoint -q "$SNAP_DATA_DIR" 2>/dev/null
    then
        success "Datenverzeichnis ${SNAP_DATA_DIR} ist bereits gemountet – überspringe Festplatten-Setup."
        return
    fi

    # Root-Festplatte ermitteln, um sie von der Suche auszuschließen
    local root_src root_disk
    root_src=$(findmnt -no SOURCE /)
    root_disk=$(lsblk -no PKNAME "$root_src" 2>/dev/null | head -n1)
    if [[ -z "$root_disk" ]]
    then
        # Root liegt direkt auf einer Disk ohne erkennbares Partitionsschema
        root_disk=$(basename "$root_src")
    fi

    # Alle Block-Devices vom Typ "disk" durchsuchen und die erste leere
    # (weder Dateisystem noch Mountpoint auf ihr oder ihren Partitionen)
    # Nicht-Root-Festplatte auswählen
    local disk second_disk=""
    while read -r disk
    do
        [[ -z "$disk" || "$disk" == "$root_disk" ]] && continue

        local fs_found
        fs_found=$(lsblk -no FSTYPE,MOUNTPOINT "/dev/${disk}" 2>/dev/null | tr -d ' \n')
        if [[ -z "$fs_found" ]]
        then
            second_disk="$disk"
            break
        fi
    done < <(lsblk -dno NAME,TYPE | awk '$2=="disk"{print $1}')

    if [[ -z "$second_disk" ]]
    then
        warn "Keine leere zweite Festplatte gefunden – ${SNAP_DATA_DIR} verbleibt auf der Root-Disk."
        return
    fi

    info "Leere zweite Festplatte gefunden: /dev/${second_disk} – wird für ${SNAP_DATA_DIR} eingerichtet."

    # Nextcloud-Snap stoppen, damit das Datenverzeichnis gefahrlos ersetzt
    # werden kann (Snap legt es bereits beim Installieren mit Vorbelegung an)
    run snap stop nextcloud

    # Ursprüngliche Rechte des Snap-Datenverzeichnisses merken, damit sie nach
    # dem Einhängen der neuen Festplatte wiederhergestellt werden können.
    # Direkt nach der Installation existiert das Verzeichnis unter Umständen
    # noch nicht – der Snap legt es erst beim ersten Start an – daher mit
    # sinnvollen Standardwerten (root:root, 750) arbeiten.
    local orig_owner="root:root" orig_mode="750"
    run mkdir -p "$SNAP_DATA_DIR"
    if ! $dry_run
    then
        orig_owner=$(stat -c '%u:%g' "$SNAP_DATA_DIR")
        orig_mode=$(stat -c '%a' "$SNAP_DATA_DIR")
    else
        echo -e "${YELLOW}[DRYRUN]${NC} Rechte von ${SNAP_DATA_DIR} ermitteln"
    fi

    run parted -s "/dev/${second_disk}" mklabel gpt
    run parted -s "/dev/${second_disk}" mkpart primary ext4 0% 100%
    run partprobe "/dev/${second_disk}"
    run sleep 2

    local part
    if ! $dry_run
    then
        part="/dev/$(lsblk -rno NAME "/dev/${second_disk}" | sed -n '2p')"
    else
        part="/dev/${second_disk}1"
        echo -e "${YELLOW}[DRYRUN]${NC} Partition ermitteln: ${part}"
    fi

    run mkfs.ext4 -F "$part"

    if ! $dry_run
    then
        local uuid
        uuid=$(blkid -s UUID -o value "$part")
        if grep -q "$uuid" /etc/fstab 2>/dev/null
        then
            warn "fstab-Eintrag für ${part} existiert bereits."
        else
            echo "UUID=${uuid}  ${SNAP_DATA_DIR}  ext4  defaults,nofail  0  2" >> /etc/fstab
        fi
    else
        echo -e "${YELLOW}[DRYRUN]${NC} UUID ermitteln und Eintrag zu /etc/fstab hinzufügen"
    fi

    run mount "$SNAP_DATA_DIR"

    run chown "$orig_owner" "$SNAP_DATA_DIR"
    run chmod "$orig_mode" "$SNAP_DATA_DIR"

    success "Zweite Festplatte /dev/${second_disk} als ${SNAP_DATA_DIR} (ext4) eingehängt."
}

# =============================================================================
# configure_nextcloud – Nextcloud-Snap starten und einrichten
# =============================================================================
configure_nextcloud() {
    info "Schritt 5/7: Nextcloud einrichten …"

    run snap start nextcloud

    if $dry_run
    then
        echo -e "${YELLOW}[DRYRUN]${NC} Warten bis Nextcloud bereit ist"
        if [[ -n "$ROOT_PASS" ]]
        then
            echo -e "${YELLOW}[DRYRUN]${NC} nextcloud.manual-install ${ADMIN_USER} <-rootpass>"
        else
            echo -e "${YELLOW}[DRYRUN]${NC} nextcloud.manual-install ${ADMIN_USER} <generiertes Passwort>"
        fi
        if [[ -n "$DOMAIN" ]]
        then
            echo -e "${YELLOW}[DRYRUN]${NC} nextcloud.occ config:system:set trusted_domains 1 --value=${DOMAIN}"
            echo -e "${YELLOW}[DRYRUN]${NC} nextcloud.enable-https lets-encrypt (Domain: ${DOMAIN}, E-Mail: ${LETSENCRYPT_EMAIL:-admin@${DOMAIN}})"
        else
            echo -e "${YELLOW}[DRYRUN]${NC} nextcloud.enable-https self-signed (keine -domain angegeben)"
        fi
        return
    fi

    info "Warte auf Nextcloud-Snap-Dienste …"
    local tries=0
    until nextcloud.occ status &>/dev/null || [[ $tries -ge 30 ]]
    do
        sleep 2
        tries=$((tries + 1))
    done

    local admin_pass="${ROOT_PASS:-$(openssl rand -base64 18)}"

    if nextcloud.occ status 2>/dev/null | grep -q "installed: true"
    then
        warn "Nextcloud ist bereits eingerichtet – überspringe Ersteinrichtung."
        if [[ -n "$ROOT_PASS" ]]
        then
            OC_PASS="$ROOT_PASS" nextcloud.occ user:resetpassword --password-from-env "$ADMIN_USER"
            success "Nextcloud-Admin-Passwort auf -rootpass gesetzt."
        fi
        echo "$ADMIN_USER" > /root/.nextcloud-admin-user
        echo "$admin_pass" > /root/.nextcloud-admin-pass
        chmod 600 /root/.nextcloud-admin-user /root/.nextcloud-admin-pass
    else
        nextcloud.manual-install "$ADMIN_USER" "$admin_pass"
        echo "$ADMIN_USER" > /root/.nextcloud-admin-user
        echo "$admin_pass" > /root/.nextcloud-admin-pass
        chmod 600 /root/.nextcloud-admin-user /root/.nextcloud-admin-pass
        success "Nextcloud-Administratorkonto angelegt."
    fi

    if [[ -n "$DOMAIN" ]]
    then
        info "Domain ${DOMAIN} angegeben – richte Let's Encrypt ein …"
        nextcloud.occ config:system:set trusted_domains 1 --value="$DOMAIN"

        local email="${LETSENCRYPT_EMAIL:-admin@${DOMAIN}}"
        if printf 'y\n%s\n%s\n' "$email" "$DOMAIN" | nextcloud.enable-https lets-encrypt
        then
            success "Let's-Encrypt-Zertifikat für ${DOMAIN} eingerichtet."
        else
            warn "Let's-Encrypt-Einrichtung für ${DOMAIN} fehlgeschlagen (DNS/Firewall prüfen) – verwende selbstsigniertes Zertifikat."
            nextcloud.enable-https self-signed
        fi
    else
        warn "Keine Domain angegeben (-domain <fqdn>) – verwende selbstsigniertes Zertifikat."
        nextcloud.enable-https self-signed
    fi

    success "Nextcloud-Snap konfiguriert."
}

# =============================================================================
# tune_nextcloud – Empfohlene Performance-Einstellungen setzen
#                   (siehe https://github.com/nextcloud-snap/nextcloud-snap/wiki)
# =============================================================================
tune_nextcloud() {
    info "Schritt 6/7: Performance-Einstellungen anwenden …"

    # PHP-Speicherlimit erhöhen (Standard 512M -> hier 1024M, per Snap-Option
    # gesetzt und ohne Neustart des Snaps über den Configure-Hook angewendet)
    run snap set nextcloud "php.memory-limit=${PHP_MEMORY_LIMIT}"
    success "PHP memory_limit auf ${PHP_MEMORY_LIMIT} gesetzt."

    # Upload-Chunk-Größe verdoppeln (Standard 10 MiB -> 20 MiB) für Umgebungen
    # mit hoher Upload-Bandbreite. upload_max_filesize/post_max_size sind im
    # Snap bereits werkseitig auf 16G gesetzt und müssen nicht angepasst werden.
    run nextcloud.occ config:app:set files max_chunk_size --value "$UPLOAD_CHUNK_SIZE"
    success "Upload-Chunk-Größe auf $((UPLOAD_CHUNK_SIZE / 1024 / 1024)) MiB gesetzt."
}

# =============================================================================
# setup_fail2ban – SSH gegen Brute-Force-Angriffe absichern
# =============================================================================
setup_fail2ban() {
    info "Schritt 7/7: fail2ban für SSH einrichten …"

    run apt-get install -y fail2ban

    run "cat > /etc/fail2ban/jail.local <<'EOF'
[sshd]
enabled  = true
port     = ssh
maxretry = 5
findtime = 10m
bantime  = 1h
EOF"

    run systemctl enable fail2ban
    run systemctl restart fail2ban

    success "fail2ban aktiv (sshd-Jail: 5 Versuche / 10 Min → 1 Std. Sperre)."
}

# =============================================================================
# print_summary – Abschlussmeldung
# =============================================================================
print_summary() {
    echo ""
    echo "============================================================"
    echo -e "${GREEN}  Installation abgeschlossen!${NC}"
    echo "============================================================"
    echo ""
    echo "  Nextcloud-Oberfläche:"
    if [[ -n "$DOMAIN" ]]
    then
        echo -e "  ${BLUE}https://${DOMAIN}${NC}"
    else
        echo -e "  ${BLUE}https://<DEINE-SERVER-IP>${NC}"
    fi
    echo ""
    echo "  Datenverzeichnis: ${SNAP_DATA_DIR}"
    if mountpoint -q "$SNAP_DATA_DIR" 2>/dev/null && ! $dry_run
    then
        echo "  • $(df -h --output=source,size "$SNAP_DATA_DIR" | tail -n1 | awk '{print $1" ("$2")"}') ist unter ${SNAP_DATA_DIR} eingehängt."
    fi
    echo ""
    if [[ -f /root/.nextcloud-admin-pass ]]
    then
        echo "  Admin-Zugangsdaten (auch in /root/.nextcloud-admin-user und -pass):"
        echo "  • Benutzer:  $(cat /root/.nextcloud-admin-user 2>/dev/null)"
        echo "  • Passwort:  $(cat /root/.nextcloud-admin-pass 2>/dev/null)"
        echo ""
    fi
    echo "  Hinweise:"
    if [[ -n "$DOMAIN" ]]
    then
        echo "  • Let's-Encrypt-Zertifikat für ${DOMAIN} wurde eingerichtet (Auto-Renewal aktiv)."
        echo "    Falls das fehlschlug, wurde ersatzweise ein selbstsigniertes Zertifikat verwendet."
    else
        echo "  • Es wird ein selbstsigniertes Zertifikat verwendet."
        echo "    Für Let's Encrypt beim nächsten Lauf: -domain <fqdn> [-email <adresse>] angeben."
    fi
    echo "  • Ports ${HTTP_PORT} und ${HTTPS_PORT} müssen in der Firewall freigegeben sein."
    echo "  • PHP memory_limit: ${PHP_MEMORY_LIMIT} · Upload-Chunk-Größe: $((UPLOAD_CHUNK_SIZE / 1024 / 1024)) MiB"
    echo "  • Upload-Limit (upload_max_filesize/post_max_size): 16G (Snap-Standard)"
    echo "  • Verwaltung: sudo nextcloud.occ <befehl>"
    echo "  • Logs: sudo snap logs nextcloud"
    echo ""
    echo "  Dokumentation:"
    echo "  https://github.com/nextcloud-snap/nextcloud-snap"
    echo "============================================================"
}

# =============================================================================
# Einstiegspunkt
# =============================================================================
options "$@"
