#!/usr/bin/env bash
# build-trailer.sh: join trailer pieces in play order, level each piece to -16 LUFS,
# and print every piece length, the planned total and the measured total.
# Usage: bash build-trailer.sh pieces.txt trailer.mp3
# pieces.txt holds one audio file per line (intro, clips, outro), in play order.
# Output is 44.1 kHz MP3, mono by default (fine for speech). For stereo music under the intro, run:
#   CHANNELS=stereo bash build-trailer.sh pieces.txt trailer.mp3
set -euo pipefail
list="${1:-}"
out="${2:-trailer.mp3}"
layout="${CHANNELS:-mono}"
if [ "$layout" != mono ] && [ "$layout" != stereo ]; then echo "error: CHANNELS must be mono or stereo, got: $layout" >&2; exit 2; fi
if [ -z "$list" ] || [ ! -f "$list" ]; then echo "error: list file not found: ${list:-<none>}" >&2; exit 2; fi
if [ ! -s "$list" ]; then echo "error: list file is empty: $list" >&2; exit 2; fi
args=(); filt=""; labels=""; n=0; sum=0
while IFS= read -r line || [ -n "$line" ]; do
  f="${line%$'\r'}"                      # tolerate Windows line breaks
  [ -z "$f" ] && continue
  if [ ! -f "$f" ]; then echo "error: piece not found: $f" >&2; exit 2; fi
  if [ ! -s "$f" ]; then echo "error: piece is empty: $f" >&2; exit 2; fi
  if [ -z "$(ffprobe -v error -select_streams a -show_entries stream=index -of csv=p=0 -i "$f" 2>/dev/null)" ]; then echo "error: no audio stream in: $f" >&2; exit 2; fi
  d=$(ffprobe -v error -show_entries format=duration -of csv=p=0 -i "$f")
  printf 'piece %d\t%s\t%.3f s\n' "$((n+1))" "$f" "$d"
  sum=$(awk -v a="$sum" -v b="$d" 'BEGIN{printf "%.6f", a+b}')
  args+=(-i "$f")
  filt+="[$n:a]loudnorm=I=-16:TP=-1.5:LRA=11,aresample=44100,aformat=sample_fmts=fltp:channel_layouts=$layout[p$n];"
  labels+="[p$n]"
  n=$((n+1))
done < "$list"
if [ "$n" -lt 2 ]; then echo "error: need at least 2 pieces, got $n" >&2; exit 2; fi
ffmpeg -hide_banner -loglevel error -y "${args[@]}" \
  -filter_complex "${filt}${labels}concat=n=$n:v=0:a=1[out]" \
  -map "[out]" -c:a libmp3lame -q:a 2 "$out"
got=$(ffprobe -v error -show_entries format=duration -of csv=p=0 -i "$out")
awk -v s="$sum" -v g="$got" -v o="$out" 'BEGIN{printf "sum of pieces\t%.3f s\n%s\t%.3f s\ndifference\t%+.3f s\n", s, o, g, g-s}'
