#!/bin/sh

set -eu
set -o xtrace

# if ffmpeg is not installed, exit with an error message
if ! command -v ffmpeg >/dev/null 2>&1; then
  printf "Can't find ffmpeg. Please install it (or check your path).\n"
  exit 1
fi

makeGIF() {
  input=$1
  framerate=$2
  width=$3
  basename=$4
  maxColors=$5

  # GIFs of 60fps videos have to be 50fps
  if [ "${framerate}" = "60" ]; then
    framerate=50
  fi

  if [ "${maxColors}" = "" ]; then
    maxColors=256
  fi

  ffmpeg \
    -i "${input}" \
    -framerate "${framerate}" \
    -vf "fps=${framerate},scale=${width}:-1:flags=lanczos,split[s0][s1];[s0]palettegen=max_colors=${maxColors}[p];[s1][p]paletteuse" \
    "${basename}.gif"
}

makeMP4() {
  input=$1
  framerate=$2
  width=$3
  basename=$4

  ffmpeg \
    -i "${input}" \
    -framerate "${framerate}" \
    -vcodec libx264 \
    -pix_fmt yuv420p \
    -an \
    -crf 20 \
    -filter:v scale="${width}":-1 \
    "${basename}.mp4"
}

makeWebM() {
  input=$1
  framerate=$2
  width=$3
  basename=$4

  ffmpeg \
    -i "${input}" \
    -framerate "${framerate}" \
    -pix_fmt yuv420p \
    -an \
    -crf 30 \
    -b:v 0 \
    -filter:v scale="${width}":-1 \
    "${basename}.webm"
}

requirePositiveInt() {
  # if [ ! "$2" =~ ^[0-9]+$ ]; then
  if ! echo "$2" | grep -q -P -- "^[0-9]+$"; then
    printf "%s must be a positive integer.\n" "$1"
    exit 1
  fi
}

input="$(gum file --header "Input")"
if [ ! -f "${input}" ]; then
  printf "Input file '%s' does not exist.\n" "${input}"
  exit 1
fi

outputBase="$(gum input --header "Output base name" --value="$(basename "${input%.*}")")"
if [ -z "${outputBase}" ]; then
  printf "Output base name cannot be empty.\n"
  exit 1
fi

framerate="$(gum input --header "Framerate" --value="24")"
requirePositiveInt "Framerate" "${framerate}"

width="$(gum input --header "Width" --value="1920")"
requirePositiveInt "Width" "${width}"

type="$(gum choose --header "Output type" "gif" "mp4" "webm")"
if [ -z "${type}" ]; then
  printf '%s\n' "$(basename "$0") [gif | mp4 | webm]"
  printf "No output type selected.\n"
  exit 1
fi

maxColors=""
if [ "${type}" = "gif" ]; then
  maxColors="$(gum input --header "Max GIF colors" --value="256")"
  # if [ ! "${maxColors}" =~ ^[0-9]+$ ]; then
  if ! echo "${maxColors}" | grep -q -P -- "^[0-9]+$"; then
    printf "Max GIF colors must be a positive integer.\n"
    exit 1
  fi
fi

case ${type} in
  gif)
    makeGIF "${input}" "${framerate}" "${width}" "${outputBase}" "${maxColors}"
    ;;
  mp4)
    makeMP4 "${input}" "${framerate}" "${width}" "${outputBase}"
    ;;
  webm)
    makeWebM "${input}" "${framerate}" "${width}" "${outputBase}"
    ;;
  *)
    printf "Unknown output type '%s'.\n" "${type}"
    exit 1
    ;;
esac

{ set +o xtrace; } 2>/dev/null
