#!/bin/bash
# fix-ssl.sh — Retry SSL for an existing cPanel account
# Usage: fix-ssl.sh <username> [expected_ip]
set -euo pipefail

if [[ $# -lt 1 ]]; then
  echo "Usage: fix-ssl.sh <username> [expected_ip]"
  exit 1
fi

USERNAME="$1"
EXPECTED_IP="${2:-$(curl -s --max-time 5 https://api.ipify.org 2>/dev/null || hostname -I | awk '{print $1}')}"

# Detect domain from cPanel
DOMAIN=$(whmapi1 listaccts --output=json 2>/dev/null | python3 -c "
import json,sys
data = json.load(sys.stdin)
for a in data.get('data',{}).get('acct',[]):
    if a.get('user') == sys.argv[1]:
        print(a.get('domain',''))
        break
" "$USERNAME" 2>/dev/null)

if [[ -z "$DOMAIN" ]]; then
  echo "ERROR: No cPanel account found for user '$USERNAME'"
  exit 1
fi

echo "Fixing SSL for $DOMAIN (user: $USERNAME, expected IP: $EXPECTED_IP)"

# 1. Check DNS
RESOLVED_IP=$(dig +short A "$DOMAIN" @8.8.8.8 2>/dev/null | grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}' | head -1 || true)
echo "DNS resolves to: ${RESOLVED_IP:-none}"

if [[ "$RESOLVED_IP" != "$EXPECTED_IP" ]]; then
  echo "WARNING: DNS points to $RESOLVED_IP, not $EXPECTED_IP"
  echo "SSL may fail if domain doesn't point here. Continuing anyway..."
fi

# 2. Clear AutoSSL exclusions
echo "Clearing AutoSSL exclusions..."
uapi --user="$USERNAME" SSL set_autossl_excluded_domains >/dev/null 2>&1 || true

# 3. Trigger AutoSSL
echo "Triggering AutoSSL..."
whmapi1 start_autossl_check_for_one_user username="$USERNAME" >/dev/null 2>&1

# 4. Verify (up to 5 minutes)
echo "Waiting for Let's Encrypt certificate..."
for i in $(seq 1 30); do
  sleep 10

  CERT_ISSUER=$(echo | timeout 5 openssl s_client \
    -connect "${DOMAIN}:443" \
    -servername "${DOMAIN}" 2>/dev/null \
    | openssl x509 -noout -issuer 2>/dev/null || true)

  if echo "$CERT_ISSUER" | grep -qi "Let's Encrypt"; then
    echo "SUCCESS: Let's Encrypt certificate installed for $DOMAIN"
    exit 0
  fi

  # Re-trigger if self-signed detected
  if echo "$CERT_ISSUER" | grep -qi "$DOMAIN"; then
    echo "Self-signed detected, re-triggering AutoSSL... (attempt $i/30)"
    uapi --user="$USERNAME" SSL set_autossl_excluded_domains >/dev/null 2>&1 || true
    whmapi1 start_autossl_check_for_one_user username="$USERNAME" >/dev/null 2>&1 || true
  else
    echo "Waiting... (attempt $i/30)"
  fi
done

echo "FAILED: SSL not installed after 5 minutes."
echo "Check AutoSSL logs or run: whmapi1 start_autossl_check_for_one_user username=$USERNAME"
exit 1
