#!/bin/bash
# Startup Verification Script for Church Music Database
# Verifies all services are running after a reboot/restart

echo "========================================="
echo "Church Music Database - Startup Check"
echo "========================================="
echo ""

# Color codes
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

check_service() {
    service_name=$1
    if systemctl is-active --quiet "$service_name"; then
        echo -e "${GREEN}✓${NC} $service_name is running"
        return 0
    else
        echo -e "${RED}✗${NC} $service_name is NOT running"
        return 1
    fi
}

check_port() {
    port=$1
    service=$2
    if ss -tlnp | grep -q ":$port "; then
        echo -e "${GREEN}✓${NC} Port $port ($service) is listening"
        return 0
    else
        echo -e "${RED}✗${NC} Port $port ($service) is NOT listening"
        return 1
    fi
}

echo "Checking System Services..."
echo "----------------------------"
check_service postgresql
check_service church-music-backend
check_service church-music-frontend
check_service nginx
check_service certbot.timer
echo ""

echo "Checking Network Ports..."
echo "-------------------------"
check_port 5432 "PostgreSQL"
check_port 8080 "Backend API"
check_port 5100 "Frontend"
check_port 80 "HTTP"
check_port 443 "HTTPS"
echo ""

echo "Checking Web Access..."
echo "----------------------"
if curl -s -o /dev/null -w "%{http_code}" http://localhost | grep -q "200\|301\|302"; then
    echo -e "${GREEN}✓${NC} Local HTTP access working"
else
    echo -e "${RED}✗${NC} Local HTTP access failed"
fi

if curl -sk -o /dev/null -w "%{http_code}" https://localhost | grep -q "200"; then
    echo -e "${GREEN}✓${NC} Local HTTPS access working"
else
    echo -e "${RED}✗${NC} Local HTTPS access failed"
fi

# Check DNS resolution
echo ""
echo "Checking DNS & Public Access..."
echo "--------------------------------"
PUBLIC_IP=$(curl -s -4 ifconfig.me 2>/dev/null)
DNS_IP=$(dig +short houseofprayer.ddns.net @8.8.8.8 2>/dev/null | head -1)

echo "Public IP: $PUBLIC_IP"
echo "DNS Points To: $DNS_IP"

if [ "$PUBLIC_IP" != "$DNS_IP" ]; then
    echo -e "${YELLOW}⚠${NC} Warning: DNS does not match public IP"
    echo "   You may need to update your DDNS or router settings"
else
    echo -e "${GREEN}✓${NC} DNS correctly points to public IP"
fi
echo ""

echo "========================================="
echo "Startup verification complete!"
echo "========================================="
echo ""
echo "Access your site at: https://houseofprayer.ddns.net"
