#!/bin/bash


# don't change these variables
confdir=/etc/verlihub
[ -d ~/.verlihub ] && confdir=~/.verlihub
[ -d ./.verlihub ] && confdir=./.verlihub
[ "x$VERLIHUB_CFG" != "x" ] && confdir=$VERLIHUB_CFG

needfiles="dbconfig motd faq rules help_admin help_master help_op help_usr help_reg help_reg"

# feel free to change these

exepath="" # default location for the hub config directory
pidfile=$confdir/pid
logfile=$confdir/log
errfile=$confdir/err

# check config dir
if [ ! -d $confdir ]; then
	echo FATAL ERROR: missing configuration directory $confdir
	echo You must run verlihub from the directory that contains configuration	dir:$confdir
	exit 1
fi;

# check the pid file
running=0
if [ -e $pidfile ]; then
	oldpid=`cat $pidfile`
	ps -p $oldpid > /dev/null && running=1
fi;

if [[ $running == 1 && "$1" != "-f" && "$1" != "-s" ]]; then
	echo Hub is already running with pid $oldpid use $0 -f
	exit 1
fi;

if [[ $running == 1 ]]; then
	echo "Killing old process ($oldpid) as you wish by using switch -f"
	kill -3 $oldpid
fi;

# if it's only to stop
[[ "$1" == "-s" ]] && exit 0;

# chechk files
for f in $needfiles ; do
	file=$confdir/$f
	if [ ! -e $file ]; then
		echo "WARNING: missing file	$file maybe you'll need it"
	fi;
done;

# backup logs
mv -f $errfile $errfile.old
mv -f $logfile $logfile.old

# run it
$exepath"verlihub" >$logfile 2>$errfile &
pid=$!
disown $pid
echo Runnig with pid $pid
echo $pid > $pidfile
