#!/bin/sh
#
# This is the Linux/Unix installer script for Project Based Calendaring System
#
# Written by Roalt Zijlstra <roalt@kwenie.org>
# First released with PBCS v0.4

# START of Defines
SCRIPT_VERSION=0.6.2
INSTALL_VERSION=0.6.2
INSTALL_EXTRA_VERSION=
TARBALL=pbcs-$INSTALL_VERSION$INSTALL_EXTRA_VERSION.tar.gz
TARBALL2=pbcs-$INSTALL_VERSION$INSTALL_EXTRA_VERSION.tar.bz2
TMP_DIR=/tmp
PATH=$PATH:/bin:/sbin:/usr/bin:/usr/sbin
# END of Defines - do not edit below.

function check_apache() {
# do a lot of hocus-spocus with httpd and the httpd.conf file to find
# all document roots of Apache.
# This only works with virtual host setups.

#	rm $TMP_DIR/PBCS-Installer.httpd.tmpfile 2>&1 > /dev/null
	rm $TMP_DIR/PBCS-Installer.httpd.tmpfile2 2>&1 > /dev/null
	`$HTTPD -S &> $TMP_DIR/PBCS-Installer.httpd.tmpfile`
	cat $TMP_DIR/PBCS-Installer.httpd.tmpfile | grep "default server" | cut -d '(' -f 2 | cut -d ')' -f 1 > $TMP_DIR/PBCS-Installer.httpd.tmpfile2
	cat $TMP_DIR/PBCS-Installer.httpd.tmpfile | grep "namevhost" | cut -d '(' -f 2 | cut -d ')' -f 1 >> $TMP_DIR/PBCS-Installer.httpd.tmpfile2
	COUNTER=1
	rm $TMP_DIR/PBCS-Installer.httpd.tmpfile 2>&1 > /dev/null
	rm $TMP_DIR/PBCS-Installer.httpd.docroot  2>&1 > /dev/null
	rm $TMP_DIR/PBCS-Installer.httpd.docroots  2>&1 > /dev/null
	touch $TMP_DIR/PBCS-Installer.httpd.docroot
	for LINE in `cat $TMP_DIR/PBCS-Installer.httpd.tmpfile2`; do
		FILENAME=`echo $LINE | cut -d ':' -f 1`
		DOCROOTLINE=`echo $LINE | cut -d ':' -f 2`
		head -$DOCROOTLINE $FILENAME | grep -v "#" | grep DocumentRoot | tail -1 | sed 's/"//g' | sed 's/DocumentRoot//g' | sed 's/ //g' >> $TMP_DIR/PBCS-Installer.httpd.docroot
		COUNTER=$((COUNTER+1))
	done
	# Check wether any virtualhosts where found, if not try to find
	# original httpd.conf config files.
	if [ `wc -l $TMP_DIR/PBCS-Installer.httpd.docroot | awk '{ print $1}'` -eq 0 ]; then 

		# Debian config file is here
		if [ -f /etc/apache/httpd.conf ]; then
			cat /etc/apache/httpd.conf | grep -v "#" | grep DocumentRoot | tail -1 | sed 's/"//g' | sed 's/DocumentRoot//g' | sed 's/ //g' > $TMP_DIR/PBCS-Installer.httpd.docroot
		fi

		# Red Hat config file
		if [ -f /etc/httpd/conf/httpd.conf ]; then
			cat /etc/httpd/conf/httpd.conf | grep -v "#" | grep DocumentRoot | tail -1 | sed 's/"//g' | sed 's/DocumentRoot//g' | sed 's/ //g' > $TMP_DIR/PBCS-Installer.httpd.docroot
		fi
		# SuSE config file
		if [ -f /etc/httpd/httpd.conf ]; then
			cat /etc/httpd/httpd.conf | grep -v "#" | grep DocumentRoot | tail -1 | sed 's/"//g' | sed 's/DocumentRoot//g' | sed 's/ //g' > $TMP_DIR/PBCS-Installer.httpd.docroot
		fi
	fi	
	sort $TMP_DIR/PBCS-Installer.httpd.docroot | uniq > $TMP_DIR/PBCS-Installer.httpd.docroots	
}

function show_result() {
	ARG=$*
	if [ "$ARG" = "" ]; then 
		echo "[NOT FOUND]"
	else
		echo "[FOUND] $ARG"
	fi
}

ARGS=$*
if [ "`echo $ARGS | cut -d '=' -f 1`" = "--temp-dir" ]; then
	TMP_DIR=`echo $ARGS | cut -d '=' -f 2`
fi
if [ "$ARGS" = "-h" ] || [ "$ARGS" = "--help" ]; then
	echo "Syntax: $0 [--temp-dir=<path>]"
	echo "PBCS-Installer.sh version $SCRIPT_VERSION - written by Roalt Zijlstra "
	echo 
	echo "This script will do a fresh install PBCS on Linux systems running MySQL "
	echo "and the Apache webserver."
	echo
	echo "Optional arguments:"
	echo "        --temp-dir        - Set the temporary directory where the tarball "
	echo "                            will be unpacked prior to installation."
	echo "        -h --help         - Shows this help message"
	echo
	exit
fi


clear
echo "Starting PBCS Installer $SCRIPT_VERSION which installs PBCS version" \
"$INSTALL_VERSION$INSTALL_EXTRA_VERSION."
echo
echo "This installation script requires you to know the following:"
echo
echo "- A tarball of PBCS $INSTALL_VERSION$INSTALL_EXTRA_VERSION in the current or the parent directory."
echo "- Apache webserver installed on the system"
echo "- The path where the Webserver document tree resides. (ie. /var/www)"
echo "- MySQL install on the system"
echo "- A special restricted user and password combination which can access"
echo "  the PBCS database only. (for testing root access can be used though)"
echo "- Enough space to hold 5Mb of data in /tmp. If you don't want /tmp to be used "
echo "  as temporary directory press Ctrl-C right now and start this script with "
echo "  added arguments --temp-dir=<your-tmp-dir>"
echo
echo "Checking some settings for you now...."
echo -n "Seeking PBCS tarred zip file $TARBALL: "
# Check if a pbcs tar.gz can be found.
if [ -f ./$TARBALL ]; then
	PBCS_TAR=./$TARBALL
elif [ -f ../$TARBALL ]; then
	PBCS_TAR=../$TARBALL
elif [ -f ../../$TARBALL ]; then
	PBCS_TAR=../../$TARBALL
else
	PBCS_TAR=""
fi
show_result $PBCS_TAR

# Also check for a .bz2 
if [ -f ./$TARBALL2 ]; then
	PBCS_TAR2=./$TARBALL2
elif [ -f ../$TARBALL2 ]; then
	PBCS_TAR2=../$TARBALL2
elif [ -f ../../$TARBALL2 ]; then
	PBCS_TAR2=../../$TARBALL2
else
	PBCS_TAR2=""
fi
show_result $PBCS_TAR2

echo -n "Seeking httpd using 'which httpd': "
HTTPD=`which httpd`
if [ "$HTTPD" = "" ]; then
	HTTPD=`which apache`
fi
show_result $HTTPD

check_apache

echo -n "Seeking mysql using 'which mysql': "
MYSQL=`which mysql`
show_result $MYSQL

echo -n "Seeking mysqladmin using 'which mysqladmin': "
MYSQLADMIN=`which mysqladmin`
show_result $MYSQLADMIN

echo "Temporary unpack directory is $TMP_DIR"

echo
echo "Press <RETURN> to proceed."
read BLOB

if [ "$HTTPD" = "" ]; then 
	echo "Cannot find the Apache binary (searched for httpd and apache)"
	echo "using the which-command. Bailing out now!"
	exit
fi

if [ "$PBCS_TAR" = "" ]; then
	if [ "$PBCS_TAR2" = "" ]; then
		echo "PBCS tarball not automatically found. It is needed for this script"
		echo "to install properly. Please enter the full path where it can be found."
	
		read TAR_PATH
		if [ -f $TAR_PATH/$TARBALL ]; then
			PBCS_TAR=$TAR_PATH/$TARBALL
		else
			echo "Tarball still not found, bailing out! Try again when you know where it is."
			exit
		fi
	fi
fi

if [ "$PBCS_TAR" != "" ]; then
	echo "Tarball found at $PBCS_TAR. Very good!"
fi
if [ "$PBCS_TAR2" != "" ]; then
	echo "Tarball found at $PBCS_TAR2. Very good!"
fi
echo
#echo "Now let's see if we can find all needed commands for you."
# commando's: mysql, mysqladmin, tar
#MYSQL=`which mysql`
#MYSQLADMIN=`which mysqladmin`
if [ ! -f $MYSQL ]; then
	echo "The command 'mysql' was not found.\nPlease specify the path" \
	     "where it can be found:"
	read MYSQL_PATH
	if [ -f $MYSQL_PATH/mysql ]; then
		MYSQL=$MYSQL_PATH/mysql
		if [ -f $MYSQL_PATH/mysqladmin ]; then
			MYSQLADMIN=$MYSQL_PATH/mysqladmin
		else
			echo "Cannot find 'mysqladmin' in $MYSQL_PATH, bailing out!"
			exit
		fi
	else
		echo "Cannot find 'mysql' in $MYSQL_PATH, bailing out!"
		exit
	fi
fi

if [ ! -f $MYSQLADMIN ]; then
	echo "The command 'mysqladmin' was not found.\nPlease specify the path" \
	     "where it can be found:"
	read MYSQLADMIN_PATH
	if [ -f $MYSQLADMIN_PATH/mysqladmin ]; then
		MYSQLADMIN=$MYSQLADMIN_PATH/mysqladmin
	else
		echo "Cannot find 'mysqladmin' in $MYSQL_PATH, bailing out!"
		exit
	fi
fi

echo "Found $MYSQL and $MYSQLADMIN. Good!"
echo

DOCROOTNUM=`wc -l $TMP_DIR/PBCS-Installer.httpd.docroots | awk '{ print $1}'`
if [ "$DOCROOTNUM" -gt "0" ]; then 
	echo "We found one or more DocumentRoots in your Apache config. Choose one "
	echo "of the following options: "
	COUNTER=1
        for LINE in `cat $TMP_DIR/PBCS-Installer.httpd.docroots`; do
		echo "[$COUNTER] - $LINE"
                COUNTER=$((COUNTER+1))
        done
	echo "[$COUNTER] - Specify a custom path"
	CUSTOM_PATH_ID=$COUNTER
	echo -n "Your choice: "
	read HTDOC_CHOICE
	# Sanity check the input
	NUM=`echo $HTDOC_CHOICE | awk '{ printf("%d",$1) }'`
	if [ $NUM -eq 0 ] || [ $NUM -gt $CUSTOM_PATH_ID ]; then
		echo "You made an invalid choice. This script will exit and you have to "
		echo "try again choosing a valid choice."
		exit
	fi
	if [ $NUM -eq $CUSTOM_PATH_ID ]; then
		echo "Enter the path where the Apache DocumentRoot can be found:"
		echo -n "Path: "
		read PBCS_INSTALL_PATH
		if [ ! -d $PBCS_INSTALL_PATH ]; then
			echo "The specified path does not exist so it probably is not a DocumentRoot of Apache."
			echo "Installation will be halted."
			exit
		fi
	else
		COUNTER=1
       		for LINE in `cat $TMP_DIR/PBCS-Installer.httpd.docroots`; do
			if [ $NUM -eq $COUNTER ]; then
				PBCS_INSTALL_PATH=$LINE
			fi
                	COUNTER=$((COUNTER+1))
        	done
	fi
fi

echo "The DocumentRoot of Apache is $PBCS_INSTALL_PATH."
echo
echo "Please specify the sub-directory name where PBCS should be installed in the "
echo "above DocumentRoot. Default is pbcs-$INSTALL_VERSION$INSTALL_EXTRA_VERSION and will be used if you "
echo "press ENTER on the prompt below."
echo -n "Install sub-directory: "
read PBCS_INSTALL_DIRNAME

if [ "$PBCS_INSTALL_DIRNAME" = "" ]; then
	PBCS_INSTALL_DIRNAME=pbcs-$INSTALL_VERSION$INSTALL_EXTRA_VERSION
fi

PBCS_INSTALL_FULLPATH=$PBCS_INSTALL_PATH/$PBCS_INSTALL_DIRNAME
echo "Okay, I will install it in $PBCS_INSTALL_FULLPATH"
mkdir $PBCS_INSTALL_FULLPATH
if [ ! -d $PBCS_INSTALL_FULLPATH ]; then
	echo "Could not create destination directory. Bailing out!"
	exit
fi
echo
echo "Extracting tarball."
if [ "$PBCS_TAR" ]; then
	tar -C $TMP_DIR -xzf $PBCS_TAR
fi
if [ "$PBCS_TAR2" ]; then
	tar --use=bzip2 -C $TMP_DIR -xf $PBCS_TAR2
fi
echo "Copying files into $PBCS_INSTALL_FULLPATH."
cp -a $TMP_DIR/pbcs-$INSTALL_VERSION$INSTALL_EXTRA_VERSION/* $PBCS_INSTALL_FULLPATH
echo "Removing temporary files."
rm -Rf $TMP_DIR/pbcs-$INSTALL_VERSION$INSTALL_EXTRA_VERSION
echo
echo "Now we get to the SQL part of PBCS. We need to create a new database"
echo "in which all PBCS data will be stored. But before we can do that we "
echo "need to know a username and password combination with enough rights"
echo "to create a database and add some tables."
echo
echo -n "Give an admin username for MySQL: "
read MYSQL_USER

echo -n "Give the password for it: "
read  MYSQL_PASSWORD

clear
echo -n "What will be the name of the database? : "
read DATABASE

echo -n "Does this database already exist? (y/n)"
read DB_YES_NO
if [ "$DB_YES_NO" = "y" ] || [ "$DB_YES_NO" = "Y" ]; then
	echo "Skipping database creation"
else
	echo "Creating database '$DATABASE'"
	$MYSQLADMIN -u $MYSQL_USER --password="$MYSQL_PASSWORD" create $DATABASE
	RETVAL=$?
	if [ "$RETVAL" -eq "1" ]; then
		echo "Failed to create database. Bailing out!"
		exit
	fi
fi

echo "Inserting tables for PBCS."
$MYSQL -u $MYSQL_USER --password="$MYSQL_PASSWORD" $DATABASE < $PBCS_INSTALL_FULLPATH/installation/Create-MySQL-Tables.sql
RETVAL=$?
if [ "$RETVAL" -eq "1" ]; then
	echo "Failed to insert tables. Bailing out!"
	exit
fi

echo "We are nearly done now."
echo "But we can do some extra configuration for you now."
echo
echo "The database needs to be accessed using a username and password."
echo "You can use the root user for that but that is not recommended."
echo "It will work though. The best thing to do is to add a special"
echo "'pbcs' user to the MySQL user table which has access to the PBCS"
echo "database only."
echo "Is there a special user which will be used to access the PBCS "
echo "database? (y/n)"
read S_USER_YN

if [ "$S_USER_YN" = "y" ]; then
	echo -n "Give the username: "
	read DB_USER
	echo -n "Give its password: "
	read DB_PASSWORD

	echo "This installer can create a MySQL user for you if it doesn't exist."
	echo "Does this user '$DB_USER' already exists? (y/n)"
	read USER_EXISTS

	if [ "$USER_EXISTS" = "n" ]; then
		SQL_CREATE=" \
INSERT INTO user (Host,User,Password) \
VALUES('localhost','$DB_USER',PASSWORD('$DB_PASSWORD')); \
INSERT INTO db \
(Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv, \
Create_priv,Drop_priv) \
VALUES \
('localhost','$DATABASE','$DB_USER','Y','Y','Y','Y','Y','Y'); \
FLUSH PRIVILEGES; \
"
		echo $SQL_CREATE | $MYSQL -u $MYSQL_USER --password="$MYSQL_PASSWORD" mysql
		echo "User created and database privileges flushed."
	else
		echo "OK! We assume that the given database user exists."
	fi

else
	echo "Using the earlier given admin user and password combo."
	echo "If you want to change it later. Edit the db.php file in the PBCS "
	echo "install directory."
	DB_USER=$MYSQL_USER
	DB_PASSWORD=$MYSQL_PASSWORD
fi



cat < $PBCS_INSTALL_FULLPATH/installation/install-templates/db-new1.php > \
      $PBCS_INSTALL_FULLPATH/db.php

echo "define(\"PBCS_DB\",\"mysql://$DB_USER:$DB_PASSWORD@localhost/$DATABASE\");" >> \
      $PBCS_INSTALL_FULLPATH/db.php

cat < $PBCS_INSTALL_FULLPATH/installation/install-templates/db-new2.php >> \
      $PBCS_INSTALL_FULLPATH/db.php

echo "Created a modified db.php file in $PBCS_INSTALL_FULLPATH"
echo
echo "Configfile setup"
echo
echo "We will also install a customized config.php in the config directory for you."
echo "But we need some more information for that."
echo
echo "At login an organisation name is shown. What name do you want to be displayed?"
echo -n "Organisation name: "
read ORG_NAME
echo
echo "In the about page a maintainer email address is shown. "
echo "What email address do you want to be displayed?"
echo -n "Email address: "
read SITE_MAINTAINER
echo
echo "PBCS now has a logging facility. Where do you want log files to go?"
echo "The default is in $PBCS_INSTALL_FULLPATH/logs. If you press ENTER this "
echo "path will be used. "
echo -n "Log path: "
read LOG_PATH

if [ "$LOG_PATH" = "" ]; then
	LOG_PATH=$PBCS_INSTALL_FULLPATH/logs
fi

echo "Be sure that the Apache user is able to write in the log directory $LOG_PATH."
echo 
echo -n "Writing config file in $PBCS_INSTALL_FULLPATH/config: "

IFS="
"
rm $PBCS_INSTALL_FULLPATH/config/config.php
touch $PBCS_INSTALL_FULLPATH/config/config.php
for LINE in `cat $PBCS_INSTALL_FULLPATH/installation/install-templates/config-install.php`; do 
	echo $LINE | grep "%%" > /dev/null
	RETVAL=$?
	if [ "$RETVAL" -eq 0 ]; then
		VARIABLE=`echo $LINE | cut -d '%' -f 3`
		case "$VARIABLE" in 
			PBCS_RELATIVE)
				echo "\$pbcs_relative_path = \"/$PBCS_INSTALL_DIRNAME/\";" >> $PBCS_INSTALL_FULLPATH/config/config.php
				;;
			PBCS_ABSOLUTE)
				echo "\$pbcs_absolute_path = \"$PBCS_INSTALL_PATH\".\$pbcs_relative_path;" >> $PBCS_INSTALL_FULLPATH/config/config.php
				;;
			ORGNAME)
				echo "\$org_name = \"$ORG_NAME\";" >> $PBCS_INSTALL_FULLPATH/config/config.php
				;;
			SITE_MAINTAINER)
				echo "\$site_maintainer = \"$SITE_MAINTAINER\";" >> $PBCS_INSTALL_FULLPATH/config/config.php
				;;
			LOG_PATH)
				echo "\$log_path = \"$LOG_PATH/\";" >> $PBCS_INSTALL_FULLPATH/config/config.php
				;;
		esac
	else 
		echo $LINE >> $PBCS_INSTALL_FULLPATH/config/config.php
	fi
done
echo " [DONE]"
echo
echo "And ready! You should now be able to browse PBCS on your webserver."
echo "To change the login image and a lot of  other settings, have a look at  the config/config.php file."

