#!/usr/bin/env bash
set -euo pipefail

if [[ $# -ne 4 ]]; then
  echo "Usage: $0 OUTPUT_DIRECTORY OPTION_1.html OPTION_2.html OPTION_3.html" >&2
  exit 2
fi

if [[ "$(uname -s)" != "Darwin" ]]; then
  echo "The bundled HTML preview renderer currently requires macOS." >&2
  exit 3
fi

output_dir="$1"
shift

temporary_dir="$(mktemp -d)"
trap 'rm -rf "$temporary_dir"' EXIT
mkdir -p "$temporary_dir/html" "$temporary_dir/rendered" "$output_dir"

index=1
for input in "$@"; do
  if [[ ! -f "$input" ]]; then
    echo "HTML option not found: $input" >&2
    exit 4
  fi
  cp "$input" "$temporary_dir/html/option-$index.html"
  index=$((index + 1))
done

/usr/bin/qlmanage -t -s 1600 -o "$temporary_dir/rendered" \
  "$temporary_dir/html/option-1.html" \
  "$temporary_dir/html/option-2.html" \
  "$temporary_dir/html/option-3.html" >/dev/null

for index in 1 2 3; do
  thumbnail="$temporary_dir/rendered/option-$index.html.png"
  if [[ ! -f "$thumbnail" ]]; then
    echo "Failed to render HTML option $index." >&2
    exit 5
  fi
  /usr/bin/sips -c 1000 1600 "$thumbnail" \
    --out "$output_dir/option-$index.png" >/dev/null
  printf '%s\n' "$output_dir/option-$index.png"
done
