#!/bin/sh

help() {
  echo "`color 2 Usage:` to-gif <file> [fps] [scale] [duration] [start_at]"
  echo ""
  echo "`color 2 Options:`"
  echo "    `color 3 file`      File to convert to gif. Required."
  echo "    `color 3 fps`       Defaults to 15."
  echo "    `color 3 scale`     GIF resolution. Defaults to 1."
  echo "    `color 3 duration`  How long the gif will be, in seconds. Defaults to 999999."
  echo "    `color 3 start_at`  Where the video starts, in seconds. Defaults to 0"
}

FILE=$1
FPS=$2
SCALE=$3
DURATION=$4
START_AT=$5

if [[ "$FILE" ]]
then

  if ! [[ "$FPS" ]]; then FPS=15; fi
  if ! [[ "$SCALE" ]]; then SCALE=1; fi
  if ! [[ "$DURATION" ]]; then DURATION=999999; fi
  if ! [[ "$START_AT" ]]; then START_AT=0; fi

  PALETTE=palette-rp7w8zsw2dx83dsxrgqmt6f5.png

  echo "Generate a palette:"
  ffmpeg -y -ss $START_AT -t $DURATION -i $FILE -vf fps=$FPS,scale=w=${SCALE}*iw:h=${SCALE}*ih:-1:flags=lanczos,palettegen ${PALETTE}

  echo "Output the GIF using the palette:"
  ffmpeg -ss $START_AT -t $DURATION -i $FILE -i ${PALETTE} -filter_complex "fps=${FPS},scale=w=${SCALE}*iw:h=${SCALE}*ih:flags=lanczos[x];[x][1:v]paletteuse" ${FILE%.*}.gif

  rm -f ${PALETTE}

else
  help
fi
