#! /bin/sh

set -e

ROOT_SBIN=root-system/usr/local/sbin/

if [ -d root-system ]
then
	echo "Removing old glasnost://system environment..."
	rm -rf root-system
fi

echo "Installing glasnost://system environment in root-system/"
test -d system/data || mkdir system/data
rm -f config && make config config-system install \
	     GLASNOST=glasnost-system PORT=8500 \
	     PREFIX=`pwd`/root-system/usr/local \
	     VARPREFIX=`pwd`/root-system/var/lib/ \
	     ETC_DIR=`pwd`/root-system/etc/glasnost-system \
	     LOGPREFIX=`pwd`/root-system/var/log \
	     SERVER_USER=`id -u` SERVER_GROUP=`id -u` \
	     WEB_USER=`id -u` WEB_GROUP=`id -u` &> /dev/null

SERVERS="Dispatcher ArticlesServer IdentitiesServer GroupsServer \
         PasswordAccountsServer VirtualHostsServer UploadFilesServer \
	 PageNamesServer TranslationsServer"
echo "Starting Glasnost servers..."
for SERVER in $SERVERS
do
	$ROOT_SBIN/glasnost-system-ctl start-one $SERVER
done

(cd tmp-system && ./generate-system.py) < /dev/null
$ROOT_SBIN/glasnost-system-ctl stop

echo "Creating system/data"
$ROOT_SBIN/glasnost-system-ctl make-system localhost
rm -rf system/data
cp -rp root-system/var/lib/glasnost-system/system system/data
find system/data/ -type d | xargs chmod 755
find system/data/ -type f | xargs chmod 644

