#!/usr/bin/env bash set -euo pipefail if [[ $# -lt 2 ]]; then echo "usage: $0 [file...]" >&2 exit 1 fi OUTPUT_DIR="$1" shift MEDIA_DIR="$OUTPUT_DIR/media" escape_regex() { printf '%s' "$1" | sed -e 's/[][(){}.^$*+?|\\/]/\\&/g' } escape_replacement() { printf '%s' "$1" | sed -e 's/[\\/&]/\\&/g' } replace_path() { local target_file="$1" local from_path="$2" local to_path="$3" local from_escaped to_escaped from_escaped="$(escape_regex "$from_path")" to_escaped="$(escape_replacement "$to_path")" perl -0777 -i -pe "s#${from_escaped}(?=[\\\"'\\)\\s>])#${to_escaped}#g" "$target_file" } # Convert PDFs to PNG for browser-friendly rendering. if [[ -d "$MEDIA_DIR" ]] && command -v pdftoppm >/dev/null 2>&1; then while IFS= read -r -d '' pdf_file; do png_file="${pdf_file%.pdf}.png" if [[ ! -f "$png_file" ]]; then pdftoppm -singlefile -png "$pdf_file" "${pdf_file%.pdf}" >/dev/null 2>&1 || true fi done < <(find "$MEDIA_DIR" -type f -name '*.pdf' -print0) fi # Ensure extensionless media files also have stable, browser-friendly suffixes. if [[ -d "$MEDIA_DIR" ]] && command -v file >/dev/null 2>&1; then while IFS= read -r -d '' raw_file; do mime_type="$(file -b --mime-type "$raw_file" || true)" case "$mime_type" in image/png) normalized_file="${raw_file}.png" ;; image/jpeg) normalized_file="${raw_file}.jpg" ;; image/webp) normalized_file="${raw_file}.webp" ;; image/svg+xml) normalized_file="${raw_file}.svg" ;; application/pdf) normalized_file="${raw_file}.pdf" ;; text/plain) normalized_file="${raw_file}.txt" ;; *) continue ;; esac [[ -f "$normalized_file" ]] || cp "$raw_file" "$normalized_file" done < <(find "$MEDIA_DIR" -type f ! -name '*.*' -print0) fi for target_file in "$@"; do [[ -f "$target_file" ]] || continue # Replace embeds with imgs and drop hard-coded sizing attributes. perl -0777 -i -pe ' s#