#!/usr/bin/env bash
# install-gateway.sh - wystawianie aplikacji na swiat z jednowezlowego klastra kubeadm:
#   Envoy Gateway (Gateway API) + cert-manager (Let's Encrypt, HTTP-01) + testowy whoami.
#
# Uruchamiac jako root na serwerze z klastrem (kubeconfig: /etc/kubernetes/admin.conf):
#   sudo DOMAIN=k8s.example.com ./install-gateway.sh
#   sudo DOMAIN=k8s.example.com ISSUER=letsencrypt-staging ./install-gateway.sh   # test bez limitow LE (cert niezaufany)
#
# Skrypt mozna puscic ponownie (kubectl apply). Opis: https://skwarna.eu/blog/
#
# Jak ruch trafia do Envoya (jeden wezel, brak LoadBalancera):
#   Service Envoya (typ LoadBalancer) dostaje externalIPs = publiczne IP serwera.
#   kube-proxy DNAT-uje pakiety na $PUBLIC_IP:80/443 prosto na pod Envoya (PREROUTING),
#   wiec ruch idzie przez FORWARD, a UFW ma "allow (routed)". Nie trzeba "ufw allow 80,443".
#   Nic nie slucha na 80/443 na hoscie (ss -ltn tego nie pokaze), robi to iptables.
set -euo pipefail

DOMAIN=${DOMAIN:?ustaw DOMAIN, np. DOMAIN=k8s.example.com (wildcard *.DOMAIN -> A publiczne IP)}
ENVOY_GATEWAY_VERSION=${ENVOY_GATEWAY_VERSION:-v1.9.3}   # zawiera tez CRD Gateway API
CERT_MANAGER_VERSION=${CERT_MANAGER_VERSION:-v1.21.3}
ISSUER=${ISSUER:-letsencrypt-prod}               # albo letsencrypt-staging
ACME_EMAIL=${ACME_EMAIL:-}                       # opcjonalny (LE nie wysyla juz maili o wygasaniu)
GW_NS=gateway                                    # namespace wspolnego Gatewaya "web"

export KUBECONFIG=${KUBECONFIG:-/etc/kubernetes/admin.conf}

log() { echo "$(date +%H:%M:%S) $*"; }
die() { echo "BLAD: $*" >&2; exit 1; }

[[ $EUID -eq 0 ]] || die "uruchom jako root"
PUBLIC_IP=${PUBLIC_IP:-$(ip -4 route get 1.1.1.1 | awk '{for(i=1;i<=NF;i++) if($i=="src") print $(i+1)}')}
[[ -n $PUBLIC_IP ]] || die "nie wykryto publicznego IP, ustaw PUBLIC_IP=..."
log "Domena: *.$DOMAIN -> $PUBLIC_IP, Envoy Gateway $ENVOY_GATEWAY_VERSION, cert-manager $CERT_MANAGER_VERSION, issuer: $ISSUER"

dns=$(getent ahostsv4 "whoami.$DOMAIN" | awk 'NR==1{print $1}')
[[ $dns == "$PUBLIC_IP" ]] || die "whoami.$DOMAIN wskazuje na '${dns:-nic}', a nie na $PUBLIC_IP (wildcard DNS?)"

# --- 1. Envoy Gateway + CRD Gateway API -------------------------------------------
# --server-side: CRD-y sa za duze na adnotacje last-applied zwyklego apply.
log "Instaluje Envoy Gateway $ENVOY_GATEWAY_VERSION (z CRD Gateway API)"
kubectl apply --server-side --force-conflicts \
    -f "https://github.com/envoyproxy/gateway/releases/download/$ENVOY_GATEWAY_VERSION/install.yaml"
kubectl -n envoy-gateway-system wait --for=condition=Available deployment/envoy-gateway --timeout=300s

# --- 2. cert-manager z obsluga Gateway API ------------------------------------------
# Integracja z Gateway API jest wylaczona domyslnie: flaga --enable-gateway-api.
# CRD Gateway API musza istniec przed startem kontrolera (dlatego krok 1 jest pierwszy).
log "Instaluje cert-manager $CERT_MANAGER_VERSION"
kubectl apply -f "https://github.com/cert-manager/cert-manager/releases/download/$CERT_MANAGER_VERSION/cert-manager.yaml"
if ! kubectl -n cert-manager get deployment cert-manager -o jsonpath='{.spec.template.spec.containers[0].args}' \
        | grep -q -- '--enable-gateway-api'; then
    log "cert-manager: dodaje --enable-gateway-api"
    kubectl -n cert-manager patch deployment cert-manager --type=json \
        -p '[{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--enable-gateway-api"}]'
fi
kubectl -n cert-manager rollout status deployment/cert-manager --timeout=300s
kubectl -n cert-manager rollout status deployment/cert-manager-webhook --timeout=300s
kubectl -n cert-manager rollout status deployment/cert-manager-cainjector --timeout=300s

# --- 3. GatewayClass + EnvoyProxy (externalIPs) -------------------------------------
log "GatewayClass eg + EnvoyProxy z externalIPs $PUBLIC_IP"
kubectl apply -f - <<EOF
apiVersion: gateway.envoyproxy.io/v1alpha1
kind: EnvoyProxy
metadata:
  name: public-ip
  namespace: envoy-gateway-system
spec:
  provider:
    type: Kubernetes
    kubernetes:
      envoyService:
        type: LoadBalancer                 # domyslny; zostaje <pending> bez LB, ale externalIPs dzialaja
        externalTrafficPolicy: Local       # aplikacje widza prawdziwe IP klienta
        allocateLoadBalancerNodePorts: false   # bez NodePortow (bylyby otwarte do internetu przez FORWARD)
        patch:
          type: StrategicMerge
          value:
            spec:
              externalIPs:
                - $PUBLIC_IP
---
apiVersion: gateway.networking.k8s.io/v1
kind: GatewayClass
metadata:
  name: eg
spec:
  controllerName: gateway.envoyproxy.io/gatewayclass-controller
  parametersRef:
    group: gateway.envoyproxy.io
    kind: EnvoyProxy
    name: public-ip
    namespace: envoy-gateway-system
EOF

# --- 4. ClusterIssuery Let's Encrypt (HTTP-01 przez Gateway API) --------------------
# Solver tworzy tymczasowy HTTPRoute /.well-known/acme-challenge/<token> podpiety pod Gateway "web".
log "ClusterIssuery letsencrypt-staging i letsencrypt-prod"
email_line=""
[[ -n $ACME_EMAIL ]] && email_line="    email: $ACME_EMAIL"
for name in letsencrypt-staging letsencrypt-prod; do
    server=https://acme-v02.api.letsencrypt.org/directory
    [[ $name == letsencrypt-staging ]] && server=https://acme-staging-v02.api.letsencrypt.org/directory
    kubectl apply -f - <<EOF
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
  name: $name
spec:
  acme:
    server: $server
$email_line
    privateKeySecretRef:
      name: $name-account
    solvers:
      - http01:
          gatewayHTTPRoute:
            parentRefs:
              - name: web
                namespace: $GW_NS
                kind: Gateway
                sectionName: http
EOF
done

# --- 5. Gateway "web" + przekierowanie HTTP -> HTTPS --------------------------------
# Jeden wspolny Gateway (= jeden Envoy na 80/443). Kazda aplikacja z HTTPS dostaje tu
# wlasny listener (hostname + Secret z certem), cert-manager widzi adnotacje i robi Certificate.
log "Gateway web ($GW_NS) z listenerem dla whoami.$DOMAIN"
kubectl create namespace "$GW_NS" --dry-run=client -o yaml | kubectl apply -f -
kubectl apply -f - <<EOF
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: web
  namespace: $GW_NS
  annotations:
    cert-manager.io/cluster-issuer: $ISSUER
spec:
  gatewayClassName: eg
  listeners:
    - name: http
      protocol: HTTP
      port: 80
      allowedRoutes:
        namespaces:
          from: All
    # --- listenery HTTPS, po jednym na aplikacje ---
    - name: whoami
      protocol: HTTPS
      port: 443
      hostname: whoami.$DOMAIN
      tls:
        mode: Terminate
        certificateRefs:
          - name: whoami-tls          # Secret w $GW_NS, tworzy go cert-manager
      allowedRoutes:
        namespaces:
          from: All
---
# Wszystko po HTTP -> 301 na HTTPS. Challenge ACME (dokladna sciezka) wygrywa z tym prefiksem "/".
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: https-redirect
  namespace: $GW_NS
spec:
  parentRefs:
    - name: web
      sectionName: http
  hostnames:
    - "*.$DOMAIN"
  rules:
    - filters:
        - type: RequestRedirect
          requestRedirect:
            scheme: https
            statusCode: 301
EOF

# --- 6. Testowa aplikacja whoami ----------------------------------------------------
log "Aplikacja testowa whoami (namespace demo)"
kubectl create namespace demo --dry-run=client -o yaml | kubectl apply -f -
kubectl apply -f - <<EOF
apiVersion: apps/v1
kind: Deployment
metadata:
  name: whoami
  namespace: demo
spec:
  replicas: 1
  selector:
    matchLabels: {app: whoami}
  template:
    metadata:
      labels: {app: whoami}
    spec:
      containers:
        - name: whoami
          image: traefik/whoami:v1.12.0
          ports:
            - containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: whoami
  namespace: demo
spec:
  selector: {app: whoami}
  ports:
    - port: 80
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: whoami
  namespace: demo
spec:
  parentRefs:
    - name: web
      namespace: $GW_NS
      sectionName: whoami             # tylko listener HTTPS; HTTP obsluguje https-redirect
  hostnames:
    - whoami.$DOMAIN
  rules:
    - backendRefs:
        - name: whoami
          port: 80
EOF

# --- 7. Czekam na Gateway i certyfikat ----------------------------------------------
log "Czekam, az Gateway web bedzie Programmed"
kubectl -n "$GW_NS" wait --for=condition=Programmed gateway/web --timeout=300s
kubectl -n "$GW_NS" get gateway web
kubectl -n envoy-gateway-system get svc -l gateway.envoyproxy.io/owning-gateway-name=web

log "Czekam na certyfikat whoami-tls (HTTP-01, do 3 min)"
if kubectl -n "$GW_NS" wait --for=condition=Ready certificate/whoami-tls --timeout=180s; then
    kubectl -n "$GW_NS" get certificate
    log "Gotowe. Test:  curl https://whoami.$DOMAIN"
else
    log "Certyfikat jeszcze nie gotowy. Diagnoza:"
    echo "  kubectl -n $GW_NS describe certificate whoami-tls"
    echo "  kubectl get certificaterequest,order,challenge -A"
    echo "  kubectl -n cert-manager logs deploy/cert-manager --tail=50"
fi

# --- 8. Sciagawka: co doszlo do klastra ---------------------------------------------
cat <<EOT

==================== Co doszlo do klastra i jak to obejrzec ====================

Namespace'y:
  kubectl get ns envoy-gateway-system cert-manager $GW_NS demo

Envoy Gateway (kontroler + Envoy dla Gatewaya "web"):
  kubectl -n envoy-gateway-system get deploy,pods,svc
  kubectl -n envoy-gateway-system get envoyproxy public-ip -o yaml
  kubectl -n envoy-gateway-system logs deploy/envoy-gateway --tail=50

CRD Gateway API i Envoy Gateway:
  kubectl get crd | grep -E 'gateway.networking.k8s.io|gateway.envoyproxy.io'
  kubectl api-resources --api-group=gateway.networking.k8s.io

Gateway API (klasa, Gateway, trasy):
  kubectl get gatewayclass
  kubectl get gateway,httproute -A
  kubectl -n $GW_NS describe gateway web          # listenery, adres, status tras
  kubectl -n demo describe httproute whoami       # Accepted / ResolvedRefs

cert-manager (wystawcy, certyfikaty, wyzwania ACME):
  kubectl -n cert-manager get deploy,pods
  kubectl get clusterissuer
  kubectl get certificate,certificaterequest -A
  kubectl get order,challenge -A                  # puste = nic nie czeka
  kubectl -n $GW_NS get secret whoami-tls -o jsonpath='{.data.tls\.crt}' | base64 -d | openssl x509 -noout -subject -issuer -dates

Aplikacja testowa:
  kubectl -n demo get deploy,pods,svc,httproute
  curl -I http://whoami.$DOMAIN                   # 301 -> https
  curl https://whoami.$DOMAIN                     # RemoteAddr = Twoje IP

Siec (iptables kube-proxy dla externalIP $PUBLIC_IP):
  iptables -t nat -S KUBE-SERVICES | grep $PUBLIC_IP

Opis calosci: https://skwarna.eu/blog/
EOT
