#! /bin/bash

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

# This script is an example for copying Moodle already installed to another
# directory and for let it accessible via another URI.

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

# このスクリプトは，
# すでにインストールされている Moodle のファイルを別のディレクトリにコピーし，
# 別の URI で独立して動作するように設置，設定します。

# サンプルですので，使う場合は適当に変更して使ってください。
# 特に，最初の２つの dirroot0, wwwroot0 の値は
# お使いのサーバの環境に合わせる必要があります。

# アップグレードする時も，
# コピー元のMoodleファイルを更新してからこのスクリプトを実行すれば
# ファイルをコピーして更新するようにしてあります。

# --------- これから作るMoodleサイトの設定 (config.php parameters)
dirroot0=/var/www/html/moodle
wwwroot0=http://${HOSTNAME}/moodle

dataroot0=/var/lib/moodledatdir/moodle

# dbname は，他の Moodle とは重ならないように注意。
# dbname must be unique.
# '_' (underscore) 等の記号も避けた方がよい。
dbname0=moodlerpm
dbuser0=moodlerpm

# 複数のMoodleサイトを作りたいとき，
# 例えば5個作りたいときは，以下の配列 instpf に5個書いてください。
# これらの文字を wwwroot0, dirroot0等の末尾に付け加えて設定を行います。
# instpf を定義しない場合は，付け加えずにそのまま1個だけ設置します。
# instpf=(01 02 03)

# 5分毎にMoodleのスケジュールタスクを動かすためのファイル
cronfile0=/etc/cron.hourly/moodle-chk

# ----------------------------------------------------------------------
# 元の Moodle のファイルがあるところ
origdirroot=/var/lib/moodle-rpm/moodle

# このスクリプトでのメッセージを日本語で出すかどうか，
# デフォルトを日本の設定にするか
if [ "$LANG" == "ja_JP.eucJP" ] ; then
    langja=yes
else
    unset langja
fi

rerun_msg(){
    echo ""
    if [ "$langja" == "" ] ; then
	echo "Setup failed. Rerun $0."
    else
	echo "コピーは失敗です。再度 $0 を実行してください。"
    fi
}
input_timeout_msg(){
    echo ""
    echo "Input timed out."
}

copy_all_files(){
    set -x
    rsync -au --delete --exclude='CVS' --exclude='.orig' --exclude='/config.php' $origdirroot/  $dirroot/
    set +x
}

if [ $UID -ne 0 ]; then
        if [ "$langja" == "" ] ; then
	    read -p "This script is not run as root. OK? [y/N] : " ans
        else
	    read -p "root 権限で実行していません。途中で失敗する可能性がありますが，いいですか? [y/N] : " ans
        fi
	if [ \( "$ans" != "Y" \) -a \( "$ans" != "y" \) ] ; then echo "nothing done."; exit 0; fi
fi


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

# アンインストールの場合   uninstall
if [ "$1" == "--uninstall" ]; then
    if [ "$langja" == "" ] ; then
	read -p "Remove all files under $dirroot and the DB($dbname). OK? [yes/no] : " ans
    else
	read -p "$dirroot の全ファイルとそのDB($dbname)のデータを消去していいですか? [yes/no] : " ans
    fi
    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

# アップグレードの場合   upgrade
#elif [ -e $dirroot/config.php ] || [ -e $dirroot/config-dist.php ] ; then
elif [ -e $dirroot/ ] ; then
    tmpdir=/tmp/`date --iso-8601=seconds`$dbname
    if [ "$langja" == "" ] ; then
	read -p "start upgrading $dirroot, OK? [Y/n] : " ans
    else
	read -p "$dirroot をアップグレードします。いいですか? [Y/n] : " ans
    fi		
    if [ \( "$ans" != "" \) -a \( "$ans" != "Y" \) -a \( "$ans" != "y" \) ] ; then echo "nothing done."; exit 0; fi
    set -x
    mkdir $tmpdir
    cp -a $dirroot/config.php $tmpdir/
    # 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 "$wwwroot に admin でログインして更新作業を行ってください。"

# 新規にコピーする場合 make a new copy
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
    if [ "$langja" == "" ] ; then
	echo "MySQL is not running.  You need to run MySQL to use moodle."
    else
	echo "MySQLが動いていません。MySQLを動かしてください。"
    fi
    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
    if [ "$langja" == "" ] ; then
	echo -n "Input MySQL root password : "
    else
	echo -n "MySQL の root のパスワードを入力してください : "
    fi
    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
    if [ "$langja" == "" ] ; then
	echo "MySQL root password is wrong."
    else
	echo "MySQL root パスワードが違います。"
    fi
    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
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; 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\";
     if('$langja' ne ''){
       print '\$INSTALL[\'language\']='.\"'ja_utf8';\n\";
       print '\$CFG->lang=' . \"'ja_utf8';\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 
#  -------------------------------------------------------------------

# patching lib/setup.php by perl -------------------------------------
#cp -a  $dirroot/lib/setup.php $dirroot/lib/setup.php.orig
#echo "patching lib/setup.php .."
#perl -pe " \
# s|(^\s*\\\$CFG->sessioncookie\s*=\s*).*$|\$1'$dbname';|; \
#" $dirroot/lib/setup.php.orig > $dirroot/lib/setup.php

### if( '$langja' ne ''){ s|en_utf8|ja_utf8|; }
#  -------------------------------------------------------------------

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 is done as follows:"
echo -e "\
--------------------------------------------------\n\
Web address (ウェブアドレス) : $wwwroot\n\
Moodle Directory (Moodleディレクトリ) : $dirroot\n\
Data Directory (データディレクトリ) : $dataroot\n\
Database (データベース) : $dbname\n\
User (of DB) (ユーザ) : $dbuser\n\
Password (パスワード) : $dbpass\n\
sessioncookie : $dbname\n\
--------------------------------------------------"
echo ""

if [ "$langja" == "" ] ; then
  echo "Visit $wwwroot and follow the instructions to finalize the installation(it is OK to proceed without changing the default data on the form)."
else
  echo "Webブラウザで $wwwroot にアクセスし，指示に従ってインストールしてください。（フォーム上のデータは変更せずにデフォルトのまま進んで大丈夫です。）"
fi

fi    ##  if [ "$1" == "--uninstall" ]; then

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