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

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
. "$script_dir/common.sh"

usage() {
  cat <<'EOF'
Usage:
  burn-captions.sh [--dry-run] <input> <captions.(srt|vtt|ass)> <output>

Examples:
  burn-captions.sh video.mp4 captions.srt capped.mp4
  burn-captions.sh video.mp4 captions.ass capped.mp4

Environment:
  CRF  Video quality. Default: 18
EOF
}

dry_run=0
crf="${CRF:-18}"

while [ "$#" -gt 0 ]; do
  case "$1" in
    --dry-run)
      dry_run=1
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    --)
      shift
      break
      ;;
    -*)
      die "unknown option: $1"
      ;;
    *)
      break
      ;;
  esac
done

[ "$#" -eq 3 ] || {
  usage
  exit 1
}

input_file="$1"
captions_file="$2"
output_file="$3"

[ -f "$input_file" ] || die "input file not found: $input_file"
[ -f "$captions_file" ] || die "captions file not found: $captions_file"
assert_positive_number "CRF" "$crf"

require_command ffmpeg
require_command ffprobe

has_stream "$input_file" v:0 || die "missing video stream: $input_file"

captions_ext="$(normalized_extension "$captions_file")"
case "$captions_ext" in
  ass)
    video_filter="ass=$(escape_filter_value "$captions_file")"
    ;;
  srt|vtt)
    video_filter="subtitles=$(escape_filter_value "$captions_file")"
    ;;
  *)
    die "captions file must be .srt, .vtt, or .ass"
    ;;
esac

has_audio=0
if has_stream "$input_file" a:0; then
  has_audio=1
fi

if [ "$dry_run" -eq 1 ]; then
  cat <<EOF
input_file=$input_file
captions_file=$captions_file
captions_ext=$captions_ext
has_audio=$has_audio
output_file=$output_file
EOF
  exit 0
fi

ensure_parent_dir "$output_file"

faststart_args=()
case "$(normalized_extension "$output_file")" in
  mp4|m4v|mov)
    faststart_args=(-movflags +faststart)
    ;;
esac

if [ "$has_audio" -eq 1 ]; then
  ffmpeg \
    -y \
    -i "$input_file" \
    -vf "$video_filter" \
    -map 0:v:0 \
    -map 0:a:0 \
    -c:v libx264 \
    -crf "$crf" \
    -pix_fmt yuv420p \
    -c:a copy \
    "${faststart_args[@]}" \
    "$output_file"
else
  ffmpeg \
    -y \
    -i "$input_file" \
    -vf "$video_filter" \
    -map 0:v:0 \
    -c:v libx264 \
    -crf "$crf" \
    -pix_fmt yuv420p \
    "${faststart_args[@]}" \
    "$output_file"
fi
