#! /bin/bash
# vim: set filetype=sh:

# opt-gif: Recompresses .gif files

# Copyright (C) 2004-2020 by Brian Lindholm.  This file is part of the
# littleutils utility set.
#
# The opt-gif utility is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 3, or (at your option) any later version.
#
# The opt-gif utility is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along with
# the littleutils.  If not, see <https://www.gnu.org/licenses/>.

# get a valid temporary directory and set up traps
TMPWILD=`tempname -w opt-gif_$$` || exit 99
trap 'rm -f ${TMPWILD} ; exit 1' 1 2 3 13 15
trap 'rm -f ${TMPWILD} ; exit 0' 0

# get command-line options
TOUCH=n
VERBOSE=y
while getopts hqt opts
do
  case $opts in
    h) echo 'opt-gif 1.2.3'
       echo 'usage: opt-gif [-h(elp)] [-q(uiet)] [-t(ouch)] GIF_filename ...'
       exit 0 ;;
    q) VERBOSE=n ;;
    t) TOUCH=y ;;
    *) echo 'opt-gif 1.2.3'
       echo 'usage: opt-gif [-h(elp)] [-q(uiet)] [-t(ouch)] GIF_filename ...'
       exit 1 ;;
  esac
done
shift `expr ${OPTIND} - 1`

# run through files
while [ $# -gt 0 ]; do

  # make sure we can read and modify file
  if [ ! -f "$1" -o ! -r "$1" -o ! -w "$1" ]; then
    echo "opt-gif warning: $1 is not a writeable non-directory file"
    shift; continue
  fi

  # make sure it's a GIF
  imagsize "$1" | grep -q 'type=gif'
  OUT="$?"
  if [ "$OUT" -ne 0 ]; then
    echo "opt-gif warning: $1 is not a GIF"
    shift; continue
  fi

  # run through gifsicle
  TMPGIF=`tempname -s .gif opt-gif_$$` || exit 99
  gifsicle --careful -O3 --no-warnings < "$1" > ${TMPGIF}

  # ensure that new file is smaller
  if [ "$TOUCH" = 'y' ]; then
    touch -r "$1" ${TMPGIF}
  fi
  S0=`filesize "$1"`
  S1=`filesize "$TMPGIF"`
  if [ "$S1" -lt "$S0" ]; then
    cp --preserve=timestamps ${TMPGIF} "$1"
    if [ "$VERBOSE" = 'y' ]; then
      echo "$1: ${S0} vs. ${S1}"
    fi
  else
    if [ "$VERBOSE" = 'y' ]; then
      echo "$1: unchanged"
    fi
  fi

  # clean up afterwards
  rm -f ${TMPGIF}
  shift

done
rm -f ${TMPWILD}
