#!/usr/bin/env bash
# Serve this folder (and everything under it) over HTTP on 0.0.0.0:18444.
set -euo pipefail

cd "$(dirname "$(readlink -f "$0")")"

PORT=18444
HOST=0.0.0.0
ROOT="$PWD"

# 0.0.0.0 is not a URL: advertise loopback + first LAN address instead.
LAN_IP="$(hostname -I 2>/dev/null | awk '{print $1}')"
URLS=("http://127.0.0.1:${PORT}/")
[[ -n "$LAN_IP" ]] && URLS+=("http://${LAN_IP}:${PORT}/")

echo "Serving $ROOT on ${HOST}:${PORT}"
for u in "${URLS[@]}"; do echo "  $u"; done
echo "Directories with an index.html open it automatically; use the parent link ('..') to list the folder."
echo

# Show where the browsable pages actually are.
while IFS= read -r idx; do
    printf '  %s%s\n' "${URLS[0]%\/}/" "${idx#./}"
done < <(find . -type f -name 'index.html' -not -path './node_modules/*' | sort)
echo

if command -v python3 >/dev/null 2>&1; then
    exec python3 -m http.server "$PORT" --bind "$HOST" --directory "$ROOT"
elif command -v python >/dev/null 2>&1; then
    cd "$ROOT" && exec python -m http.server "$PORT" --bind "$HOST"
elif command -v php >/dev/null 2>&1; then
    exec php -S "${HOST}:${PORT}" -t "$ROOT"
else
    echo "error: need python3, python, or php to serve files" >&2
    exit 1
fi