#!/usr/bin/env bash
# ImaScreen local converter. No network calls. Requires FFmpeg + FFprobe.
set -euo pipefail
export PATH="/opt/homebrew/bin:/usr/local/bin:$PATH"
fail() { printf '\n%s\n' "$*" >&2; exit 1; }
command -v ffmpeg >/dev/null || fail 'Install FFmpeg first: https://ffmpeg.org/download.html'
command -v ffprobe >/dev/null || fail 'Install FFprobe with FFmpeg first.'
source_file="${1:-}"
if [[ -z "$source_file" ]]; then
  source_file=$(osascript -e 'POSIX path of (choose file with prompt "ImaScreen — choisir le rush / select footage")') || exit 0
fi
[[ -f "$source_file" ]] || fail 'No readable source file selected.'
# Absolute path avoids option injection for files starting with a dash.
source_file="$(cd -- "$(dirname -- "$source_file")" && pwd)/$(basename -- "$source_file")"
mode="${2:-}"
if [[ -z "$mode" ]]; then
  printf '1: Light copy (960 px) / Copie legere\n2: Original dimensions / Definition originale\n'
  read -r -p 'Choice / Choix [1/2]: ' mode
fi
case "$mode" in
  1|proxy) suffix='imascreen-proxy'; filter="scale=w='min(960,iw)':h='min(960,ih)':force_original_aspect_ratio=decrease:force_divisible_by=2,format=yuv420p"; crf=23 ;;
  2|original) suffix='imascreen-compatible'; filter='pad=ceil(iw/2)*2:ceil(ih/2)*2,format=yuv420p'; crf=18 ;;
  *) fail 'Choose 1 / proxy or 2 / original.' ;;
esac
output="${source_file%.*}-${suffix}.mp4"
[[ ! -e "$output" ]] || fail "Output already exists; no file changed: $output"
printf '\nSource: %s\nOutput: %s\nH.264 8-bit 4:2:0, AAC. Original untouched.\n' "$source_file" "$output"
# Reject missing video before creating any output.
source_codec=$(ffprobe -v error -select_streams v:0 -show_entries stream=codec_name -of csv=p=0 "$source_file")
[[ -n "$source_codec" ]] || fail 'No video track found.'
work=$(mktemp -d "$(dirname -- "$source_file")/.imascreen-convert.XXXXXX")
trap 'rm -rf -- "$work"' EXIT
trap 'exit 130' INT TERM
ffmpeg -hide_banner -nostdin -n -i "$source_file" -map 0:v:0 -map '0:a?' -map_metadata 0 \
  -vf "$filter" -c:v libx264 -preset fast -crf "$crf" -pix_fmt yuv420p -fps_mode passthrough \
  -c:a aac -b:a 192k -movflags +faststart "$work/result.mp4"
codec=$(ffprobe -v error -select_streams v:0 -show_entries stream=codec_name -of csv=p=0 "$work/result.mp4")
pixels=$(ffprobe -v error -select_streams v:0 -show_entries stream=pix_fmt -of csv=p=0 "$work/result.mp4")
[[ "$codec" == 'h264' && "$pixels" == 'yuv420p' ]] || fail 'Output validation failed: expected H.264 yuv420p.'
in_audio=$(ffprobe -v error -select_streams a -show_entries stream=index -of csv=p=0 "$source_file" | wc -l | tr -d ' ')
out_audio=$(ffprobe -v error -select_streams a -show_entries stream=index -of csv=p=0 "$work/result.mp4" | wc -l | tr -d ' ')
[[ "$in_audio" == "$out_audio" ]] || fail 'Audio validation failed.'
# Same-directory hard link atomically refuses overwrite, even if a file appeared during encoding.
ln -- "$work/result.mp4" "$output" || fail 'Cannot publish output; no existing file overwritten.'
printf '\nDone / Termine: %s\nImport this MP4 into your ImaScreen project.\n' "$output"
if [[ -t 0 && $# -eq 0 ]]; then read -r -p 'Enter to close / Entree pour fermer: ' _; fi
