#!/usr/bin/env bash
set -euo pipefail
[[ "$EUID" -eq 0 ]] || { echo 'Bitte mit sudo ausführen.' >&2; exit 1; }
config=/etc/puppyhub/deployment.json
[[ -f "$config" ]] || { echo 'PuppyHub wurde noch nicht eingerichtet.' >&2; exit 1; }
admin() { runuser -u puppyhub -- /opt/puppyhub/bin/forgejo --work-path /data/puppyhub/forgejo --custom-path /data/puppyhub/forgejo/custom --config /etc/puppyhub/app.ini "$@"; }
enable_https() {
    local domain email certificate_name temp old_conf
    domain="$(python3 -c 'import json; print(json.load(open("/etc/puppyhub/deployment.json"))["domain"])')"
    email="$(python3 -c 'import json; print(json.load(open("/etc/puppyhub/deployment.json"))["email"])')"
    certificate_name="$(python3 -c 'import json; c=json.load(open("/etc/puppyhub/deployment.json")); print(c.get("certificate_name","puppyhub"))')"
    certbot certonly --webroot -w /var/lib/puppyhub-acme --cert-name "$certificate_name" --domain "$domain" --email "$email" --agree-tos --non-interactive --keep-until-expiring
    temp="$(mktemp)"
    old_conf="$(mktemp)"
    cp /etc/nginx/sites-available/puppyhub "$old_conf"
    python3 /opt/puppyhub/app/scripts/configure.py nginx-https > "$temp"
    install -m 0644 "$temp" /etc/nginx/sites-available/puppyhub
    if nginx -t; then
        systemctl reload nginx
        rm -f -- "$temp" "$old_conf"
        echo "HTTPS bereit: https://${domain}"
    else
        install -m 0644 "$old_conf" /etc/nginx/sites-available/puppyhub
        rm -f -- "$temp" "$old_conf"
        echo 'Neue Nginx-Konfiguration war ungültig; bisherige Datei wiederhergestellt.' >&2
        exit 1
    fi
}
backup() {
    local was_forgejo=0 was_bridge=0 destination temp
    install -d -m 0700 /data/puppyhub-backups
    exec 9>/run/puppyhub-backup.lock
    flock -n 9 || { echo 'Ein Backup läuft bereits.' >&2; return 1; }
    systemctl is-active --quiet puppyhub && was_forgejo=1
    systemctl is-active --quiet puppyhub-mcp && was_bridge=1
    restart_services() { [[ "$was_forgejo" -eq 0 ]] || systemctl start puppyhub; [[ "$was_bridge" -eq 0 ]] || systemctl start puppyhub-mcp; }
    trap "if [[ $was_forgejo -eq 1 ]]; then systemctl start puppyhub; fi; if [[ $was_bridge -eq 1 ]]; then systemctl start puppyhub-mcp; fi" EXIT
    systemctl stop puppyhub-mcp puppyhub
    destination="/data/puppyhub-backups/puppyhub-$(date -u +%Y%m%dT%H%M%SZ).tar.gz"
    temp="${destination}.partial"
    if ! tar --numeric-owner -czf "$temp" -C / data/puppyhub etc/puppyhub opt/puppyhub etc/nginx/sites-available/puppyhub etc/systemd/system/puppyhub.service etc/systemd/system/puppyhub-mcp.service; then
        rm -f -- "$temp"
        echo 'Backup fehlgeschlagen; Dienste werden wieder gestartet.' >&2
        return 1
    fi
    mv "$temp" "$destination"
    chmod 0600 "$destination"
    restart_services
    trap - EXIT
    echo "Backup erstellt: $destination"
    echo 'Das Backup enthält Zugangsdaten. Außerhalb des Servers geschützt aufbewahren.'
}
action="${1:-help}"
case "$action" in
    status) systemctl status puppyhub puppyhub-mcp --no-pager -l ;;
    logs) journalctl -u puppyhub -u puppyhub-mcp -n 100 --no-pager ;;
    admin) shift; admin "$@" ;;
    invite)
        [[ "$#" -eq 3 ]] || { echo 'Aufruf: sudo puppyhub invite BENUTZER EMAIL' >&2; exit 1; }
        admin admin user create --username "$2" --email "$3" --random-password --random-password-length 24 --must-change-password
        echo 'Das Konto wurde angelegt. Temporäres Passwort persönlich übergeben; es muss beim ersten Login geändert werden.'
        ;;
    mcp-client)
        python3 - <<'PY'
import json
c = json.load(open('/etc/puppyhub/mcp-client.json'))
print('MCP URL:       ' + c['url'])
print('OAuth Client:  ' + c['client_id'])
print('OAuth Secret:  ' + c['client_secret'])
print('In ChatGPT unter Plugins → Add custom MCP server → OAuth eintragen. Nicht in einen Chat kopieren.')
PY
        ;;
    revoke-chatgpt)
        bridge_was_active=0
        systemctl is-active --quiet puppyhub-mcp && bridge_was_active=1
        trap "if [[ $bridge_was_active -eq 1 ]]; then systemctl start puppyhub-mcp; fi" EXIT
        systemctl stop puppyhub-mcp
        python3 - <<'PY'
import json, sqlite3
c = json.load(open('/etc/puppyhub/bridge.json'))
with sqlite3.connect(c['database']) as db:
    for table in ('access','refresh','grants','codes','pending'):
        db.execute('DELETE FROM ' + table)
print('Alle bisherigen ChatGPT-Verbindungen wurden widerrufen.')
PY
        [[ "$bridge_was_active" -eq 0 ]] || systemctl start puppyhub-mcp
        trap - EXIT
        ;;
    enable-https) enable_https ;;
    backup) backup ;;
    update)
        [[ "$#" -eq 2 && "$2" =~ ^15\.[0-9]+\.[0-9]+$ ]] || { echo 'Aufruf: sudo puppyhub update 15.x.y (nur innerhalb der geprüften LTS-Hauptversion).' >&2; exit 1; }
        backup
        staged="$(mktemp /opt/puppyhub/bin/forgejo.XXXXXX)"
        /opt/puppyhub/app/scripts/download-forgejo.sh "$2" "$staged"
        systemctl stop puppyhub
        mv /opt/puppyhub/bin/forgejo /opt/puppyhub/bin/forgejo.previous
        mv "$staged" /opt/puppyhub/bin/forgejo
        systemctl start puppyhub
        /opt/puppyhub/app/scripts/check-health.py
        echo 'Forgejo aktualisiert. Vor einem Versionswechsel Theme und MCP erneut prüfen.'
        ;;
    help|*)
        echo 'PuppyHub: status | logs | invite BENUTZER EMAIL | mcp-client | revoke-chatgpt | enable-https | backup | update 15.x.y | admin ...'
        ;;
esac
