#!/bin/sh

# Create HTML file listing for a website
# Public domain (or under the Unlicense, if desired)

cd "${1:-.}"
PREFIX="${2:-}"
BASE_DIR="$(pwd)/"

get_dir() {
	printf "<ul>\n"
	# TODO: maybe iterate over directories first? Not sure
	for ITEM in * .*; do
		# POSIX specifies that "The operators "&&" and "||" shall have equal 
		# precedence and shall be evaluated with left associativity." :)
		[ "$ITEM" != "." ] && [ "$ITEM" != ".." ] || continue
		if [ -f "$ITEM" ]; then
			CURRENT_DIR="$(pwd)/"
			printf "<li><a href=\"%s\">" \
				"$PREFIX${CURRENT_DIR#"$BASE_DIR"}$ITEM"
			printf "<code>%s</code></a></li>\n" "$ITEM"
		elif [ -d "$ITEM" ]; then
			printf "<li><a href=\"%s/\">" \
				"$PREFIX${CURRENT_DIR#"$BASE_DIR"}$ITEM"
			printf "<code>%s/</code></a>\n" "$ITEM"
			(
				cd "$ITEM"
				get_dir
			)
			printf "</li>\n"
		fi
	done
	printf "</ul>\n"
}

get_dir
