#!/bin/sh

if [ "$1" == "" ]; then
	echo "Usage: ${0##*/} PATH_TO_mirror.conf_ROOT"
	exit 0
fi

CFGROOT=$1
CONF=$CFGROOT/mkmirror.conf
EXCLS=$CFGROOT/excludes
INCLS=$CFGROOT/includes
LOGFILE=$CFGROOT/mkmirror.log

OPT_INCEXC=
TARGET=

if [ ! -d "$CFGROOT" ]; then
	echo "ERROR: '$CFGROOT' is not a directory"
	exit 1
fi

if [ ! -f "$CONF" ]; then
	echo "ERROR: can't find 'mirror.conf' file under '$CFGROOT'"
	exit 2
fi

if [ -f "$EXCLS" -a -f "$INCLS" ]; then
	OPT_INCEXC="--exclude-from=$EXCLS --files-from=$INCLS"
fi

# source conf file
. "$CONF"

if [ -z "$TARGET" -o ! -d "$TARGET" ]; then
	echo "ERROR: target directory not specified or do not exist"
	exit 3
fi

CURDATE=`date "+%Y-%m-%d %H:%M:%S"`
echo "######## $CURDATE Starting mkmirror... ########" | tee -a $LOGFILE
echo "#### CFGROOT: $CFGROOT"
echo "####  TARGET: $TARGET"
echo

# don't qoute SOURCES here, as we expect it to be a whitespace-separated list
for SRC in $SOURCES; do
	echo "  # source: $SRC"
	#list=$(rsync --list-only --exclude-from="$EXCLS" --include-from="$INCLS" "$SRC/")
	#list=$(rsync --dry-run --stats -W -v -a --delete-after --include-from="$INCLS" --exclude-from="$EXCLS" --log-file="$LOGFILE" "$SRC/" "$TARGET/")
#	list=$(rsync --dry-run --stats -W -v -a -r --delete-after $OPT_INCEXC --log-file="$LOGFILE" "$SRC/" "$TARGET/")
#	echo "$list" >$CFGROOT/mkmirror.lst
	#rsync --list-only --dry-run --stats -W -v -a -r --delete-after $OPT_INCEXC --log-file="$LOGFILE" "$SRC/" "$TARGET/"
#	rsync --dry-run -v $OPT_INCEXC --log-file=$LOGFILE $SRC/ $TARGET/
	#rsync --list-only -r $OPT_INCEXC --log-file=$LOGFILE $SRC/ $TARGET/
#	rsync --list-only -r $OPT_INCEXC --log-file=$LOGFILE $SRC/ $TARGET/

	rsync -v --stats --delete-after -a -H -r $OPT_INCEXC --log-file=$LOGFILE $SRC/ $TARGET/
	break
done

## good cmd
# rsync -v --stats --delete-after -a -H $OPT_INCEXC --log-file=$LOGFILE $SRC/ $TARGET/
##

exit 0
