#!/bin/bash
# h42 new – Docker-Dienst in einem Rutsch veröffentlichen: DNS (ns1) + Pi-hole (LAN) + Zertifikat + nginx.
#   sudo h42 new <name|fqdn> <port|/verzeichnis> [zugriff] [--challenge http|dns] [--skip schritt,...]
#     zugriff      lan+auth (Default), lan, auth, public – siehe h42 help vhost
#     --challenge  Let's-Encrypt-Challenge, Default: CERT_CHALLENGE aus /etc/h42/h42.conf (http)
#     --skip       Schritte auslassen: dns, pihole, cert, vhost (z. B. weil schon vorhanden)
# Beispiel: sudo h42 new yuvomi 8044            -> https://yuvomi.h42.net
#           sudo h42 new pkg /srv/pkg public   -> statische Dateien (apt-/F-Droid-Repo)
# Der Container muss auf 127.0.0.1:<port> lauschen (ports: "127.0.0.1:<port>:<containerport>").
# Einzelschritte von Hand: h42 dns add, h42 pihole add, h42 cert add, h42 vhost add.
set -euo pipefail
. "${H42_LIB:-/usr/lib/h42}/common.sh"
need_root

pos=(); challenge=${CERT_CHALLENGE:-http}; skip=
while [ $# -gt 0 ]; do
  case $1 in
    --challenge) challenge=${2:-}; shift 2 || usage ;;
    --challenge=*) challenge=${1#*=}; shift ;;
    --skip) skip=${2:-}; shift 2 || usage ;;
    --skip=*) skip=${1#*=}; shift ;;
    -*) usage ;;
    *) pos+=("$1"); shift ;;
  esac
done
[ ${#pos[@]} -ge 2 ] && [ ${#pos[@]} -le 3 ] || usage
fqdn=${pos[0]}; [[ $fqdn == *.* ]] || fqdn=$fqdn.$DEFAULT_ZONE
port=${pos[1]}; access=${pos[2]:-lan+auth}
case $access in lan+auth|lan|auth|public) ;; *) die "unbekannter Zugriff: $access (lan+auth|lan|auth|public)" ;; esac
case $challenge in http|dns) ;; *) die "unbekannte Challenge: $challenge (http|dns)" ;; esac
for s in ${skip//,/ }; do
  case $s in dns|pihole|cert|vhost) ;; *) die "unbekannter Schritt bei --skip: $s (dns, pihole, cert, vhost)" ;; esac
done
step() { [[ ,$skip, != *,$1,* ]]; }

if step vhost; then h42 vhost check "$fqdn" "$port"; fi   # vor DNS/Zertifikat abbrechen, wenn der Port nicht passt

if step dns;    then echo "== DNS";        h42 dns add "$fqdn"; h42 dns wait "$fqdn"; fi
if step pihole; then echo "== Pi-hole";    h42 pihole add "$fqdn" || echo "Pi-hole-Eintrag fehlgeschlagen (LAN geht dann über Hairpin-NAT)"; fi
if step cert;   then echo "== Zertifikat ($challenge)"; h42 cert add "$fqdn" --challenge "$challenge"; fi
if step vhost;  then
  echo "== nginx"; h42 vhost add "$fqdn" "$port" "$access"
  sleep 2   # nginx-Reload läuft asynchron
  curl -s -o /dev/null -w "Test lokal: HTTP %{http_code}\n" --resolve "$fqdn:443:127.0.0.1" "https://$fqdn/" || true
fi
