#!/bin/bash -e

# DEFAULTOFFSET=5
DEFAULTOFFSET=1
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}
}

move_and_touch()
{
  img=$1
  DATE=$2
  NAME=$3
  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/'`
  if [ "$TOUCHDATE" != "" ] ; then
     touch --date="$TOUCHDATE" "$img" && true
  fi
  chmod uga-x "$img"
  if [ "$NAME" = "" ] ; then
    echo "ERROR: No proper name found for image $img"
  else
    newname=`echo ${DATE}_${NAME} | tr 'A-Z' 'a-z'` # make sure new name will be completely lower case
    mv "$img" "${newname}"
  fi
}

# Cleanup some duplicates created by Galaxy S22 with different image operations like "remastered" or "resized"
UNWANTED="_remastered
          _resized
          (0)
         "
for uw in $UNWANTED ; do
  for i in 20*${uw}.jpg ; do
    if [ -e "$(basename $i ${uw}.jpg).jpg" ] ; then
      if [ "$(exiftool -Model $i | sed 's/^.* : //')" = "SM-S901B" ] ; then # remove only if Model is SM-S901B (Samsung S22)
        echo "Removing duplicate $i"
        rm $i
      fi
    fi
  done
done

inputoffset=0
gpsoffset=1
signed=""
gpsoffset=$DEFAULTOFFSET
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

# echo "DEBUG: gpsoffset=$gpsoffset"
# echo "inputoffset = ${inputoffset}"

DATE=""
CAMADD=""
rename 's/\.jpeg$/.jpg/' [A-z]*.jpeg 2>/dev/null
rename 's/ /_/g' [A-z]*.jpg [A-z]*.JPG [1-9]*.JPG [1-9]*.jpg [A-z]*.jpeg [A-z]*.JPEG
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 [A-z]*.heic [A-z]*.HEIC 2>/dev/null` ; do
  DATE=""
  EXT=$(echo "$img" | awk -F. '{print $NF}' | tr [A-Z] [a-z])
  if [ "$EXT" = 'jpeg' ] ; then
    EXT=jpg
  fi
  if [ `exiftool "$img" | grep -i 'Date' | grep -v -e '^File' -e '^Profile' | wc -l` -eq 0 ] ; then
    echo "No date information in exif tags of $img"
    continue
  fi
  # check for valid date first
  # This does not work for HEIC files which whould need something like  $(exiftool -DateTimeOriginal $img )
  if [ "$EXT" = "jpg" ] ; then
    if [ $(exif --tag='DateTimeOriginal' $img  | grep -i VALUE | sed -e 's/^.*VALUE:[[:space:]]*//i' -e 's/://g' -e 's/ /_/') = "00000000_000000" ] ; then
      echo "Image $img has no valid DateTimeOriginal - stop here"
      exit 1
    fi
  fi
  if [ -s $img ] ; then
    offset=$inputoffset
    dosomething=0
    if echo "$img" | grep -q '^IMG_20[012][0-9]\{5\}_[0-9]\{6\}' ; then
      newimg=`echo "$img" | sed 's/^IMG_//'`
      mv $img $newimg
      img=$newimg
      DATE=`echo $img | sed "s/^\(20[0-9]\{6\}_[0-9]\{6\}\)_[0-9~]\+\.$EXT/\1/"`
      CAMADD=`echo $img | sed "s/^20[0-9]\{6\}_[0-9]\{6\}\(_[0-9~]\+\)\.$EXT/\1/"`
      dosomething=1
    fi
    if echo "$img" | grep -q '^VID_20[012][0-9]\{5\}_[0-9]\{6\}' ; then
      newimg=`echo "$img" | sed 's/^VID_//'`
      mv $img $newimg
      img=$newimg
      DATE=`echo $img | sed "s/^\(20[0-9]\{6\}_[0-9]\{6\}\)_[0-9~]\+\.$EXT/\1/"`
    fi
    if echo "$img" | grep -q '^20[012][0-9]\{5\}_[0-9]\{6\}' ; then
        processimage=0
        if echo "$img" | grep -qi '^20[012][0-9]\{5\}_[0-9]\{6\}\.jpg' ; then
            processimage=1
        fi
        if echo "$img" | grep -qi '^20[012][0-9]\{5\}_[0-9]\{6\}_remastered\.jpg' ; then
            processimage=1
        fi
	if [ $processimage -eq 1 -o $dosomething -eq 1 ] ; then
            if [ "$DATE" = "" ] ; then
                DATE=$(echo $img | sed -e 's/^\(20[0-9]\{6\}_[0-9]\{6\}\)\.jpg/\1/' -e 's/^\(20[0-9]\{6\}_[0-9]\{6\}\)_remastered\.jpg/\1/')
            fi
            if [ "$DATE" = "" ] ; then
                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'`
                offset=$gpsoffset
            fi
            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=`exiftool "$img" | grep -i "Metadata *Date" | head -n 1 | sed -e 's/^.*Metadata *Date[[:space:]]*//i' -e 's/: *//g' -e 's/ /_/g' -e 's/+[0-9]\{4\}$//'`
            fi
            if ! echo $DATE | grep -q "^[0-9]\{8\}_[0-9]\{6\}$" ; then
                echo "Illegal date format $DATE for $img"
                if echo $DATE | grep -q "^[0-9]\{8\}_[0-9]\{4\}$" ; then
                    DATE="${DATE}00"
                    echo "Fix date to ${DATE}"
                else
                    echo "Continue with other images"
                    continue
                fi
            fi
            if [ "$DATE" != "" ] ; then
	        RAWDEVEL=`exiftool "$img" | grep -i "camera profile" | head -n 1 | sed -e 's/^.*camera profile[[:space:]]*//i' -e 's/: *//g' -e 's/ /_/g' -e 's/^/_/'`
	        CAM=`exiftool "$img" | grep -i "model.*name" | head -n 1 | sed -e 's/^.*model.*name[[:space:]]*//i' -e 's/: *//g' -e 's/ /_/g' -e 's:/:_:g'`
	        if [ "$CAM" = "" ] ; then
	            CAM=`exif --tag='Model' "$img" 2>/dev/null | grep -i VALUE | head -n 1 | sed -e 's?^.*VALUE:[[:space:]]*\([^[:space:]/,]\+\)[/,]*.*?\1?i' -e 's:/:_:g'`
	        fi
                CAM="$CAM$RAWDEVEL"
                CAM=`echo $CAM | sed 's/,.*//'` # some camera model names are featuring ',' - remove everything after ','
	        IUID=`exif --tag='ImageUniqueID' "$img" 2>/dev/null | grep -i VALUE | head -n 1 | sed -e 's?^.*VALUE:[[:space:]]*\([^[:space:]/,]\+\)[/,]*.*?\1?i'`
	        if [ "$IUID" = "" ] ; then
	            IUID=`exiftool "$img" | grep -i "Image Unique ID" | head -n 1 | sed -e 's/^.*Image Unique ID[[:space:]]*//i' -e 's/: *//g' -e 's/ /_/g'`
	        fi
	        # echo "Need to add camera type $CAM and id $IUID to this image"
                #  $IUID ist gar nicht unterschiedlich für unterschiedliche Bilder :-(
#  Bei den Bildern hat Gero schon ein manuelles Datum gesetzt -> kein Offset
#                if [ $offset -ne 0 ] ; then
#                   DATE=`dateoffset $DATE`
#                fi
                # not sure whether this is used at all but it does not harm
                if echo $DATE | grep -q '+[0-9]\{4\}_DST$' ; then
                    DATE=`echo $DATE | sed 's/+[0-9]\{4\}_DST$//'`
                fi
                move_and_touch $img $DATE "${CAM}${CAMADD}.${EXT}"
            else
                echo "Failed to detect date of image $img"
            fi
	else
	    echo "do nothing with image $img"
	fi
    else
        ext=$(echo "$img" | sed 's/.*\.\([^.]\+\)$/\1/')
        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/ /_/'`
	else
	    offset=$gpsoffset
        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 [ "$ext" = "mp4" -o "$ext" = "MP4" ] ; then
           thm=$(echo $img | sed 's/\.mp4$/.THM/I')
           if [ -e $thm ] ; then
              echo "Obtain CAM from $thm"
              CAM=`exiftool "$thm" | grep -i "model.*name" | head -n 1 | sed -e 's/^.*model.*name[[:space:]]*//i' -e 's/: *//g' -e 's/ /_/g' -e 's:/:_:g'`
              if [ "$CAM" = "" ] ; then
                 CAM=`exif --tag='Model' "$thm" 2>/dev/null | grep -i VALUE | head -n 1 | sed -e 's?^.*VALUE:[[:space:]]*\([^[:space:]/,]\+\)[/,]*.*?\1?i' -e 's:/:_:g'`
              fi
              if [ "$DATE" = "" ] ; then
	         DATE=`exiftool "$thm" | grep -i "date.*original" | head -n 1 | sed -e 's/^.*date.*original[[:space:]]*//i' -e 's/: *//g' -e 's/ /_/g'`
	      fi
           fi
        fi
        if [ "$DATE" = "" ] ; then
            DATE=`exiftool "$img" | grep -i "Metadata *Date" | head -n 1 | sed -e 's/^.*Metadata *Date[[:space:]]*//i' -e 's/: *//g' -e 's/ /_/g' -e 's/+[0-9]\{4\}$//'`
            if ! echo $DATE | grep -q "^[0-9]\{8\}_[0-9]\{6\}$" ; then
                echo "Illegal date format $DATE for $img"
                if echo $DATE | grep -q "^[0-9]\{8\}_[0-9]\{4\}$" ; then
                    DATE="${DATE}00"
                    echo "Fix date to ${DATE}"
                else
                    echo "Continue with other images"
                    continue
                fi
            fi
        fi
	if [ "$DATE" = "" ] ; then
	    DATE=`exiftool "$img" | grep -i "Media Create Date" | head -n 1 | sed -e 's/^.*Media Create Date[[:space:]]*//i' -e 's/: *//g' -e 's/ /_/g'`
	fi
	if [ "$DATE" != "" ] ; then
	    RAWDEVEL=`exiftool "$img" | grep -i "camera profile" | head -n 1 | sed -e 's/^.*camera profile[[:space:]]*//i' -e 's/: *//g' -e 's/ /_/g' -e 's/^/_/'`
	    CAM=`exiftool "$img" | grep -i "model.*name" | head -n 1 | sed -e 's/^.*model.*name[[:space:]]*//i' -e 's/: *//g' -e 's/ /_/g' -e 's:/:_:g'`
	    if [ "$CAM" = "" ] ; then
	        CAM=`exif --tag='Model' "$img" 2>/dev/null | grep -i VALUE | head -n 1 | sed -e 's?^.*VALUE:[[:space:]]*\([^[:space:]/,]\+\)[/,]*.*?\1?i' -e 's:/:_:g'`
	    fi
            CAM="$CAM$RAWDEVEL"
            CAM=`echo $CAM | sed 's/,.*//'` # some camera model names are featuring ',' - remove everything after ','
            ext=`echo $img | sed 's/.*\.\([^.]\+\)/\1/'`
            if [ "$ext" = "mp4" -o "$ext" = "MP4" ] ; then
               thm=`basename $img .$ext`.THM
               if [ -e $thm ] ; then
                  echo "Obtain CAM from $thm"
                  CAM=`exiftool "$thm" | grep -i "model.*name" | head -n 1 | sed -e 's/^.*model.*name[[:space:]]*//i' -e 's/: *//g' -e 's/ /_/g' -e 's:/:_:g'`
                  if [ "$CAM" = "" ] ; then
                     CAM=`exif --tag='Model' "$thm" 2>/dev/null | grep -i VALUE | head -n 1 | sed -e 's?^.*VALUE:[[:space:]]*\([^[:space:]/,]\+\)[/,]*.*?\1?i' -e 's:/:_:g'`
                  fi
               fi
            fi
            if [ "$ext" = "mts" -o "$ext" = "MTS" ] ; then
              DATE=`echo $DATE | sed 's/+[0-9][0-9]00$//'`
              # echo "Obtain CAM from $img (DATE = $DATE)"
              CAM=`exiftool "$img" | grep -i "model.*name" | head -n 1 | sed -e 's/^.*model.*name[[:space:]]*//i' -e 's/: *//g' -e 's/ /_/g' -e 's:/:_:g'`
              if [ "$CAM" = "" ] ; then
                 CAM=`exif --tag='Model' "$thm" 2>/dev/null | grep -i VALUE | head -n 1 | sed -e 's?^.*VALUE:[[:space:]]*\([^[:space:]/,]\+\)[/,]*.*?\1?i' -e 's:/:_:g'`
              fi
            fi
	    IMGSC=`echo "$img" | tr 'A-Z' 'a-z'`
#            echo DATE=$DATE
            if [ $offset -ne 0 ] ; then
              if [ "${CAM}" = "DSC-QX100" ] ; then
                echo "HACK: Do not apply offset for image $img since it was taken with $CAM."
              else
                DATE=`dateoffset $DATE`
              fi
            fi
            if echo $DATE | grep -q '+[0-9]\{4\}_DST$' ; then
                DATE=`echo $DATE | sed 's/+[0-9]\{4\}_DST$//'`
            fi
            move_and_touch $img $DATE "${CAM}_$IMGSC"
	fi
    fi
  else
    echo "File $img is empty ... ignoring"
  fi
done
