#!/bin/bash -e
#
# mkv-convert - convert `.mkv` video files to other formats - mp4, webm, ogg
# dependencies: ffmpeg

if ! command -v ffmpeg >/dev/null 2>&1; then
  echo "ffmpeg is not installed. Please install ffmpeg to use this script."
  exit 1
fi

# check if input is a .mkv file
if [ "$#" -eq 0 ]; then
  echo "Error: Please provide a .mkv file as argument"
  printf 'Usage: %s <input.mkv>\n' "$(basename "$0")" >&2
  exit 1
fi

INPUT_FILE="$1"

# make sure file actually exists and is the right format, .mkv
if [ ! -f "${INPUT_FILE}" ] || [ "${INPUT_FILE##*.}" != "mkv" ]; then
  echo "Error: '${INPUT_FILE}' is not a valid .mkv file"
  exit 1
fi

printf "Enter the desired output base name: "
read -r OUTPUT_BASENAME

# convert to MP4 (H.264 + AAC)
ffmpeg -i "${INPUT_FILE}" -c:v libx264 -crf 23 -preset slow -c:a aac -b:a 128k \
  "${OUTPUT_BASENAME}.mp4"

# convert to WebM (VP9 + Opus)
ffmpeg -i "${INPUT_FILE}" -c:v libvpx-vp9 -b:v 1M -c:a libopus \
  "${OUTPUT_BASENAME}.webm"

# convert to Ogg (Theora + Vorbis)
ffmpeg -i "${INPUT_FILE}" -c:v libtheora -q:v 7 -c:a libvorbis -q:a 5 \
  "${OUTPUT_BASENAME}.ogv"

# check that all the output files exist before announcing your success
if [ -f "${OUTPUT_BASENAME}.mp4" ] && [ -f "${OUTPUT_BASENAME}.webm" ] \
  && [ -f "${OUTPUT_BASENAME}.ogv" ]; then
  echo "Conversion complete! Files generated:"
  echo "${OUTPUT_BASENAME}.mp4"
  echo "${OUTPUT_BASENAME}.webm"
  echo "${OUTPUT_BASENAME}.ogv"
else
  echo "Error: Some output files are missing!"
  [ ! -f "${OUTPUT_BASENAME}.mp4" ] && echo "Missing: ${OUTPUT_BASENAME}.mp4"
  [ ! -f "${OUTPUT_BASENAME}.webm" ] && echo "Missing: ${OUTPUT_BASENAME}.webm"
  [ ! -f "${OUTPUT_BASENAME}.ogv" ] && echo "Missing: ${OUTPUT_BASENAME}.ogv"
  exit 1
fi
