#!/bin/sh
unset LANG
unset LANGUAGE
unset LC_ALL

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}
}

inputoffset=0
gpsoffset=1
signed=""
if date | grep -q CEST ; then
    gpsoffset=2
fi
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
            inputoffset=$MINUS$o
            gpsoffset=$inputoffset
            ;;
        *)
            usage
            ;;
    esac
done
shift $((OPTIND-1))

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


for img in `ls [A-z]*.jpg [A-z]*.JPG [0-9]*.JPG [0-9]*.jpg [A-z]*.mp4 [A-z]*.MP4 [A-z]*.thm [A-z]*.THM [0-9]*.mts [0-9]*.MTS 2>/dev/null` ; do
    DATE=`exiftool -GPSDateTime $img | sed -e 's/^GPS[^:]\+: *//'g -e 's/Z$//g'`
    if [ "$DATE" != "" ] ; then
        exiftool -overwrite_original -quiet -alldates="$DATE" $img
        exiftool -overwrite_original -quiet -alldates+=$gpsoffset:00:00 $img
        if echo "$img" | grep -q rx100 ; then
            exiftool -overwrite_original -quiet -SonyDateTime="$DATE" $img
            exiftool -overwrite_original -quiet -SonyDateTime+=$gpsoffset:00:00 $img
        fi
    fi
done


    # This could be used to set time according to file timestamp
    # rather than GPS date
    # timestamp=`stat --printf=%y $1 | cut -d. -f1`
