#!/usr/bin/env bash
#
# This script is intended for provide a "sane" video conversion and
# recompression. It is useful for recompressing high quality video taken with a
# camera so less storage is taken.
#
# Note: This does not delete the original.
#
# Requirements:
#   ffmpeg
#   libtheora

new_ext="ogv"

if [[ -z $1 ]]; then
  echo "Please specify a file to compress"
  exit 1
fi

orig="${1}"
ext_index=""

# Note that we're going backwards (right to left) here so we don't stop early
# on filenames with multiple periods in their name.
for (( i=${#orig}; i>0; i-- )); do
  if [[ ${orig:$i:1} == "." ]]; then
    # Set where the extension starts so we know what to replace for the new
    # extension
    ext_index=$i
    break
  fi
done

# Exit of an extension couldn't be determined
if [[ ${ext_index} == "" ]]; then
  echo "Fatal Error: Filename could not be determined for file ${orig}."
  exit 1
fi

# Set the new filename for output
# TODO: Make the extension a little less hard coded
new=${orig:0:$ext_index}.${new_ext}

echo -e "\bBeginning recompression of ${orig}...."
# Assume theora/vorbis for now
ffmpeg -i "${orig}"  -loglevel error -codec:a libvorbis -codec:v libtheora -qscale:a 7 -qscale:v 7 "${new}"