#!/bin/bash
#
# SSL Certificate Initialization Script
# Obtains initial Let's Encrypt certificates for production deployment
#
# Usage: ./scripts/ssl-init.sh [domain] [email]
#

set -euo pipefail

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# Default values from environment or command line
DOMAIN="${1:-${DOMAIN_NAME:-michaelschiemer.de}}"
EMAIL="${2:-${SSL_EMAIL:-mail@michaelschiemer.de}}"
STAGING="${LETSENCRYPT_STAGING:-0}"

echo -e "${BLUE}=== Let's Encrypt SSL Certificate Initialization ===${NC}"
echo -e "${BLUE}Domain:${NC} $DOMAIN"
echo -e "${BLUE}Email:${NC} $EMAIL"
echo -e "${BLUE}Mode:${NC} $([ "$STAGING" = "1" ] && echo "Staging (Testing)" || echo "Production")"
echo ""

# Check if running with docker-compose
if ! command -v docker-compose &> /dev/null; then
    echo -e "${RED}Error: docker-compose not found${NC}"
    exit 1
fi

# Check if .env.production exists
if [ ! -f ".env.production" ]; then
    echo -e "${YELLOW}Warning: .env.production not found${NC}"
    echo -e "${YELLOW}Creating from .env.production.example...${NC}"
    cp .env.production.example .env.production
    echo -e "${YELLOW}Please edit .env.production and run this script again${NC}"
    exit 1
fi

# Create required directories
echo -e "${BLUE}Creating required directories...${NC}"
mkdir -p ./docker/nginx/certbot-www/.well-known/acme-challenge
mkdir -p ./docker/nginx/certbot-conf/live/${DOMAIN}

# Check if certificates already exist
if [ -f "./docker/nginx/certbot-conf/live/${DOMAIN}/fullchain.pem" ]; then
    echo -e "${YELLOW}Certificates already exist for ${DOMAIN}${NC}"
    read -p "Do you want to renew them? (y/N) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo -e "${BLUE}Skipping certificate generation${NC}"
        exit 0
    fi
fi

# Start only web and php services (not full stack)
echo -e "${BLUE}Starting nginx and php services...${NC}"
docker-compose -f docker-compose.yml up -d web php

# Wait for nginx to be ready
echo -e "${BLUE}Waiting for nginx to be ready...${NC}"
sleep 5

# Test if port 80 is accessible
if ! curl -sf http://localhost/.well-known/acme-challenge/test > /dev/null 2>&1; then
    echo -e "${YELLOW}Port 80 test endpoint not accessible, continuing anyway...${NC}"
fi

# Obtain certificate
echo -e "${BLUE}Obtaining SSL certificate from Let's Encrypt...${NC}"

CERTBOT_CMD="certbot certonly --webroot -w /var/www/certbot \
    --email ${EMAIL} \
    --agree-tos \
    --no-eff-email"

# Add staging flag if needed
if [ "$STAGING" = "1" ]; then
    CERTBOT_CMD="$CERTBOT_CMD --staging"
fi

# Add domain
CERTBOT_CMD="$CERTBOT_CMD -d ${DOMAIN}"

# Run certbot in docker
docker run --rm \
    -v "$(pwd)/docker/nginx/certbot-conf:/etc/letsencrypt" \
    -v "$(pwd)/docker/nginx/certbot-www:/var/www/certbot" \
    certbot/certbot:latest \
    $CERTBOT_CMD

# Check if certificates were created
if [ -f "./docker/nginx/certbot-conf/live/${DOMAIN}/fullchain.pem" ]; then
    echo -e "${GREEN}✓ SSL certificates obtained successfully!${NC}"
    echo -e "${GREEN}✓ Location: ./docker/nginx/certbot-conf/live/${DOMAIN}/${NC}"

    # Update nginx to use Let's Encrypt certificates
    echo -e "${BLUE}Updating nginx configuration...${NC}"

    # Reload nginx
    echo -e "${BLUE}Reloading nginx...${NC}"
    docker-compose -f docker-compose.yml -f docker-compose.production.yml restart web

    echo -e "${GREEN}✓ Nginx reloaded with new certificates${NC}"
    echo ""
    echo -e "${GREEN}=== SSL Setup Complete ===${NC}"
    echo -e "${GREEN}Your site should now be accessible at: https://${DOMAIN}${NC}"
    echo ""
    echo -e "${BLUE}Next steps:${NC}"
    echo -e "  1. Test HTTPS: curl -I https://${DOMAIN}"
    echo -e "  2. Start certbot renewal service: docker-compose -f docker-compose.yml -f docker-compose.production.yml up -d certbot"
    echo -e "  3. Check SSL grade: https://www.ssllabs.com/ssltest/analyze.html?d=${DOMAIN}"

else
    echo -e "${RED}✗ Failed to obtain SSL certificates${NC}"
    echo -e "${RED}Check the logs above for errors${NC}"
    exit 1
fi
