#!/bin/bash
#
# SSL Certificate Testing & Validation Script
# Tests SSL configuration and certificate validity
#
# Usage: ./scripts/ssl-test.sh [domain]
#

set -euo pipefail

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

DOMAIN="${1:-${DOMAIN_NAME:-michaelschiemer.de}}"

echo -e "${BLUE}=== SSL Certificate Testing ===${NC}"
echo -e "${BLUE}Domain:${NC} $DOMAIN"
echo ""

# Test 1: Check if port 443 is accessible
echo -e "${BLUE}[1/7] Testing HTTPS port accessibility...${NC}"
if curl -sf --connect-timeout 5 https://${DOMAIN} > /dev/null 2>&1; then
    echo -e "${GREEN}✓ Port 443 accessible${NC}"
else
    echo -e "${RED}✗ Port 443 not accessible${NC}"
    echo -e "${YELLOW}Make sure firewall allows port 443${NC}"
fi

# Test 2: Check certificate validity
echo -e "${BLUE}[2/7] Checking certificate validity...${NC}"
CERT_INFO=$(echo | openssl s_client -servername ${DOMAIN} -connect ${DOMAIN}:443 2>/dev/null | openssl x509 -noout -dates 2>/dev/null || true)

if [ -n "$CERT_INFO" ]; then
    echo -e "${GREEN}✓ Certificate found${NC}"
    echo "$CERT_INFO" | sed 's/^/  /'

    # Extract and check expiry date
    EXPIRY=$(echo "$CERT_INFO" | grep "notAfter" | cut -d= -f2)
    EXPIRY_EPOCH=$(date -d "$EXPIRY" +%s 2>/dev/null || date -j -f "%b %d %T %Y %Z" "$EXPIRY" +%s 2>/dev/null)
    NOW_EPOCH=$(date +%s)
    DAYS_LEFT=$(( ($EXPIRY_EPOCH - $NOW_EPOCH) / 86400 ))

    if [ $DAYS_LEFT -gt 30 ]; then
        echo -e "${GREEN}✓ Certificate valid for $DAYS_LEFT days${NC}"
    elif [ $DAYS_LEFT -gt 7 ]; then
        echo -e "${YELLOW}⚠ Certificate expires in $DAYS_LEFT days${NC}"
    else
        echo -e "${RED}✗ Certificate expires in $DAYS_LEFT days - RENEW SOON!${NC}"
    fi
else
    echo -e "${RED}✗ No certificate found${NC}"
fi

# Test 3: Check certificate issuer
echo -e "${BLUE}[3/7] Checking certificate issuer...${NC}"
ISSUER=$(echo | openssl s_client -servername ${DOMAIN} -connect ${DOMAIN}:443 2>/dev/null | openssl x509 -noout -issuer 2>/dev/null || true)

if echo "$ISSUER" | grep -q "Let's Encrypt"; then
    echo -e "${GREEN}✓ Issued by Let's Encrypt${NC}"
    echo "  $ISSUER"
elif [ -n "$ISSUER" ]; then
    echo -e "${YELLOW}⚠ Issued by: $ISSUER${NC}"
else
    echo -e "${RED}✗ Could not determine issuer${NC}"
fi

# Test 4: Check TLS versions
echo -e "${BLUE}[4/7] Checking TLS version support...${NC}"
if echo | openssl s_client -servername ${DOMAIN} -connect ${DOMAIN}:443 -tls1_3 2>/dev/null | grep -q "Protocol  : TLSv1.3"; then
    echo -e "${GREEN}✓ TLS 1.3 supported${NC}"
else
    echo -e "${YELLOW}⚠ TLS 1.3 not supported${NC}"
fi

if echo | openssl s_client -servername ${DOMAIN} -connect ${DOMAIN}:443 -tls1_2 2>/dev/null | grep -q "Protocol  : TLSv1.2"; then
    echo -e "${GREEN}✓ TLS 1.2 supported${NC}"
else
    echo -e "${RED}✗ TLS 1.2 not supported${NC}"
fi

# Test 5: Check HTTP to HTTPS redirect
echo -e "${BLUE}[5/7] Testing HTTP to HTTPS redirect...${NC}"
HTTP_REDIRECT=$(curl -sI -w "%{http_code}" -o /dev/null http://${DOMAIN} || true)

if [ "$HTTP_REDIRECT" = "301" ] || [ "$HTTP_REDIRECT" = "302" ]; then
    echo -e "${GREEN}✓ HTTP redirects to HTTPS (${HTTP_REDIRECT})${NC}"
else
    echo -e "${YELLOW}⚠ HTTP response code: ${HTTP_REDIRECT}${NC}"
fi

# Test 6: Check HSTS header
echo -e "${BLUE}[6/7] Checking HSTS header...${NC}"
HSTS=$(curl -sI https://${DOMAIN} | grep -i "strict-transport-security" || true)

if [ -n "$HSTS" ]; then
    echo -e "${GREEN}✓ HSTS header present${NC}"
    echo "  $HSTS"
else
    echo -e "${YELLOW}⚠ HSTS header not found${NC}"
fi

# Test 7: Check security headers
echo -e "${BLUE}[7/7] Checking security headers...${NC}"
HEADERS=$(curl -sI https://${DOMAIN})

check_header() {
    local header=$1
    local name=$2
    if echo "$HEADERS" | grep -qi "$header"; then
        echo -e "${GREEN}✓ ${name}${NC}"
    else
        echo -e "${YELLOW}⚠ ${name} missing${NC}"
    fi
}

check_header "X-Content-Type-Options" "X-Content-Type-Options"
check_header "X-Frame-Options" "X-Frame-Options"
check_header "X-XSS-Protection" "X-XSS-Protection"
check_header "Content-Security-Policy" "Content-Security-Policy"

echo ""
echo -e "${BLUE}=== SSL Test Summary ===${NC}"
echo -e "${GREEN}Testing complete!${NC}"
echo ""
echo -e "${BLUE}Additional checks:${NC}"
echo -e "  • SSL Labs Test: ${YELLOW}https://www.ssllabs.com/ssltest/analyze.html?d=${DOMAIN}${NC}"
echo -e "  • Mozilla Observatory: ${YELLOW}https://observatory.mozilla.org/analyze/${DOMAIN}${NC}"
echo -e "  • Security Headers: ${YELLOW}https://securityheaders.com/?q=${DOMAIN}${NC}"
