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

CMD=`basename $0`

# get system wide defines
#
. /etc/default/kusa-services	|| exit $?

confdir="$PRJ/src"
reposerver="$KUSA_SERVICE_FILE"
repodir="/w/ftp/kusa"
repouser="ftp:ftp"

usage()
{
	echo -e "\nusage: $CMD orgname" >&2
	echo -en "\norgnames: " >&2
	cd $confdir
	for dir in *
	do
		[ -d $dir ] && echo -en "$dir " >&2
	done
	echo -e "\n" >&2
	exit 1
}

# (MAIN)

[ $# != 1 ] && usage

org="$1"

[ -d "$confdir" ] || {
	echo "error: configuration directory '$confdir' not exists" >&2
	exit 1
}

cd "$confdir"

[ -d "$org" ] || {
	echo "error: directory '$org' not exists under confdir" >&2
	usage
}

# get overrides
#
[ -f $PRJ/etc/repodir ]		&& repodir=`cat $PRJ/etc/repodir`
[ -f $PRJ/etc/reposerver ]	&& reposerver=`cat $PRJ/etc/reposerver`
[ -f $PRJ/etc/repouser ]	&& repouser=`cat $PRJ/etc/repouser`

# build compressed packed version
#
for dir in `find $org/* -type d | fgrep -v "$org/auto"`
do
	cd "$confdir/$dir"
	files=
	for file in `ls`
	do
		[ -f $file ] && files="$files $file"
	done
	[ "$files" ] && {
		out=kusa-bundle.bz2
		echo -n "  building $out in $dir ... "
		tar cfj $out.tmp --exclude '*.bz2' --exclude '*.tmp' $files || {
			rm -f $out.tmp
			exit $?
		}
		echo "ok"
		[ -f $out ] && {
			cmp $out $out.tmp >/dev/null || rm -f $out
		}
		[ -f $out ] || {
			mv $out.tmp $out || exit $?
		}
		rm -f $out.tmp
	}
done


# records timestamp
#
cd "$confdir/$org"
date --utc '+%Y.%m.%d %H:%M:%S' >timestamp


# updates server
#
sudo mirror "$confdir/$org" "$reposerver:$repodir/$org"
sudo ssh root@$reposerver chown -R $repouser "$repodir/$org"

exit 0
