#!/bin/sh -e
#
# gifify - convert a video to gif
# dependencies: ffmpeg | gifsicle (optional)

if [ -z "$1" ] || [ ! -f "$1" ]; then
  printf "Usage: %s <media file>\n" "${0##*/}" >&2
  exit 1
fi

if command -v gifsicle >/dev/null 2>&1; then
  if [ -n "$1" ]; then
    if [ "$2" = "--good" ]; then
      ffmpeg -i "$1" -r 10 -vcodec png out-static-%05d.png
      command time convert -verbose +dither -layers Optimize \
        -resize 600x600\> out-static*.png GIF:- | gifsicle \
        --colors 128 --delay=5 --loop --optimize=3 --multifile - >"$1".gif
      rm out-static*.png
    else
      ffmpeg -i "$1" -s 600x400 -pix_fmt rgb24 -r 10 -f gif - \
        | gifsicle --optimize=3 --delay=3 >"$1".gif
    fi
  else
    printf "%s: [input_movie.mov]. You DO need to include extension.\n" "${0##*/}"
  fi
else
  ffmpeg -i "$1" \
    -filter_complex "[0:v] fps=10,scale=720:-1,split [a][b];[a] palettegen [p];[b][p] paletteuse" \
    output.gif
fi
