#!/bin/bash

# Get the MKV file path as the first argument
mkv_file="$1"

# Check if the file exists
if [ ! -f "$mkv_file" ]; then
  echo "Error: File '$mkv_file' does not exist."
  exit 1
fi

# Use ffprobe to identify subtitle tracks
tracks=$(ffprobe -v error -select_streams s -show_entries stream=index:stream_tags=language:stream_tags=title -of csv=p=0 "$mkv_file" | grep -E ',(eng)')
echo tracks
# Extract each track to a separate SRT file
while read -r index language title; do
  # Remove quotes and commas
  index="${index#\"}" index="${index%\"}"
  language="${language#\"}" language="${language%\"}"
  title="${title#\"}" title="${title%\"}"

  # Create output filename based on language or title
  output_file="$mkv_file.($language${title:+ - $title}).srt"

  # Extract subtitle track using ffmpeg
  ffmpeg -y -vn -an -map 0:$index -c copy "$mkv_file" -codec:s srt "$output_file" &> /dev/null

  echo "Extracted subtitle track $index (language: $language, title: $title) to '$output_file'"
done <<< "$tracks"

echo "All subtitle tracks extracted successfully."
