#!/usr/bin/env bash
## Create an index.html file with links to files in the same directory and any
## subdirectories.
##
## Usage: mkindex [] []
##
## Options:
## -c CSS file
## -f Footer file
## -h Header file
## -i Intro file
## -o Outro file
## -t Title
## -y Skip confirmation prompt
##
## Dependencies: GNU coreutils, GNU sed
set -euo pipefail
shopt -s inherit_errexit dotglob globstar nullglob
die() { echo -e "$(basename "$0"): $1" >&2; exit 1; }
[[ " $* " =~ ' --help ' ]] && sed -n 's/^## *//p' "$0" && exit
while getopts c:f:h:i:o: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") ;;
i) [[ -f $OPTARG ]] || die "intro file not found: $OPTARG"
intro=$(< "$OPTARG") ;;
o) [[ -f $OPTARG ]] || die "outro file not found: $OPTARG"
outro=$(< "$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=""
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+="$file | $date |
"
done
tee "$index" <<-EOF > /dev/null
$title
${css_link-}
${header-}
$title
${intro-}
${outro-}
${footer-}
EOF