#!/usr/bin/env bash
# Force SSL cert renewal for a domain via cPanel AutoSSL, then do a safe reload.
# Usage: cert-renew <domain>
#        cert-renew --all            (renew all expiring/expired certs)

set -uo pipefail

LOG_FILE="/opt/server-resilience/logs/cert-renew-$(date +%Y%m%d).log"
ALERT_SCRIPT="/opt/server-resilience/bin/send-alert"
SAFE_RESTART="/opt/server-resilience/bin/safe-apache-restart"
SSL_TLS_DIR="/var/cpanel/ssl/apache_tls"

RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; BOLD='\033[1m'; NC='\033[0m'

log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" | tee -a "$LOG_FILE"; }

[[ $# -lt 1 ]] && { echo "Usage: $0 <domain> | --all"; exit 1; }

renew_domain() {
    local domain="$1"
    log "Renewing cert for: $domain"
    echo -e "${BOLD}Renewing: $domain${NC}"

    # Find cPanel user for this domain
    local cpanel_user
    cpanel_user=$(grep "^${domain}:" /etc/userdatadomains 2>/dev/null | cut -d= -f2 | cut -d= -f1 || true)
    if [[ -z "$cpanel_user" ]]; then
        cpanel_user=$(find /var/cpanel/userdata -name "${domain}_SSL" 2>/dev/null | awk -F/ '{print $5}' | head -1 || true)
    fi

    if [[ -z "$cpanel_user" ]]; then
        echo -e "${YELLOW}  WARNING: Could not find cPanel user for $domain — trying whmapi1 directly${NC}"
        log "No cPanel user found for $domain — trying whmapi1 global autossl"
        /usr/local/cpanel/bin/whmapi1 start_autossl_check_for_one_user user="" 2>/dev/null || true
        return 1
    fi

    log "cPanel user: $cpanel_user (domain: $domain)"

    # Run AutoSSL for this specific user
    echo "  Running AutoSSL for user: $cpanel_user"
    if /usr/local/cpanel/scripts/autossl_check --user="$cpanel_user" 2>&1 | tee -a "$LOG_FILE"; then
        sleep 5
        # Verify the cert was actually renewed/fixed
        local combined="$SSL_TLS_DIR/$domain/combined"
        local key_file="$SSL_TLS_DIR/$domain/key"
        if [[ -f "$combined" && -f "$key_file" ]]; then
            local cert_md5 key_md5
            cert_md5=$(openssl x509 -noout -modulus -in "$combined" 2>/dev/null | openssl md5 | awk '{print $2}')
            key_md5=$(openssl rsa -noout -modulus -in "$key_file" 2>/dev/null | openssl md5 | awk '{print $2}')
            if [[ -n "$cert_md5" && "$cert_md5" == "$key_md5" ]]; then
                log "SUCCESS: cert/key match confirmed for $domain"
                echo -e "  ${GREEN}✓ Cert renewed and verified for $domain${NC}"
                return 0
            else
                log "FAIL: cert/key still mismatched after AutoSSL for $domain"
                echo -e "  ${RED}✗ Cert still mismatched after AutoSSL. May need manual intervention.${NC}"
                return 1
            fi
        fi
    else
        log "AutoSSL check failed for $cpanel_user"
        echo -e "  ${RED}AutoSSL check failed for $cpanel_user${NC}"
        return 1
    fi
}

if [[ "$1" == "--all" ]]; then
    log "=== cert-renew --all ==="
    TODAY_TS=$(date +%s)
    WARN_TS=$((TODAY_TS + 30*86400))
    RENEWED=0; FAILED=0

    for dir in "$SSL_TLS_DIR"/*/; do
        domain=$(basename "$dir")
        combined="$dir/combined"
        key_file="$dir/key"
        [[ ! -f "$combined" || ! -f "$key_file" ]] && continue

        # Check if active in Apache
        grep -q "apache_tls/$domain/" /etc/apache2/conf/httpd.conf /etc/apache2/conf.d/*.conf 2>/dev/null || continue

        # Check for mismatch or expiry
        cert_md5=$(openssl x509 -noout -modulus -in "$combined" 2>/dev/null | openssl md5 | awk '{print $2}')
        key_md5=$(openssl rsa -noout -modulus -in "$key_file" 2>/dev/null | openssl md5 | awk '{print $2}')
        expiry_str=$(openssl x509 -noout -enddate -in "$combined" 2>/dev/null | cut -d= -f2)
        expiry_ts=$(date -d "$expiry_str" +%s 2>/dev/null || echo 0)

        needs_renewal=false
        [[ -z "$cert_md5" || "$cert_md5" != "$key_md5" ]] && needs_renewal=true
        [[ $expiry_ts -gt 0 && $expiry_ts -lt $WARN_TS ]] && needs_renewal=true

        if $needs_renewal; then
            if renew_domain "$domain"; then ((RENEWED++)); else ((FAILED++)); fi
        fi
    done

    echo ""
    echo "Renewal complete: $RENEWED renewed, $FAILED failed"
    log "cert-renew --all complete: renewed=$RENEWED failed=$FAILED"

    if [[ $RENEWED -gt 0 ]]; then
        echo "Running safe Apache reload to pick up new certs..."
        "$SAFE_RESTART" graceful
    fi
else
    DOMAIN="$1"
    if renew_domain "$DOMAIN"; then
        "$SAFE_RESTART" graceful
    else
        "$ALERT_SCRIPT" "WARN" "cert-renew failed for $DOMAIN — manual action may be required" 2>/dev/null || true
        exit 1
    fi
fi
