#!/usr/bin/env sh
#
# resize-video - create new video resized by the specified amount
# dependencies: ffmpeg
#
# variables:
#   $1: path to the original video file
#   $2: resolution (default is '1920:1080')
#   $3: start time (default is '00:00:00')
#   $4: constant rate factor (default is '25')
#
# usage: resize-video ./path/to/video.mp4 "1080:1920" "00:00:01.500" "23"

if ! command -v ffmpeg >/dev/null 2>&1; then
  printf '%s' "${0##*/}: ffmpeg not found in PATH!\n" >&2
  exit 1
fi
set -x
# check if the file is a video file
mime="$(file -L -i -- "$1" | cut -d'/' -f 1)"

if ! echo "${mime}" | grep -q ':.*video'; then
  printf "'%s' is not a video file.\n" "$1"
  exit 1
fi

filename="$(basename "$1")"
filepath="$(dirname "${1%/}")"
scale="${2:-1920:1080}"
starttime=${3:-00:00:00}
crf=${4:-25}

outputfilename="${filepath}/_${filename%.*}.mp4"

# options used below try to offer a good balance between:
# cross-platform interoperability, quality, and file size
ffmpeg \
  -i "$1" \
  -ss "${starttime}" \
  -acodec aac \
  -ac 2 \
  -strict -2 \
  -crf "${crf}" \
  -nostdin \
  -preset veryslow \
  -vcodec libx264 \
  -vf "scale=${scale},setsar=1,format=yuv420p" \
  -y \
  "${outputfilename}" \
  && printf "* %s / %s / %s\n" \
    "${outputfilename}" \
    "${scale}" \
    "${starttime}"
