#!/bin/bash
# Convert videos browsers can't play (.mkv, .avi, .wmv, .flv, .mov) into .mp4
# (H.264 video + AAC audio) that opens and plays inline in any web browser.
#
# Your original files are left untouched -- a new .mp4 is written next to each.
#
# Requires ffmpeg:   sudo apt install ffmpeg
#
# Usage:
#   ./convert-to-mp4.sh                    # convert videos in the current folder
#   ./convert-to-mp4.sh stuff/uploads      # convert videos in a given folder
#   ./convert-to-mp4.sh movie.mkv clip.avi # convert specific files
#
# Tip: after converting, drop the .mp4 files into your shared folder and they'll
# open in the browser like your other videos.

set -u

if ! command -v ffmpeg >/dev/null 2>&1; then
  echo "ffmpeg is not installed. Install it first with:  sudo apt install ffmpeg"
  exit 1
fi

# No arguments -> act on the current directory.
[ "$#" -eq 0 ] && set -- .

# Collect the files to convert (directories are scanned one level deep).
targets=()
for arg in "$@"; do
  if [ -d "$arg" ]; then
    while IFS= read -r -d '' f; do targets+=("$f"); done < <(
      find "$arg" -maxdepth 1 -type f \
        \( -iname '*.mkv' -o -iname '*.avi' -o -iname '*.wmv' \
           -o -iname '*.flv' -o -iname '*.mov' \) -print0
    )
  elif [ -f "$arg" ]; then
    targets+=("$arg")
  else
    echo "not found, skipping: $arg"
  fi
done

if [ "${#targets[@]}" -eq 0 ]; then
  echo "No .mkv/.avi/.wmv/.flv/.mov files found."
  exit 0
fi

converted=0
for src in "${targets[@]}"; do
  out="${src%.*}.mp4"
  if [ -e "$out" ]; then
    echo "skip (mp4 already exists): $out"
    continue
  fi
  echo "converting: $src"
  # -movflags +faststart puts the index at the front so playback can start
  # before the whole file has loaded (important for streaming from the server).
  if ffmpeg -hide_banner -loglevel error -stats -i "$src" \
       -c:v libx264 -preset slow -crf 20 \
       -c:a aac -b:a 160k \
       -movflags +faststart \
       "$out"; then
    echo "  -> $out"
    converted=$((converted + 1))
  else
    echo "  FAILED (left original in place): $src"
    rm -f "$out"   # remove any half-written output
  fi
done

echo "Done. Converted $converted file(s)."
