#!/bin/bash
# HTTPS/SSL setup voor test.baro-edegem.com met Let's Encrypt
# Auteur: Senior DevOps Engineer
# Datum: 2025-12-29

set -e

echo "=========================================="
echo "BLOK 7: Certbot installatie check"
echo "=========================================="

# Check of certbot geïnstalleerd is
if ! command -v certbot &> /dev/null; then
    echo "Certbot niet gevonden, installeren..."
    sudo apt update
    sudo apt install -y certbot python3-certbot-nginx
    echo "✓ Certbot geïnstalleerd"
else
    echo "✓ Certbot is al geïnstalleerd"
fi

echo ""

echo "=========================================="
echo "BLOK 8: Firewall check (UFW)"
echo "=========================================="

# Check of UFW actief is
if sudo ufw status | grep -q "Status: active"; then
    echo "UFW is actief, checking ports..."
    
    # Check en open poort 80 en 443
    if ! sudo ufw status | grep -q "80.*ALLOW"; then
        echo "Poort 80 openen..."
        sudo ufw allow 80/tcp
    fi
    
    if ! sudo ufw status | grep -q "443.*ALLOW"; then
        echo "Poort 443 openen..."
        sudo ufw allow 443/tcp
    fi
    
    echo "✓ Firewall ports 80 en 443 zijn open"
else
    echo "ℹ UFW is niet actief, overslaan..."
fi

echo ""

echo "=========================================="
echo "BLOK 9: SSL certificaat aanvragen"
echo "=========================================="

echo "Let's Encrypt certificaat aanvragen voor test.baro-edegem.com..."
echo "Dit kan 30-60 seconden duren..."
echo ""

# Certbot met nginx plugin (automatische configuratie)
sudo certbot --nginx -d test.baro-edegem.com --non-interactive --agree-tos --register-unsafely-without-email --redirect

echo ""
echo "✓ SSL certificaat succesvol aangevraagd en geconfigureerd"
echo ""

echo "=========================================="
echo "BLOK 10: HTTPS verificatie"
echo "=========================================="

echo "Testing HTTPS respons..."
sleep 2
curl -Ik https://test.baro-edegem.com

echo ""

echo "=========================================="
echo "HTTPS SETUP COMPLEET!"
echo "=========================================="
echo ""
echo "✓ Je site is nu beveiligd met SSL/TLS"
echo "✓ HTTP wordt automatisch omgeleid naar HTTPS"
echo "✓ Certificaat vernieuwt automatisch via certbot"
echo ""
echo "Test nu in je browser:"
echo "  https://test.baro-edegem.com"
echo ""
echo "Certificaat info:"
sudo certbot certificates | grep -A 10 "test.baro-edegem.com" || echo "  Run: sudo certbot certificates"
echo ""
