#!/bin/sh
set -eu


usage() {
	cat <<-'EOF'
		Usage:
		  serve [-d DIRECTORY] [-n] [-p PORT]
		  serve -h
	EOF
}

help() {
	cat <<-'EOF'


		Options:
		  -d DIRECTORY    the directory to serve (default: ".")
		  -n              do not open browser
		  -p PORT         the port to listen on (default: find one)
		  -h, --help      show this message


		Serve DIRECTORY via HTTP as a static file server, and open the
		URL on the $BROWSER.


		Examples:

		  Serve "." on the default PORT:

		    $ serve


		  Serve "public/" on port 1234:

		    $ serve -d public/ -p 1234
	EOF
}


for flag in "$@"; do
	case "$flag" in
		(--)
			break
			;;
		(--help)
			usage
			help
			exit
			;;
		(*)
			;;
	esac
done

DIRECTORY='.'
PORT="$(free-port)"
OPEN_BROWSER=true
while getopts 'd:np:h' flag; do
	case "$flag" in
		(d)
			DIRECTORY="$OPTARG"
			;;
		(p)
			PORT="$OPTARG"
			;;
		(n)
			OPEN_BROWSER=false
			;;
		(h)
			usage
			help
			exit
			;;
		(*)
			usage >&2
			exit 2
			;;
	esac
done

if [ "$OPEN_BROWSER" = true ]; then
	open "http://localhost:$PORT" &
fi
python3 -m http.server -d "$DIRECTORY" "$PORT"
wait
