#!/bin/sh

#
# small helper for windows cygwin users to sync a
# directory containing static site sources with
# a remote server. the script runs forever. it looks
# into your source directory for any changes. if
# something has changed, it syncs it with the remote
# end.
#
# requires cywin and inside cygwin: rsync + openssh.
# ssh account needs to have public-key installed
# and the key has to be password-less.
#
# to run as a service:
# cygrunsrv -I websync -d "Sync Static Web Source" -p /bin/bash.exe -a /home/$USER/bin/websync-service
# cygrunsrv -S websync
#
# you might consider changing some of the variables
# on top of this file according to your environment.
#
# part of Quietly::Confident tool suite.
#
# 2012 T.LINDEN.
#
# Perl Artificial License

base="/cygdrive/c/temp"
source="$base/WWW"
dest="USER@REMOTESERVER:tmp" # contains WWW afterwards!
idrsa="/home/$CygwinUser/.ssh/id_rsa"
log="$base/rsynclog.txt"
opts="-r -v --force --del -h --progress --log-file=$log -u -q"
lslr="$base/lslr.txt"

sync() {
    /bin/rsync $opts -e "ssh -o ConnectTimeout=3 -o UserKnownHostsFile=/tmp/knownhosts -o StrictHostKeyChecking=no -o IdentityFile=$idrsa" "$source" "$dest"
}

lslr() {
    /bin/ls -lR "$source" | /bin/md5sum | /bin/awk '{print $1}'
}

readlslr() {
    /bin/cat $lslr
}

changed() {
    old=`readlslr`
    new=`lslr`
    if test -z "$old"; then
	echo "Could not fetch old ls-LR output"
	exit 1
    fi
    if test -z "$new"; then
	echo "Failed to get current ls-LR output"
	exit 1
    fi

    if test "$old" == "$new"; then
	echo 0
    else
	echo $new
    fi
}

if ! test -e "$lslr"; then
    lslr > $lslr
fi

while :; do
    check=`changed`
    if test "$check" != "0"; then
	sync
	echo "$check" > $lslr
    fi
    sleep 10
done
