#!/bin/bash -e
# Configure HTTPS support for Dangerous Pi
# Sets up SSL certificate generation and nginx configuration switching
# Note: Scripts and configs are already in /opt/dangerous-pi/ from stage 03

echo "=== Setting up HTTPS support ==="

# Create SSL directory for certificates
mkdir -p /opt/dangerous-pi/ssl

# Set executable permissions on scripts (already copied by stage 03)
echo "Setting script permissions..."
chmod 755 /opt/dangerous-pi/scripts/generate-ssl-cert.sh
chmod 755 /opt/dangerous-pi/scripts/configure-nginx.sh

# Install systemd service for first-boot certificate generation
echo "Installing SSL certificate generation service..."
install -m 644 /opt/dangerous-pi/systemd/dangerous-pi-ssl-gen.service /etc/systemd/system/

# Install systemd service for nginx configuration switching
echo "Installing nginx configuration service..."
install -m 644 /opt/dangerous-pi/systemd/dangerous-pi-nginx-config.service /etc/systemd/system/

# Create nginx service override to depend on our config service
mkdir -p /etc/systemd/system/nginx.service.d
cat > /etc/systemd/system/nginx.service.d/dangerous-pi-ssl.conf << 'EOF'
[Unit]
After=dangerous-pi-nginx-config.service
Wants=dangerous-pi-nginx-config.service
EOF

# Enable services
echo "Enabling HTTPS services..."
systemctl enable dangerous-pi-ssl-gen.service
systemctl enable dangerous-pi-nginx-config.service

# Set proper permissions on SSL directory
chmod 700 /opt/dangerous-pi/ssl

# Print status
echo ""
echo "=== HTTPS Support Configuration Complete ==="
echo ""
echo "HTTPS is DISABLED by default."
echo ""
echo "To enable HTTPS:"
echo "  1. Edit /opt/dangerous-pi/.env"
echo "  2. Set HTTPS_ENABLED=true"
echo "  3. Reboot or run: sudo systemctl restart dangerous-pi-nginx-config nginx"
echo ""
echo "On first boot with HTTPS enabled, a self-signed certificate will be"
echo "automatically generated for:"
echo "  - 192.168.4.1 (AP gateway IP)"
echo "  - dangerous-pi.local (mDNS hostname)"
echo "  - localhost"
echo ""
echo "Note: Browsers will show a certificate warning for self-signed certs."
echo ""
