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

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

usage() {
  cat <<'EOF'
Usage:
  replace-audio.sh [--dry-run] <video> <audio> <output>

Examples:
  replace-audio.sh video.mp4 music.m4a out.mp4

Environment:
  AUDIO_BITRATE  Output audio bitrate. Default: 192k
EOF
}

dry_run=0
audio_bitrate="${AUDIO_BITRATE:-192k}"

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
}

video_file="$1"
audio_file="$2"
output_file="$3"

[ -f "$video_file" ] || die "video file not found: $video_file"
[ -f "$audio_file" ] || die "audio file not found: $audio_file"

require_command ffmpeg
require_command ffprobe

has_stream "$video_file" v:0 || die "missing video stream: $video_file"
has_stream "$audio_file" a:0 || die "missing audio stream: $audio_file"

if [ "$dry_run" -eq 1 ]; then
  cat <<EOF
video_file=$video_file
audio_file=$audio_file
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

ffmpeg \
  -y \
  -i "$video_file" \
  -i "$audio_file" \
  -map 0:v:0 \
  -map 1:a:0 \
  -c:v copy \
  -c:a aac \
  -b:a "$audio_bitrate" \
  -shortest \
  "${faststart_args[@]}" \
  "$output_file"
