#!/usr/bin/env bash

## Create an index.html file with links to files in the same directory and any
## subdirectories.
##
## Usage: mkindex [<options>] [<dir>]
##
## Options:
##   -c <file>    CSS file
##   -f <file>    Footer file
##   -h <file>    Header file
##   -t <title>   Page title
##   -y           Skip confirmation prompt
##
## Dependencies: GNU coreutils, GNU sed

set -euo pipefail
shopt -s inherit_errexit dotglob globstar nullglob

die() { echo "$(basename "$0"): $1" >&2; exit 1; }

[[ " $* " =~ ' --help ' ]] && sed -n 's/^## \?//p' "$0" && exit

while getopts c:f:h:t:y opt; do
  case $opt in
    c) [[ -f $OPTARG ]] || die "CSS file not found: $OPTARG"
       css_file=$OPTARG ;;
    f) [[ -f $OPTARG ]] || die "footer file not found: $OPTARG"
       footer=$(< "$OPTARG") ;;
    h) [[ -f $OPTARG ]] || die "header file not found: $OPTARG"
       header=$(< "$OPTARG") ;;
    t) title=$OPTARG ;;
    y) assume_yes=true ;;
    *) exit 1 ;;
  esac
done
shift "$(( OPTIND - 1 ))"

dir=${1:-.}; [[ -d $dir ]] || die "directory not found: $dir"
index=$dir/index.html
title=${title:-$(realpath "$dir")}
[[ -v css_file ]] &&
  css_link="<link rel=stylesheet href='$(realpath --relative-to="$dir" "$css_file")'>"

if [[ -e $index && ! -v assume_yes ]]; then
  read -rp "$index already exists. Overwrite it? " input
  [[ $input =~ ^[Yy] ]] || exit
fi

# Create table rows.
for file in "$dir"/**; do
  [[ -d $file || $file == "$index" ]] && continue
  date=$(date -r "$file" +%Y-%m-%d)
  file=$(realpath --relative-to="$dir" "$file")
  rows+="<tr><td><a href='$file'>$file</a></td><td>$date</td></tr>"
done

tee "$index" <<-EOF > /dev/null
	<!doctype html>
	<html lang=en>
	<meta charset=utf-8>
	<title>$title</title>
	<meta name=viewport content="width=device-width,initial-scale=1">
	${css_link:-}
	${header:-}
	<main id=content>
	<h1>$title</h1>
	<table>
	<thead><tr><td>File</td><td>Last update</td></tr></thead>
	<tbody>${rows:-}</tbody>
	</table>
	</main>
	${footer:-}
	</html>
	EOF