#!/bin/sh
# postinst script for moodle
#
# see: dh_installdeb(1)
#
# summary of how this script can be called:
#        * <postinst> `configure' <most-recently-configured-version>
#        * <old-postinst> `abort-upgrade' <new version>
#        * <conflictor's-postinst> `abort-remove' `in-favour' <package>
#          <new-version>
#        * <postinst> `abort-remove'
#        * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
#          <failed-install-package> <version> `removing'
#          <conflicting-package> <version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package

set -e
#set -x

if [ -f /etc/dbconfig-common/moodle.conf ] ; then
	. /etc/dbconfig-common/moodle.conf
fi

# source debconf stuff
. /usr/share/debconf/confmodule
# source dbconfig-common stuff
. /usr/share/dbconfig-common/dpkg/postinst

check_php5mysql_notinstalled() {
    dpkg -s php5-mysql | grep Status | grep -q installed >/dev/null 2>&1 && return 1
    return 0
}

check_php5psql_notinstalled() {
    dpkg -s php5-pgsql | grep Status | grep -q installed >/dev/null 2>&1 && return 1
    return 0
}

moodle_config() {
	local cfile=/etc/moodle/config.php
	local tempfile=`tempfile`
	local wwwroot

	db_get moodle/www
	wwwroot="$RET"
	if [ -z "$dbc_dbserver" ]; then
		dbc_dbserver="localhost";
	fi
	if [ "$dbc_dbtype" = "pgsql" ]; then
		dbc_dbtype="postgres7"
	fi
	cat > $tempfile <<EOF
<?php
 # This file has been generated by debconf
 # You can find a commented config file in /usr/share/doc/moodle/

 unset(\$CFG);
 \$CFG = new stdClass();

 \$CFG->dbtype = '${dbc_dbtype}';
 \$CFG->dbhost = '${dbc_dbserver}';
 \$CFG->dbname = '${dbc_dbname}';
 \$CFG->dbuser = '${dbc_dbuser}';
 \$CFG->dbpass = '${dbc_dbpass}';
 \$CFG->prefix = 'mdl_';

 \$CFG->wwwroot = '${wwwroot}';
 \$CFG->dirroot = '/usr/share/moodle';
 \$CFG->dataroot = '/var/lib/moodle';
 \$CFG->directorypermissions = 0750;
 \$CFG->admin = 'admin';

 \$CFG->pathtodu = '/usr/bin/du';
 \$CFG->unzip = '/usr/bin/unzip';
 \$CFG->zip = '/usr/bin/zip';

 \$CFG->respectsessionsettings = true;

 # For improved security, make sure html purifier is used.
 \$CFG->enablehtmlpurifier = true;

        if (file_exists("\$CFG->dirroot/lib/setup.php"))  {       // Do not edit
                include_once("\$CFG->dirroot/lib/setup.php");
        } else {
                if (\$CFG->dirroot == dirname(__FILE__)) {
                        echo "<p>Could not find this file: \$CFG->dirroot/lib/setup.php</p>";
                        echo "<p>Are you sure all your files have been uploaded?</p>";
                } else {
                        echo "<p>Error detected in config.php</p>";
                        echo "<p>Error in: \\\$CFG->dirroot = '\$CFG->dirroot';</p>";
                        echo "<p>Try this: \\\$CFG->dirroot = '".dirname(__FILE__)."';</p>";
                }
                die;
        }
// MAKE SURE WHEN YOU EDIT THIS FILE THAT THERE ARE NO SPACES, BLANK LINES,
// RETURNS, OR ANYTHING ELSE AFTER THE TWO CHARACTERS ON THE NEXT LINE.
?>
EOF
    ucf --debconf-ok $tempfile $cfile
    chmod 640 $cfile
    chown www-data:www-data $cfile
}

apache_config() {
	local wwwroot
	local alias
	local tmp
	local tempfile=`tempfile`
	local cfile="/etc/moodle/apache.conf"
	local php_settings

	php_settings="<IfModule mod_php5.c>
        php_flag magic_quotes_gpc Off
        php_flag magic_quotes_runtime Off
        php_flag file_uploads On
        php_flag short_open_tag On
        php_flag session.auto_start Off
        php_flag session.bug_compat_warn Off

        php_value upload_max_filesize 2M
        php_value post_max_size 2M
</IfModule>"
	
	db_get moodle/www
	wwwroot="$RET"
	
	#check if it's possible to do the alias
	tmp=`echo $wwwroot | sed 's#^https*://[^/]*/*##'`

	if [ -n "$tmp" ]; then
		tmp_alias="#Uncomment the line below if you want to use alias
#This will not work well with virtual hosts
Alias /${tmp} /usr/share/moodle/"
	else
		tmp_alias="#You can't use alias becuse you Moodls is not in a sub-directory
#Create appropriate virtual host insted."
	fi

	cat > $tempfile <<EOF
# This file has been generated by debconf 

${tmp_alias}

<DirectoryMatch /usr/share/moodle/>

Options +FollowSymLinks
AllowOverride None

order deny,allow
deny from all

allow from 127.0.0.0/255.0.0.0
allow from localhost
#comment out the line below to allow remote access
#allow from all

${php_settings}

<IfModule mod_dir.c>
        DirectoryIndex index.php
</IfModule>

</DirectoryMatch>
EOF
    ucf --debconf-ok $tempfile $cfile
    chmod 640 $cfile
    chown www-data:www-data $cfile


#Sample config for the virtual host
	tempfile=`tempfile`
        cfile="/etc/moodle/apache.vhost.conf"
	server=`echo $wwwroot |cut -d'/' -f3`
	cat > $tempfile <<EOF
<VirtualHost *:80>
        ServerAdmin webmaster@${server}
	ServerName ${server}
        DocumentRoot /usr/share/moodle/
        <Directory /usr/share/moodle/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride None
                Order allow,deny
                allow from all
${php_settings}
        </Directory>

        ErrorLog \${APACHE_LOG_DIR}/error.log

        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel warn

        CustomLog \${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
EOF

    ucf --debconf-ok $tempfile $cfile
    chmod 640 $cfile
    chown www-data:www-data $cfile

}

dbc_first_version="1.9.8-1"
dbc_go moodle $@
#wwwroot="http://localhost/moodle"

case "$1" in
    configure)
#	tempcfile=`tempfile`
	moodle_config
	apache_config
#	ucf --debconf-ok $tempfile $cfile
#	chmod 640 $cfile
#	chown www-data:www-data $cfile
	cfile=/etc/moodle/config.php
	moodledir=/usr/share/moodle

#        if [ -r /etc/moodle/config.php ]; then
        [ -f $moodledir/config.php ] && rm $moodledir/config.php
        ln -s $cfile $moodledir/config.php
#        fi

	# Allow for conflicting debian/ubuntu smarty paths..
        if [ -e /usr/share/php/smarty/libs/Smarty.class.php ]; then
            # Debian has the smarty class in /usr/share/php/smarty/libs
            # Make sure the link is correct (#603255)
            rm -rf /usr/share/moodle/lib/smarty
            ln -s /usr/share/php/smarty/libs /usr/share/moodle/lib/smarty
        else
            # Where as Ubuntu has the smarty class in /usr/share/php/smarty
            [ ! -h /usr/share/moodle/lib/smarty ] && ln -s /usr/share/php/smarty /usr/share/moodle/lib/smarty
        fi

        # Make sure the link is correct (#603255)
        rm -rf /usr/share/moodle/lib/yui
        ln -s /usr/share/javascript/yui /usr/share/moodle/lib/yui

        [ ! -h /usr/share/moodle/lib/magpie ] && ln -s /usr/share/php/magpierss /usr/share/moodle/lib/magpie

	[ ! -h /usr/share/moodle/lib/fpdf/font ] && ln -s /usr/share/php/fpdf/font /usr/share/moodle/lib/fpdf/font
	[ ! -h /usr/share/moodle/lib/fpdf/fpdf.php ] && ln -s /usr/share/php/fpdf/fpdf.php /usr/share/moodle/lib/fpdf/fpdf.php

	[ ! -h /usr/share/moodle/lib/pclzip ] && ln -s /usr/share/php/libphp-pclzip /usr/share/moodle/lib/pclzip

	[ ! -h /usr/share/moodle/lib/snoopy/Snoopy.class.inc ] && ln -s /usr/share/php/libphp-snoopy/Snoopy.class.php /usr/share/moodle/lib/snoopy/Snoopy.class.inc

	repository=/var/lib/moodle
        if [ -d $repository ]; then
            chown -R www-data:www-data $repository
            chmod 0750 $repository
        fi

	if [ "$dbc_dbtype" = "mysql" ] && check_php5mysql_notinstalled ; then
		echo 'Error - You have specified that you wish to use a mysql' >&2
	        echo 'database, but php5-mysql is not installed. You must install' >&2
		echo 'php5-mysql before you can complete your moodle installation.' >&2
	fi

	if [ "$dbc_dbtype" = "postgresql" ] && check_php5psql_notinstalled ; then
		echo 'Error - You have specified that you wish to use a postgresql' >&2
		echo 'database, but php5-pgsql is not installed. You must install' >&2
		echo 'php5-pgsql before you can complete your moodle installation.' >&2
	fi
    ;;

    abort-upgrade|abort-remove|abort-deconfigure)
    ;;

    *)
        echo "postinst called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac


#DEBHELPER#

exit 0
