#!/bin/bash
# Better signal handling - forward signals to child processes
trap 'kill -TERM $SERVER_PID; kill -TERM $CADDY_PID; exit' TERM INT
set -eu
echo "==> Starting Ente Cloudron app (DEBUG MODE)..."
# Create necessary directories
mkdir -p /app/data/config /app/data/logs /app/data/caddy
# Check if web directories exist
echo "==> Checking web app directories:"
for app in photos accounts auth cast; do
    if [ -d "/app/web/$app" ]; then
        echo "==> Found: /app/web/$app"
        ls -la "/app/web/$app" | head -5
    else
        echo "==> WARNING: Missing /app/web/$app - creating placeholder"
        mkdir -p "/app/web/$app"
        echo "
$app app placeholder
" > "/app/web/$app/index.html"
    fi
done
# Create a simple test Caddyfile first
echo "==> Creating simple test Caddyfile"
cat > /app/data/Caddyfile <<'EOT'
{
    admin off
    auto_https off
}
:3080 {
    log {
        output stdout
        format console
        level DEBUG
    }
    # Health check endpoint
    handle /health {
        header Content-Type "application/json"
        respond "{\"status\": \"OK\", \"timestamp\": \"{{now | date \"2006-01-02T15:04:05Z07:00\"}}\"}" 200
    }
    # Test endpoint
    handle /test {
        respond "Caddy is working on port 3080!" 200
    }
    # API proxy to Museum server
    handle /api/* {
        uri strip_prefix /api
        reverse_proxy localhost:8080 {
            transport http {
                read_timeout 60s
                write_timeout 60s
            }
            # Add error handling
            handle_errors {
                respond "{\"error\": \"Museum server not available\"}" 503
            }
        }
    }
    # Serve web apps with fallback
    handle {
        root * /app/web/photos
        try_files {path} {path}/ /index.html
        file_server {
            browse
        }
    }
}
EOT
# Start a simple Museum mock server for testing
echo "==> Starting mock Museum server on port 8080"
cat > /tmp/museum-mock.js <<'EOF'
const http = require('http');
const server = http.createServer((req, res) => {
    console.log(`Museum mock: ${req.method} ${req.url}`);
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ status: 'ok', path: req.url, timestamp: new Date().toISOString() }));
});
server.listen(8080, '127.0.0.1', () => {
    console.log('Museum mock server running on http://127.0.0.1:8080');
});
EOF
node /tmp/museum-mock.js > /app/data/logs/museum-mock.log 2>&1 &
SERVER_PID=$!
echo "==> Mock Museum server started (PID: $SERVER_PID)"
# Wait for Museum mock to be ready
sleep 2
# Test Museum mock
echo "==> Testing Museum mock server..."
curl -s http://localhost:8080/test || echo "WARNING: Museum mock not responding"
# Validate Caddyfile
echo "==> Validating Caddyfile..."
caddy validate --config /app/data/Caddyfile --adapter caddyfile || {
    echo "==> ERROR: Caddyfile validation failed!"
    exit 1
}
# Start Caddy with explicit environment
echo "==> Starting Caddy web server..."
CADDY_FORMAT=console caddy run --config /app/data/Caddyfile --adapter caddyfile 2>&1 | tee /app/data/logs/caddy-combined.log &
CADDY_PID=$!
echo "==> Caddy started (PID: $CADDY_PID)"
# Wait for Caddy to start
echo "==> Waiting for Caddy to start..."
for i in {1..30}; do
    if curl -s http://localhost:3080/health > /dev/null; then
        echo "==> Caddy is responding!"
        break
    fi
    echo -n "."
    sleep 1
done
echo
# Check process status
echo "==> Process status:"
ps aux | grep -E "(caddy|node)" | grep -v grep || echo "No processes found"
# Check port status
echo "==> Port status:"
netstat -tlnp 2>/dev/null | grep -E "(3080|8080)" || lsof -i :3080 -i :8080 2>/dev/null || echo "Cannot check port status"
# Test endpoints
echo "==> Testing endpoints:"
echo "Health check:"
curl -s http://localhost:3080/health | jq . || echo "Failed"
echo -e "\nTest endpoint:"
curl -s http://localhost:3080/test || echo "Failed"
echo -e "\nAPI proxy:"
curl -s http://localhost:3080/api/status | jq . || echo "Failed"
echo "==> Startup complete. Services:"
echo "   - Caddy PID: $CADDY_PID"
echo "   - Museum Mock PID: $SERVER_PID"
echo "==> Logs: /app/data/logs/"
# Keep running
wait $SERVER_PID $CADDY_PID