#!/bin/bash
# =====================================================================
# caddy.sh - Simple script to start Caddy server
# =====================================================================
# Usage: 
#   ./caddy.sh - Start/restart the Caddy server
# 
# This script handles all Caddy server operations from the correct directory
# =====================================================================

set -e

# Ensure we're in the correct directory (where this script is located)
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
cd "$SCRIPT_DIR"

# Stop any existing Caddy processes
echo "=== Stopping Caddy Server ==="
killall caddy 2>/dev/null || true
pkill -f "caddy run" 2>/dev/null || true
sleep 1
echo "All Caddy processes stopped."

# Update CSP hashes
echo "=== Updating CSP Hashes ==="
# Run the update-csp-hashes.sh script
if [ -f "./update-csp-hashes.sh" ]; then
    ./update-csp-hashes.sh
else
    echo "WARNING: update-csp-hashes.sh not found. Skipping CSP hash updates."
fi

# Start Caddy
echo "=== Starting Caddy Server ==="
echo "Working directory: $(pwd)"

# Check if Caddyfile.local exists
if [ ! -f "Caddyfile.local" ]; then
    echo "ERROR: Caddyfile.local not found in $(pwd)"
    echo "Please ensure you're running this script from the directory containing Caddyfile.local"
    exit 1
fi

# Launch Caddy
echo "Starting Caddy with Caddyfile.local..."
caddy run --config Caddyfile.local &

# Wait a moment to check if Caddy started successfully
sleep 2
if ! pgrep -f "caddy run" > /dev/null; then
    echo "ERROR: Caddy failed to start. Check the error messages above."
    exit 1
fi

echo "=== Caddy Server Started Successfully ==="
echo "Local server running at: http://localhost:8080"

exit 0 