#!/bin/sh
    ##############################################
   ### MySource ------------------------------###
  ##- Installation Script ---- SH ------------##
 #-- Copyright Squiz.net ---------------------#
##############################################
## This file is subject to version 1.0 of the
## MySource License, that is bundled with
## this package in the file LICENSE, and is
## available at through the world-wide-web at
## http://mysource.squiz.net/
## If you did not receive a copy of the MySource
## license and are unable to obtain it through
## the world-wide-web, please contact us at
## mysource@squiz.net so we can mail you a copy
## immediately.
##
## $Source: /home/cvsroot/mysource/configure,v $
## $Revision: 2.25.2.3 $
## $Author: brobertson $
## $Date: 2002/12/13 00:56:31 $
#######################################################################

# Set up the configlog
CONFIGLOG="`pwd`/config.log"
DATADIRLIST="web site site/design page users user"
DATADIRTYPE="restricted unrestricted"
USERSQLFILES="mysql_users.sql mysql_users_populate.sql"
WEBSQLFILES="mysql_web.sql mysql_web_populate.sql"
REQUIRED_PHP_VERSION="4.2.0"
REQUIRED_MYSQL_VERSION="3.23.35"
echo  "Thank you for choosing MySource."
echo ""

linuxip() {
	ipaddress=`/sbin/ifconfig | grep -w "inet addr" | grep -vw "127.0.0.1" | cut -f2 -d':' | cut -f1 -d' ' | head -n 1`
}

bsdip() {
	ipaddress=`/sbin/ifconfig -a | grep -w "inet" | grep -vw "127.0.0.1" | cut -f2 -d' ' | head -n 1`
}

ostype=`uname`
case "$ostype" in
	Linux)
		linuxip
		;;
	*)
		bsdip
		;;
esac

echo "OSTYPE is $ostype." > $CONFIGLOG

echo  "Finding MySQL.."

if [ ! -f "/usr/bin/mysql" ]; then
    echo -n "Enter the BIN path for MySQL (include the bin dir) [/usr/bin]: "
    read mysqlpath
    if [ "$mysqlpath" = "" ]; then
        mysqlpath="/usr/bin"
    fi
else
    mysqlpath="/usr/bin"
fi

mysqlbin="$mysqlpath/mysql"
echo "MySQL binaries located at $mysqlpath." >> $CONFIGLOG
echo "MySQL located at $mysqlbin." >> $CONFIGLOG

if [ ! -f "$mysqlpath/mysqlshow" ]; then
    echo -n "Please enter the full path to the mysqlshow program [$mysqlpath/mysqlshow]: "
    read mysqlshow
else
    mysqlshow="$mysqlpath/mysqlshow"
fi
echo "mysqlshow is $mysqlshow." >> $CONFIGLOG

if [ ! -f "$mysqlpath/mysqladmin" ]; then
    echo -n "Please enter the full path to the mysqladmin program [$mysqlpath/mysqladmin]: "
    read mysqladmin
else
    mysqladmin="$mysqlpath/mysqladmin"
fi
echo "mysqladmin is $mysqladmin." >> $CONFIGLOG

echo -n "Checking version of MySQL..."

mysqlversion=`$mysqlbin -V | cut -f6 -d' '| cut -f1 -d','`
mysql_fullversion=`echo $mysqlversion | awk -F awk -F'.' '{ print $1$2$3 }'`

req_mysql_fullversion=`echo $REQUIRED_MYSQL_VERSION | awk -F awk -F'.' '{ print $1$2$3 }'`

echo "MySQL version is $mysqlversion" >> $CONFIGLOG

if [ ! $mysql_fullversion -ge $req_mysql_fullversion ]; then
    echo ""
    echo "Sorry, we need a MySQL version later than $REQUIRED_MYSQL_VERSION"
    echo "We recommend the latest stable release, available at http://www.mysql.com/"
    echo "After installing this, please try running the configure command again."
    echo "MySQL version not recent enough, aborting." >> $CONFIGLOG
    exit 0
else
    echo " OK."
fi

echo  -n "Checking version of PHP..."
phpfile="/usr/local/include/php/php_version.h"
if [ ! -f "$phpfile" ]; then
    echo "Couldn't find the version file for PHP."
    echo -n "Please type in the PHP version you are using (the full version number, no patch levels) [$REQUIRED_PHP_VERSION]: "
    read phpversion
    if [ "$phpversion" = "" ]; then
        phpversion="$REQUIRED_PHP_VERSION"
    fi
else
    phpversion=`cat $phpfile | grep -w "PHP_VERSION" | cut -d' ' -f3 | cut -d'"' -f2`
fi

echo "PHP version is $phpversion" >> $CONFIGLOG

php_fullversion=`echo $phpversion | awk -F'.' '{ print $1$2$3 }'`
req_php_fullversion=`echo $REQUIRED_PHP_VERSION | awk -F'.' '{ print $1$2$3 }'`

if [ ! $php_fullversion -ge $req_php_fullversion ]; then
    echo ""
    echo  "Sorry, we need a PHP version greater than $REQUIRED_PHP_VERSION"
    echo  "We recommend the latest stable release, available at http://www.php.net/"
    echo  "After installing or upgrading PHP, please try running the configure command again."
    echo  "PHP version not recent enough, aborting." >> $CONFIGLOG
    exit 0
else
    echo " OK."
fi

echo -n "Please enter a system name [$LOGNAME's system]: "
read systemname
if [ "$systemname" = "" ]; then
    systemname="$LOGNAME's system"
fi

currdir=`pwd`

echo -n "Please enter the System Root Directory for MySource [$currdir]: "
read systemroot
if [ "$systemroot" = "" ]; then
    systemroot="$currdir"
fi

echo ""
echo "Now setting up MySQL."
echo "The database(s) that you enter here will automatically be created."
echo ""

defaultwebdatabase=`pwd | awk -F '/' '{ print $(NF) }'`

echo -n "Please enter a Web Database Name [$defaultwebdatabase]: "
read webdatabase
if [ "$webdatabase" = "" ]; then
    webdatabase="$defaultwebdatabase"
fi
echo "Web database is $webdatabase" >> $CONFIGLOG

echo -n "Please enter your MySQL Web Database Host: [localhost]: "
read mysqlwebhost
if [ "$mysqlwebhost" = "" ]; then
    mysqlwebhost="localhost"
fi

echo -n "Please enter your MySQL Web Database Username: [root]: "
read mysqlwebusername
if [ "$mysqlwebusername" = "" ]; then
    mysqlwebusername="root"
fi

echo -n "Please enter your MySQL Web Database Password: []: "
read mysqlwebpassword

echo ""

echo -n "Please enter a User Database Name (This can be the same as the Web Database) [$webdatabase]: "
read userdatabase
if [ "$userdatabase" = "" ]; then
    userdatabase="$webdatabase"
fi
echo "User database is $userdatabase" >> $CONFIGLOG

echo -n "Please enter your MySQL User Database Host: [$mysqlwebhost]: "
read mysqluserhost
if [ "$mysqluserhost" = "" ]; then
    mysqluserhost="$mysqlwebhost"
fi

echo -n "Please enter your MySQL User Database Username: [$mysqlwebusername]: "
read mysqluserusername
if [ "$mysqluserusername" = "" ]; then
    mysqluserusername="$mysqlwebusername"
fi

echo -n "Please enter your MySQL User Database Password: []: "
read mysqluserpassword

echo ""

fullhostname=`uname -n`
echo -n "Please enter a MySource Web Master Email Address [$LOGNAME@$fullhostname]: "
read webmasteremail
if [ "$webmasteremail" = "" ]; then
    webmasteremail="$LOGNAME@$fullhostname"
fi
default_mysourcepassword=`uname -n`

echo "MySource uses its own user database. The first user account 'root' has been created."
echo -n "You will use this to log in intially. Please enter a MySource password to use [$default_mysourcepassword]: "
read mysourcepassword
if [ "$mysourcepassword" = "" ]; then
    mysourcepassword="$default_mysourcepassword"
fi

echo ""
echo "Finished setting up MySource. Now setting up Web Server."

echo -n "Please enter the user your webserver runs as [htdocs]: "
read webserveruser
if [ "$webserveruser" = "" ]; then
    webserveruser="htdocs"
fi

echo -n "Please enter the group your webserver runs as [htdocs]: "
read webservergroup
if [ "$webservergroup" = "" ]; then
    webservergroup="htdocs"
fi

echo -n "Please enter your server name [$fullhostname]: "
read webservername
if [ "$webservername" = "" ]; then
    webservername="$fullhostname"
fi

echo ""
echo "Please wait..."
echo ""

if [ "$systemroot" != `pwd` ]; then
    echo -n "Copying MySource to $systemroot..."
    echo "Copying MySource to $systemroot.." >> $CONFIGLOG
    if [ ! -d "$systemroot" ]; then
        echo "Creating $systemroot.." >> $CONFIGLOG
        mkdir $systemroot
        echo -n "This might take a little bit of time..."
        cp -rf * $systemroot
        echo " OK."
    else
        echo "This directory already exists. Either remove this directory, or choose another directory to install to."
        echo "We will abort the installation procedure so you can correct this error."
        echo "Directory $systemroot already exists, aborting." >> $CONFIGLOG
        exit 0
    fi
fi

echo -n "Checking database(s)..."
if [ "$mysqluserpassword" != "" ]; then
    userdblist=`$mysqlshow -h $mysqluserhost -u $mysqluserusername --password=$mysqluserpassword | grep -w "$userdatabase" | cut -f2 -d' '`
else
    userdblist=`$mysqlshow -h $mysqluserhost -u $mysqluserusername | grep -w "$userdatabase" | cut -f2 -d' '`
fi
if [ "$mysqlwebpassword" != "" ]; then
    webdblist=`$mysqlshow -h $mysqlwebhost -u $mysqlwebusername --password=$mysqlwebpassword | grep -w "$webdatabase" | cut -f2 -d' '`
else
    webdblist=`$mysqlshow -h $mysqlwebhost -u $mysqlwebusername | grep -w "$webdatabase" | cut -f2 -d' '`
fi
echo  "Userdblist returned '$userdblist'" >> $CONFIGLOG
echo  "Webdblist returned '$webdblist'" >> $CONFIGLOG

if [ "$userdblist" = "" ] && [ "$webdblist" = "" ]; then
    echo " OK."
else
    echo "We've come across an error."
    if [ "$webdblist" != "" ]; then
        echo "The Web database ($webdatabase) already exists."
        echo "Database $webdatabase already exists, aborting." >> $CONFIGLOG
    fi
    if [ "$userdblist" != "" ]; then
        echo  "The User database ($userdatabase) already exists."
        echo  "Database $userdatabase already exists, aborting." >> $CONFIGLOG
    fi
    echo "Stopping the installation. Please investigate & correct the error(s) above. After correcting the errors, run configure again."
    exit 0
fi

if [ "$webdatabase" = "$userdatabase" ]; then
    if [ "$mysqluserpassword" != "" ]; then
        mysqlrunning=`$mysqladmin -h $mysqluserhost --password=$mysqluserpassword -u $mysqluserusername ping`
    else
        mysqlrunning=`$mysqladmin -h $mysqluserhost -u $mysqluserusername ping`
    fi
    mysqlrunning2="$mysqlrunning"
else
    if [ "$mysqluserpassword" != "" ]; then
        mysqlrunning=`$mysqladmin -h$mysqluserhost --password=$mysqluserpassword -u $mysqluserusername ping`
    else
        mysqlrunning=`$mysqladmin -h$mysqluserhost -u $mysqluserusername ping`
    fi
    if [ "$mysqlwebpassword" != "" ]; then
        mysqlrunning2=`$mysqladmin -h$mysqlwebhost --password=$mysqlwebpassword -u $mysqlwebusername ping`
    else
        mysqlrunning2=`$mysqladmin -h$mysqlwebhost -u $mysqlwebusername ping`
    fi
fi
echo "'$mysqladmin ping' returned '$mysqlrunning'" >> $CONFIGLOG
echo "'$mysqladmin ping' returned '$mysqlrunning2'" >> $CONFIGLOG

if [ "$mysqlrunning" != "mysqld is alive" ] || [ "$mysqlrunning2" != "mysqld is alive" ]; then
    echo "MySQL is not running right now. Please start MySQL and run configure again."
    echo "MySQL is not running.. aborting." >> $CONFIGLOG
    exit 0
fi

# Create the database(s)...
echo -n "Creating the database(s)..."

if [ "$webdatabase" = "$userdatabase" ]; then
    if [ "$mysqluserpassword" != "" ]; then
    `$mysqladmin -h $mysqlwebhost --password=$mysqlwebpassword -u $mysqlwebusername create $webdatabase`
    else
    `$mysqladmin -h $mysqlwebhost -u $mysqlwebusername create $webdatabase`
    fi
else
    if [ "$mysqluserpassword" != "" ]; then
    `$mysqladmin -h $mysqluserhost --password=$mysqluserpassword -u $mysqluserusername create $userdatabase`
    else
    `$mysqladmin -h $mysqluserhost -u $mysqluserusername create $userdatabase`
    fi
    if [ "$mysqlwebpassword" != "" ]; then
    `$mysqladmin -h $mysqlwebhost --password=$mysqlwebpassword -u $mysqlwebusername create $webdatabase`
    else
    `$mysqladmin -h $mysqlwebhost -u $mysqlwebusername create $webdatabase`
    fi
fi
echo "created databases.." >> $CONFIGLOG
echo " OK."
echo ""

# Now we actually write the conf file.... overwrite it too!
# If it exists, rename it to .prev

conffile="$systemroot/conf/mysource.conf"

if [ -f "$conffile" ]; then
    echo "A previous configuration file already exists. Moving it to $conffile.prev"
    echo "conf file $conffile already exists. Moving." >> $CONFIGLOG
    mv -f $conffile $conffile.prev
fi
cat > $conffile <<-EOA
SystemName $systemname
SystemOwner $systemowner

WebDatabase $webdatabase $mysqlwebhost $mysqlwebusername $mysqlwebpassword

UserDatabase $userdatabase $mysqluserhost $mysqluserusername $mysqluserpassword

SuperUsers root

WebMasters root

WebMasterEmail $webmasteremail

MaxIdleTime 6000

MaxLoginAttempts 3

DefaultFrontendLanguage en

DefaultCharacterSet iso-8859-1

BackendSuffix _edit

EOA

# The main configure script imports all of the *.sql files.
# If a module needs to do it's own stuff, it runs it's own configure.

import_sql () {
# 1 = host
# 2 = username
# 3 = database password
# 4 = database name
# 5 = sql file location
# 6 = database type (mysql or pgsql - eventually)
	echo "Importing SQL from $5 into $4" >> $CONFIGLOG
	if [ -z "$3" ]; then
		`$mysqlbin -h $1 -u $2 $4 < $5`
	else
		`$mysqlbin -h $1 -u $2 --password=$3 $4 < $5`
	fi
	if [ $? -ne 0 ]; then
		echo "" >> $CONFIGLOG
		echo "*** Problem importing SQL file $5 into the database" >> $CONFIGLOG
		echo "" >> $CONFIGLOG
	fi
	return 0
}

echo -n "Importing Data.."

import_sql "$mysqluserhost" "$mysqluserusername" "$mysqluserpassword" "$userdatabase" "$systemroot/db/mysql_users.sql"
import_sql "$mysqlwebhost"  "$mysqlwebusername"  "$mysqlwebpassword"  "$webdatabase"  "$systemroot/db/mysql_web.sql"

# set up the root password.
cat > ./mysource-root.import <<-EOA
INSERT INTO user (userid,login,password,firstname) VALUES (1,'root',password('$mysourcepassword'),'ROOT');
EOA

import_sql "$mysqluserhost" "$mysqluserusername" "$mysqluserpassword" "$userdatabase" "./mysource-root.import"

echo "imported data & setup root user." >> $CONFIGLOG

echo "Cleaning Up.."
rm -f ./mysource-root.import
echo ""

echo -n "Setting up system directories..."

if [ ! -d "$systemroot/cache" ]; then
	mkdir $systemroot/cache
	echo "Making cache dir" >> $CONFIGLOG
else
	rm -f $systemroot/cache/*.*
	echo "Resetting cache dir" >> $CONFIGLOG
fi

for j in $DATADIRTYPE; do
	for i in $DATADIRLIST; do
		if [ ! -d "$systemroot/data/$j/$i" ]; then
			mkdir -p $systemroot/data/$j/$i
			echo "Making data directory $systemroot/data/$j/$i" >> $CONFIGLOG
		else
			echo "Data directory $systemroot/data/$j/$i already exists. It will not be re-created."
			echo "Data directory $systemroot/data/$j/$i already exists." >> $CONFIGLOG
		fi
	done;
done;

# Now we'll create the data directory for the root user since we're manually creating it.
if [ ! -d "$systemroot/data/unrestricted/user/1" ]; then
	mkdir -p $systemroot/data/unrestricted/user/1
	echo "Making data dirtectory for root user $systemroot/data/unrestricted/user/1" >> $CONFIGLOG
else
	echo "Data directory $systemroot/data/unrestricted/user/1 for root user already exists. It will not be re-created."
	echo "Data directory $systemroot/data/unrestricted/user/1 already exists." >> $CONFIGLOG
fi

echo " Done."

echo -n "Fixing file permissions..."
find $systemroot ! -name "configure" -type f -exec chmod 664 {} \;
find $systemroot -name "configure" -type f -exec chmod 775 {} \;
find $systemroot -type d -exec chmod 775 {} \;
echo  " OK."
echo ""

if [ "$UID" -eq 0 ]; then
	case "$ostype" in
		SunOS)
			chown -R $webserveruser:$webservergroup $systemroot
			;;
		*)
			chown -R $webserveruser.$webservergroup $systemroot
			;;
	esac
	echo "Logged in as root. Reset file ownerships to web-server user." >> $CONFIGLOG
else
	echo "I can't reset the file ownerships. You are currently not logged in as root."
	echo "Please log in as root, then run the command:"
	echo "    chown -R $webserveruser.$webservergroup $systemroot"
	echo "Thanks."
	echo "couldn't fix file permissions." >> $CONFIGLOG
fi

echo "Now configuring extensions (if available)..."

# Export some environment variables so the other configure scripts can find things more easily.
export MYSQLBIN=$mysqlbin
export MYSOURCEROOT=$systemroot

for i in `find $systemroot -type f -name "configure" -mindepth 2`; do
	extdirname=`dirname $i`
	echo "running $extdirname/configure" >> $CONFIGLOG
	echo "running $extdirname/configure" 
	cd $extdirname
	$i
	cd $systemroot
	echo
done

for i in $WEBSQLFILES; do
	for a in `find $systemroot/xtras -type f -name "$i"`; do
		import_sql "$mysqlwebhost"  "$mysqlwebusername"  "$mysqlwebpassword"  "$webdatabase"  "$a"
	done
done

for i in $USERSQLFILES; do
	for a in `find $systemroot/xtras -type f -name "$i"`; do
		import_sql "$mysqluserhost" "$mysqluserusername" "$mysqluserpassword" "$userdatabase" "$a"
	done
done

echo "Extensions plugged in."
echo ""

# Generate the Apache Conf section needed.
# Assumes some sort of setup already, we don't need to write the whole config!
echo "Generating necessary Apache Configuration Section.."
echo ""
echo "Apache Config below" >> $CONFIGLOG
echo ""
cat > $systemroot/Apache.conf <<-EOA
<VirtualHost $ipaddress>
    Port 80
    ServerAdmin $webmasteremail
    DocumentRoot $systemroot/web
    ServerName $webservername
    <Directory $systemroot/web>
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
    
    <Directory $systemroot/squizlib>
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>

    <Directory $systemroot/data/unrestricted>
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>

    AliasMatch "^(/.*)?/__lib(.*)$"       "$systemroot/web/__lib\$2"
    AliasMatch "^(/.*)?/__squizlib(.*)$"  "$systemroot/squizlib\$2"
    AliasMatch "^(/.*)?/__data(.*)$"      "$systemroot/data/unrestricted\$2"

    # Any HTTP request made at this domain followed by '/_edit'
    # will open the editing interface for that site, page etc.
    AliasMatch "^(/.*)?/_edit(.*)$"       "$systemroot/web/edit\$2"

    # Any *other* HTTP request made at this domain gets handled
    # by the MySource web frontend controller script.
    AliasMatch "^(/.*)?$"                 "$systemroot/web/index.php"

    # Example alternative at a particular subdirecory of this domain:
    #AliasMatch "^/path/to/mysource/section(/.*)?/__lib(.*)$"       "$systemroot/web/__lib\$2"
    #AliasMatch "^/path/to/mysource/section(/.*)?/__squizlib(.*)$"  "$systemroot/squizlib\$2"
    #AliasMatch "^/path/to/mysource/section(/.*)?/__data(.*)$"      "$systemroot/data/unrestricted\$2"
    #AliasMatch "^/path/to/mysource/section(/.*)?/_edit(.*)$"       "$systemroot/web/edit\$2"
    #AliasMatch "^/path/to/mysource/section(/.*)?$"                 "$systemroot/web/index.php"
</VirtualHost>
EOA

echo "Please add this section to your apache configuration file."
echo "It has also been saved as Apache.conf in the $systemroot directory for further reference."
echo "----- Start -----"
echo ""
cat Apache.conf
cat Apache.conf >> $CONFIGLOG
echo ""
echo "------ End ------"

echo "We have now finished configuring MySource."
echo "After adding the above configuration to your Apache configuration file, restart apache and check it works."
echo "Check you have a line in your apache configuration, with these entries (at a minimum):"
echo "    DirectoryIndex index.html index.php"
echo "To log in, open a web-browser, and go to $webservername/_edit (unless you changed our default Apache config)."
echo "Your username is root, your password is $mysourcepassword."
echo "Thank you for choosing MySource!"
echo "Your MySource Team,"
echo "http://mysource.squiz.net/"
echo "done." >> $CONFIGLOG
exit 0
