#! /bin/sh

echo GenEthic1.2.2 configuration process...

for NEEDED in perl cat ps grep awk su kill sed
do
	echo -n "looking for : $NEEDED -> "
	CMD=`which $NEEDED`
	if [ -x "$CMD" ]
	then
		echo "$CMD"
	else
		echo "not found"
		exit 1
	fi
done

if [ "$1" = "" ]
then
	echo 'Syntax error'
	echo "$0 <path_to_install>"
	exit 1
else
	TEST=`echo $1 | sed "s/^\/.*/X/"`
	if [ "$TEST" != "X" ]
	then
		echo Error, $1 is not an absolute path
		echo example: $0 /home/genethic
		exit 1
	fi
fi

if [ -d "$1" ]
then
	echo Looks good, using $1 as installation directory
else
	echo Creating $1 directory
	mkdir -p $1
fi

echo Looking for manadatory perl modules ...
for module in IO::Socket
do

echo -n "perl module $module ... "

PERL=`which perl`
MODTEST=`$PERL -M$module -e 'print "ok";'`

if [ -n "$MODTEST" ]
then
	echo ok
else
	echo not found
	exit 1
fi

done

echo Creating needed directories...
mkdir $1/etc
mkdir $1/bin
mkdir $1/var
mkdir $1/log
mkdir $1/tmp

PERL=`which perl | sed "s/\//\\\\\\\\\//g"`
CAT=`which cat | sed "s/\//\\\\\\\\\//g"`
PS=`which ps | sed "s/\//\\\\\\\\\//g"`
GREP=`which grep | sed "s/\//\\\\\\\\\//g"`
AWK=`which awk | sed "s/\//\\\\\\\\\//g"`
SU=`which su | sed "s/\//\\\\\\\\\//g"`
KILL=`which kill | sed "s/\//\\\\\\\\\//g"`
SED=`which sed | sed "s/\//\\\\\\\\\//g"`
DIR2=`echo $1 | sed "s/\//\\\\\\\\\//g"`

echo Copying files...
for files in 644/var/example_external.data 644/etc/help.txt 755/bin/mrtginfo.pl 644/etc/sample.conf 755/bin/genethic.pl 755/bin/keepalive.pl 755/bin/runbot.sh 755/bin/dcc.pl
do
MODE=`echo $files | awk -F\/ '{print $1}'`
DIR=`echo $files | awk -F\/ '{print $2}'`
FILE=`echo $files | awk -F\/ '{print $3}'`

echo "installing src/$FILE to $1/$DIR/$FILE"
cat src/$FILE            \
| sed "s/%PERL%/$PERL/g" \
| sed "s/%CAT%/$CAT/g"   \
| sed "s/%PS%/$PS/g"     \
| sed "s/%GREP%/$GREP/g" \
| sed "s/%AWK%/$AWK/g"   \
| sed "s/%SU%/$SU/g"     \
| sed "s/%KILL%/$KILL/g" \
| sed "s/%SED%/$SED/g"   \
| sed "s/%PATH%/$DIR2/g"   > $1/$DIR/$FILE
echo "chmod $MODE $1/$DIR/$FILE"
chmod $MODE $1/$DIR/$FILE
done
echo "installing README to $1/README"
cp README $1/README
echo "chmod 444 $1/README"
chmod 444 $1/README
echo "installing LICENSE to $1/LICENSE"
cp LICENSE $1/LICENSE
echo "chmod 444 $1/LICENSE"
chmod 444 $1/LICENSE


echo ""
echo ""
echo "Installation done."
echo "cd $1 and read the README file!!"
echo ""
echo "##### WARNING #####"
echo "You MUST read the README or you wont able to make the bot run correctly!!!"
echo "Have FUN!!"

