#!/bin/bash

trap 'rc=$? ; rm -f /tmp/*.$$ ; exit "${rc}"' 0 1 2 3 13 15

# --- options ---------------------------------------------------------------
#   --all, -a   extract subtitle tracks in every language
#   (default)    English tracks only
#   -h, --help  show usage and exit

lang_mode="eng"
input=""
while [ "$#" -gt 0 ]
do
	case "${1}" in
		--all|-a)
			lang_mode="all"
		;;
		-h|--help)
			printf 'usage: extractsubs [--all|-a] <media-file>\n  (default: English tracks only)\n' >&2
			exit 0
		;;
		-*)
			printf 'unknown option: %s\n' "${1}" >&2
			exit 1
		;;
		*)
			[ -z "${input}" ] && input="${1}"
		;;
	esac
	shift
done

if [ -z "${input}" ]
then
	printf 'usage: extractsubs [--all|-a] <media-file>\n  (default: English tracks only)\n' >&2
	exit 1
fi

# --- dependency checks ------------------------------------------------------
# ffprobe, ffmpeg and sup2vob must all be on PATH, and the ffmpeg build must
# include muxers for every extension stage 2 can write ("sup" is the one
# minimal builds strip). Check up front so a missing or broken tool prints a
# clear message and exits 1 instead of failing per track mid-pipeline.
# (--help has already exited, so these run only for real jobs.)

die()
{
	printf 'extractsubs: %s\n' "${1}" >&2
	exit 1
}

missing=()
for tool in ffprobe ffmpeg sup2vob
do
	command -v "${tool}" >/dev/null 2>&1 || missing+=("${tool}")
done
if [ "${#missing[@]}" -gt 0 ]
then
	printf 'extractsubs: missing dependency on PATH: %s\n' "${missing[*]}" >&2
	for tool in "${missing[@]}"
	do
		case "${tool}" in
			ffprobe)
				printf '  ffprobe ships with ffmpeg: e.g. brew install ffmpeg\n' >&2
			;;
			ffmpeg)
				printf '  e.g. brew install ffmpeg\n' >&2
			;;
			sup2vob)
				printf '  build and install it from sup2vob/: make && sudo make install\n' >&2
			;;
		esac
	done
	exit 1
fi

# Found on PATH is not enough — a broken install (bad arch, half-updated
# Homebrew) must fail here too, so give each tool a cheap smoke run.

ffprobe -version >/dev/null 2>&1 || die "ffprobe is on PATH but does not run (ffprobe -version failed)"
ffmpeg -version >/dev/null 2>&1 || die "ffmpeg is on PATH but does not run (ffmpeg -version failed)"
sup2vob --help >/dev/null 2>&1 || die "sup2vob is on PATH but does not run (sup2vob --help failed)"

# Feature check: ffmpeg must be able to mux every format stage 2 can write —
# "sup" for pgs, "srt", "ass" and "webvtt" for text. There is no "ssa" muxer
# to check: the "ass" muxer declares extensions "ass,ssa" (assenc.c
# .p.extensions — :241 in the subs/ffmpeg master clone, :234 in old 4.2.4)
# and picks SSA mode from the extradata, so .ssa rides on ass.
# (ttf/otf/unknown_type have never had a muxer and still fail per-track as
# before.) In the "ffmpeg -muxers" list the flag column reads D/E/d — E means
# muxing supported — and the format name follows it; -h muxer=x cannot be
# used because it exits 0 even for unknown names.

muxout=$( ffmpeg -hide_banner -muxers 2>/dev/null )
muxfail=()
for muxer in sup srt ass webvtt
do
	printf '%s\n' "${muxout}" | awk -v m="${muxer}" \
		'$1 ~ /E/ && $2 == m { found = 1 } END { exit !found }' \
		|| muxfail+=("${muxer}")
done
if [ "${#muxfail[@]}" -gt 0 ]
then
	die "this ffmpeg build cannot write: ${muxfail[*]} (needs muxers sup/srt/ass/webvtt; .ssa rides on ass)"
fi

ffprobe "${input}"  2>&1 | grep Stream | grep "Subtitle:" | while read line
do
	# The "Stream #0:3(eng):" prefix carries the track number and, when present,
	# the language code in parentheses. Tracks without a language code get "und"
	# (undetermined), e.g. "Stream #0:2: Subtitle: ass (ssa)".

	idpart=$( echo "${line}" | cut -f 2 -d ':' )
	tracknum=$( echo "${idpart}" | egrep -o "^[0-9]+" )
	lang=$( echo "${idpart}" | sed -n 's/.*(\([^)]*\)).*/\1/p' )
	[ -z "${lang}" ] && lang="und"
	type=$( echo "${line}" | awk '{ print $4;}' )

	case "${type}"
	in
		"hdmv_pgs_subtitle" | "hdmv_pgs_subtitle,")
			ext="sup"
		;;
		"subrip")
			ext="srt"
		;;
		"dvd_subtitle" | "dvd_subtitle,")
			ext="sub"
		;;
		"ass")
			ext="ass"
		;;
		"ssa")
			ext="ssa"
		;;
		"webvtt" | "webvtt,")
			ext="vtt"
		;;
		"ttf")
			ext="ttf"
		;;
		"otf")
			ext="otf"
		;;
		*)
			ext="unknown_type"
		;;
	esac

    # English tracks only by default; --all emits every language. "en" and "eng"
    # are both the English code (2- vs 3-letter forms, e.g. DVD vs Blu-ray).

    if [ "${lang_mode}" = "all" ] || [ "${lang}" = "eng" ] || [ "${lang}" = "en" ]
    then
        # Descriptive tags such as "hearing impaired", "comment", or "forced"
        # appear in parentheses after the codec's own extra-info paren (e.g.
        # "(pgssub)" or "(srt)"). Collect every tag after that first paren,
        # lowercase them and squash spaces/'.'/'-' to "_", then map the whole
        # set onto ONE short type token in the importer's closed set
        # (sdh, cc, commentary, lyrics, forced), trying its priority order
        # SDH > CC > Commentary > Lyrics > Forced. Tags that match nothing
        # ("default", a bare "caption"/"subtitle", unknown flags) emit no
        # type token — the track imports unnamed, which is what the importer
        # does with an unrecognized token anyway. The bucket patterns cover
        # the importer's own token table ("visual impaired" rides the
        # impaired pattern into sdh, matching its bare-"impaired" row) plus
        # ffprobe's flag spellings: its "comment" flag (the MKV comment
        # flag) means commentary, and the importer knows "commentary" but
        # not "comment".

        tags=$( printf '%s' "${line}" | sed 's/.*: Subtitle: *//' \
            | grep -oE '\([^)]+\)' | sed '1d; s/[()]//g' | paste -sd' ' - \
            | tr '[:upper:]' '[:lower:]' | tr ' .-' '_' )

        subtype=""
        case "_${tags}_" in
            *_sdh_* | *_impaired_* | *_deaf_* | *_hearingimpaired_*)
                subtype="sdh"
            ;;
            *_cc_* | *_closed_caption_* | *_closed_captions_* \
            | *_closedcaption_* | *_closedcaptions_*)
                subtype="cc"
            ;;
            *_commentary_* | *_commentaries_* | *_comment_*)
                subtype="commentary"
            ;;
            *_lyrics_* | *_lyric_*)
                subtype="lyrics"
            ;;
            *_forced_*)
                subtype="forced"
            ;;
        esac

        # Naming shape the importer probes: language LAST (right before the
        # extension — the position it scans first, right-to-left) and the
        # short type token immediately before it, as its own dot-separated
        # token, with the extension still trailing both:
        #   <basename>.<tracknum>[.<type>].<lang>.<ext>  e.g. Movie.mkv.3.sdh.eng.sup

        outname="$( basename "${input}" ).${tracknum}"
        [ -n "${subtype}" ] && outname="${outname}.${subtype}"
        outname="${outname}.${lang}.${ext}"
        # Temp line format: <tracknum>:<tool>:<outname>; <tool> is "ff"
        # (extract with ffmpeg) or "mkv" (extract with mkvextract, where
        # <tracknum> is then the MKV track *ID* mkvextract wants, not the
        # ffprobe index). Split with %%:* / #*: — never with cut/word
        # splitting, the name may contain spaces.
        echo "${tracknum}:ff:${outname}"
    fi
done > /tmp/extractsubs.$$

# --- unrecognized-codec WebVTT rescue ----------------------------------------
# WebVTT-in-MKV exists under two codec IDs: the WebM-profile "D_WEBVTT/*"
# (which ffprobe reports as type "webvtt" and ffmpeg copies fine — handled
# above), and the current Matroska-spec "S_TEXT/WEBVTT" that recent
# mkvtoolnix writes. ffmpeg 9.1 and the master clone map ONLY D_WEBVTT/*
# (matroska.c has no S_TEXT/WEBVTT entry), so such a track shows up as
# "Subtitle: none" -> unknown_type here, and ffmpeg emits no packets for it
# at all — no extension or mapping change can make the ffmpeg path work.
# If mkvtoolnix is available, ask mkvmerge which unrecognized tracks really
# are WebVTT and route those to mkvextract (it reconstructs the "WEBVTT"
# header from the track's CodecPrivate).
#
# Mapping between the two tools: ffprobe's "#0:N" index is the track's
# position in the file (0-based); mkvmerge's properties."number" is the same
# position (1-based), while its "id" is the raw TrackNumber mkvextract
# selects by — the two coincide only when IDs are sequential.

if grep -q '\.unknown_type$' /tmp/extractsubs.$$
then
	if command -v mkvmerge >/dev/null 2>&1 && command -v mkvextract >/dev/null 2>&1 \
		&& command -v python3 >/dev/null 2>&1
	then
		vttmap=$( mkvmerge -J "${input}" 2>/dev/null | python3 -c '
import json, sys
try:
	info = json.load(sys.stdin)
except Exception:
	sys.exit(1)
for t in info.get("tracks", []):
	cid = t.get("properties", {}).get("codec_id", "")
	if t.get("type") == "subtitles" and "WEBVTT" in cid.upper():
		print(t["properties"]["number"], t["id"])' )
		if [ -n "${vttmap}" ]
		then
			newlist="/tmp/extractsubs.new.$$"
			while IFS= read -r line
			do
				case "${line}" in
					*.unknown_type)
						tracknum="${line%%:*}"
						outname="${line#*:}"; outname="${outname#*:}"
						mkvid=$( printf '%s\n' "${vttmap}" | awk \
							-v n=$(( tracknum + 1 )) '$1 == n { print $2 }' )
						if [ -n "${mkvid}" ]
						then
							outname="${outname%.unknown_type}.vtt"
							line="${mkvid}:mkv:${outname}"
							printf 'track %s is WebVTT (ffmpeg cannot read its codec id); extracting via mkvextract\n' \
								"${tracknum}" >&2
						fi
					;;
				esac
				printf '%s\n' "${line}"
			done < /tmp/extractsubs.$$ > "${newlist}"
			mv "${newlist}" /tmp/extractsubs.$$
		fi
	else
		printf 'extractsubs: unrecognized subtitle codec(s); install mkvtoolnix and python3 to check whether they are WebVTT\n' >&2
	fi
fi

# Read the temp file one line at a time into an array, then split each entry
# with parameter expansion (no word-splitting of the whole list). That is what
# lets the output filename match the input, spaces included.

subargs=()
while IFS= read -r line
do
	subargs+=("${line}")
done < /tmp/extractsubs.$$

# Extract the selected tracks with ffmpeg's stream copy in ONE invocation.
# "0:N" maps the same global stream index ffprobe reported in the "Stream #0:N"
# prefix, so the track numbers line up without translation, and "-c copy"
# writes each track bit-for-bit (no re-encode) into whatever the output
# extension promises. Repeating "-map ... -c copy <out>" adds another output
# file, and ffmpeg demuxes the input once for all of them — the old one-call-
# per-track loop reopened and re-read the whole file each time. Outputs are
# byte-identical either way (verified with cmp on a four-PGS-track remux);
# measured 3.5 s combined vs 13.6 s per-track. The trade is failure isolation:
# if one output cannot initialize, ffmpeg aborts all of them — so the
# per-track loop remains as a retry path.

if [ "${#subargs[@]}" -gt 0 ]
then
	ffargs=( -nostdin -hide_banner -loglevel error -y -i "${input}" )
	selected=()
	for trackfile in "${subargs[@]}"
	do
		tracknum="${trackfile%%:*}"
		rest="${trackfile#*:}"
		tool="${rest%%:*}"
		outname="${rest#*:}"

		# FFmpeg has no VobSub muxer, so dvd_subtitle tracks cannot be written
		# as .sub; say so and carry on with the remaining tracks.

		case "${outname}" in
			*.sub)
				printf 'skipping track %s (%s): ffmpeg cannot write VobSub .sub\n' \
					"${tracknum}" "${outname}" >&2
				continue
			;;
		esac

		# S_TEXT/WEBVTT tracks (see the rescue pass above): ffmpeg cannot even
		# demux them, so run mkvextract per track right away instead of adding
		# them to the combined call. "tracks <ID>:<out>" selects by raw MKV
		# track ID, which is what <tracknum> holds for these lines.

		if [ "${tool}" = "mkv" ]
		then
			printf 'extracting track %s as %s (mkvextract)\n' "${tracknum}" "${outname}" >&2
			mkvextract -q "${input}" tracks "${tracknum}:${outname}" \
				|| printf 'failed to extract track %s (%s)\n' \
					"${tracknum}" "${outname}" >&2
			continue
		fi

		printf 'extracting track %s as %s\n' "${tracknum}" "${outname}" >&2
		ffargs+=( -map "0:${tracknum}" -c copy "${outname}" )
		selected+=( "${trackfile}" )
	done

	if [ "${#selected[@]}" -gt 0 ] && ! ffmpeg "${ffargs[@]}"
	then
		printf 'combined extraction failed; retrying one track at a time\n' >&2
		for trackfile in "${selected[@]}"
		do
			tracknum="${trackfile%%:*}"
			outname="${trackfile#*:}"; outname="${outname#*:}"
			ffmpeg -nostdin -hide_banner -loglevel error -y \
				-i "${input}" -map "0:${tracknum}" -c copy "${outname}" \
				|| printf 'failed to extract track %s (%s)\n' \
					"${tracknum}" "${outname}" >&2
		done
	fi
fi

# Convert every extracted .sup into a .sub with BDSup2Sub. (Temp lines are
# <tracknum>:<tool>:<outname>, so the name starts at field 3.)
cat /tmp/extractsubs.$$ | egrep "\.sup$" | cut -f 3- -d ':' | while IFS= read -r supfile
do
	[ -z "${supfile}" ] && continue
	sup2vob --full "${supfile}"
done
