#!/bin/bash
# Check DNS and setup SSL when ready

DOMAIN="quickbooksposhelp.access.ly"
PUBLIC_IP="170.254.17.146"

echo "Checking DNS for $DOMAIN..."
echo ""

# Check DNS resolution
RESOLVED_IP=$(dig +short "$DOMAIN" | tail -1)

if [ -z "$RESOLVED_IP" ]; then
    echo "❌ DNS not resolving yet"
    echo ""
    echo "In your No-IP account:"
    echo "  1. Go to Dynamic DNS → Hostnames"
    echo "  2. Find: $DOMAIN"
    echo "  3. Set IP to: $PUBLIC_IP"
    echo "  4. Save and wait 2-5 minutes"
    exit 1
fi

echo "✅ DNS resolving to: $RESOLVED_IP"

if [ "$RESOLVED_IP" != "$PUBLIC_IP" ]; then
    echo "⚠️  Warning: DNS points to $RESOLVED_IP but should be $PUBLIC_IP"
fi

echo ""
echo "Testing HTTP access..."
if curl -f -s -m 10 "http://$DOMAIN/POS_Help.html" > /dev/null 2>&1; then
    echo "✅ Site accessible via HTTP"
else
    echo "⚠️  HTTP access failed - check router port forwarding for port 80"
fi

echo ""
echo "Testing port 8888 access..."
if curl -f -s -m 10 "http://$DOMAIN:8888/POS_Help.html" > /dev/null 2>&1; then
    echo "✅ Site accessible on port 8888"
else
    echo "⚠️  Port 8888 access failed"
fi

echo ""
read -p "DNS is working. Get SSL certificate now? (y/n): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo ""
    echo "Getting SSL certificate..."
    sudo certbot --nginx -d "$DOMAIN" --non-interactive --agree-tos --email admin@prompttech.com --redirect
    
    if [ $? -eq 0 ]; then
        echo ""
        echo "🎉 SSL Setup Complete!"
        echo ""
        echo "Your site is now accessible at:"
        echo "  🔒 https://$DOMAIN"
        echo "  🔒 https://$DOMAIN:8888"
    else
        echo "❌ SSL certificate installation failed"
    fi
fi
