#!/bin/bash

usage="
Usage: $0 <input_file.gif>
"

exists() { which "$1" &> /dev/null ; }

if ! exists convert ; then
    echo "ImageMagick is required (hint: sudo apt-get install imagemagick)!" 1>&2;
    exit 1;
fi

if ! exists avconv ; then
    echo "AVConv is required (hint: sudo apt-get install libav-tools)!" 1>&2;
    exit 1;
fi

if [ ! -e "$1" ]; then
    echo "File '$1' does not exist!";
    echo $usage;
    exit
fi

GIF="$1"
IMGMASK="${GIF/.gif/-%04d.png}";

TMPDIR=$(mktemp -d);
trap 'rm -rf "$TMPDIR"' EXIT INT QUIT TERM;

echo -n "splitting GIF into frames...";
convert -coalesce "$GIF" "$TMPDIR/$IMGMASK";
echo " done!";

echo -n "combining frames into video...";
avconv -f image2 -i "$TMPDIR/$IMGMASK" $TMPDIR/intermediate.mp4 &> /dev/null;
echo " done!";

echo -n "converting video to Android format...";
avconv -i $TMPDIR/intermediate.mp4 -y -s qcif -vcodec h263 -r 10 -b 180k "${GIF/.gif/.3gp}" &> /dev/null;
echo " done!";
