#!/bin/bash
#
# From :
# https://gist.github.com/kowalcj0/ae0bdc43018e2718fb75290079b8839a

# Can be improve to call ffmpeg only one time :
# https://gist.github.com/kowalcj0/ae0bdc43018e2718fb75290079b8839a?permalink_comment_id=4187491#gistcomment-4187491

function subs() {
    movie="${1}"
    filename="${1%.*}"
    mappings=`ffprobe -loglevel error -select_streams s -show_entries stream=index:stream_tags=language -of csv=p=0 "${movie}"`
    OLDIFS=$IFS
    IFS=,
    ( while read -r idx lang
    do
        echo "Exctracting ${lang} subtitle #${idx} from ${movie}"
        ffmpeg -nostdin -hide_banner -loglevel quiet -i "${movie}" -map 0:"$idx" "${filename}_${lang}_${idx}.srt"
    done <<< "${mappings}" )
    IFS=$OLDIFS
}

subs "${1}"