#!/bin/sh
set -euC

# Bail if pandoc is not available.
if ! command -v pandoc > "/dev/null"
then
    exit
fi

# Find readme.
file="$(
    git ls-tree HEAD \
    | sed 's/^[^\t]\+\t//' \
    | grep -i '^readme' \
    | head -n 1
)"
if [ -z "$file" ]
then
    exit
fi

# Write the readme to a temporary directory so that pandoc's automatic filetype
# detection works.
tmp_dir="$(mktemp -d)"
trap 'rm -rf "$tmp_dir"' EXIT
in="$tmp_dir/$(basename "$file")"
git cat-file blob "HEAD:$file" > "$in"

# `--from` overrides.
ext="$(printf "%s\n" "${file##*.}" | tr '[:upper:]' '[:lower*]')"
case "$ext" in
    *.md|*mkd|*.markdown)
        from='--from gfm'
        ;;
esac

# Run pandoc.
out="${GIT_DIR:-"$(git rev-parse --git-dir)"}/README.html"
pandoc ${from:-} --output "$out" "$in"