#!/usr/bin/env bash
#
# Startet den Krisenvorrat Dev-Server im LAN.
#
# Verwendung:
#   ./start-server.sh                              # Standard API-Key
#   ./start-server.sh --build                       # Fat-JAR neu bauen
#   ./start-server.sh --api-key "mein-key"          # Eigener API-Key
#
set -euo pipefail
cd "$(dirname "$0")"

API_KEY="dev-api-key-change-in-production"
FORCE_BUILD=false

while [[ $# -gt 0 ]]; do
    case "$1" in
        --build)
            FORCE_BUILD=true
            shift
            ;;
        --api-key)
            API_KEY="$2"
            shift 2
            ;;
        *)
            echo "Unknown option: $1" >&2
            exit 1
            ;;
    esac
done

JAR_PATH="server/build/libs/server.jar"

# Fat-JAR bauen falls nötig
if [ "$FORCE_BUILD" = true ] || [ ! -f "$JAR_PATH" ]; then
    echo "Building server fat JAR..."
    ./gradlew :server:buildFatJar
    echo "Build successful."
fi

# LAN-IP ermitteln
LAN_IP=""
if command -v ip &>/dev/null; then
    LAN_IP=$(ip -4 addr show scope global | grep -oP 'inet \K[\d.]+' | head -1)
elif command -v ifconfig &>/dev/null; then
    LAN_IP=$(ifconfig | grep 'inet ' | grep -v '127.0.0.1' | awk '{print $2}' | head -1)
fi

echo ""
echo "=== Krisenvorrat Dev-Server ==="
echo "Local:   http://localhost:8080"
if [ -n "$LAN_IP" ]; then
    echo "LAN:     http://${LAN_IP}:8080"
fi
echo "API-Key: $API_KEY"
echo "Press Ctrl+C to stop"
echo ""

# Server starten
export KRISENVORRAT_API_KEY="$API_KEY"
java -jar "$JAR_PATH"
