#!/usr/bin/env bash

set -e

usage() {
    echo "Usage: tile-letter IMAGE [dpi=300] [overlap_inches=0] [orientation=portrait|landscape] [pdf=yes]"
    exit 1
}

command -v magick >/dev/null || { echo "ImageMagick required"; exit 1; }
command -v img2pdf >/dev/null || { echo "img2pdf required (optional if pdf=no)"; }

input="$1"
dpi="${2:-300}"
overlap_in="${3:-0}"
orientation="${4:-landscape}"
make_pdf="${5:-yes}"

[[ -f "$input" ]] || usage

base=$(basename "$input")
name="${base%.*}"

# Letter size in inches
portrait_w=8.5
portrait_h=11

if [[ "$orientation" == "landscape" ]]; then
    letter_w=11
    letter_h=8.5
else
    letter_w=$portrait_w
    letter_h=$portrait_h
fi

tile_w=$(awk "BEGIN {print int($letter_w * $dpi)}")
tile_h=$(awk "BEGIN {print int($letter_h * $dpi)}")

overlap_px=$(awk "BEGIN {print int($overlap_in * $dpi)}")

echo "Input: $input"
echo "DPI: $dpi"
echo "Orientation: $orientation"
echo "Page size: ${tile_w}x${tile_h}"
echo "Overlap: ${overlap_in}in (${overlap_px}px)"

mkdir -p "${name}_tiles"

crop_w=$((tile_w + overlap_px))
crop_h=$((tile_h + overlap_px))

magick "$input" \
  -crop ${crop_w}x${crop_h} \
  -background white \
  -gravity northwest \
  -extent ${tile_w}x${tile_h} \
  +repage \
  "${name}_tiles/${name}_%03d.jpg"

echo "Tiles written to ${name}_tiles/"

if [[ "$make_pdf" == "yes" ]]; then
    pdf="${name}_poster.pdf"
    img2pdf "${name}_tiles"/*.jpg -o "$pdf"
    echo "PDF written to $pdf"
fi

