#!/bin/bash
# 응용 예제 ③ — TLS termination + HTTP→HTTPS 리다이렉트
# 자가서명 인증서 생성 + nginx HTTPS 활성화
set -e

CFG="$(dirname "$0")/configs/04_lab-tls"

# 1) hosts 추가
grep -q "api.lab.local" /etc/hosts || echo "127.0.0.1  api.lab.local" | sudo tee -a /etc/hosts

# 2) 자가서명 인증서 생성 (1년)
sudo mkdir -p /etc/nginx/certs
if [ ! -f /etc/nginx/certs/api.lab.local.crt ]; then
    sudo openssl req -x509 -newkey rsa:2048 -nodes -days 365 \
        -keyout /etc/nginx/certs/api.lab.local.key \
        -out    /etc/nginx/certs/api.lab.local.crt \
        -subj   "/CN=api.lab.local"
    sudo chmod 600 /etc/nginx/certs/api.lab.local.key
fi

# 3) 설정 배포 + 기존 site 비활성화
sudo cp "$CFG" /etc/nginx/sites-available/lab-tls
sudo rm -f /etc/nginx/sites-enabled/lab-proxy \
           /etc/nginx/sites-enabled/lab-location \
           /etc/nginx/sites-enabled/lab-upstream \
           /etc/nginx/sites-enabled/default
sudo ln -sf /etc/nginx/sites-available/lab-tls \
            /etc/nginx/sites-enabled/lab-tls

# 4) syntax 검사 + reload
sudo nginx -t
sudo systemctl reload nginx

# 5) 검증
echo
echo "=== TLS 검증 ==="
echo "→ HTTP → HTTPS 리다이렉트 (301)"
curl -sI http://api.lab.local/ | head -5
echo
echo "→ HTTPS 응답 (자가서명 -k 옵션)"
curl -ksI https://api.lab.local/ | head -5
echo
echo "→ TLS 버전 + cipher 확인"
curl -ksv https://api.lab.local/ 2>&1 | grep -E "SSL connection|TLSv|cipher" | head -5
