#!/bin/bash
# Recursively finds and compresses video files to AV1/MP4 format with reduced quality/size.
# Converts to 1080p max, reduces high framerates, and uses low bitrate audio.
# Original files are removed after successful compression.

# Set IFS to newline only to properly handle filenames with spaces
# Disable globbing with set -f to prevent special character interpretation
IFS=$'\n'; set -f

# Set up trap to handle Ctrl+C (SIGINT) gracefully
# This ensures clean exit when user interrupts script execution
trap "exit" INT

for f in $(find $PWD \( -iname '*.mp4' -or -iname '*.mkv' -or -iname '*.avi' -or -iname '*.wmv' -or -iname '*.mov' -or -iname '*.m4v' -or -iname '*.ts' -or -iname '*flv' -or -iname '*mpg' \) -and -not -name '*.cmp.*' | sort --reverse); do
  if grep -q "\.cmp\." <<< "$f"; then
    echo -e "\033[0;32mSkipping\033[0m $f, already compressed"
  else
    if grep -q "\.wip\." <<< "$f"; then
      echo -e "\033[0;31mRemoving unfinished conversion file:\033[0m $f"
      rm $f
    else
      if [ ! -f ${f%.*}.cmp.mp4 ]; then
        ffmpeg -y -i $f -vf "fps='if(gte(source_fps,100),source_fps/4,if(gte(source_fps,50),source_fps/2,source_fps))',scale=-2:'min(1080,ih)'" -c:v libsvtav1 -crf 40 -c:a aac -b:a 64k ${f%.*}.wip.mp4 \
          && mv "${f%.*}.wip.mp4" "${f%.*}.cmp.mp4" && rm $f
      else
        echo -e "\033[0;34mRemoving\033[0m $f, already compressed"
        rm $f
      fi
      rm -f "${f%.*}.wip.mp4"
    fi
  fi
done

unset IFS; set +f
