#!/bin/bash
#
# Postinstall tasks for IRIS 3DView
# - create user for running background process
# - install and launch Xvfb service
# - install and launch iris3dviewd service
#

# add background user and set config file privileges 
add_user() {
	if ! id $username  >/dev/null 2>&1;
	then
		echo "Adding background user $1"
       	useradd $1
	else
		echo "User $1 already exists"
	fi

	home=`grep $1 /etc/passwd | cut -d ":" -f6`
	config=$home/.config/Vaisala
	echo "Preparing configuration file in $config"
    mkdir -p $config
    touch $config/iris3dviewd.conf
    touch $config/IRIS3D.conf
    # set config directory and config files writable by the group
    chmod 775 $config
    chmod -R g+x $config 
    chmod 664 $config/iris3dviewd.conf
    chmod 664 $config/IRIS3D.conf
	chown -R $1:$1 $home/.config

	logdir=$home/.iris3d/log
	mkdir -p $logdir
	rotfile=$config/logrotate.conf
	
	if [ ! -f ${rotfile} ]; then
       	echo "$home/iris3dviewd.log">  ${rotfile}
       	echo "{"                    >> ${rotfile}
       	echo "  rotate 50"          >> ${rotfile}
       	echo "  olddir $logdir"     >> ${rotfile}
       	echo "  nocompress"         >> ${rotfile}
       	echo "}"                    >> ${rotfile}
        chmod 664 ${rotfile}
   fi
	
}

# enable and start a background service
start_service() {
	echo "Starting service $1"
	chkconfig --add $1
	chkconfig $1 on
	service $1 start
}


PATH=/usr/sbin:/sbin:$PATH; export PATH
# source default settings
. /etc/sysconfig/iris3dviewd
username=${BG_USER-iris3d}
add_user $username 
start_service xvfb
start_service iris3dviewd
