#!/bin/bash
set -euo pipefail

# Transcodes the selected pictures or videos to the format and resolution
# named in FOLIO_TARGET (<format>-<resolution>), writing beside each input
# without overwriting existing files.

target="${FOLIO_TARGET:-}"
case "$target" in
  jpg-high|jpg-medium|jpg-low|png-high|png-medium|png-low)
    kind=picture ;;
  mp4-4k|mp4-1080p|mp4-720p|gif-1080p|gif-720p)
    kind=video ;;
  *)
    echo "Unsupported target: $target" >&2
    exit 1 ;;
esac

if (( $# == 0 )); then
  echo "No files to transcode." >&2
  exit 1
fi

format="${target%%-*}"
resolution="${target#*-}"

tmp_dir=""
cleanup() {
  local pids
  pids=$(jobs -p)
  if [[ -n "$pids" ]]; then
    kill $pids 2>/dev/null || true
    wait $pids 2>/dev/null || true
  fi
  if [[ -n "$tmp_dir" ]]; then
    rm -rf -- "$tmp_dir"
  fi
}
trap cleanup EXIT
trap 'exit 129' HUP
trap 'exit 130' INT
trap 'exit 143' TERM

run_child() {
  "$@" &
  local pid=$! rc=0
  wait "$pid" || rc=$?
  return "$rc"
}

publish_output() {
  local src="$1" dir="${2%/}" stem="$3" resolution="$4" format="$5"
  local candidate="${dir}/${stem}-${resolution}.${format}"
  local n=1 err
  while :; do
    if [[ ! -e "$candidate" && ! -L "$candidate" ]]; then
      if err=$(mv --update=none-fail -- "$src" "$candidate" 2>&1); then
        return 0
      fi
      if [[ ! -e "$candidate" && ! -L "$candidate" ]]; then
        printf '%s\n' "$err" >&2
        return 1
      fi
    fi
    (( n += 1 ))
    candidate="${dir}/${stem}-${resolution}-${n}.${format}"
  done
}

transcode_picture() {
  local input="$1" format="$2" resolution="$3" output="$4"
  local resize
  case "$resolution" in
    high) resize='3160x>' ;;
    medium) resize='2160x>' ;;
    low) resize='1080x>' ;;
  esac
  case "$format" in
    jpg)
      run_child magick "$input" -delete 1--1 -auto-orient -resize "$resize" -quality 85 -strip "$output" ;;
    png)
      run_child magick "$input" -delete 1--1 -auto-orient -resize "$resize" -strip \
        -define png:compression-filter=5 \
        -define png:compression-level=9 \
        -define png:compression-strategy=1 \
        -define png:exclude-chunk=all \
        "$output" ;;
  esac
}

transcode_video() {
  local input="$1" format="$2" resolution="$3" output="$4"
  local scale
  case "$resolution" in
    4k) scale='scale=-2:2160' ;;
    1080p) scale='scale=-2:1080' ;;
    720p) scale='scale=-2:720' ;;
  esac
  case "$format" in
    mp4)
      if [[ "$resolution" == "4k" ]]; then
        run_child ffmpeg -nostdin -hide_banner -loglevel error -y -i "$input" -vf "$scale" \
          -c:v libx265 -preset slow -crf 24 -c:a aac -b:a 192k -movflags +faststart "$output"
      else
        run_child ffmpeg -nostdin -hide_banner -loglevel error -y -i "$input" -vf "$scale" \
          -c:v libx264 -preset fast -crf 23 -c:a aac -b:a 192k -movflags +faststart "$output"
      fi ;;
    gif)
      run_child ffmpeg -nostdin -hide_banner -loglevel error -y -i "$input" \
        -vf "fps=10,${scale}:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse" \
        "$output" ;;
  esac
}

for input in "$@"; do
  [[ "$input" != /* && "$input" != ./* ]] && input="./$input"
  [[ -f "$input" ]] || { echo "File not found: $input" >&2; exit 1; }
  dir=$(dirname -- "$input")
  base=$(basename -- "$input")
  if [[ "$base" == ?*.* ]]; then
    stem="${base%.*}"
  else
    stem="$base"
  fi

  # Stage on the destination filesystem so large videos never fill /tmp
  # and publishing is an atomic rename; TERM/INT/HUP traps clean up promptly.
  tmp_dir=$(mktemp -d --tmpdir="$dir" ".transcode.XXXXXX")
  tmp_out="${tmp_dir}/out.${format}"

  if [[ "$kind" == "picture" ]]; then
    transcode_picture "$input" "$format" "$resolution" "$tmp_out"
  else
    transcode_video "$input" "$format" "$resolution" "$tmp_out"
  fi

  publish_output "$tmp_out" "$dir" "$stem" "$resolution" "$format"
  rmdir -- "$tmp_dir"
  tmp_dir=""
done

if (( $# == 1 )); then
  echo '{"notice": "Transcoded."}'
else
  printf '{"notice": ["Transcoded %%1 files.", "%d"]}\n' "$#"
fi
