#!/bin/sh
# SSL certificate renewal script for Let's Encrypt

set -e

# Configuration
DOMAIN=${DOMAIN:-localhost}
EMAIL=${SSL_EMAIL:-admin@roa2web.local}
WEBROOT_PATH=/var/www/certbot

# Function to log messages
log() {
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1"
}

# Check if running in production
if [ "$ENVIRONMENT" = "production" ]; then
    log "Starting SSL certificate renewal for domain: $DOMAIN"
    
    # Initial certificate generation
    if [ ! -f "/etc/letsencrypt/live/$DOMAIN/fullchain.pem" ]; then
        log "Generating initial SSL certificate..."
        certbot certonly \
            --webroot \
            --webroot-path=$WEBROOT_PATH \
            --email=$EMAIL \
            --agree-tos \
            --no-eff-email \
            --force-renewal \
            -d $DOMAIN
    fi
    
    # Renew certificates
    log "Attempting certificate renewal..."
    certbot renew --webroot --webroot-path=$WEBROOT_PATH
    
    # Reload nginx if certificates were renewed
    if [ $? -eq 0 ]; then
        log "Certificate renewal successful, reloading nginx..."
        nginx -s reload
    else
        log "Certificate renewal failed or not needed"
    fi
else
    log "Not in production environment, skipping SSL renewal"
fi

log "SSL renewal script completed"