#!/bin/bash

###############################################################################
#  My  Function
###############################################################################

encryptionBin=`pwd`"/mssBak/script/encryption"

#mysql_user=`$encryptionBin 1 "6266706d736f7a7c7b6b7f7b7f"`
#mysql_pw=`$encryptionBin 1 "2b3a392757557b697b7e7e757b777c"`

mysql_user=administrator
mysql_pw=*86#ROtartsinim
service mysql stop

step=0
myShowTitle()
{
	#thisVersion=`cat ./emsVersion |grep Version|awk '{print $2}'`
	#clear
	#echo -e "10  [1;29m WELCOME to INSTALL AGrandTech litCore Soft Switch EMS $thisVersion ![0;39m  
 #"
    local title="$1"
	echo "+-----------------------------------------------------------------------------+"
	# echo -e "60  [1;32m $1[0;39m"
    echo -e "\033[1;32mStep $step: $title\033[0;39m"
	echo "+-----------------------------------------------------------------------------+"
    step=$((step + 1))
}

myShowResultOrg()
{
	if [ "$1" = "OK" ] || [ "$1" = "ok" ] ; then
		echo "[60G[  [1;32mOK[0;39m  ]
$2"
	elif [ "$1" == "FAILED" ] || [ "$1" == "failed" ] ; then
		echo "[60G[[1;31mFAILED[0;39m]
$2"
	else
		echo "[60G[[1;32m $1 [0;39m]
$2"
	fi
}

myShowResult()
{
	if [ "$1" = "OK" ] || [ "$1" = "ok" ] ; then
		echo "[72G[  [1;32mOK[0;39m  ]$2"
	elif [ "$1" == "FAILED" ] || [ "$1" == "failed" ] ; then
		echo "[72G[[1;31mFAILED[0;39m]$2"
	else
		echo "[72G[[1;32m $1 [0;39m]$2"
	fi
}

#useage:myAddUser $userName $userPwd $groupName $homeDir $remark $shType
myAddUser()
{
	echo "Add user $1 ..."
	groupadd -f $3 
	useradd -c "$5" -g $3 -d $4 -s $6 $1 2>>/dev/null
	echo "$2" | passwd --stdin $1
	chown -R $1:$3 $4
}

#useage: upGradeDb $dbName $tableName
upGradeDb()
{
	echo -n "Upgrade $1.$2"
	if [ `uname -r |grep -c '2.4.7-10'` -eq 1 ] ; then
		dataDir="/usr/local/mysql/data"
		mysqlBinDir="/usr/local/mysql/bin"
	else
		dataDir="/usr/local/mysql"
		mysqlBinDir="/usr/bin/"
	fi
	rm -rf $dataDir/$1_BK
	cp -r /usr/local/omcBak/data/$1 $dataDir/$1_BK
	chgrp -R mysql $dataDir/
	chown -R mysql $dataDir/
	chmod -R 755   $dataDir/
    echo "CREATE DATABASE IF NOT EXISTS $1;" | $mysqlBinDir/mysql -u$mysql_user -p$mysql_pw

    # Check if the database exists
    if [ -z "$2" ]; then
        tableArr=`echo "show tables from $1_BK;" | $mysqlBinDir/mysql -u$mysql_user -p$mysql_pw | sed -e '1d'`
    else
        tableArr=`echo "show tables from $1_BK like '$2';" | $mysqlBinDir/mysql -u$mysql_user -p$mysql_pw | sed -e '1d'`
    fi
	for table in $tableArr; do
		if ( test -e "$dataDir/$1/$table.frm" ) then
			diffFlag_frm=`diff $dataDir/$1/$table.frm $dataDir/$1_BK/$table.frm`
		else
			continue
		fi

		if [ "$diffFlag_frm" != "" ] ; then
			echo "show fields from $1.$table;"|$mysqlBinDir/mysql -u$mysql_user -p$mysql_pw | sed -e '1d' > /tmp/upGradeTmp
			echo "show fields from $1_BK.$table;"|$mysqlBinDir/mysql -u$mysql_user -p$mysql_pw | sed -e '1d' > /tmp/upGradeTmp1
			diff -C0 /tmp/upGradeTmp /tmp/upGradeTmp1 | awk '$1 ~/+/{print "ALTER TABLE " "'$1'" "_BK." "'$table'" " DROP " $2 ";"}' |$mysqlBinDir/mysql -u$mysql_user -p$mysql_pw
			fieldArr=`echo "show fields from $1_BK.$table;"|$mysqlBinDir/mysql -u$mysql_user -p$mysql_pw | sed -e '1d' | awk '{print $1}'`
			
			tmpStr=""
			for tmpField in $fieldArr; do
				if [ "$tmpStr" = "" ] ; then
					tmpStr=$tmpStr$tmpField
				else
					tmpStr=$tmpStr","$tmpField
				fi
			done

			# Check if the database is CSTA_DB
            if [ $1 == "CSTA_DB" ]; then
                #echo "Skipping data insertion for $1.$table"
                continue
            fi
			#echo "$tmpStr"

			rm -f /tmp/tmpContent

			echo "select * into outfile '/tmp/tmpContent' fields terminated by '\',\'' from $1_BK.$table;" |$mysqlBinDir/mysql -u$mysql_user -p$mysql_pw
			tmpChar="'"
			#cat /tmp/tmpContent | sed -e s/'\\\N'/NULL/g | sed -e s/\'NULL\'/NULL/g |awk '{print "replace into " "'$1'" "." "'$table'" " (" "'$tmpStr'" ") values (" "'$tmpChar'" $0 "'$tmpChar'" ");"}' 
			cat /tmp/tmpContent | sed -e s/'\\\N'/NULL/g | sed -e s/\'NULL\'/NULL/g |awk '{print "replace into " "'$1'" "." "'$table'" " (" "'$tmpStr'" ") values (" "'$tmpChar'" $0 "'$tmpChar'" ");"}' |$mysqlBinDir/mysql -u$mysql_user -p$mysql_pw
		else
			# Check if the database is CSTA_DB
			if [ "$1" == "CSTA_DB" ]; then
				#echo "Skipping data insertion for $1.$table"
				continue
			fi		
			echo "replace into $1.$table select * from $1_BK.$table" |$mysqlBinDir/mysql -u$mysql_user -p$mysql_pw
		fi
		echo -n "."
	done

	chgrp -R mysql $dataDir/
	chown -R mysql $dataDir/
	chmod -R 755 $dataDir/

	rm -f /tmp/upGradeTmp
	rm -f /tmp/upGradeTmp1
	rm -f /tmp/tmpContent

	rm -fr $dataDir/$1_BK

	myShowResult "OK"
}

###############################################################################
if [ `hostname -s 2>&1 |grep -c "failure"` -eq 1 ] ;then
    echo "############################### Warning #######################################"
    echo "# Please configure the /etc/hosts, add host like following                    #"
    echo "# 172.18.128.1 omc-0.iwv omc-0                                                #";
    echo "###############################################################################";
    myShowTitle "Install exit."
    exit
fi


hostname=`hostname -s|awk -F'-' '{print $1}'`
if [ `grep -c "$hostname-[01].*$hostname-[01]" /etc/hosts` -eq 0 ] ;then
    echo "############################### Warning #######################################"
    echo "# Please configure the /etc/hosts, add host like following                    #"
    echo "# 172.18.128.1 omc-0.iwv omc-0                                                #";
    echo "###############################################################################";
    myShowTitle "Install exit."
    exit
fi
# Operation system version
osversion=`uname -a`
if [ `echo $osversion|grep -c "2.6.18-92.el5"` -eq 1 ] ;then
    isCentOS=1
else
    isCentOS=0
fi

if [ $isCentOS -eq 0 ] ;then
	mkdir -p /home/ems
	chmod -R 700 /home/ems
	chown -R ems:omc /home/ems
	usermod -d /home/ems ems
fi

#sed '/mysql/d' /etc/vsftpd/ftpusers > /etc/vsftpd/a.out
#echo "mysql" >> /etc/vsftpd/a.out
#mv -f /etc/vsftpd/a.out /etc/vsftpd/ftpusers

sed '/mysql/d' /etc/ftpusers > /etc/a.out
echo "mysql" >> /etc/a.out
mv -f /etc/a.out /etc/ftpusers

sed '/mysql/d' /etc/vsftpd.ftpusers > /etc/b.out
echo "mysql" >> /etc/b.out
mv -f /etc/b.out /etc/vsftpd.ftpusers
clear

thisVersion=`cat ./emsVersion |grep Version|awk '{print $2}'`
echo "WELCOME to INSTALL AGrandTech litCore Soft Switch EMS $thisVersion !"
if [ `whoami` != "root" ] ; then
	myShowTitle "Just root user can install EMS"
	exit
fi

if [ `pwd|grep -c "htdocs"` -gt 0 ] ; then
	myShowTitle "Can not install EMS in this directory! (default is /usr/local/src)"
	exit
fi

if [ "$1" == "-auto" ] ; then
	isAutoInstall=1
else
	isAutoInstall=0
fi

thisVersion=`cat ./emsVersion |grep Version|awk '{print $2}'`
isNeedReboot=0

omcWebName='wxc2_omc'
omcdName='wxc2_omcd'
isInstalledOmc=0
srcDir=`pwd` 
srcBinDir=$srcDir/bin
srcSrcDir=$srcDir/src
srcConfDir=$srcDir/config
srcWebDir=$srcDir/web
srcDataDir=$srcDir/data
srcRelsDir=$srcDir/release
srcToolsDir=$srcDir/tools
srcMssBakScriptDir=$srcDir/mssBak/script
srcMssBakDataDir=$srcDir/mssBak/mssBakData
srcSqlDir=$srcDir/sql

omcDir=/usr/local/omc
dstBinDir=$omcDir/bin
dstSrcDir=$omcDir/src
dstConfDir=$omcDir/config
phpIniDir=/etc/php/5.6/apache2/
phpCliiDir=/etc/php/5.6/cli/
dstWebDir=/usr/local/apache/htdocs
dstDbBackup=/db_backup
if [ `uname -r |grep -c '2.4.7-10'` -eq 1 ] ; then
	dstDataDir=/usr/local/mysql/data
	mysqlBinDir=/usr/local/mysql/bin
else
	dstDataDir=/usr/local/mysql
	mysqlBinDir=/usr/bin
fi


dstRelsDir=$omcDir/release
dstToolsDir=/usr/local/omc/tools
dstMssBakScriptDir=/usr/local/mssBak/script
dstMssBakDataDir=/usr/local/apache/htdocs/mssBakData

#initDir=/etc/rc.d/init.d
initDir=/etc/init.d

mkdir -p /usr/local/apache/htdocs

if [ "$isAutoInstall" == "0" ] ; then
	echo "==========================================="
	echo -n "Are you sure to install this EMS?(y/n)"
	read sureInstall
	if [ "$sureInstall" != "y" ] && [ "$sureInstall" != "Y" ] ; then
		myShowTitle "Install exit."
		exit
	fi
fi


###############################################################################
# 1.Check this system
###############################################################################
#Check installed omc's version
if (test -x $initDir/omcd) && [ "$isAutoInstall" == "0" ] ; then
	isInstalledOmc=1
	
	myShowTitle "Please Select Installation Mode "

	#echo "=============Installation History ============"
	#`omcd version`
	#cat $omcDir/install.log |grep Version
	#echo "==========================================="

	#Get install mode
	echo "=========== Installation Mode ============="
	echo "==1.Initialize Database and Software     =="
	echo "==2.Upgrade Software                     =="
	echo "==0.Exit                                 =="
	echo "==========================================="
	echo -n "Please select Installation Mode.(0/1/2):"
	read installMode

	case "$installMode" in
		'1')
			clear
			myShowTitle "You have selected 'Initialize Database and Software' mode."
			#Check free space of hard disk
			#freeDiskMB=`df -m |grep /usr|grep dev|awk '{print $4}'`
			freeDiskMB=$(df -m /usr | awk 'NR==2 {print $4}')
			echo "There is $freeDiskMB MB available space in /usr"
			if [ $freeDiskMB -lt 2000 ]; then
				echo "EMS need 2G disk space,No enough space in /usr !!"
				df -h /usr
				exit
			fi
			;;
		'2')
			clear
			myShowTitle "You have selected 'Upgrade Software' mode."
			echo "Installed `tail -4 $omcDir/install.log|grep Version`"
			
			;;
		*)
			myShowTitle "Install exit."
			exit
			;;
	esac
else
	if [ "$isAutoInstall" == "1" ] ; then
		myShowTitle "Install EMS by auto mode"
	else
		myShowTitle "Ready for installing EMS"	
	fi
	installMode=1
fi

#stopList="omcd httpd mysql"
stopList="omcd apache2 mysql"
for procName in $stopList; do
	if ( test -e "$initDir/$procName" ) then
		echo "Shutdown $procName..."
		#$initDir/$procName stop
        service $procName stop
	fi
	if [ -n "`pidof $procName`" ] ;then
		kill -9 `pidof $procName`
	fi
done

if [ -n "`pidof httpd`" ] ;then
	kill -9 `pidof httpd`
fi

if [ -n "`pidof mysqld`" ] ;then
    kill -9 `pidof mysqld`
fi

###############################################################################
# 2.Change system configure
###############################################################################

myShowTitle "Checking system configuration"
echo -n "Check user...."
#Step 1:Add User
#By fuction:myAddUser $userName $userPwd $groupName $homeDir $remark $shType

#add user www 
#if [ `grep -c "www:x" /etc/passwd` -eq 0 ] ; then
#	myAddUser "www" "123456" "omc" "/usr/local/apache/htdocs" "web operator" "/bin/bash"
#fi

myShowResult "OK"

#Step 2:Set system Time 
#echo -n "Set system clock.... "
#set time zone = GMT
#rm /etc/localtime 
#cp -f /usr/share/zoneinfo/GMT  /etc/localtime 

#sync sysclock to hardware clock
#hwclock --systohc

#myShowResult "OK"

#Step 3:Set path in profile
echo -n "Set path....."

if [ `grep -c "/etc/rc.d/init.d" /etc/profile` -eq 0 ] ; then
	echo "PATH=/etc/rc.d/init.d:\$PATH" >> /etc/profile
fi
myShowResult "OK"

sleep 2
###############################################################################
# 3.Install omc files
###############################################################################
myShowTitle "Copying EMS files (Backup old files to /usr/local/omcBak)"

#backup the omc/bin/conf
if [ "$installMode" == "2" ] ; then
	orignalConfDir=$dstBinDir/conf
	bk_conf_file_list="iptrans.conf mtp3.conf NR.conf sccp.conf smeg.conf smpp.conf system.ini welcomeSMS.conf snmp.conf omctrap_iplist.conf mcms_conf.txt"
	for conf_file in $bk_conf_file_list; do
		if [ -f $orignalConfDir/$conf_file ] ;then
	        	cp -f $orignalConfDir/$conf_file /tmp/
		fi
	done

	#backup the dual sync data
    if [ -f /usr/local/omc/bin/dual/cdr_io_proc ] ;then
        rm -rf /usr/local/cdr_io_proc
        cp -Rf /usr/local/omc/bin/dual/cdr_io_proc /usr/local/
    fi
    if [ -f /usr/local/omc/bin/dual/cdr_data_proc ] ;then
        rm -rf /usr/local/cdr_data_proc
        cp -Rf /usr/local/omc/bin/dual/cdr_data_proc /usr/local/
    fi
fi

#step 1:Create bak up dir
mkdir -p $omcDir
omcBakDir=/usr/local/omcBak
mkdir -p $omcBakDir
rm -rf $omcBakDir/*

#Step 2:Copy bin files
if [ "$installMode" == "2" ] ; then
    echo -n "Copy bin files ...."
    mkdir -p $dstBinDir
    cp -rf $dstBinDir $omcBakDir/
    #rm -rf $dstBinDir/*
    #cp -f $srcBinDir/* $dstBinDir
    # only copy bin file exclude subdirectory (conf, mib, ...)
    find $srcBinDir -maxdepth 1 -type f -exec cp -f {}  $dstBinDir \;
    # update subdirectory mib, daul.
    cp -rf $srcBinDir/mib/* $dstBinDir/mib
    cp -rf $srcBinDir/dual $dstBinDir/dual
    chmod +x $dstBinDir/*
    myShowResult "OK"
else
    echo -n "Copy bin files ...."
    mkdir -p $dstBinDir
    cp -rf $dstBinDir $omcBakDir/
    rm -rf $dstBinDir/*
    cp -rf $srcBinDir/* $dstBinDir
    chmod +x $dstBinDir/*

	touch $dstBinDir/conf/system.ini

    myShowResult "OK"
fi

#Step 3:Copy web files 
echo -n "Copy web files ...."
#needKeepDirList="ftpFile db_backup/cdr db_backup/other db_backup/paramConf db_backup/csta db_backup/subsData db_backup/meetConf db_backup/alarmLog db_backup/operLog tftp"
#needKeepDirList="ftpFile db_backup/cdr db_backup/other db_backup/paramConf db_backup/csta db_backup/subsData db_backup/meetConf db_backup/alarmLog db_backup/operLog"

if ( test -d "$dstWebDir/ftpFile" ) then
	echo -n "."
else
	mkdir -p $dstWebDir/ftpFile
	echo -n "."
fi
needKeepDirList="cdr other paramConf csta subsData meetConf alarmLog operLog cdrsending cdrsent cstasending cstasent"
for tmpDir in $needKeepDirList; do
	if ( test -d "$dstDbBackup/$tmpDir" ) then
		echo -n "."
	else
		mkdir -p $dstDbBackup/$tmpDir
		echo -n "."
	fi
done
ln -fs $dstDbBackup $dstWebDir/
rm -f $dstDbBackup/db_backup
chown -R mysql:mysql $dstDbBackup

cp -rf $srcWebDir/index.php $dstWebDir/

if [ -L $dstWebDir/$omcWebName ] ;then
    rm -f $dstWebDir/$omcWebName
fi

if ( test -d "$dstWebDir/omcWeb" ) then
	mv $dstWebDir/omcWeb  $omcBakDir/
else
	if ( test -d "$dstWebDir/$omcWebName" ) then
		mv $dstWebDir/$omcWebName $omcBakDir/
	fi
fi
cp -Rf $srcWebDir/$omcWebName $dstWebDir/

# Restore alto_logo_40.gif 
if [ -f $omcBakDir/$omcWebName/images/alto_logo_40.gif ]; then
	cp -f $omcBakDir/$omcWebName/images/alto_logo_40.gif $dstWebDir/$omcWebName/images/
	echo -n "alto_logo_40.gif.."
fi

# Restore alto_logo_80.gif 
if [ -f $omcBakDir/$omcWebName/images/alto_logo_80.gif ]; then
	cp -f $omcBakDir/$omcWebName/images/alto_logo_80.gif $dstWebDir/$omcWebName/images/
	echo -n "alto_logo_80.gif..."
fi

#ln -s $dstWebDir/omcWeb $dstWebDir/$omcWebName
if [ $isCentOS -eq 1 ] ;then
	chown -R www:omc  $dstWebDir
else
	chown -R www-data:www-data  $dstWebDir
fi

# Change the permission of the wxc2_omc
dir_mode=500
file_mode=400
mod_dir=$dstWebDir/$omcWebName/
chmod $dir_mode $mod_dir
cd $mod_dir
obj_list="`ls -R`"
for obj in $obj_list; do
    if [ `echo $obj|grep -c '^\.'` -gt 0 ] ;then
        #echo $obj is a dir
        cur_dir="`echo $obj|awk -F: '{print $1}'`"
        chmod $dir_mode $cur_dir
    else
        #echo $obj is file,cur_dir=$cur_dir chmod $dir_mode $cur_dir/$obj
        chmod $file_mode $cur_dir/$obj
    fi
done
needExcuteFileList="configuration/mscSync/getFile configuration/mscSync/put configuration/mscSync/putFile configuration/mscSync/startMsc configuration/mscSync/stopMsc configuration/nibConf/beforeClearSubs configuration/nibConf/beforeFtp configuration/nibConf/bssReboot configuration/nibConf/mssStart"
for file in $needExcuteFileList; do
	chmod 500 $dstWebDir/$omcWebName/$file
done
chmod -R 700 /usr/local/apache/htdocs/wxc2_omc/performance
if [ $isCentOS -eq 1 ] ;then
    cp -f /usr/local/apache/htdocs/wxc2_omc/security/login/login.php_centos /usr/local/apache/htdocs/wxc2_omc/security/login/login.php
	chmod 400 /usr/local/apache/htdocs/wxc2_omc/security/login/login.php
	chown www /usr/local/apache/htdocs/wxc2_omc/security/login/login.php
	chgrp omc /usr/local/apache/htdocs/wxc2_omc/security/login/login.php
fi

#needRwxDirList="ftpFile db_backup tftp"
needRwxDirList="ftpFile db_backup"
for tmpDir in $needRwxDirList; do
	chmod -R 755 $dstWebDir/$tmpDir
done
myShowResult "OK"

chmod 777 $dstWebDir/ftpFile
if [ $isInstalledOmc -gt 0 ] ; then
	myShowTitle "Copying database files (Backup old files to /usr/local/omcBak)"
	echo -n "Backup database files...."
	mkdir -p $omcBakDir/data
	needBakDbList=`ls  -l $dstDataDir/|grep drwx|awk '{print $9}'`
	count=0
	for tmpDb in $needBakDbList ; do
		cp -rf $dstDataDir/$tmpDb $omcBakDir/data
		count=$((count + 1))
		if [ $((count % 2)) -eq 1 ]; then
			echo -n "."
		fi
	done
	myShowResult "OK"
else
	myShowTitle "Copying database files"
fi

#step 3.1:Copy database files
if [ $installMode == "1" ] ; then
	#Copy database file
	echo -n "Copy database files..."

	if [ -d $dstDataDir/ESME_DB ] ;then
		mv -f $dstDataDir/ESME_DB /tmp/
		esme_exist=1
	fi

	needCopyDirList="mysql performance_schema sys phpmyadmin"
	#needCopyDirList=`ls $srcDataDir`

	#echo $needCopyDirList;
	for tmpDir in $needCopyDirList ; do
		cp -Rf $srcDataDir/$tmpDir $dstDataDir/
		echo -n "."
	done 

	if [ "$esme_exist" == 1 ] ;then
		mv -f /tmp/ESME_DB $dstDataDir
	fi
	myShowResult "OK"

	#delete the mysql link
	if [ -L "/var/lib/mysql" ] ; then
		if [ -n "`pidof mysqld`" ] ;then
			kill -9 `pidof mysqld`
		fi
		rm -rf /var/lib/mysql
	fi

	#cp -f $srcConfDir/my.cnf /etc/my.cnf

	#cp -rf $srcDataDir/mysql $dstDataDir
	chown -R mysql  $dstDataDir/
	chgrp -R mysql  $dstDataDir/
	chmod -R 755    $dstDataDir/

	#if ( test -e "$initDir/mysql" ) then
	if ( test -e "$initDir/mariadb" && test -e "/usr/lib/systemd/system/mariadb.service" ) then
		sed -i 's/ProtectSystem=full/ProtectSystem=false/g' /usr/lib/systemd/system/mariadb.service
		systemctl daemon-reload
		#$initDir/mysql start
		service mysql start
		sleep 2
	else
		myShowTitle "Can not Upgrade EMS.You have not installed the mysql"
		exit
	fi
	myShowResult "OK"
fi

#step 3.2:Upgrade databases
if [ "$installMode" == "2" ] ; then
	myShowTitle "Upgrade EMS databases"
	service mysql restart		
	upgradeSqlDir=$srcSqlDir/upgrade
	dbScriptList=`ls $upgradeSqlDir/*.sql`
    for dbScript in $dbScriptList; do
		dbFileName=`basename $dbScript`
        echo -n "Executing $dbFileName ... "
        $mysqlBinDir/mysql -u$mysql_user -p$mysql_pw < "$dbScript"
		myShowResult "OK"
    done
	chown -R mysql  $dstDataDir/
	chgrp -R mysql  $dstDataDir/
	chmod -R 755    $dstDataDir/
	echo -n "Upgrade EMS databases ...."
	myShowResult "OK"
fi

#step 4:Copy config files
myShowTitle "Copying configuration and tools files"
echo -n "Copy configuration files ...."
mkdir -p $dstConfDir
cp -r $dstConfDir  $omcBakDir/
rm -rf $dstConfDir/*
cp -rf $srcConfDir/*  $dstConfDir/
myShowResult "OK"

#step 5:Copy tools files
echo -n "Copy tools files ...."
mkdir -p $dstToolsDir
cp -r $dstToolsDir  $omcBakDir/
rm -rf $dstToolsDir/*
cp -rf $srcToolsDir/*  $dstToolsDir/
cp -rf $dstToolsDir/functions /etc/init.d/
myShowResult "OK"

#./checkExpect
#install expect tool
if [ ! -f /usr/bin/expect ] && [ ! -f /usr/local/bin/expect ] ;then
	cp -f $srcToolsDir/expect/expect /usr/bin
	cp -f $srcToolsDir/expect/expect /usr/local/bin
	chmod 755 /usr/bin/expect
	chmod 755 /usr/local/bin/expect
fi

#install phpMyAdmin
#USER=root
#PORT=3306
#HOST=localhost
#sql_phpmyadmin_user="grant all privileges on *.* to phpmyadmin@'localhost' IDENTIFIED BY 'admin123@EMS';flush privileges;"
echo -n "Install phpMyAdmin ..."
rm -rf $dstWebDir/phpMyAdmin
cp $srcToolsDir/phpMyAdmin.tgz $dstWebDir/
cd $dstWebDir
tar zxvf phpMyAdmin.tgz > /dev/null
chown -R www-data:www-data $dstWebDir/phpMyAdmin
rm -rf $dstWebDir/phpMyAdmin.tgz
#mysql -u${USER} -e "${sql_phpmyadmin_user}"
myShowResult "OK"

# configure ems
myShowTitle "Configuring EMS"
echo -n "Configuring EMS ..."
cd $srcDir

#Update httpd.conf
httpdConfDir="/etc/apache2"
if [ $isCentOS -eq 1 ] ;then
	cp -f $srcConfDir/httpd.conf_centos $httpdConfDir/httpd.conf
else
	cp -f $dstConfDir/apache2-000-default.conf $httpdConfDir/sites-available/000-default.conf
	sed -i 's/Require all denied/Require all granted/g' $httpdConfDir/apache2.conf
fi
chmod 644 $httpdConfDir/sites-available/*

if [ `cat /etc/rc.local |grep -c 'httpd'` -eq 0 ] ; then
    echo "/etc/rc.d/init.d/httpd start">>/etc/rc.local
fi
chmod 755 /usr/local/omc
chmod 755 /usr/local/omc/bin
chmod 755 /usr/local/omc/bin/conf
chmod 644 /usr/local/omc/bin/conf/*

if [ -d $httpdConfDir/extra/ ] ;then
	cp -f $dstConfDir/httpd-ssl.conf $httpdConfDir/extra/
else
	mkdir $httpdConfDir/extra/
	chmod 644 $httpdConfDir/extra/
	cp -f $dstConfDir/httpd-ssl.conf $httpdConfDir/extra/
fi
cp -f $dstConfDir/cacert.pem $httpdConfDir/
cp -f $dstConfDir/*.crt $httpdConfDir/
cp -f $dstConfDir/*.key $httpdConfDir/
cp -f $dstConfDir/*.csr $httpdConfDir/

#update php.ini
cp -f $dstConfDir/php.ini $phpIniDir/php.ini
cp -f $dstConfDir/php.ini $phpCliiDir/php.ini

#for old omc version,must replace the mysql config file and  profile, rsyncd.conf
if [ `grep -c "/usr/local/omc_exec" /etc/profile` -gt 0 ] ; then
	#cp -f $dstConfDir/mariadb-50-server.cnf  /etc/mysql/mariadb.conf.d/50-server.cnf
	cp -f $dstConfDir/profile /etc/
fi

cp -f $dstConfDir/rsyncd.conf /etc/
chmod 644 /etc/rsyncd.conf
myShowResult "OK"

#step 5:Copy mssBak files
echo -n "Copy mssBak files ...."
mkdir -p $dstMssBakScriptDir
mkdir -p $dstMssBakDataDir

if [ ! -d "$srcMssBakDataDir" ] ; then		
#echo "$srcMssBakDataDir already exist"
mkdir -p $srcMssBakDataDir		
fi
myShowResult "OK"	

cp -r $dstMssBakDataDir  $omcBakDir/
rm -rf $dstMssBakDataDir/*
#cp -rf $srcMssBakDataDir/*  $dstMssBakDataDir/
cp -rf $srcMssBakDataDir  $dstMssBakDataDir
cp -rf $srcMssBakScriptDir/*  $dstMssBakScriptDir/
chmod -R 755 $dstMssBakDataDir
chmod 700 $dstMssBakScriptDir/*

#step 6:Create log dir
echo -n "Create log directory ...."
mkdir -p /usr/local/omc/log/
myShowResult "OK"

#Step 7:set auto run service
myShowTitle "Set auto run service"
echo -n "Set auto run ...."
serviceName="omcd"
echo -n "update $serviceName service..."
#chkconfig --del $serviceName
update-rc.d -f $serviceName remove

rm -f $initDir/omcd
ln -fs $dstBinDir/$omcdName  $initDir/omcd
#chkconfig --add omcd
#update-rc.d omcd defaults
cp $dstConfDir/omcd.service /usr/lib/systemd/system/
systemctl enable omcd.service > /dev/null 2>&1
runLevels="2 3 4 5"
for level in $runLevels; do
	mv -f /etc/rc${level}.d/S01omcd /etc/rc${level}.d/S99omcd
done
myShowResult "OK"

#Step 8:set omc's run mode
#$initDir/mysql start
myShowTitle "Set EMS run mode"
service mysql start
if [ "$isAutoInstall" == "0" ] ; then
	$dstBinDir/setRunMode space install
else
	$dstBinDir/setRunMode -auto install
fi

#step 9:Record into install.log
installDate=` date +%Y-%m-%d' '%H:%M:%S`
cat ./emsVersion >>$omcDir/install.log
echo "$installDate $omcName $thisVersion" >> $omcDir/install.log
echo "-------------------------------------- " >> $omcDir/install.log

#step 10: install EMS databases
if [ "$installMode" == "1" ] ; then
	myShowTitle "Install EMS databases"
	service mysql restart
	installSqlDir=$srcSqlDir/install
	dbScriptList=`ls $installSqlDir/*.sql`
    for dbScript in $dbScriptList; do
        # Get the database name from the script file name
        dbFileName=$(basename "$dbScript")
        dbName="${dbFileName%%.sql}"     # Remove the .sql extension
        echo -n "Creating database $dbName and executing $dbFileName ... "
        $mysqlBinDir/mysql -u$mysql_user -p$mysql_pw -e "CREATE DATABASE IF NOT EXISTS \`$dbName\` DEFAULT CHARACTER SET utf8mb4;"
        $mysqlBinDir/mysql -u$mysql_user -p$mysql_pw "$dbName" < "$dbScript"
		myShowResult "OK"
    done
	echo -n "Install EMS databases ... "
	myShowResult "OK"
fi

#Get the original conf file back
if [ "$installMode" == "2" ] ; then
	for conf_file in $bk_conf_file_list; do
		if [ -f /tmp/$conf_file ] ;then
	        mv -f /tmp/$conf_file $orignalConfDir/
		fi
	done

	if [ -f /usr/local/cdr_io_proc ] ;then
		rm -rf /usr/local/omc/bin/dual/cdr_io_proc
        mv /usr/local/cdr_io_proc /usr/local/omc/bin/dual/
    fi
    if [ -f /usr/local/cdr_data_proc ] ;then
		rm -rf /usr/local/omc/bin/dual/cdr_data_proc
        mv /usr/local/cdr_data_proc /usr/local/omc/bin/dual/
		chmod 777 /usr/local/omc/bin/dual/cdr_data_proc
    fi
	if [ $isCentOS -eq 1 ]; then
		if [ -d /usr/local/omc/bin/dual/cdr_io_proc ] ;then
  			chown -R www:omc /usr/local/omc/bin/dual/cdr_data_proc
		fi
	else
		if [ -d /usr/local/omc/bin/dual/cdr_data_proc ] ;then
			chown -R www-data:www-data /usr/local/omc/bin/dual/cdr_data_proc
		fi 
	fi

fi

chmod -R 755 /usr/local/omc/bin/dual

externalRCMStr=`/usr/bin/mysql -u$mysql_user -p$mysql_pw <<_EOF_
SELECT pubVarValue FROM OMC_PUB.omcPubVarConf WHERE pubVarName='ExternalRCM';
_EOF_`

externalRCM=`echo $externalRCMStr | awk '{print $2}'`
if [ "$externalRCM" == "0" ] ;then
/usr/bin/mysql -u$mysql_user -p$mysql_pw <<_EOF_
update OMC_PUB.sysMenuConf set privilege='-1' where level_1=3 and level_2=21 and level_3=0;
update OMC_PUB.sysMenuConf set privilege='2' where level_1=3 and level_2=20 and level_3=0;
update OMC_PUB.sysMenuConf set privilege='-1' where level_1=5 and level_2=3 and level_3=0;
update OMC_PUB.sysMenuConf set privilege='3' where level_1=5 and level_2=2 and level_3=0;
update OMC_PUB.sysMenuConf set privilege='-1' where level_1=7 and level_2=4 and level_3=2;
update OMC_PUB.sysMenuConf set privilege='4' where level_1=7 and level_2=4 and level_3=1;
_EOF_
else
/usr/bin/mysql -u$mysql_user -p$mysql_pw <<_EOF_
update OMC_PUB.sysMenuConf set privilege='2' where level_1=3 and level_2=21 and level_3=0;
update OMC_PUB.sysMenuConf set privilege='-1' where level_1=3 and level_2=20 and level_3=0;
update OMC_PUB.sysMenuConf set privilege='3' where level_1=5 and level_2=3 and level_3=0;
update OMC_PUB.sysMenuConf set privilege='-1' where level_1=5 and level_2=2 and level_3=0;
update OMC_PUB.sysMenuConf set privilege='4' where level_1=7 and level_2=4 and level_3=2;
update OMC_PUB.sysMenuConf set privilege='-1' where level_1=7 and level_2=4 and level_3=1;
_EOF_
fi

if [ -n "`pidof mysqld`" ] ;then
    kill -9 `pidof mysqld`
fi

rm -rf /usr/local/mysql/master.info

#$initDir/mysql start
service mysql start

if [ -n "`pidof httpd`" ] ;then
    kill -9 `pidof httpd`
fi
#$initDir/httpd start
service apache2 start

$srcBinDir/changehostname

#install Intel raid service
myShowTitle "Install RAID service"
raid_package=`dpkg -l sas_snmp`
if [ `echo $raid_package |grep -c 'not'` -eq 1 ] ; then
    echo "Do you want to install the service of RAID(y/n)"
    read sureInstallRaid
    if [ "$sureInstallRaid" == "y" ] || [ "$sureInstallRaid" == "Y" ] ; then
        cd $dstToolsDir
        tar zxvf sas_snmp_install.tgz
        cd sas_snmp_install/
        ./sas_snmp_install
		cd $dstToolsDir
		rm -rf sas_snmp_install

/usr/bin/mysql -u$mysql_user -p$mysql_pw <<_EOF_
UPDATE OMC_PUB.elementExistConf SET existFlag='1' WHERE elementTypeNo='234';
_EOF_

	else

/usr/bin/mysql -u$mysql_user -p$mysql_pw <<_EOF_
UPDATE OMC_PUB.elementExistConf SET existFlag='0' WHERE elementTypeNo='234';
_EOF_

    fi
else
	echo -n "Do you want to open the service of RAID(y/n)"
	read sureInstallRaid
    if [ "$sureInstallRaid" == "y" ] || [ "$sureInstallRaid" == "Y" ] ; then
/usr/bin/mysql -u$mysql_user -p$mysql_pw <<_EOF_
UPDATE OMC_PUB.elementExistConf SET existFlag='1' WHERE elementTypeNo='234';
_EOF_
	else
/usr/bin/mysql -u$mysql_user -p$mysql_pw <<_EOF_
UPDATE OMC_PUB.elementExistConf SET existFlag='0' WHERE elementTypeNo='234';
_EOF_
	fi
fi

# Be sure to restart the mysql
if [ -n "`pidof mysqld`" ] ;then
    kill -9 `pidof mysqld`
fi
chown -R mysql /usr/local/mysql
chgrp -R mysql /usr/local/mysql

service mysql start
chown -R mysql /var/lib/mysql
chgrp -R mysql /var/lib/mysql

###############################################################################
# 4. EMS Install Finished
##############################################################################o
myShowTitle "EMS Installation Process is complete"
echo -n "Starting EMS service ...."
#Start EMS service
systemctl daemon-reload
systemctl restart omcd.service
if [ $? -ne 0 ] ; then
	echo "Failed to start EMS service. Please check the logs in /usr/local/omc/log"
	myShowResult "Failed"
	exit 1
fi
myShowResult "OK"

exit

