#! /bin/bash

# KITA Toshihiro  http://t-kita.net/
# Thanks to the suggestions from YOSHIDA Mitsuhiro http://mitstek.com/

# This script is for preparing Moodle installation before you install Moodle with Web browser.
# tested on CentOS 5, VineLinux 4.2. 

# This script is distributable under the same license as Moodle (i.e. GPL).

# usage:
# to install, or to upgrade, put the latest Moodle archive file and run
#  mk-moodle-instance.sh
# to uninstall
#  mk-moodle-instance.sh --uninstall
#
# be sure to set the following PARAMETERS according to your server settings.

# PARAMETERS -----------------------

# specify Moodle archive file to extract
# moodlefile=./moodle-1.9.tgz
# or specify the directory of (extracted) Moodle files to be copied from
# origdirroot=/home/foo/tmp/moodle
origdirroot=/var/lib/moodle-rpm/moodle

# config.php parameters (maybe you should edit dirroot0 and wwwroot0)
dirroot0=/var/www/html/moodle
wwwroot0=http://${HOSTNAME}/moodle
dataroot0=/var/lib/moodledatdir/moodle

dbname0=moodlerpm
dbuser0=moodlerpm
cronfile0=/etc/cron.hourly/moodle-chk   # this file runs every 5 minutes

# If you want to set up several Moodle instances at at time,
# for example five instances, put five words into the array 'instpf'.
# Setup is peformed adding these words to wwwroot0, dirroot0, .., cronfile0 as the suffixes.
# If 'instpf' is not defined, only one instance will be created without adding a suffix.
#  instpf=(01 02 03)

# PARAMETERS END --------------------


rerun_msg(){
    echo "Setup failed. Rerun $0."
}
input_timeout_msg(){
    echo ""
    echo "Input timed out."
}
extract_moodle_files(){
    if [ "$origdirroot" == "" ] ; then
       origdirroot=/tmp/moodle
       if [ -e $origdirroot/ ] ; then rm -r $origdirroot/; fi
       echo "Extracting $moodlefile ..."
       tar xzf $moodlefile -C /tmp/
       if [ ! -e $origdirroot/ ] ; then
         echo "Extracting failed."
         exit 0
       fi
    else
       echo "Using $origdirroot"
    fi
}
copy_all_files(){
    set -x
    rsync -au --delete --exclude='CVS' --exclude='.orig' --exclude='/config.php' $origdirroot/  $dirroot/
    set +x
}


if [ $UID -ne 0 ]; then
    read -p "This script is not run as root. OK? [Y/n] : " ans
    if [ \( "$ans" == "N" \) -o \( "$ans" == "n" \) ] ; then echo "nothing done."; exit 0; fi
fi

# preparation (CentOS 5)
# yum install mysql mysql-server
# yum install php-gd php-mysql php-mbstring php-xmlrpc
# service mysqld restart
# service httpd restart


if [ "$instpf" == "" ] ; then
    instpf=("__withoutpf__")
fi

######################### loop for all in $instpf ########################
for pf in ${instpf[@]}; do

if [ "$pf" == "__withoutpf__" ] ; then
    wwwroot=$wwwroot0
    dirroot=$dirroot0
    dataroot=$dataroot0
    dbname=$dbname0
    dbuser=$dbuser0
    cronfile=$cronfile0
else
    wwwroot=$wwwroot0$pf
    dirroot=$dirroot0$pf
    dataroot=$dataroot0$pf
    dbname=$dbname0$pf
    dbuser=$dbuser0$pf
    cronfile=$cronfile0$pf
fi


# ------------- uninstalling ---------------
if [ "$1" == "--uninstall" ]; then
    read -p "Remove all files under $dirroot and the DB($dbname). OK? [yes/no]: " ans
    if [ "$ans" == "yes" ] ; then
	set -x
	rm -rf $dirroot $dataroot
	rm $cronfile
	set +x
	SQL_uninst="revoke ALL ON $dbname.* FROM $dbuser@localhost; drop database $dbname;"
	echo $SQL_uninst
	echo "for clearing DB $dbname... "
	echo -n "MySQL "; mysql -u root --exec="$SQL_uninst" -p
	echo "for reloading MySQL.. "
	echo -n "MySQL "; mysqladmin -u root -p reload 
    fi
# ------------- uninstalling end ---------------

# ------------- upgrading ---------------
#elif [ -e $dirroot/config.php ] || [ -e $dirroot/config-dist.php ] ; then
elif [ -e $dirroot/ ] ; then
    tmpdir=/tmp/`date --iso-8601=seconds`$dbname
    read -p "start upgrading $dirroot, OK? [Y/n] : " ans
    if [ \( "$ans" != "" \) -a \( "$ans" != "Y" \) -a \( "$ans" != "y" \) ] ; then echo "nothing done."; exit 0; fi
    extract_moodle_files
    set -x
    mkdir $tmpdir
    cp -a $dirroot/config.php $tmpdir/
    # make diff just in case
    diff -Naru --exclude='CVS' $origdirroot $dirroot > $tmpdir/diff
    set +x
    copy_all_files
    # chown apache $dirroot  # for config.php creation
    echo ""
    echo "Login $wwwroot as admin to complete the upgrading process."
# ------------- upgrading end ---------------

# ---------- making a new instance (almost until the end of this file) -------------
else    ##    if [ "$1" == "--uninstall" ]; then
# if MySQL is not running, exit.
mysqladmin -u dummy ping > /dev/null 2>&1
RETVAL=$?
if [ $RETVAL -ne 0 ] ; then
   echo "MySQL is not running.  You need to run MySQL to use moodle."
   rerun_msg
   exit 1
fi

# remember MySQL password if any
mysql -u root --exec="" > /dev/null 2>&1
RETVAL=$?
if [ $RETVAL -ne 0 ] && [ "$pas" == "" ] ; then
    echo -n "Input MySQL root password : "
    read -t 300 -s pas < /dev/tty
    RETVAL=$?
    if [ $RETVAL -ne 0 ] ; then input_timeout_msg; rerun_msg; exit 1;  fi
    echo ""
fi
# check if the password is right
mysql -u root --exec="" --password="$pas" > /dev/null 2>&1
RETVAL=$?
if [ $RETVAL -ne 0 ] ; then
    echo "MySQL root password is wrong."
    rerun_msg
    exit 3
fi

# if database named $dbname exists, do not overwrite.
mysqlshow -u root --password="$pas" $dbname > /dev/null 2>&1
RETVAL=$?
if [ $RETVAL -eq 0 ] ; then
    echo "It seems DB '$dbname' already exists. Exiting."
    exit 0
fi

echo ""
if [ -e $dirroot/* ]; then
    echo "Some file exists in copying destination $dirroot. Exiting."
    rerun_msg
    exit 4
fi
mkdir -p $dirroot $dataroot
chown apache $dataroot || chmod 777 $dataroot
extract_moodle_files
copy_all_files
# chown apache $dirroot  # for config.php creation

# generate dbpass randomly
dbpass=`awk 'BEGIN{srand(); s="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; for(i=0;i<12;i++){ printf("%s",substr(s,rand()*61.9+1,1)); }}'`

# DB setup SQL command
SQL_POST="CREATE DATABASE $dbname DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci; GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP,INDEX,ALTER ON $dbname.* TO $dbuser@localhost IDENTIFIED BY '$dbpass';"
echo $SQL_POST

mysql -u root --exec="$SQL_POST" --password="$pas" > /dev/null 2>&1
RETVAL=$?
mysqladmin -u root  --password="$pas" reload 
if [ $RETVAL -eq 0 ] ; then
	echo "DB setup for moodle is done."
else
	echo "DB setup error!"
fi

# patching install.php by perl ----------------------------------------
echo -n "patching install.php .."
cp -a  $dirroot/install.php  $dirroot/install.php.orig
perl -e "
while(<>){
 print \$_;
 if (/if\s*\(\s*empty\(\\\$INSTALL\['language'\]\)/){
  if (/{/){ \$pco++; }
   while(<>){
    if (/{/){ \$pco++; }
    if (/}/){
     \$pco--;
     if (\$pco==0){
     print \"\n\";
     print '\$INSTALL[\'wwwrootform\']=' . \"'$wwwroot';\n\";
     print '\$INSTALL[\'dirrootform\']=' . \"'$dirroot';\n\";
     print '\$INSTALL[\'dataroot\']=' . \"'$dataroot';\n\";
     print '\$INSTALL[\'dbuser\']=' . \"'$dbuser';\n\";
     print '\$INSTALL[\'dbpass\']=' . \"'$dbpass';\n\";
     print '\$INSTALL[\'dbname\']=' . \"'$dbname';\n\";
     print \$_;
     last;
    }
   }
   print \$_;
  }
 }
}
" $dirroot/install.php.orig > $dirroot/install.php
# chgrp apache $dirroot/config.php  &&  chmod 640 $dirroot/config.php
#  -------------------------------------------------------------------

# patching admin/index.php by perl ----------------------------------
# cp -a  $dirroot/admin/index.php $dirroot/admin/index.php.orig
# echo ""
# echo "patching admin/index.php .."
# perl -pe " 
# \$replstr= \"apply_default_exception_settings(array(
#  'country' => 'JP',
#  'sessioncookie' => '$dbname',
#  'fullnamedisplay' => 'language' ));\n\"; 
# if( '$langja' ne ''){ 
#  s|(^\s*apply_default_exception_settings\()|\$replstr\$1|; 
# }
# " $dirroot/admin/index.php.orig > $dirroot/admin/index.php 
#  -------------------------------------------------------------------

echo "putting $cronfile .."
echo -e "#! /bin/sh\n\
for a in 0 5 10 15 20 25 30 35 40 45 50 55; do\n\
        wget -q -O /dev/null  $wwwroot/admin/cron.php\n\
        sleep 300\n\
done " >> $cronfile
chmod +x $cronfile

echo -e "setup (including DB and DB user creation) is done as follows:"
echo -e "\
--------------------------------------------------\n\
Web address  : $wwwroot\n\
Moodle Directory  : $dirroot\n\
Data Directory  : $dataroot\n\
Database  : $dbname\n\
User (of DB)  : $dbuser\n\
Password  : $dbpass\n\
sessioncookie : $dbname\n\
--------------------------------------------------"
echo ""

echo "Visit $wwwroot and follow the instructions to finalize the installation (it is OK to proceed without changing the default data on the first several pages of installation)."

fi    ##  if [ "$1" == "--uninstall" ]; then
# ------------- making a new instance end ---------------

done

######################### loop for all in $instpf ########################
