#!/bin/bash
# Script to fix wrong names when forgeting offset for cam_rename 

unset LANG
unset LANGUAGE
unset LC_ALL

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

move_and_touch()
{
  img=$1
  newimg=$2
  TOUCHDATE=`echo $newimg | 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/'`
  mv "$img" "$newimg"
  if [ "$TOUCHDATE" != "" ] ; then
    touch --date="$TOUCHDATE" "$newimg" && true
  fi
}

inputoffset=0
signed=""
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
            ;;
        *)
            usage
            ;;
    esac
done
shift $((OPTIND-1))

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

if [ $inputoffset -eq 0 ] ; then
    echo "There is no point to rename the file by no offset."
    exit 1
fi
# echo "inputoffset = ${inputoffset}"

for img in `ls [A-z]*.jpg [A-z]*.JPG [0-9]*.JPG [0-9]*.jpg [0-9]*.mp4 [0-9]*.jpg [0-9]*.thm 2>/dev/null` ; do
    HOUR1=`echo $img | sed 's/^201[0-9]\{5\}_\([0-9][0-9]\)[0-9]\{4\}_.*\.[jmt][ph][g4m]/1\1/'`
    HOUR1=$((HOUR1-inputoffset))
    NEWHOUR=`echo ${HOUR1}|sed 's/^1//'`
    NEWNAME=`echo $img | sed "s/^\(201[0-9]\{5\}_\)[0-9][0-9]\([0-9]\{4\}_.*\.[jmt][ph][g4m]\)/\1$NEWHOUR\2/"`
    move_and_touch $img $NEWNAME
done
