#!/bin/bash
#
# ::copy::
# ::maintainer::

CMD=`basename $0`
me=`id | sed -e 's/uid=//' -e 's/(.*//'`
tmpscript="kusacfg-tmp-getinfos"
tmplog="/tmp/$CMD.log"


usage()
{
	echo "usage: $CMD hosts" >&2
	cleanup
	exit 1
}


cleanup()
{
	cd /
	rm -rf $tdir $tmplog
}

do_scp()
{
	local stat=
	#echocr " getting $1 ... "
	sudo scp -p "$1" "$2" >$tmplog 2>$tmplog || {
		stat=$?
		cat $tmplog >&2
		return $stat
	}
	#echocr
}

echocr()
{
	echo -en "\r\033[K$*"
}

# (MAIN)

tdir=`mktemp -d /tmp/${CMD}-XXXXXX`

trap "cleanup; exit 255" 1 2 3

[ "$me" = 0 ] && me="kanna"	# FIXME just for now, under devel

[ $# == 0 ] && usage

kusacfg-list	# print headers

# cache sudo credentials
#
sudo ls >/dev/null


for host
do
	[ -d $host ] || continue

	echocr " ping $host ... "
	ping -c 1 -w 3 $host 2>/dev/null >/dev/null || {
		continue
	}

	echocr " $host, getting files ... "

	rm -rf $tdir/*

	do_scp /usr/share/kusa/templates/$tmpscript $host:/tmp/. || continue


	sudo ssh $host "bash /tmp/$tmpscript; rm -f /tmp/$tmpscript"

	do_scp "$host:/tmp/$tmpscript.tmp/*" $tdir/.

	sudo chown -R $me:users $tdir

	# clean actual host files
	#
	for file in `ls $host`
	do
		[ -s $host/$file ] || {
			#echo "  purge $host/$file (empty)"
			rm -f $host/$file
			continue
		}
		[ -f $tdir/$file ] || {
			#echo "  purge $host/$file (obsolete)"
			rm -f $host/$file
			continue
		}
	done

	# install changed files
	#
	for file in `ls $tdir`
	do
		[ -s $tdir/$file ] || continue
		[ -f $host/$file ] && {
			cmp $tdir/$file $host/$file >/dev/null && continue
		}
			#echo "  add   $host/$file (updated)"
		mv -f $tdir/$file $host/.
	done

	echocr

	kusacfg-list --no-header $host
done
echocr
echo ""

rm -rf $tdir

exit 0
