#!/bin/bash
# SSL auto-repair — fixes mismatched/missing cert-key pairs in apache_tls by
# matching the installed cert against private keys in cPanel user keystores,
# then rebuilding the combined file with correct PEM newline handling.
# This is what prevents a single bad cert from crashing Apache (today's root cause).
TLS=/var/cpanel/ssl/apache_tls
LOG=/opt/site-guardian/logs/ssl-repair.log
ts(){ date '+%Y-%m-%d %H:%M:%S'; }
log(){ echo "[$(ts)] $*" >> "$LOG"; }

# Build index of all candidate private keys -> modulus md5
declare -A KEYBYMOD
while IFS= read -r k; do
  [ -f "$k" ] || continue
  m=$(openssl rsa -in "$k" -noout -modulus 2>/dev/null | openssl md5 | awk '{print $NF}')
  [ -n "$m" ] && KEYBYMOD[$m]="$k"
done < <(find /home/*/ssl/keys -name '*.key' 2>/dev/null; find /var/cpanel/ssl -name '*.key' 2>/dev/null)

fixed=0
for d in "$TLS"/*/; do
  dom=$(basename "$d")
  comb="$d/combined"; key="$d/key"; certs="$d/certificates"
  # Determine the authoritative cert modulus from 'certificates' (cPanel source) or combined
  src="$certs"; [ -s "$src" ] || src="$comb"
  [ -s "$src" ] || continue
  certmod=$(sed -n '/-----BEGIN CERTIFICATE-----/,/-----END CERTIFICATE-----/p' "$src" 2>/dev/null | sed '/-----END CERTIFICATE-----/q' | openssl x509 -noout -modulus 2>/dev/null | openssl md5 | awk '{print $NF}')
  [ -z "$certmod" ] && continue
  keymod=$(openssl rsa -in "$key" -noout -modulus 2>/dev/null | openssl md5 | awk '{print $NF}')

  if [ "$certmod" != "$keymod" ] || [ ! -s "$key" ] || [ ! -s "$comb" ]; then
    goodkey="${KEYBYMOD[$certmod]}"
    if [ -n "$goodkey" ]; then
      cp -a "$key" "$key.bak.$(date +%s)" 2>/dev/null
      install -m 0600 -o root -g root "$goodkey" "$key"
      awk 1 "$key" "$certs" > "$comb.new" 2>/dev/null
      # validate
      nm=$(sed -n '/-----BEGIN CERTIFICATE-----/,/-----END CERTIFICATE-----/p' "$comb.new" | sed '/-----END CERTIFICATE-----/q' | openssl x509 -noout -modulus 2>/dev/null | openssl md5 | awk '{print $NF}')
      km=$(openssl rsa -in "$key" -noout -modulus 2>/dev/null | openssl md5 | awk '{print $NF}')
      if [ "$nm" = "$km" ] && openssl x509 -in "$comb.new" -noout >/dev/null 2>&1; then
        chmod 0640 "$comb.new"; chown root:root "$comb.new"; mv -f "$comb.new" "$comb"
        log "REPAIRED pair: $dom (key from $goodkey)"
        fixed=$((fixed+1))
      else
        rm -f "$comb.new"; log "REPAIR FAILED validate: $dom"
      fi
    else
      log "NO MATCHING KEY for $dom (certmod=$certmod) — manual cert reissue needed"
    fi
  fi
done
log "ssl-repair complete: $fixed pair(s) fixed"
exit 0
