#!/usr/bin/env bash
# Per-domain health check: DNS, HTTP, HTTPS, SSL cert, Apache vhost status
# Usage: domain-status <domain>
#        domain-status --all

set -uo pipefail

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

SSL_TLS_DIR="/var/cpanel/ssl/apache_tls"
TODAY_TS=$(date +%s)
WARN_TS=$((TODAY_TS + 30*86400))

check_domain() {
    local domain="$1"
    echo -e "\n${BOLD}─── $domain ───${NC}"

    # ── DNS check ──────────────────────────────────────────────────────────────
    local dns_ip
    dns_ip=$(dig +short "$domain" A 2>/dev/null | grep -E '^[0-9]' | head -1 || true)
    local server_ip
    server_ip=$(curl -s4 ifconfig.me 2>/dev/null || hostname -I | awk '{print $1}')

    if [[ -z "$dns_ip" ]]; then
        echo -e "  DNS:       ${RED}NXDOMAIN (not resolving)${NC}"
    elif [[ "$dns_ip" == "$server_ip" ]]; then
        echo -e "  DNS:       ${GREEN}OK${NC} → $dns_ip (this server)"
    else
        echo -e "  DNS:       ${YELLOW}PROXIED/REMOTE${NC} → $dns_ip (server: $server_ip)"
    fi

    # ── HTTP/HTTPS check ───────────────────────────────────────────────────────
    local http_code https_code
    http_code=$(curl -sk -o /dev/null -w "%{http_code}" --max-time 8 "http://${domain}/" 2>/dev/null || echo "ERR")
    https_code=$(curl -sk -o /dev/null -w "%{http_code}" --max-time 8 "https://${domain}/" 2>/dev/null || echo "ERR")

    local http_color="${RED}" https_color="${RED}"
    [[ "$http_code" =~ ^(200|301|302|304)$ ]] && http_color="${GREEN}"
    [[ "$https_code" =~ ^(200|301|302|304)$ ]] && https_color="${GREEN}"
    [[ "$http_code" == "ERR" ]] && http_color="${RED}"
    [[ "$https_code" == "ERR" ]] && https_color="${RED}"

    echo -e "  HTTP:      ${http_color}${http_code}${NC}"
    echo -e "  HTTPS:     ${https_color}${https_code}${NC}"

    # ── SSL cert check ─────────────────────────────────────────────────────────
    local cert_dir="$SSL_TLS_DIR/$domain"
    if [[ -d "$cert_dir" ]]; then
        local combined="$cert_dir/combined"
        local key_file="$cert_dir/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 [[ -z "$cert_md5" || "$cert_md5" != "$key_md5" ]]; then
                echo -e "  SSL cert:  ${RED}MISMATCH — cert/key do not match!${NC}"
            else
                local expiry_str expiry_ts
                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)
                if [[ $expiry_ts -lt $TODAY_TS ]]; then
                    echo -e "  SSL cert:  ${RED}EXPIRED${NC} (${expiry_str})"
                elif [[ $expiry_ts -lt $WARN_TS ]]; then
                    local days=$(( (expiry_ts - TODAY_TS) / 86400 ))
                    echo -e "  SSL cert:  ${YELLOW}Expiring in ${days}d${NC} (${expiry_str})"
                else
                    local days=$(( (expiry_ts - TODAY_TS) / 86400 ))
                    echo -e "  SSL cert:  ${GREEN}OK${NC} (expires in ${days}d)"
                fi
            fi
        else
            echo -e "  SSL cert:  ${RED}Missing cert or key file${NC}"
        fi
    else
        echo -e "  SSL cert:  ${YELLOW}No SSL installed${NC}"
    fi

    # ── Apache vhost check ─────────────────────────────────────────────────────
    if grep -q "ServerName $domain" /etc/apache2/conf/httpd.conf 2>/dev/null; then
        echo -e "  Apache:    ${GREEN}vhost found in httpd.conf${NC}"
    else
        echo -e "  Apache:    ${YELLOW}no vhost in httpd.conf${NC}"
    fi

    # ── Nginx block check ──────────────────────────────────────────────────────
    BLOCK_FILE="/etc/nginx/conf.d/blocked/${domain}.conf"
    if [[ -f "$BLOCK_FILE" ]]; then
        local reason
        reason=$(grep "^# Reason:" "$BLOCK_FILE" 2>/dev/null | sed 's/^# Reason: //' || echo "unknown")
        echo -e "  Nginx:     ${RED}BLOCKED (503)${NC} — $reason"
    else
        echo -e "  Nginx:     ${GREEN}passing through${NC}"
    fi

    # ── cPanel user ───────────────────────────────────────────────────────────
    local cpanel_user
    cpanel_user=$(grep "^${domain}:" /etc/userdatadomains 2>/dev/null | cut -d: -f2 | cut -d= -f1 | xargs || true)
    [[ -n "$cpanel_user" ]] && echo -e "  cPanel:    ${CYAN}$cpanel_user${NC}"
}

if [[ "${1:-}" == "--all" ]]; then
    echo -e "${BOLD}=== Domain Status — All Active Vhosts ===${NC}"
    # Get all unique ServerName values from Apache
    while IFS= read -r domain; do
        [[ -z "$domain" ]] && continue
        check_domain "$domain"
    done < <(grep "^\s*ServerName" /etc/apache2/conf/httpd.conf 2>/dev/null | awk '{print $2}' | sort -u)
elif [[ "${1:-}" == "" ]]; then
    echo "Usage: $0 <domain> | --all"
    exit 1
else
    check_domain "$1"
fi

echo ""
