#!/usr/bin/env bash
# Run the sis-server in Docker.
#
# Usage: ./scripts/run [--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
#   ./scripts/run --port 9090
set -euo pipefail

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

HOST_PORT=8080
while [ $# -gt 0 ]; do
    case "$1" in
        --port)
            HOST_PORT="$2"
            shift 2
            ;;
        *)
            echo "Unknown option: $1" >&2
            exit 1
            ;;
    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 "[sis] 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" \
    -e STACK_ROOT=/stack-root \
    -w /work \
    -p "${HOST_PORT}:8080" \
    "${IMAGE}" \
    stack exec sis-server -- --port 8080
