#!/bin/bash

. ${TOOLKIT}-functions.sh

# cleanup ....
#
rm -f /webmin-setup.out


# 2014.02
#  FIXME provvisorio durante porting custom, rimuovo eventuale
# 	 package webmin installato, copio tarfile locale
#
is_installed webmin && {
	sh /etc/init.d/webmin stop
	remove_pkgs webmin
}

set -e

if [ -f /etc/webmin/serial ]
then
	serial=$(cat /etc/webmin/serial)
else
	serial=0
fi

newserial=$(kusa-conf webmin.serial)
tmpdir=/tmp/webmin_inst

[ $serial != $newserial ] && {
	echo " webmin serial changed, installed=$serial, new=$newserial"
	repo=$(jtconf service.repos)/pub/webmin
	tarfile1=ku-webmin-etc.tar.bz2
	tarfile2=ku-webmin-usr-share.tar.bz2
	tarfile3=ku-webmin-init.tar.bz2
	rm -rf $tmpdir
	mkdir $tmpdir
	cd $tmpdir

	wgetfile ftp://$repo/$tarfile1
	wgetfile ftp://$repo/$tarfile2
	wgetfile ftp://$repo/$tarfile3

	sh /etc/init.d/webmin stop || :

	# etc and usr/share, mirror from temp dir
	#
	tar xfpj $tarfile1
	tar xfpj $tarfile2
	for dir in etc/webmin usr/share/webmin
	do
		mirror --include-sysfs $dir /$dir \
			--exclude='history/' --exclude '*.cache'
	done

	# init, overwrite files directly
	#
	cd /
	tar xvfpj $tmpdir/$tarfile3

	echo $newserial >/etc/webmin/serial
}


# populate /var
#
create_dir /var/webmin			root:bin 700
create_dir /var/webmin/ajaxterm		root:bin 700
create_dir /var/webmin/output		root:bin 700
create_dir /var/log/webmin		root:bin 770


# check ssl certificate
#
sslfile=/etc/webmin/miniserv.pem
certfile=$(kusa-conf cert.filename)
cat /etc/ssl/certs/$certfile.pem /etc/ssl/private/$certfile.key >miniserv.pem.tmp
installfile miniserv.pem.tmp $sslfile root:bin 400

sh /etc/init.d/webmin restart || :

rm -rf $tmpdir

exit 0
