#!/usr/local/bin/bash
# $Id: syp,v 1.11 2011/07/23 00:43:17 grog Exp grog $
# Copy photos to corresponding directory on dereel
#
# What a pain!  The file system assumes that the dates are UTC and
# adjusts them, so we need to adjust back with touch -A.
#
# Calculate time zone offset from UTC
# First get current time.  We need this mainly because of DST.
NOW=`date +%G%m%d%H%M.%S`
# And in local time zone
LOCAL=`date -j $NOW +%s`
# Convert to seconds at UTC
UTC=`TZ=GMT date -j $NOW +%s`
# The difference is the time zone offset.
TZOFFSET=`expr $LOCAL - $UTC`
HOURS=`expr 0 + $TZOFFSET / 3600 `
SECONDS=`expr 0 + $TZOFFSET - $HOURS \* 3600`
MINUTES=`expr $SECONDS / 60 `
ADJUST=`printf %02d%02d00 $HOURS $MINUTES`

DEST=/home/grog/Photos

YEAR=`date +%Y`    # we have to believe this, or get it from ls -l

for drive in a b c; do
  DIRS=`mdir $drive:/dcim 2>/dev/null | grep ^[0-9] | sed "s!^!$drive:/dcim/!; s: .*::"`
  for dir in $DIRS; do
    echo Copying files from $dir to $DEST
    for file in `mdir -b $dir`; do
      i=`basename $file`
      MON=`echo $i | sed 's:.\(.\).*:\1:'`
      DAY=`echo $i | sed 's:..\(..\).*:\1:'`
    # echo $MON $DAY $file
      case $MON in
      [1-9])
        MON=0$MON;;
      A)
        MON=10;;
      B)
        MON=11;;
      C)
        MON=12;;
      
      *)
        echo $file has an invalid name
        break;;
      esac
      mkdir -p $DEST/$YEAR$MON$DAY/orig
      # check for existence of file
      FILE=$DEST/$YEAR$MON$DAY/orig/$i
# saved file that we don't want to use
      SFILE=$DEST/$YEAR$MON$DAY/orig/camera/$i
# 0EV file that we don't want to use
      EFILE=$DEST/$YEAR$MON$DAY/orig/0EV/$i
      if [ -e $FILE -o -e $SFILE -o -e $EFILE ]; then
        echo `basename $FILE` exists already
      else
        echo mcopy -pm $file $FILE
        mcopy -pm $file $FILE
	# Put in author's name ($AUTHOR, default grog)
	setauthor $FILE > /dev/null &
        touch -A $ADJUST $FILE
      fi
      if [ -e $FILE ]; then
	chmod 664 $FILE
      fi
    done
  done
  if [ "$DIRS" != "" ]; then
    mdir $drive:
  fi
done
exit

