#!/usr/bin/env bash
# Run the roux-server in Docker, mounting a local recipe directory.
#
# Usage: ./scripts/run <recipe-dir> [--host HOST] [--port PORT]
#
# The server listens on port 8080 inside the container, mapped to PORT
# on the host (default 8080).  Pass --port to change the host-side port.
#
# Examples:
#   ./scripts/run ~/recipes
#   ./scripts/run ./cooklang-examples --port 9090
set -euo pipefail

PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

if [ $# -lt 1 ]; then
    echo "Usage: $0 <recipe-dir> [--host HOST] [--port PORT]" >&2
    exit 1
fi

# Resolve the recipe directory to an absolute path so Docker can mount it.
RECIPE_DIR="$(cd "$1" && pwd)"
shift

# Parse --port from remaining args; everything else is passed to the server.
HOST_PORT=8080
SERVER_ARGS=()
while [ $# -gt 0 ]; do
    case "$1" in
        --port)
            HOST_PORT="$2"
            shift 2
            ;;
        --host)
            SERVER_ARGS+=("$1" "$2")
            shift 2
            ;;
        *)
            SERVER_ARGS+=("$1")
            shift
            ;;
    esac
done

IMAGE="${HAWAT_HASKELL_TOOLS_IMAGE:-ghcr.io/flipstone/haskell-tools:debian-ghc-9.10.3-5d6640d}"
STACK_ROOT_HOST="${PROJECT_DIR}/.stack-root"
mkdir -p "${STACK_ROOT_HOST}"

echo "[roux] mounting recipes from ${RECIPE_DIR}"
echo "[roux] listening on http://127.0.0.1:${HOST_PORT}/"

exec docker run --rm -i $([ -t 0 ] && printf -- -t) \
    -v "${PROJECT_DIR}:/work" \
    -v "${STACK_ROOT_HOST}:/stack-root" \
    -v "${RECIPE_DIR}:/recipes" \
    -e STACK_ROOT=/stack-root \
    -w /work \
    -p "${HOST_PORT}:8080" \
    "${IMAGE}" \
    stack exec roux-server -- --recipe-dir /recipes --port 8080 "${SERVER_ARGS[@]}"
