#!/usr/bin/env bash

# Serve a file directory as a static web server and open it in Firefox.
#
# Usage
#
#   Serve the local directory:
#
#   $ serve
#
#   Serve a different directory:
#
#   $ serve ~/some-directory/results
#
# Inspiration: https://evanhahn.com/scripts-i-wrote-that-i-use-all-the-time/#internet

set -e
set -u
set -o pipefail

# Directory to serve (default to current directory)
DIR="${1:-.}"

# Find a random available port
PORT=$(python3 -c 'import socket; s=socket.socket(); s.bind(("",0)); print(s.getsockname()[1]); s.close()')

echo "Starting HTTP server on http://localhost:$PORT"
echo "Serving directory: $DIR"

# Open Firefox in background
firefox "http://localhost:$PORT" &

# Start the HTTP server (this blocks until Ctrl+C)
python3 -m http.server "$PORT" --directory "$DIR"
