#!/bin/bash
# Check Echomark CORS Configuration
# Usage: ./check-echomark-cors.sh <path-to-ssh-key>

set -e

SSH_KEY="$1"
SERVER="ec2-52-8-108-29.us-west-1.compute.amazonaws.com"

if [ -z "$SSH_KEY" ]; then
    echo "Usage: $0 <path-to-ssh-key>"
    echo "Example: $0 ~/echomark-key.pem"
    exit 1
fi

echo "🔍 Checking Echomark CORS Configuration..."
echo ""

echo "📡 Testing CORS from command line..."
curl -I -X POST https://$SERVER:5345/echomark/api/v2/document/mark/pdf \
  -H "Authorization: Bearer 79f8eaa8-735d-480c-a594-891a9afe9b89" \
  -H "Origin: chrome-extension://test" 2>&1 | grep -i "access-control" || echo "No CORS headers found!"

echo ""
echo "🔐 SSHing into server to check configuration..."
echo ""

ssh -i "$SSH_KEY" ubuntu@$SERVER << 'ENDSSH'
echo "📁 Looking for Echomark installation..."
ECHOMARK_DIR=$(find /opt /var /etc -name "*echomark*" -type d 2>/dev/null | head -1)

if [ -z "$ECHOMARK_DIR" ]; then
    echo "❌ Could not find Echomark installation directory"
    echo "Searching for Python files..."
    find /opt /var /etc -name "*.py" 2>/dev/null | grep -i echomark | head -5
else
    echo "✅ Found Echomark at: $ECHOMARK_DIR"
    echo ""
    echo "📄 Configuration files:"
    find "$ECHOMARK_DIR" -name "*.py" -o -name "*.conf" -o -name "*.ini" 2>/dev/null | head -10
fi

echo ""
echo "🔧 Checking for CORS configuration in Python files..."
grep -r "CORS\|cors\|Access-Control" /opt /var /etc 2>/dev/null | grep -v ".pyc" | head -10 || echo "No CORS configuration found"

echo ""
echo "🐍 Checking Flask/Python packages..."
python3 -c "import flask_cors; print('✅ flask-cors installed')" 2>/dev/null || echo "❌ flask-cors not installed"

echo ""
echo "📋 Checking systemd services..."
systemctl list-units --type=service | grep -i echomark || echo "No echomark service found"

echo ""
echo "🌐 Checking nginx configuration..."
if [ -d /etc/nginx ]; then
    grep -r "add_header.*Access-Control" /etc/nginx/ 2>/dev/null | head -5 || echo "No CORS headers in nginx"
else
    echo "nginx not installed"
fi

echo ""
echo "📊 Current running processes..."
ps aux | grep -i echomark | grep -v grep || echo "No echomark processes found"

ENDSSH

echo ""
echo "✅ Check complete!"
echo ""
echo "📖 To fix CORS issues, see: ECHOMARK_CORS_FIX.md"
