#! /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 run it.

# このスクリプトは，
# すでにインストールされている Moodle のファイルを別のディレクトリにコピーし，
# 別の URI で独立して動作するように設定します。
# サンプルですので，使う場合は適当に変更して使ってください。

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

# 元の Moodle のファイルがあるところ
origdirroot=/var/www/html/fromCVS/moodle

# --------- これから作るMoodleサイトの設定 (config.php parameters)
wwwroot0=http://www.foo.bar/le/modlis
dirroot0=/var/www/html/le/modlis
dataroot0=/var/lib/moodledatdir/modlis

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

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

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


# ----------------------------------------------------------------------
# このスクリプトでのメッセージを日本語で出すかどうか，
# デフォルトを日本の設定にするか
if [ "$LANG" == "ja_JP.UTF-8" ] ; 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/
#	cp -a  $origdirroot/[!l]*   $dirroot/
#	cp -a  $origdirroot/l[!a]*  $dirroot/
#	mkdir $dirroot/lang
#	# 言語パックは最小限。
#	for langpack in  en ja ja_utf8 en_ja; do
#		cp -a  $origdirroot/lang/$langpack  $dirroot/lang/
#	done
    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, DB for $dirroot. OK? [yes/no] : " ans
    else
	read -p "$dirroot ファイル，DB，消していい? [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
    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
#    rm -rf $dirroot/*
    set +x
    copy_all_files # ファイルをコピー
#    cp -a  $tmpdir/config.php  $dirroot/  # config.php を戻す
    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 lib/defaults.php by perl
cp -a  $dirroot/lib/defaults.php $dirroot/lib/defaults.php.orig
echo "patching lib/defaults.php .."
perl -pe " \
 if( '$langja' ne ''){ \
  s|(^\s*'country'\s*=>\s*)'[^']*'|\$1'JP'|; \
 } \
 s|(^\s*'sessioncookie'\s*=>\s*)'[^']*'|\$1'$dbname'|; \
 s|(^\s*'fullnamedisplay'\s*=>\s*)'[^']*'|\$1'language'|; \
" $dirroot/lib/defaults.php.orig > $dirroot/lib/defaults.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 " \
 if( '$langja' ne ''){ s|en_utf8|ja_utf8|; }\
 s|(^\s*\\\$CFG->sessioncookie\s*=\s*).*$|\$1'$dbname';|; \
" $dirroot/lib/setup.php.orig > $dirroot/lib/setup.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 is done as follows:"
echo -e "\
Web address (ウェブアドレス) : $wwwroot\n\
Moodle Directory (Moodleディレクトリ) : $dirroot\n\
Data Directory (データディレクトリ) : $dataroot\n\
Database (データベース) : $dbname\n\
User (ユーザ) : $dbuser\n\
Password (パスワード) : $dbpass\n\
sessioncookie : $dbname"
echo ""
# echo "Edit $dirroot/config.php if you wish, and"
# echo "access $wwwroot and follow the instructions to finalize the installation."
#echo "もし必要なら $dirroot/config.php を変更し，"
echo "$wwwroot にアクセスし，指示に従ってインストールしてください。"
#echo "（同一ホストに複数のMoodleを置いている場合，「詳細設定」の画面で，sessioncookieを重ならないように個別に設定する必要があります。）"

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

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