#!/bin/bash
#                                                                                       #
# SCRIPT: install_primary_monmgo.sh		                                                #
# DATE:   27-Oct-2016                                                                   #
# REV:    1.0                                                                           #
# DEVELOPED BY: Parablu Systems								#
# DEVELOPER: Vaibhav K
# PURPOSE: Contains all the utility functions for mongo Installation                  	#
# PLATFORM: Ubuntu                                                                      #

UBUNTU_SERVICE_SCRIPT_PATH=./ubuntu_service.sh
MONGO_SERVICE_SCRIPT_PATH=./mongo_service.sh
PARABLU_CONFIG_SCRIPT_PATH=../config/parablu_config.sh
PARABLU_COMPONENT_SCRIPT_PATH=../config/parablu_component_config.sh
INSTALLABLES_SCRIPT_PATH=../installables
source $PARABLU_COMPONENT_SCRIPT_PATH
source $MONGO_SERVICE_SCRIPT_PATH
source $PARABLU_CONFIG_SCRIPT_PATH
source $UBUNTU_SERVICE_SCRIPT_PATH

function release_primary_mongo ()
{
	release_mongodb

	sudo systemctl enable mongod
       
#	iptables -A INPUT -p tcp --dport $LOCAL_MONGO_PORT -j ACCEPT
	if [[ $MULTI_PRIMARY_MONGO == "true" ]]; then
		primary_iptable_redirection
	fi

	restart_mongodb

        install_tables

	create_folder
#	update_mongo_conf
	if [[ $REP_ENB = "yes" ]]; then
		config_replica
	fi
	config_demon 2>&1 >> install.log
	#restart_mongodb 2>&1 >> install.log
	config_mongo_data 2>&1 >> install.log
        mongo_backup 2>&1 >> install.log
	update_mongo_conf
	configure_mongo_security 2>&1 >> install.log
	restart_mongodb 2>&1 >> install.log
	sleep 2s
}

#iptable redirection
function primary_iptable_redirection ()
{
#        ufw allow $LOCAL_MONGO_PORT
        iptables -A INPUT -p tcp --dport $MULTI_MONGO_PORT -j ACCEPT
        iptables -t nat -I PREROUTING -p tcp --dport $MULTI_MONGO_PORT -j REDIRECT --to-port $LOCAL_MONGO_PORT
        iptables-save > /etc/iptables.conf

        sed -i '/"exit 0"/i \iptables-restore < /etc/iptables.conf' /etc/rc.local
}


function config_demon () 
{
	if [ ! -e /etc/init.d/PM_autorun.sh ]; then
		echo "service mongod start" > /etc/init.d/PM_autorun.sh
		chmod a+x /etc/init.d/PM_autorun.sh
		sudo update-rc.d PM_autorun.sh defaults
	fi
}

# Creating CLOUD_CUSTOMIZABLE_DETAILS for the product
function mongo_product_append()
{
	BLUSYNC_CLOUD_CUSTOMIZABLE='DBRef("CLOUD_CUSTOMIZABLE_DETAILS", ObjectId("55968a0d8af4190fb7a4075a"))'
	BLUVAULT_CLOUD_CUSTOMIZABLE='DBRef("CLOUD_CUSTOMIZABLE_DETAILS", ObjectId("5541b64ac99cad31aff3d7a2"))'
	SERVER_BACKUP_CLOUD_CUSTOMIZABLE='DBRef("CLOUD_CUSTOMIZABLE_DETAILS", ObjectId("56a852f3fe60234cc8a4eeeb"))'
	cloud_customizable_products=""
	policy_products=""
	sync_enable=""
	backup_enable=""
	serverBackup_enable=""
	share_enable=""
	trueValue='true'
	falseValue='false'
	backuppolicy='"backupPolicy" : DBRef("BACKUP_POLICY", ObjectId("5749a797e4b04fe650d0e267"))'
	syncpolicy='"syncPolicy":DBRef("SYNC_POLICY", ObjectId("57eb8049e4b0e63d17795138"))'
	backup_sync_policy='"backupPolicy" : DBRef("BACKUP_POLICY", ObjectId("5749a797e4b04fe650d0e267")),"syncPolicy":DBRef("SYNC_POLICY", ObjectId("57eb8049e4b0e63d17795138"))'
        for a in ${product_name[@]};do
                if [ $a = Blusync ];then
                     cloud_customizable_products=$cloud_customizable_products$BLUSYNC_CLOUD_CUSTOMIZABLE","
		     policy_products=$policy_products$backup_sync_policy
		     sync_enable=$sync_enable$trueValue
		     backup_enable=$backup_enable$falseValue
		     serverBackup_enable=$serverBackup_enable$falseValue
		     share_enable=$share_enable$trueValue
                elif [ $a = Bluvault ];then
                     cloud_customizable_products=$cloud_customizable_products$BLUVAULT_CLOUD_CUSTOMIZABLE","
		     policy_products=$policy_products$backuppolicy
		     sync_enable=$sync_enable$falseValue
		     backup_enable=$backup_enable$trueValue
		     serverBackup_enable=$serverBackup_enable$falseValue
		     share_enable=$share_enable$trueValue
                elif [ $a = ServerBackup ];then
                     cloud_customizable_products=$cloud_customizable_products$SERVER_BACKUP_CLOUD_CUSTOMIZABLE","
		     policy_products=$policy_products$backuppolicy
		     sync_enable=$sync_enable$falseValue
		     backup_enable=$backup_enable$falseValue
		     serverBackup_enable=$serverBackup_enable$trueValue
		     share_enable=$share_enable$falseValue
                fi
        done
	cloud_customizable_products=$(echo $cloud_customizable_products | sed 's/.$//')
}

# Creating CLOUD_CUSTOMIZABLE_DETAILS for the product
function mongo_storage_append()
{

	all_Storage_Details=""
	Azure='DBRef("CLOUD_CUSTOMIZABLE_DETAILS", ObjectId("5541b64ac99cad31aff3d7a9"))'
	ODB='DBRef("CLOUD_CUSTOMIZABLE_DETAILS", ObjectId("562f85bdc6f71b1cb4ba3ef0"))'
	GoogleDrive='DBRef("CLOUD_CUSTOMIZABLE_DETAILS", ObjectId("58afc0c3fe617d5c50854dd6")), DBRef("CLOUD_CUSTOMIZABLE_DETAILS", ObjectId("58afc0c3fe617d5c50854dd7"))'

        for a in ${storage_name[@]};do
                if [ $a = Azure ];then
                     all_Storage_Details=$all_Storage_Details$Azure","
                elif [ $a = ODB ];then
                     all_Storage_Details=$all_Storage_Details$ODB","
                elif [ $a = GoogleDrive ];then
                     all_Storage_Details=$all_Storage_Details$GoogleDrive","
                fi
        done
	all_Storage_Details=$(echo $all_Storage_Details | sed 's/.$//')
}

function install_tables ()
{
	echo "installing tables........"
        base1="parablu_table.js"
        base2="parablu001_table.js"
	base1js=$INSTALLABLES_SCRIPT_PATH/js/$base1
	base2js=$INSTALLABLES_SCRIPT_PATH/js/$base2
	

	mkdir -p $INSTALLABLES_SCRIPT_PATH/js/backup
        cp -r $base1js $INSTALLABLES_SCRIPT_PATH/js/backup
	cp -r $base2js $INSTALLABLES_SCRIPT_PATH/js/backup


        ############## Updating parablu table ####################

        sed -i "s|EPA_VERSION|$EPA_VERSION|" $base1js
	sed -i "s|EPA_ENV_LINK|$EPA_ENV_LINK|" $base1js
        sed -i "s|NEW_CLOUD_NAME|$CLOUD_NAME|" $base1js
        sed -i "s|CLOUD_SIZE_ALL|$CLOUD_SIZE|" $base1js
        sed -i "s|NO_OF_BKUP_USER|$BACKUP_USER_NO|" $base1js
	sed -i "s|NO_OF_DEVICE_ALL|$DEVICE_PER_USER|" $base1js
        sed -i "s|MINI_CLOUD_ALL|$MINI_CLOUD|" $base1js
        sed -i "s|NO_OF_SYNC_USER|$SYNC_USER_NO|" $base1js
        sed -i "s|NO_OF_USER_ALL|$CLOUD_USER_NO|" $base1js
        sed -i "s|VALIDITY_UNTIL|$CLOUD_VALIDITY|" $base1js
        sed -i "s|CLOUD_NAME|$CLOUD_NAME|" $base1js
        sed -i "s|ADMIN_EMAIL|$ADMIN_EMAIL_ID|g" $base1js
 #       sed -i "s|SOLR_URL|https://$SOLR_URL/ParacloudSearch/search/|" $base1js
        sed -i "s|VERSION_SIZE|$CLOUD_VERSION_SIZE|" $base1js
#	sed -i "s|BV_VALUE|$BLUVAULT_IP|g" $base1js

	############## Updating Parablu001 table ###################
	sed -i "s|USER_NAME_1|$ADMIN_USER_NAME|" $base2js
        sed -i "s|EMAIL_ADDRESS|$ADMIN_EMAIL_ID|" $base2js
        sed -i "s|PASSWORD_HASH|$ADMIN_PASSWORD_HASH|" $base2js
        sed -i "s|NOW_NANOSECOND|$NANOSECOND_NOW|" $base2js
  #      sed -i "s|BK_VALUE|$BLUKRYPT_IP|" $base2js
        sed -i "s|ADMIN_EMAIL|$ADMIN_EMAIL_ID|g" $base2js
        sed -i "s|CLOUD_NAME|$CLOUD_NAME|" $base2js
 #       sed -i "s|GATEWAY_NAME|$BLUKRYPT_IP|" $base2js
#        sed -i "s|BV_VALUE|$BLUVAULT_IP|" $base2js     
	sed -i "s|CUSTOMERNAME_PLACEHOLDER|$CLOUD_NAME|" $base2js
	if [[ $storagetype == "1" ]] ; then
		sed -i 's|LOCAL_STORAGE|true|g' $base2js
	else
		sed -i 's|LOCAL_STORAGE|false|g' $base2js
	fi
	sed -i "s|CLOUD_NAME|$CLOUD_NAME|" $INSTALLABLES_SCRIPT_PATH/js/blukrypt_tables.js

	##############################################################
	custom_mongo_data

        cat $base1js >>$INSTALLABLES_SCRIPT_PATH/js/parablu_table_install.js

        cat $base2js >>$INSTALLABLES_SCRIPT_PATH/js/parablu001_table_install.js
}

	################ Updating  parablu_tables_custom   ###############
function custom_mongo_data
{
	mongo_product_append
	mongo_storage_append

	# Declaring variable which holds common values of cloud_customisable_details
	CLOUD_CUSTOMISABLE_COMMON='DBRef("CLOUD_CUSTOMIZABLE_DETAILS", ObjectId("5552e60595f190d118116bb6")), DBRef("CLOUD_CUSTOMIZABLE_DETAILS", ObjectId("5541b64ac99cad31aff3d7a3")), DBRef("CLOUD_CUSTOMIZABLE_DETAILS", ObjectId("5541b64ac99cad31aff3d7a5")),    DBRef("CLOUD_CUSTOMIZABLE_DETAILS", ObjectId("5541b64ac99cad31aff3d7a6")),  DBRef("CLOUD_CUSTOMIZABLE_DETAILS", ObjectId("5541b64ac99cad31aff3d7a7")),DBRef("CLOUD_CUSTOMIZABLE_DETAILS", ObjectId("5541b64ac99cad31aff3d7a8"))'
	LDAP_DETAIL='DBRef("CLOUD_CUSTOMIZABLE_DETAILS", ObjectId("5541b64ac99cad31aff3d7a4"))'
           echo "$sync_enable" | grep true
           if [ $? -eq 0 ]; then
               sed -i "s|SYNC_ENABLED|true|" $base2js
           else
               sed -i "s|SYNC_ENABLED|false|" $base2js
           fi

           echo "$backup_enable" | grep true
           if [ $? -eq 0 ]; then
               sed -i "s|BACKUP_ENABLED|true|" $base2js
           else
               sed -i "s|BACKUP_ENABLED|false|" $base2js
           fi
	   echo "$serverBackup_enable" | grep true
           if [ $? -eq 0 ]; then
               sed -i "s|SERVER_BACKUP_ENABLED|true|" $base2js
           else
               sed -i "s|SERVER_BACKUP_ENABLED|false|" $base2js
           fi

           echo "$share_enable" | grep true
           if [ $? -eq 0 ]; then
               sed -i "s|SHARE_ENABLED|true|" $base2js
           else
               sed -i "s|SHARE_ENABLED|false|" $base2js
           fi
           echo "$policy_products" | grep 'ObjectId("5749a797e4b04fe650d0e267")),"syncPolicy"'
           if [ $? -eq 0 ]; then
               sed -i "s|CUSTOM_POLICY|$backup_sync_policy|" $base2js
           else
               sed -i "s|CUSTOM_POLICY|$backuppolicy|" $base2js
           fi

	   CUSTOM_DETAILS=$CLOUD_CUSTOMISABLE_COMMON" ,"$cloud_customizable_products" ,"$all_Storage_Details
	   if [[ $storagetype == "1" ]] ; then
                        CUSTOM_DETAILS=$CLOUD_CUSTOMISABLE_COMMON" ,"$cloud_customizable_products
           fi
	   if [ "$LDAP" == "true" ]; then
  	   	if [[ $storagetype == "1" ]] ; then
              		CUSTOM_DETAILS=$CLOUD_CUSTOMISABLE_COMMON" ,"$cloud_customizable_products" ,"$LDAP_DETAIL
              	else
                	CUSTOM_DETAILS=$CLOUD_CUSTOMISABLE_COMMON" ,"$cloud_customizable_products" ,"$all_Storage_Details" ,"$LDAP_DETAIL
           	fi
	   fi

           sed -i "s|CLOUD_CUSTOMISABLE_DETAILS_PLACEHOLDER|$CUSTOM_DETAILS|" $base1js

	   if [[ $producttype == "1 2" ]] ; then
			bothPolicy='"policyName" : "STATISTICS_COLLECTOR","syncPolicyName" : "STATISTICS_SYNC_COLLECTOR"'
			sed -i "s|POLICY_NAME|$bothPolicy|" $base2js
	   elif [[ $producttype == "1" ]] ; then
			syncPolicyName='"syncPolicyName" : "STATISTICS_SYNC_COLLECTOR"'
			sed -i "s|POLICY_NAME|$syncPolicyName|" $base2js
			sed -i "/db.BACKUP_POLICY.insert/d" $base2js
                        sed -i "/db.BACKUP_POLICY.update/d" $base2js
	   elif [[ $producttype == "2" ]] ; then
			backupPolicyName='"policyName" : "STATISTICS_COLLECTOR"'
			sed -i "s|POLICY_NAME|$backupPolicyName|" $base2js
			sed -i "/db.SYNC_POLICY.insert/d" $base2js
                        sed -i "/db.SYNC_POLICY.update/d" $base2js
	   fi
}

function config_mongo_data ()
{
        #Mongo Scripts for user / pwd creation
	export LC_ALL=C
	
	cmd='mongo --eval "db.stats()"'
	numTimes=20
	n=0
	while [ $n -lt $numTimes ] ; do
                $cmd && break || {
                        echo "Unable to connect with MongoDB.."
                        ((n++))
                        echo "retry $n ::"
                        sleep 15;
                 }

        done

	#current_ip=$(ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}')
	sudo mongo admin $INSTALLABLES_SCRIPT_PATH/js/auth_mongo.js
        sudo mongo parablu $INSTALLABLES_SCRIPT_PATH/js/parablu_table_install.js
        sudo mongo parablu001 $INSTALLABLES_SCRIPT_PATH/js/parablu001_table_install.js
        sudo mongo support $INSTALLABLES_SCRIPT_PATH/js/support_tables.js
	sudo mongo blukrypt $INSTALLABLES_SCRIPT_PATH/js/blukrypt_tables.js
	sudo mongo parablumsg $INSTALLABLES_SCRIPT_PATH/js/parablumsg_tables.js
	if [[ "$EXCLUDE_MSJOB" != "true" ]]; then
#		sudo mongo parablumsg $INSTALLABLES_SCRIPT_PATH/js/parablumsg_tables.js
		sudo mongo localhost:27017 -u "neil" -p "parablu" --authenticationDatabase "admin" < $INSTALLABLES_SCRIPT_PATH/js/msjob_policy.js
	fi
	if [[ "$EXCHANGEBACKUP" == "true" ]]; then
                sudo mongo localhost:27017 -u "neil" -p "parablu" --authenticationDatabase "admin" < $INSTALLABLES_SCRIPT_PATH/js/msexchange.js
        fi

}

function create_folder () 
{

	mkdir -p $CLIENT_ROOT_PATH/parablusys
	mkdir -p $CLIENT_ROOT_PATH/parablusys/bin
	mkdir -p $CLIENT_ROOT_PATH/parablusys/upgrade
	mkdir -p $CLIENT_ROOT_PATH/parablusys/clients
	mkdir -p $CLIENT_ROOT_PATH/parablusys/conf
	mkdir -p $CLIENT_ROOT_PATH/parablusys/private

}

function update_mongo_conf () 
{	
	sed -i -e 's/\r//g' /etc/mongod.conf
#	sed -i "/bindIp/d" /etc/mongod.conf
	if [ "$SERVER_TYPE" == "3" ]; then
		sed -i "s|bindIp:.*|bindIp: localhost,$DB_IP|" /etc/mongod.conf
	elif [ "$SERVER_TYPE" == "0" ]; then
		sed -i "s|bindIp:.*|bindIp: localhost,$BLUVAULT_IP|" /etc/mongod.conf
	elif [ "$SERVER_TYPE" == "3 1" ]; then
                sed -i "s|bindIp:.*|bindIp: localhost,$BLUVAULT_IP|" /etc/mongod.conf
                sed -i "s|port:.*|port: $MULTI_MONGO_PORT|" /etc/mongod.conf
	fi

	sed -i '\/mongodb\/mongod.log/a   \  logRotate: reopen' /etc/mongod.conf

	sed -i '/timeZoneInfo:/a   \  pidFilePath: /parablu/data/mongodb/mongodb.pid' /etc/mongod.conf
}


function config_replica () 
{
	mongo_key_path=parablusys/private
	service mongod stop

	sed -i "s|#replSet=setname|replSet=parablu|" /etc/mongod.conf

	#copy key file to mongo_cert path
	cp $DEFAULT_FILE_PATH/$mongo_key $CLIENT_ROOT_PATH/$mongo_key_path/
	chown mongodb:mongodb $CLIENT_ROOT_PATH/$mongo_key_path/$mongo_key
	chmod 600 $CLIENT_ROOT_PATH/$mongo_key_path/$mongo_key

	## write a js script to add members
	#Call Java script to initiate replica set and add replica set members 
	echo 'rs.initiate()
	rs.add("$DB2_IP:$R_DB_PORT")
	rs.add("$DB3_IP:$R_DB_PORT")' > replSet_add.js

	service mongod restart
	sleep 2

	mongo $DB1_IP replSet_add.js
}
FILE=/etc/modsecurity/modsecurity.conf
function rollback_primary_mongo()
{
        rollback_mongodb

        rm -rf /etc/mongod.conf
        ufw disable $LOCAL_MONGO_PORT
#       rm -rf $CLIENT_ROOT_PATH/parablusys
        rm -rf $INSTALLABLES_SCRIPT_PATH/js/parablu001_table_install.js
        rm -rf $INSTALLABLES_SCRIPT_PATH/js/parablu001_table.js
        rm -rf $INSTALLABLES_SCRIPT_PATH/js/parablu_table_install.js
        rm -rf $INSTALLABLES_SCRIPT_PATH/js/parablu_table.js
	if [ -f "$FILE" ]; then
        #apt-get -y autoremove libapache2-mod-security2
        #rm -rf /etc/modsecurity/
        apt-get -y autoremove libapache2-mod-security2
        sudo apt-get -y purge --auto-remove libapache2-mod-security2
        rm -rf /etc/modsecurity/
        sudo apt-get -y purge --auto-remove modsecurity-crs
        fi

        cp -r $INSTALLABLES_SCRIPT_PATH/js/backup/* $INSTALLABLES_SCRIPT_PATH/js/
	rm -rf /etc/init.d/PM_autorun.sh
}

function update_patch_primary_mongo()
{
	update_script=$INSTALLABLES_SCRIPT_PATH/js/update_mongo.sh.1
	cp $INSTALLABLES_SCRIPT_PATH/js/update_mongo.sh $update_script
        sed -i "s|GATEWAY_NAME|$BLUKRYPT_IP|" $update_script
        sed -i "s|BV_VALUE|$BLUKRYPT_IP|" $update_script
        sed -i "s|SOLR_URL|https://$SOLR_URL/ParacloudSearch/search/|" $update_script
	sed -i "s|EPA_ENV_LINK|$EPA_ENV_LINK|" $update_script
	sudo mongo $DB1_IP:$MONGODB_PORT -u "neil" -p "parablu" --authenticationDatabase "admin" < $update_script
}


