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

# rot-jpg: Losslessly rotate JPEG files

# Copyright (C) 2019 by Brian Lindholm.  This file is part of the littleutils
# utility set.
#
# The rot-jpg 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 rot-jpg 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 rot-jpg_$$` || exit 99
trap 'rm -f ${TMPWILD} ; exit 1' 1 2 3 13 15
trap 'rm -f ${TMPWILD} ; exit 0' 0

# get command-line options
DIRECTION='none'
OPTIMIZE=y
TOUCH=n
VERBOSE=y
while getopts fhlqrtu opts
do
  case $opts in
    f) OPTIMIZE=n ;;
    h) echo 'rot-jpg 1.2.3'
       echo 'usage: rot-jpg [-f(ast)] [-h(elp)] [-l(eft)] [-q(uiet)] [-r(ight)]'
       echo '               [-t(ouch)] [-u(pside-down)] JPEG_filename ...'
       exit 0 ;;
    l) DIRECTION='left' ;;
    q) VERBOSE=n ;;
    r) DIRECTION='right' ;;
    t) TOUCH=y ;;
    u) DIRECTION='upsidedown' ;;
    *) echo 'rot-jpg 1.2.3'
       echo 'usage: rot-jpg [-l(eft)] [-h(elp)] [-o(ptimize)] [-q(uiet)]'
       echo '               [-r(ight)] [-t(ouch)] [-u(pside-down)]'
       echo '               JPEG_filename ...'
       exit 1 ;;
  esac
done
shift `expr ${OPTIND} - 1`
if [ "X$DIRECTION" = 'Xnone' ]; then
  echo 'rot-jpg error: direction not specified; use -l, -r, or -u option'
  exit 1
fi

# 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 "rot-jpg warning: $1 is not a writeable non-directory file"
    shift; continue
  fi

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

  # run through jpegtram
  TMPJPG=`tempname -s .gif rot-jpg_$$` || exit 99
  if [ "X$DIRECTION" = 'Xleft' ]; then
    jpegtran -trim -rotate 270 "$1" > ${TMPJPG}
  elif [ "X$DIRECTION" = 'Xright' ]; then
    jpegtran -trim -rotate 90 "$1" > ${TMPJPG}
  else
    jpegtran -trim -rotate 180 "$1" > ${TMPJPG}
  fi

  # optimize image to minimize filesize
  if [ "$OPTIMIZE" = 'y' ]; then
    opt-jpg -q ${TMPJPG}
  fi

  # copy back to original filename
  if [ "$TOUCH" = 'y' ]; then
    touch -r "$1" ${TMPJPG}
    cp --preserve=timestamps ${TMPJPG} "$1"
  else
    cp ${TMPJPG} "$1"
  fi

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

done
rm -f ${TMPWILD}
