#!/bin/sh
if test $# != 2; then
  exit Usage: $0 '##|v|h' file.jpg
fi

function notify() {
  konq=`dcop konqueror-\*`
  for k in $konq; do
    notify=`dcop $k KDirNotify-\*`
    for n in $notify; do
      dcop $k $n FilesChanged [ "$1" ]  # $1 must be a url
    done
  done
}

function die() {
  echo "$@"; exit 1
}

case $1 in
[1-8]|+[1-8]) o=$1 ;;
90|[+-]90) o=+6 ;;  # Use + for all these
270|[+-]270) o=+8 ;;
180|[+-]180) o=+3 ;;
v|-v) o=+4 ;;
h|-h) o=+2 ;;
*) die cannot understand transformation "$1" ;;
esac

case "$2" in
/*) url=file:"$2" ;;
*) url=file:"$PWD"/"$2" ;;
 esac

if orient.py $o "$2" | grep 'orientation changed' >/dev/null 2>&1; then
  notify "$url"
  exit 0
fi

### try jpegtran instead
if which jpegtran-mmx >/dev/null 2>&1; then
  JPEGTRAN=jpegtran-mmx
else
  if which jpegtran >/dev/null 2>&1; then
    JPEGTRAN=jpegtran
  else
    die could not change orientation
  fi
fi

case $1 in
v|-v) c='-flip vertical' ;;
h|-h) c='-flip horizontal' ;;
*90) c='-rotate 90' ;;
*180) c='-rotate 180' ;;
*270) c='-rotate 270' ;;
+5) c='-transpose' ;;
+7) c='-transverse' ;;
*) die cannot understand transformation "$1" using jpegtran ;;
esac # others could be emulated, but ...

tmp="$2.a.$$"

function cleandie() {
  mv -i "$tmp" $"2" </dev/null 2>/dev/null; die "$@"
}

mv -i "$2" "$tmp" </dev/null 2>/dev/null || die unable to move temp files
$JPEGTRAN -copy all -outfile "$2" $c "$tmp" || cleandie error using jpegtran
rm "$tmp"

notify "$url"
