#!/bin/bash
#
CMD=$(basename $0)

set -u
set -e

[ $(id -u) != 0 ] && {
	exec sudo $0 "$@"
	##echo "you need to be root for this, use sudo" >&2
	##exit 1
}


get_dist_val()
{
	jtconf --include $distfile webmin.$1
}

set_dist_val()
{
	local key=$1
	local val=$2
	cp -a $distfile $distfile.save
	(
		sed -e "/^  $key	/d" $distfile
		echo "  $key	$val"
	) | sponge $distfile
}



flagfilename()
{
	echo $here/${CMD}-$1.flag
}


check_news()
{
	local flag=$(flagfilename $1)
	local news=
	shift

	echo -n " checking $flag ... "

	if [ -f $flag ]
	then
		news=$(find $* -type f -newer $flag | egrep -v \
			'/history/|\.cache|/oscache|/update-cache|system-status/info|\.pem|serial')
	else
		news="(NO FLAGFILE)"
	fi

	[ "$news" != "" ] && {
		echo "new: " $news
		return 0
	}
	echo "(up to date)"
	return 1
}


here=$(pwd)
repodir="/w/ftp/pub/webmin"
distfile="$here/dist-mnt-webmin"

name1=$(get_dist_val name1)
tarfile1=$repodir/$(get_dist_val tarfile1)
files1=$(get_dist_val files1)

name2=$(get_dist_val name2)
tarfile2=$repodir/$(get_dist_val tarfile2)
files2=$(get_dist_val files2)

name3=$(get_dist_val name3)
tarfile3=$repodir/$(get_dist_val tarfile3)
files3=$(get_dist_val files3)

serial=$(get_dist_val serial)
modified=false

cd /

exclude="--exclude=*.cache --exclude=*/history/*"

check_news $name1 $files1 && {
	echo -n " updating $tarfile1 ... "
	tar cfj $tarfile1 $exclude $files1
	echo "ok"
	touch $(flagfilename $name1)
	modified=true
}

check_news $name2 $files2 && {
	echo -n " updating $tarfile2 ... "
	tar cfj $tarfile2 $files2
	echo "ok"
	touch $(flagfilename $name2)
	modified=true
}

check_news $name3 $files3 && {
	echo -n " updating $tarfile3 ... "
	tar cfj $tarfile3 $files3
	echo "ok"
	touch $(flagfilename $name3)
	modified=true
}

$modified || exit 0

newserial=$(expr $serial + 1)
echo " updating serial: $serial -> $newserial"
echo "$newserial" > $repodir/serial
set_dist_val serial $newserial

cd $here
chown kanna:ftp $tarfile1 $tarfile2 $tarfile3 $repodir/serial
ls -l $tarfile1 $tarfile2 $tarfile3
chown --reference . *.flag

trig-linode-update

exit 0
