#!/bin/bash -e

unset LANG
unset LANGUAGE
unset LC_ALL

usage() { echo "Usage: $0 [-o <+-0-12 hours>]" 1>&2; exit 1; }

dateoffset()
{
  DAY=`echo $1 | sed 's/_.*$//'`
  HOURS1=`echo $1 | sed 's/^.*_\([0-9][0-9]\).*/1\1/'`
  MINSEC=`echo $1 | sed 's/^.*_[0-9][0-9]\(.*\)/\1/'`
  HOURS1=$((HOURS1+offset))
  echo ${DAY}_`echo ${HOURS1}|sed 's/^1//'`${MINSEC}
}
            
offset=0
while getopts ":o:" o; do
    case "${o}" in
        o)
            o=${OPTARG}
            signed=`echo $o | sed 's/[0-9]\+//'`
            MINUS=""
            if [ "$signed" = "-" ] ; then
                MINUS="-"
                o=`echo $o | sed 's/^-//'`
            elif [ "$signed" != "" ] ; then
                usage
            fi
            ((o == 0 || o == 1 || o == 2 || o == 3 || o == 4 || o == 5 || o == 6 || o == 7 || o == 8 || o == 9 || o == 10 || o == 11 || o == 12 )) || usage
            offset=$MINUS$o
            ;;
        *)
            usage
            ;;
    esac
done
shift $((OPTIND-1))

if [ -z "${offset}" ] ; then
    usage
fi

for img in `ls [0-9A-z]*.jpg [0-9A-z]*.JPG 2>/dev/null` ; do
    DATE=`exiftool "$img" | grep -i "^GPS Date/Time" | head -n 1 | sed -e 's?^GPS Date/Time[[:space:]]*??i' -e 's/: *//g' -e 's/Z$//g' -e 's/ /_/'`
    if [ "$DATE" = "" ] ; then
        DATE=`exif --tag='DateTimeOriginal' "$img" 2>/dev/null | grep -i VALUE | sed -e 's/^.*VALUE:[[:space:]]*//i' -e 's/://g' -e 's/ /_/'`
    fi
    if [ "$DATE" = "" ] ; then
        DATE=`exiftool "$img" | grep -i "date.*original" | head -n 1 | sed -e 's/^.*date.*original[[:space:]]*//i' -e 's/: *//g' -e 's/ /_/g'`
    fi
    if [ "$DATE" = "" ] ; then
	DATE=`exif --tag='Date and Time (original)' "$img" | grep -i VALUE | sed -e 's/^.*VALUE:[[:space:]]*//i' -e 's/:/-/g' -e 's/ /_/'`
    fi
    if [ "$DATE" != "" ] ; then
        if [ $offset -ne 0 ] ; then
            DATE=`dateoffset $DATE`
        fi
        TOUCHDATE=`echo $DATE | sed 's/\([0-9][0-9][0-9][0-9]\)\([0-9][0-9]\)\([0-9][0-9]\)_\([0-9][0-9]\)\([0-9][0-9]\)\([0-9][0-9]\)/\1-\2-\3 \4:\5:\6/'`
        touch --date="$TOUCHDATE" "$img"
    fi
done
