#!/bin/bash

#
# SSL Test Script for michaelschiemer.de
# Quick verification of SSL certificate and HTTPS connectivity
#

DOMAIN="michaelschiemer.de"
SERVER_IP="94.16.110.151"

# Colors
GREEN="\e[32m"
YELLOW="\e[33m"
RED="\e[31m"
BLUE="\e[34m"
RESET="\e[0m"

log_info() { echo -e "${BLUE}[INFO]${RESET} $1"; }
log_success() { echo -e "${GREEN}[SUCCESS]${RESET} $1"; }
log_warning() { echo -e "${YELLOW}[WARNING]${RESET} $1"; }
log_error() { echo -e "${RED}[ERROR]${RESET} $1"; }

echo "=== SSL Test for $DOMAIN ==="
echo

# Test 1: DNS Resolution
log_info "Testing DNS resolution..."
resolved_ip=$(dig +short "$DOMAIN" | head -1)
if [[ "$resolved_ip" == "$SERVER_IP" ]]; then
    log_success "DNS: $DOMAIN → $resolved_ip ✓"
else
    log_warning "DNS: $DOMAIN → $resolved_ip (expected: $SERVER_IP)"
fi
echo

# Test 2: Port Connectivity
log_info "Testing port connectivity..."
if nc -z "$DOMAIN" 443 2>/dev/null; then
    log_success "Port 443: Accessible ✓"
else
    log_error "Port 443: Not accessible ✗"
fi

if nc -z "$DOMAIN" 80 2>/dev/null; then
    log_success "Port 80: Accessible ✓"
else
    log_error "Port 80: Not accessible ✗"
fi
echo

# Test 3: HTTP to HTTPS Redirect
log_info "Testing HTTP to HTTPS redirect..."
http_response=$(curl -I -s "http://$DOMAIN" | head -1)
if echo "$http_response" | grep -q "301\|302"; then
    log_success "HTTP Redirect: Working ✓"
    curl -I -s "http://$DOMAIN" | grep -i "location:" || true
else
    log_warning "HTTP Redirect: $http_response"
fi
echo

# Test 4: HTTPS Connection
log_info "Testing HTTPS connection..."
if curl -sSf "https://$DOMAIN" > /dev/null 2>&1; then
    log_success "HTTPS Connection: Working ✓"
else
    log_error "HTTPS Connection: Failed ✗"
    log_info "Trying with --insecure flag..."
    if curl -sSf --insecure "https://$DOMAIN" > /dev/null 2>&1; then
        log_warning "HTTPS works with --insecure (certificate issue)"
    else
        log_error "HTTPS completely broken"
    fi
fi
echo

# Test 5: SSL Certificate Details
log_info "Checking SSL certificate..."
cert_info=$(echo | openssl s_client -servername "$DOMAIN" -connect "$DOMAIN:443" 2>/dev/null | openssl x509 -noout -text 2>/dev/null)

if [[ -n "$cert_info" ]]; then
    echo "Certificate Details:"
    echo | openssl s_client -servername "$DOMAIN" -connect "$DOMAIN:443" 2>/dev/null | openssl x509 -noout -dates 2>/dev/null
    
    # Check if Let's Encrypt
    if echo "$cert_info" | grep -q "Let's Encrypt"; then
        log_success "Certificate: Let's Encrypt ✓"
    else
        log_warning "Certificate: Not Let's Encrypt (might be self-signed)"
    fi
    
    # Check expiration
    exp_date=$(echo | openssl s_client -servername "$DOMAIN" -connect "$DOMAIN:443" 2>/dev/null | openssl x509 -noout -enddate 2>/dev/null | cut -d= -f2)
    if [[ -n "$exp_date" ]]; then
        exp_timestamp=$(date -d "$exp_date" +%s 2>/dev/null || echo "")
        current_timestamp=$(date +%s)
        if [[ -n "$exp_timestamp" ]] && [[ $exp_timestamp -gt $current_timestamp ]]; then
            days_left=$(( (exp_timestamp - current_timestamp) / 86400 ))
            if [[ $days_left -gt 30 ]]; then
                log_success "Certificate Expiry: $days_left days remaining ✓"
            else
                log_warning "Certificate Expiry: $days_left days remaining (renew soon)"
            fi
        else
            log_error "Certificate: Expired or invalid ✗"
        fi
    fi
else
    log_error "Could not retrieve certificate information"
fi
echo

# Test 6: SSL Labs Grade (optional, requires internet)
log_info "SSL Labs test available at:"
echo "https://www.ssllabs.com/ssltest/analyze.html?d=$DOMAIN"
echo

# Test 7: Framework Health Check
log_info "Testing framework health endpoint..."
health_status=$(curl -s -o /dev/null -w "%{http_code}" "https://$DOMAIN/ping" 2>/dev/null)
if [[ "$health_status" == "200" ]]; then
    log_success "Framework Health: OK ✓"
elif [[ "$health_status" == "404" ]]; then
    log_warning "Framework Health: Endpoint not found (might be disabled)"
else
    log_error "Framework Health: HTTP $health_status ✗"
fi

# Summary
echo
echo "=== Test Summary ==="
echo "Domain: $DOMAIN"
echo "Target IP: $SERVER_IP"
echo
echo "Next steps if issues found:"
echo "1. Check DNS: dig +short $DOMAIN"
echo "2. Check firewall: nmap -p 80,443 $DOMAIN"
echo "3. Check containers: ssh deploy@$SERVER_IP 'docker compose ps'"
echo "4. Check nginx logs: ssh deploy@$SERVER_IP 'docker compose logs web'"
echo "5. Regenerate SSL: ./setup-production-ssl.sh"