#!/bin/sh

CP=`which cp`
RM=`which rm`
MKDIR=`which mkdir`
FIND=`which find`
CAT=`which cat`
CMP=`which cmp`
BASENAME=`which basename`
DIRNAME=`which dirname`
SED=`which sed`
GREP=`which grep`
AWK=`which awk`

if [ $# -ne 2 ]; then
    echo "Usage: $0 <src dir> <dst dir>"
    exit 1;
fi

SRC_DIR="$1"
DST_DIR="$2"

echo "[src=$1]"
echo "[dst=$2]"

LISTFILE=/tmp/piclist.$$

cd "$SRC_DIR"

$FIND . -type f -print > $LISTFILE

if [ ! -f $LISTFILE ]; then
   echo "generate list file failure."
   exit 1;
else
   echo "generate list file success."
fi

$CAT $LISTFILE |  while read line; do
  echo "file=$line"
  PIC_SUBDIR=`$DIRNAME "$line"`
  PIC_BASE=`$BASENAME "$line"`
  SUBSUBDIR=`echo $PIC_SUBDIR | $SED -e 's/^\(\.\/.*\/\)\(.*\)/\2/'`
  #echo "subdir=$PIC_SUBDIR"
  #echo "subsudir=$SUBSUBDIR"
  #echo "base=$PIC_BASE"
  echo $SUBSUBDIR | $GREP "\:" > /dev/null 2>&1
  if [ $? = 0 ]; then
      YEAR=`echo $SUBSUBDIR | $AWK -F ":" '{print $1}'`
      MONTH=`echo $SUBSUBDIR | $AWK -F ":" '{print $2}'`
      DAY=`echo $SUBSUBDIR | $AWK -F ":" '{print $3}'`
      #echo "$SUBSUBDIR->$YEAR/$MONTH/$DAY"
      NEWFILE="$DST_DIR/./$YEAR/$MONTH/$DAY/$PIC_BASE"
  else
      NEWFILE="$DST_DIR/$PIC_SUBDIR/$PIC_BASE"
  fi
  echo "dstfile=$NEWFILE"
  DST_SUBDIR=`$DIRNAME $NEWFILE`
  if [ ! -d $DST_SUBDIR ] ; then
      $MKDIR -p $DST_SUBDIR
  fi
  if [ -f $NEWFILE ]; then
      $CMP $line $NEWFILE > /dev/null 2>&1
      if [ $? != 0 ]; then
	 echo "copying $line"
         $CP -p  $line $NEWFILE;
      else
	 echo "skip copying $line"
      fi
  else
      echo "copying $line"
      $CP -p  $line $NEWFILE;
  fi
done

$RM -f $LISTFILE

