#!/bin/bash

set -euo pipefail

# Set default values
: ${RATHOLE_SERVER_PORT:=2333}
: ${RATHOLE_SERVER_TOKEN:=changeme}

# Generate rathole.toml configuration file with correct format
cat <<EOF > /app/data/rathole.toml
[server]
bind_addr = "0.0.0.0:$RATHOLE_SERVER_PORT"
default_token = "$RATHOLE_SERVER_TOKEN"

[server.services]
EOF

echo "Starting Rathole server on port $RATHOLE_SERVER_PORT with token: ${RATHOLE_SERVER_TOKEN:0:8}..."

# Start Rathole server in background
/app/code/rathole --server /app/data/rathole.toml &

# Wait a moment for Rathole to start
sleep 2

# Check if Rathole started successfully
if pgrep -f rathole > /dev/null; then
    echo "Rathole server started successfully"

    # Create a simple health check file
    mkdir -p /tmp/health
    echo "OK" > /tmp/health/index.html

    # Start a simple HTTP server for health checks on port 8080
    cd /tmp/health
    python3 -m http.server 8080 &

    echo "Health check server started on port 8080"

    # Keep the script running to maintain the container
    wait
else
    echo "Failed to start Rathole server"
    exit 1
fi
