#!/bin/bash
#                                                                                       #
# SCRIPT: install.sh	                                                                #
# DATE:   26-Oct-2016                                                                   #
# REV:    1.0                                                                           #
# DEVELOPED BY: Parablu Systems								#
#                                                                                       #
# PLATFORM: Ubuntu                                                                      #

PARABLU_CONFIG_SCRIPT_PATH=../config/parablu_config.sh 
PARABLU_COMPONENT_CONFIG_SCRIPT_PATH=../config/parablu_component_config.sh 
PARABLU_BLUKRYPT_SERVICE_SCRIPT_PATH=./blukrypt_service.sh 
PARABLU_PRIMARY_MONGO_SERVICE_PATH=./primary_mongo_service.sh 
PARABLU_SECONDARY_MONGO_SERVICE_PATH=./secondary_mongo_service.sh 
PARABLU_PRE_REQUISITE_SCRIPT_PATH=./pre_requisite.sh
PARABLU_PARACLOUD_SERVICE_SCRIPT_PATH=./paracloud_service.sh 
MONGO_FULL_BACKUP_SCRIPT_PATH=./mongo_full_backup.sh
PARABLU_INSTALLER_SCRIPT_PATH=../../parablu_installer.sh

source $PARABLU_PARACLOUD_SERVICE_SCRIPT_PATH 
source $PARABLU_BLUKRYPT_SERVICE_SCRIPT_PATH 
source $PARABLU_PRIMARY_MONGO_SERVICE_PATH 
source $PARABLU_SECONDARY_MONGO_SERVICE_PATH 
source $PARABLU_CONFIG_SCRIPT_PATH 
source $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH 
source $PARABLU_PRE_REQUISITE_SCRIPT_PATH

enableui=$1

function install_server () 
{
	get_ip_address
        source $PARABLU_CONFIG_SCRIPT_PATH
	sleep 3
	for x in ${SERVER_TYPE[@]}; do
	case $x in
       	 0 ) single_server "$current_ip"  ;;
       	 1 ) multipleServerBV "$current_ip" ;;
       	 2 ) multipleServerBK "$current_ip" ;;
       	 3 ) multipleServerMP "$current_ip" ;;
       	 4 ) multipleServerMS "$current_ip" ;;
       	 exit|EXIT|q|Q ) exit ;;
       	 * ) ;;
	esac
done

	source $PARABLU_CONFIG_SCRIPT_PATH
	source $PARABLU_COMPONENT_SCRIPT_PATH

	FILE_LOCATION=$NEW_FILE_LOCATION
	FILE_PATH=$NEW_FILE_PATH
	display_selected_product_details
	create_ssh_user
	add_mount_points
	enable_backblaze
	start_install 
}

function single_server ()
{
    if [ "$#" -ne 1 ]; then
       echo "Need IP Address of the machine to be installed"
       exit
    fi

    machine_ip_address=$1
    #echo "Processing Single Server Installation in " $machine_ip_address
    sed -i "s|BLUVAULT_IP.*| BLUVAULT_IP='"$machine_ip_address"' |" $PARABLU_CONFIG_SCRIPT_PATH
    sed -i "s|BLUVAULT1_URL.*| BLUVAULT1_URL='https://"$machine_ip_address"/' |" $PARABLU_CONFIG_SCRIPT_PATH
    sed -i "s|BLUKRYPT_IP.*| BLUKRYPT_IP='"$machine_ip_address"' |" $PARABLU_CONFIG_SCRIPT_PATH
    sed -i "s|SOLR_URL.*| SOLR_URL='"$machine_ip_address"' |" $PARABLU_CONFIG_SCRIPT_PATH
    sed -i "s|DB_IP.*| DB_IP='localhost' |" $PARABLU_CONFIG_SCRIPT_PATH
    sed -i "s|DB1_IP.*| DB1_IP='localhost' |" $PARABLU_CONFIG_SCRIPT_PATH
    sed -i "s|DB2_IP.*| DB2_IP='localhost' |" $PARABLU_CONFIG_SCRIPT_PATH
    sed -i "s|DB3_IP.*| DB3_IP='localhost' |" $PARABLU_CONFIG_SCRIPT_PATH
    sed -i 's|MONGODB_PORT.*|MONGODB_PORT="27017" |' $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
    sed -i 's|MONGODB1_PORT.*|MONGODB1_PORT="27017" |' $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
    sed -i 's|MONGODB2_PORT.*|MONGODB2_PORT="27017" |' $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
    sed -i 's|MONGODB3_PORT.*|MONGODB3_PORT="27017" |' $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
}


function multipleServerBV ()
{
    if [ "$#" -ne 1 ]; then
       echo "Need IP Address of the machine to be installed"
       exit
    fi
    machine_ip_address=$1
    echo "Processing BluValut Installation in " $machine_ip_address
    sed -i "s|BLUVAULT_IP.*| BLUVAULT_IP='"$machine_ip_address"' |" $PARABLU_CONFIG_SCRIPT_PATH
    sed -i "s|BLUVAULT1_URL.*| BLUVAULT1_URL='https://"$machine_ip_address"/' |" $PARABLU_CONFIG_SCRIPT_PATH        


    if [ -z $BLUKRYPT_IP ]; then
    	echo "missing blukrypt ip in config file"
	exit 0
    fi

    tput clear
    if [[ $blukryptip == '' ]]; then
    tput cup 7 15
    echo "Enter BluKrypt URL/IP"
    read blukryptip
    fi
    sed -i "s|BLUKRYPT_IP.*| BLUKRYPT_IP='"$blukryptip"' |" $PARABLU_CONFIG_SCRIPT_PATH
    sed -i "s|SOLR_URL.*| SOLR_URL='"$blukryptip"' |" $PARABLU_CONFIG_SCRIPT_PATH
    configure_mongo_ip
}

function multipleServerBK ()
{        
    if [ "$#" -ne 1 ]; then
       echo "Need IP Address of the machine to be installed"
       exit
    fi
    machine_ip_address=$1
    echo "Processing BluKrypt Installation in " $machine_ip_address
    sed -i "s|BLUKRYPT_IP.*| BLUKRYPT_IP='"$machine_ip_address"' |" $PARABLU_CONFIG_SCRIPT_PATH
    sed -i "s|SOLR_URL.*| SOLR_URL='"$machine_ip_address"' |" $PARABLU_CONFIG_SCRIPT_PATH        

    if [ -z $BLUVAULT_IP ]; then
    	echo "missing bluvault ip in config file"
    exit
    fi

    tput clear
    if [[ $bluvaultip == '' ]]; then
    tput cup 7 15
    echo "Enter Paracloud URL/IP"
    tput cup 8 15
    read bluvaultip
    fi
    sed -i "s|BLUVAULT_IP.*| BLUVAULT_IP='"$bluvaultip"' |" $PARABLU_CONFIG_SCRIPT_PATH
    sed -i "s|BLUVAULT1_URL.*| BLUVAULT1_URL='https://"$bluvaultip"/' |" $PARABLU_CONFIG_SCRIPT_PATH
    configure_mongo_ip
}


function multipleServerMP ()
{
    MULTI_PRIMARY_MONGO=true
    if [ "$#" -ne 1 ]; then
       echo "Need IP Address of the machine to be installed"
       exit
    fi
    machine_ip_address=$1
    echo "Processing Primary Database Installation in " $machine_ip_address
    sed -i "s|DB_IP.*| DB_IP='"$machine_ip_address"' |" $PARABLU_CONFIG_SCRIPT_PATH
    sed -i "s|DB1_IP.*| DB1_IP='"$machine_ip_address"' |" $PARABLU_CONFIG_SCRIPT_PATH
    sed -i "s|DB2_IP.*| DB2_IP='"$machine_ip_address"' |" $PARABLU_CONFIG_SCRIPT_PATH
    sed -i "s|DB3_IP.*| DB3_IP='"$machine_ip_address"' |" $PARABLU_CONFIG_SCRIPT_PATH
    sed -i "s|R_DB_PORT.*|R_DB_PORT='"$MULTI_MONGO_PORT"' |" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
    sed -i "s|MONGODB_PORT.*|MONGODB_PORT='"$MULTI_MONGO_PORT"' |" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
    sed -i "s|MONGODB1_PORT.*|MONGODB1_PORT='"$MULTI_MONGO_PORT"' |" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
    sed -i "s|MONGODB2_PORT.*|MONGODB2_PORT='"$MULTI_MONGO_PORT"' |" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
    sed -i "s|MONGODB3_PORT.*|MONGODB3_PORT='"$MULTI_MONGO_PORT"' |" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH

     if [ -z $BLUKRYPT_IP ]; then
     		echo "missing blukryptip in config file"
 		exit 0
     fi

     tput clear
    if [[ $blukryptip == '' ]]; then
    tput cup 7 15
    echo "Enter BluKrypt URL/IP"
    read blukryptip
    fi

    tput clear
    if [[ $bluvaultip == '' ]]; then
    tput cup 7 15
    echo "Enter Paracloud URL/IP"
    tput cup 8 15
    read bluvaultip
    fi

    sed -i "s|BLUKRYPT_IP.*| BLUKRYPT_IP='"$blukryptip"' |" $PARABLU_CONFIG_SCRIPT_PATH
    sed -i "s|BLUVAULT_IP.*| BLUVAULT_IP='"$bluvaultip"' |" $PARABLU_CONFIG_SCRIPT_PATH
    sed -i "s|SOLR_URL.*| SOLR_URL='"$blukryptip"' |" $PARABLU_CONFIG_SCRIPT_PATH
    tput clear
}

function multipleServerMS ()
{
    if [ "$#" -ne 1 ]; then
       echo "Need IP Address of the machine to be installed"
       exit
    fi
    machine_ip_address=$1
    echo "Processing Secondary Database Installation in " $machine_ip_address
    sed -i "s|DB_IP.*| DB_IP='"$machine_ip_address"' |" $PARABLU_CONFIG_SCRIPT_PATH
    sed -i "s|DB1_IP.*| DB1_IP='"$machine_ip_address"' |" $PARABLU_CONFIG_SCRIPT_PATH
}


function start_install() 
{
   for a in ${SERVER_TYPE[@]};do
        case $a in
                0) echo "Installing Database...."
		   release_primary_mongo 2>&1 >> install.log
		   echo "Database Successfully Installed"
		   sleep 2
		   echo  "==============================>>                                                                                                          [25%]"
		   sleep 2
		   echo "Installing Paracloud...."	
		   release_bluvault 2>&1 >> install.log
		   echo "Paracloud Successfully Installed"
		   sleep 2
		   echo "======================================================================================>>                                                  [65%]"
		   sleep 2
		   echo "Installing Blukrypt...."
		   release_blukrypt 2>&1 >> install.log
		   echo "Blukrypt Successfully Installed" 
		   sleep 2
		   release_watchdog 2>&1 >> install.log
       sleep 2
       release_liteversion 2>&1 >> install.log
		   echo "=======================================================================================================================================>>[100%]"
		    ;;

                1) release_bluvault 2>&1 >> install.log ;;
                2) release_blukrypt 2>&1 >> install.log ;;
                3) release_primary_mongo 2>&1 >> install.log ;;
                4) release_secondary_mongo 2>&1 >> install.log ;;
                
        esac
     done
	echo $version > /parablu/installed_version
}

function release_mongo_backup()
{
        tput clear
        tput cup 8 20
        echo "Enter Database machine IP:"
        tput cup 8 60
        read dbhost
        tput cup 10 20
        echo "Enter Database Port:"
        tput cup 10 60
        read dbport

        sed -i "s|DBHOST=.*| DBHOST='"$dbhost"' |" $MONGO_FULL_BACKUP_SCRIPT_PATH
        sed -i "s|DBPORT=.*| DBPORT='"$dbport"' |" $MONGO_FULL_BACKUP_SCRIPT_PATH

        mongo_backup
}

#PARABLU SCRIPT WITH UI
function select_server_type ()
{
       selectedserver=""
       found_zero=""
       server_count=""
	tput clear
	echo "---------------ParaBlu Inc.---------------"

	tput cup 7 15
	echo "Which component do you want to install [ If multiple values, leave a space between each value ] ?"
	
	#while true; do
	    tput cup 8 20
	    echo "0. All components( Paracloud, Blukrypt and Primary Database in SINGLE MACHINE)"
	    tput cup 9 20
	    echo "1. Paracloud"
	    tput cup 10 20
	    echo "2. BluKrypt"
	    tput cup 11 20
	    echo "3. Primary Database"
	    tput cup 12 20
	    echo "4. Secondary Database"
	    tput cup 13 20
            echo "5. Database backup"
            tput cup 14 20

	   # tput el
	    echo "Enter your choice number:"
	    tput cup 14 60 
	    read selectedserver
           ########logic which prevents installation of 3 and 4 in same machine##########
           echo $selectedserver | grep 3 | grep 4
               if [ $? -eq 0 ]; then
	           echo "Incorrect values...Primary database and secondary database cannot be installed in same machine. Enter correct values"
                   sleep 5
	           select_server_type
               fi

           ###########logic which checks if input is 0 or any other value################
	   echo $selectedserver | grep 0
           if [ $? -eq 0 ]; then
                   server_count=$(echo $selectedserver | wc -w)
                   found_zero="yes"
           fi

           if [[ $found_zero -eq "yes" ]] && [[ $server_count -gt 1 ]]; then
                   echo "Incorrect values... 0 already includes Paracloud, Blukrypt and Primary database. You cannot install same component twice. Enter correct values"
                   sleep 5
	           select_server_type
           fi

           ##################################End#########################################
	
           sed -i "s|SERVER_TYPE.*| SERVER_TYPE=$selectedserver |" $PARABLU_CONFIG_SCRIPT_PATH
		
}


function setup()
{
	if [ $# -gt 0 ] ; then
		setup=$1
		case $setup in
        		1) 
				health_check
				install_key=`cat install.key`

				IFS=':' read -ra install_params <<< "$install_key"
				selectedserver=${install_params[0]}
				producttype=${install_params[1]}
				version=${install_params[2]}
				poc=${install_params[3]}
				no_of_users=${install_params[4]}
				cloud_validity_in_days=${install_params[5]}
				cloud_name=${install_params[6]}
				email=${install_params[7]}
				SAVEIFS=$IFS
				IFS=$(echo -en "\n\b")		
				for key in ${install_params[*]}; do

					if [[ $key == *"storagetype="* ]] ; then
                                                storagetype=$(echo $key | sed -e 's/storagetype=//')
					elif [[ $key == *"hostname="* ]]; then
						current_ip=$(echo $key | sed -e 's/hostname=//')
					elif [[ $key == *"blukrypt="* ]]; then
                                                blukryptip=$(echo $key | sed -e 's/blukrypt=//')
					elif [[ $key == *"primarymongo="* ]]; then
                                                mongoipstatus=$(echo $key | sed -e 's/primarymongo=//')
					elif [[ $key == *"bluvault="* ]]; then
                                                bluvaultip=$(echo $key | sed -e 's/bluvault=//')
					elif [[ $key == *"numbackupusers="* ]]; then
                                                numbackupusers=$(echo $key | sed -e 's/numbackupusers=//')
          				elif [[ $key == *"numsyncusers="* ]]; then
                                                numsyncusers=$(echo $key | sed -e 's/numsyncusers=//')
          				elif [[ $key == *"multimongoport="* ]]; then
                                                multimongoport=$(echo $key | sed -e 's/multimongoport=//')
					elif [[ $key == *"ldapenabled="* ]]; then
                                                ldapenabled=$(echo $key | sed -e 's/ldapenabled=//')
          				elif [[ $key == *"watchdogenabled="* ]]; then
                                                watchdogenabled=$(echo $key | sed -e 's/watchdogenabled=//')
				        elif [[ $key == *"watchdogmail="* ]]; then
                                                watchdogmail=$(echo $key | sed -e 's/watchdogmail=//')
					elif [[ $key == *"watchdogfrommail="* ]]; then
                                                watchdogfrommail=$(echo $key | sed -e 's/watchdogfrommail=//')
                                        elif [[ $key == *"sshuser="* ]]; then
                                                sshuser=$(echo $key | sed -e 's/sshuser=//')
                                        elif [[ $key == *"sshport="* ]]; then
                                                sshport=$(echo $key | sed -e 's/sshport=//')
                                        elif [[ $key == *"watchdogips="* ]]; then
                                                watchdogips=$(echo $key | sed -e 's/watchdogips=//')
                                        elif [[ $key == *"paramailip="* ]]; then
                                                paramailip=$(echo $key | sed -e 's/paramailip=//') 
					elif [[ $key == *"customername="* ]]; then
                                                customername=$(echo $key | sed -e 's/customername=//')
					fi
				done
				## reset IFS
				IFS=$SAVEIFS

				if [[ $cloud_name == '' ]]; then
                                        echo "Enter installation Name"
                                        read cloud_name
				fi

				if [[ $email == '' ]]; then
                                        echo "Enter Admin Email ID"
                                        read email
                                fi

       				sed -i "s|SERVER_TYPE.*| SERVER_TYPE=\"$selectedserver\" |" $PARABLU_CONFIG_SCRIPT_PATH
				product_info
				sed -i "s|PRODUCT_TYPE.*| PRODUCT_TYPE=\"$producttype\" |" $PARABLU_CONFIG_SCRIPT_PATH
				storage_info
				sed -i "s|STORAGE_TYPE.*| STORAGE_TYPE=$storagetype |" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
				
				case "$poc" in 
  					y|Y ) 
					validity=`date --date="15 days" +%s%3N`;;
  					n|N ) 
					validity=`date --date="2 month" +%s%3N`;;
  					* ) 
					validity=`date --date="2 month" +%s%3N`;;
				esac
                                if [ ! -z $cloud_validity_in_days ]; then
                                	validity=`date --date="$cloud_validity_in_days day" +%s%3N`	
				fi
				if [ ! -z $numsyncusers ]; then
                                        sed -i "s|SYNC_USER_NO.*| SYNC_USER_NO='"$numsyncusers"' |" $PARABLU_CONFIG_SCRIPT_PATH
                                fi
                                if [ ! -z $numbackupusers ]; then
                                        sed -i "s|BACKUP_USER_NO.*| BACKUP_USER_NO='"$numbackupusers"' |" $PARABLU_CONFIG_SCRIPT_PATH
                                fi
                                if [ ! -z $multimongoport ]; then
                                        sed -i "s|MULTI_MONGO_PORT.*| MULTI_MONGO_PORT='"$multimongoport"' |" $PARABLU_CONFIG_SCRIPT_PATH
                                fi
				if [ ! -z $watchdogenabled ]; then
                                        sed -i "s|IS_WATCHDOG_ENABLED.*|IS_WATCHDOG_ENABLED=\"$watchdogenabled\" |" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
                                fi
                                if [ ! -z $liteversionenabled ]; then
                                        sed -i "s|IS_LITEVERSION_ENABLED.*|IS_LITEVERSION_ENABLED=\"$liteversionenabled\" |" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
                                fi
                                if [ ! -z "$watchdogmail" ]; then
                                        sed -i "s|WATCHDOG_MAIL_ADDRESS.*|WATCHDOG_MAIL_ADDRESS=\"$watchdogmail\" |" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
                                else
                                        sed -i "s|WATCHDOG_MAIL_ADDRESS.*| WATCHDOG_MAIL_ADDRESS=\"$email\" |" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
                                fi
				if [ ! -z $watchdogfrommail ]; then
                                        sed -i "s|WATCHDOG_FROM_MAIL_ADDRESS.*|WATCHDOG_FROM_MAIL_ADDRESS=\"$watchdogfrommail\" |" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
                                fi
                                if [ ! -z $sshuser ]; then
                                        sed -i "s|SSH_USERNAME.*|SSH_USERNAME=\"$sshuser\" |" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
                                fi
                                if [ ! -z $sshport ]; then
                                        sed -i "s|SSH_PORT.*|SSH_PORT=\"$sshport\" |" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
                                fi
                                if [ ! -z "$watchdogips" ]; then
                                        sed -i "s|OTHER_WATCHDOG_IP.*|OTHER_WATCHDOG_IP=\"$watchdogips\" |" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
                                fi
                                if [ ! -z $paramailip ]; then
                                        sed -i "s|PARAMAIL_MACHINE.*|PARAMAIL_MACHINE=\"$paramailip\" |" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
                                fi
				if [ ! -z "$customername" ]; then
                                        sed -i "s|CUSTOMER_NAME.*|CUSTOMER_NAME=\"$customername\" |" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
					sed -i "s|CUSTOMER_NAME=.*|CUSTOMER_NAME=\"$customername\" |" mongo_full_backup.sh
                                fi
				if [[ "$ldapenabled" == "true" ]] || [[ "$ldapenabled" == "false" ]];then
                                        sed -i "s|LDAP.*|LDAP=\"$ldapenabled\"|" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
                                fi

				sed -i "s|CLOUD_VALIDITY.*| CLOUD_VALIDITY='"$validity"' |" $PARABLU_CONFIG_SCRIPT_PATH
				sed -i "s|CLOUD_NAME.*| CLOUD_NAME='"$cloud_name"' |" $PARABLU_CONFIG_SCRIPT_PATH
				sed -i "s|ADMIN_EMAIL_ID.*| ADMIN_EMAIL_ID='"$email"' |" $PARABLU_CONFIG_SCRIPT_PATH

                                if [ ! -z $no_of_users ]; then
					sed -i "s|CLOUD_USER_NO.*| CLOUD_USER_NO='"$no_of_users"' |" $PARABLU_CONFIG_SCRIPT_PATH
				fi
				sed "s/^[ \t]*//" -i $PARABLU_CONFIG_SCRIPT_PATH;;
		esac
	else
		tput clear
		echo "---------------ParaBlu Inc.---------------"
		tput cup 7 20
		echo "What do you want to do?"
		tput cup 8 20
		echo "1. New Installation"
		tput cup 9 20
		echo "2. Update"
		tput cup 10 20
		echo "3. Uninstallation"
   		tput cup 11 20
       	 	echo "Enter your choice number:"
       	 	tput cup 11 50
        	read setup
		case $setup in
                        1) select_server_type
                               case $selectedserver in
                                 5) release_mongo_backup
                                        return 1 ;;
                                 *) health_check && select_product_type && storage_info && select_credentials;;
                               esac
                esac
	fi
	case $setup in
                1) if [[ $selectedserver -eq 3 ]] || [[ $selectedserver -eq 4 ]] || [[ $selectedserver -eq 5 ]] ; then
                        install_server
			bash reports.sh
			bash enable_ntp.sh
                     else
                        download_installer 2>&1 >> install.log
                        install_server
			bash reports.sh
			bash enable_ntp.sh
                   fi ;;
                2) if [[ "$SERVER_TYPE" != "4" ]] && [[ "$SERVER_TYPE" != "5" ]] ; then
			tput clear
                        echo "This method of Applying patch is no longer supported. Follow the new patch application method..!!!"
                        echo "EXAMPLE: If you want to apply patch 2.3.5.10 , then type \"bash install.sh 2.3.5.10\""
                        exit
                        echo "Downloading and Applying patches...."
                        deploy_patch
                        echo "Completed Applying Patches"
                   fi ;;
                3) select_uninstall ;;
                4) generate_key ;;
                5) download_installer 2>&1 >> install.log ;;
		6) IS_WATCHDOG_ENABLED="true"
		   tput clear
		   tput cup 8 20
                   echo "Enter Customer Name:"
                   tput cup 8 60
                   read customername
                   tput cup 9 20
                   echo "Enter Senders Mail ID for Watchdog:"
                   tput cup 9 60
                   read watchdogsendermail
                   tput cup 10 20
                   echo "Enter Receiver Mail ID for Watchdog:"
                   tput cup 10 60
                   read watchdogmail
		   tput cup 11 20
                   echo "Enter Other Watchdog Ip's:"
                   tput cup 11 60
                   read watchdogips
		   tput cup 12 20
                   echo "Enter SSH Username:"
                   tput cup 12 60
                   read sshuser
		   tput cup 13 20
                   echo "Enter SSH Port:"
                   tput cup 13 60
                   read sshport
		   tput cup 14 20
                   echo "Enter PARAMAIL IP:"
                   tput cup 14 60
                   read paramailip

		   grep -q -F "WATCHDOG_FROM_MAIL_ADDRESS" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
                  if [ $? -ne 0 ]; then
                        sed -i '/CSVFILE=..\/installables\/patch\/patch.csv/a WATCHDOG_FROM_MAIL_ADDRESS="root@ubuntu.members.linode.com"' $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
                  fi

                  grep -q -F "CUSTOMER_NAME" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
                  if [ $? -ne 0 ]; then
                        sed -i '/CSVFILE=..\/installables\/patch\/patch.csv/a CUSTOMER_NAME="PARABLU"' $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
                  fi

                  grep -q -F "WATCHDOG_MAIL_ADDRESS" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
                  if [ $? -ne 0 ]; then
                        sed -i '/CSVFILE=..\/installables\/patch\/patch.csv/a WATCHDOG_MAIL_ADDRESS="vaibhav@parablu.com"' $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
                  fi
                  grep -q -F "OTHER_WATCHDOG_IP" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
                  if [ $? -ne 0 ]; then
                        sed -i '/CSVFILE=..\/installables\/patch\/patch.csv/a OTHER_WATCHDOG_IP="localhost"' $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
                  fi

                  grep -q -F "MAIL_MACHINE" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
                  if [ $? -ne 0 ]; then
                        sed -i '/CSVFILE=..\/installables\/patch\/patch.csv/a MAIL_MACHINE="localhost"' $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
                  fi

                  grep -q -F "SSH_USERNAME" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
                  if [ $? -ne 0 ]; then
                        sed -i '/CSVFILE=..\/installables\/patch\/patch.csv/a SSH_USERNAME="root"' $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
                  fi

		  grep -q -F "SSH_PORT" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
                  if [ $? -ne 0 ]; then
                        sed -i '/CSVFILE=..\/installables\/patch\/patch.csv/a SSH_PORT="22"' $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
                  fi

		   sed -i "s|WATCHDOG_FROM_MAIL_ADDRESS.*|WATCHDOG_FROM_MAIL_ADDRESS=\"$watchdogsendermail\" |" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
		   sed -i "s|WATCHDOG_MAIL_ADDRESS.*|WATCHDOG_MAIL_ADDRESS=\"$watchdogmail\" |" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
		   sed -i "s|CUSTOMER_NAME.*|CUSTOMER_NAME=\"$customername\" |" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
		   sed -i "s|SSH_USERNAME.*|SSH_USERNAME=\"$sshuser\" |" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
		   sed -i "s|SSH_PORT.*|SSH_PORT=\"$sshport\" |" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
		   sed -i "s|OTHER_WATCHDOG_IP.*|OTHER_WATCHDOG_IP=\"$watchdogips\" |" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
		   sed -i "s|PARAMAIL_MACHINE.*|PARAMAIL_MACHINE=\"$paramailip\" |" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
		   release_watchdog ;;
		7) IS_LITEVERSION_ENABLED="true"
		   release_liteversion ;;
		8) tput clear
                   echo "This method of Applying patch is no longer supported. Follow the new patch application method..!!!"
                   echo "EXAMPLE: If you want to apply patch 2.3.5.10 , then type \"bash install.sh 2.3.5.10\""
                   exit


		   SCHEDULER_CONTEXT_OVERIDE=true
                         tput clear
                   tput cup 8 20

                        echo "If you select yes, Patch will be deployed by replacing the existing Scheduler context xml file ? (y/n)"

                        read overidexml
                        if [[ $overidexml = y ]]; then
                        tput clear
                          if [[ "$SERVER_TYPE" != "3" ]] && [[ "$SERVER_TYPE" != "4" ]] && [[ "$SERVER_TYPE" != "5" ]] ; then
                                echo "Downloading and Applying patches...."
                                deploy_patch
                                echo "Completed Applying Patches"
                           fi
			   if [[ "$IS_PG1" == "true" ]]; then
		                bash wipro_pg_replace.sh
        	           fi
                        fi ;;
		2.*)    patchversion=$setup
                        particular_patch ;;
        esac

}

function select_uninstall()
{
	tput clear
 	tput cup 8 20
            
       	echo "Do you really want to uninstall? (y/n)"

        read uninstall
	if [[ $uninstall = y ]]; then
		tput clear
		tput cup 9 20
		echo "    ========================Uninstalling Components========================"
		sleep 5
        	rollback_blukrypt
        	rollback_bluvault
        	rollback_primary_mongo
        	rollback_secondary_mongo
	fi
}

function generate_key ()
{

        select_server_type
        select_product_type
        select_storage_type

        tput clear
        #tput cup 8 20
        #echo "Enter Installation version:"
        #tput cup 8 60
        #read version
        tput cup 10
        echo "Installation for POC[Y/N]:"
        tput cup 10 70
        read poc
        tput cup 12
        echo "Enter Number of Cloud Users:"
        tput cup 12 70
        read no_of_users
        tput cup 14
	echo "Enter Email ID:"
        tput cup 14 70
        read email
        tput cup 16
        echo "Enter cloud Name:"
        tput cup 16 70
        read cloud_name
        tput cup 18
        echo "Hostname [ Domain Name or IP where you are installing ]:"
        tput cup 18 70
        read hostname

        tput cup 20
        echo "Number of Backup User [Enter 0 if it is only a sync environment]:"
        tput cup 20 70
        read bkpuser

        tput cup 22
        echo "Number of Sync User[Enter 0 if it is only a backup Environment]:"
        tput cup 22 70
        read syncuser

        tput cup 24
        echo "Is LDAP Enabled [ Enter 'true' to enable/ Enter 'false' to disable ]:"
        tput cup 24 70
	read en_ldap


version="2.2.83_0"

install_key="$selectedserver:$producttype:$version:$poc:$no_of_users:$cloud_validity_in_days:$cloud_name:$email:storagetype=$storagetype:hostname=$hostname:numbackupusers=$bkpuser:numsyncusers=$syncuser:ldapenabled=$en_ldap"
       echo $install_key
       sed -i "s|installation_key=.*|installation_key=\"$install_key\" |" $PARABLU_INSTALLER_SCRIPT_PATH
       echo "Key Generated"

}
function configure_mongo_ip ()
{
	tput clear
	if [[ $mongoipstatus == '' ]]; then
	tput cup 7 15
	echo "Enter Database Primary URL/IP"
	read mongoipstatus
	fi
	sed -i "s|DB_IP.*| DB_IP='"$mongoipstatus"' |" $PARABLU_CONFIG_SCRIPT_PATH
	sed -i "s|DB1_IP.*| DB1_IP='"$mongoipstatus"' |" $PARABLU_CONFIG_SCRIPT_PATH
	sed -i "s|DB2_IP.*| DB2_IP='"$mongoipstatus"' |" $PARABLU_CONFIG_SCRIPT_PATH
	sed -i "s|DB3_IP.*| DB3_IP='"$mongoipstatus"' |" $PARABLU_CONFIG_SCRIPT_PATH
	sed -i "s|R_DB_PORT.*|R_DB_PORT='"$MULTI_MONGO_PORT"' |" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
	sed -i "s|MONGODB_PORT.*|MONGODB_PORT='"$MULTI_MONGO_PORT"' |" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
	sed -i "s|MONGODB1_PORT.*|MONGODB1_PORT='"$MULTI_MONGO_PORT"' |" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
	sed -i "s|MONGODB2_PORT.*|MONGODB2_PORT='"$MULTI_MONGO_PORT"' |" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
	sed -i "s|MONGODB3_PORT.*|MONGODB3_PORT='"$MULTI_MONGO_PORT"' |" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH
#	tput cup 17 15
#	echo "Is Database server is cluster? (y/n)"
#	tput cup 18 15
#	read mongocus
#	if [[ $mongocus = y ]]; then
#	tput cup 18 15
#	echo "Enter Database 1st Secondary URL/IP"
#	tput cup 19 15
#	echo "Enter Database 2nd Secondary URL/IP"
#	tput cup 20 15
#	read mongos2ipstatus
#	sed -i "s|DB3_IP.*| DB3_IP='"$mongos2ipstatus"' |" $PARABLU_CONFIG_SCRIPT_PATH
#	else
#	sed -i "s|DB2_IP.*| DB2_IP='"$mongoipstatus"' |" $PARABLU_CONFIG_SCRIPT_PATH
#	sed -i "s|DB3_IP.*| DB3_IP='"$mongoipstatus"' |" $PARABLU_CONFIG_SCRIPT_PATH
#	fi
	tput clear
}


function select_product_type ()
{

        producttype=""
        found_zero=""
        product_count=""
	tput clear
	tput cup 7 15
	echo "Which product do you want to install?"
	
	tput cup 8 15
	#while true; do
	    tput el
	    tput cup 9 20
	    echo "0. All Products"
	    tput cup 10 20
	    echo "1. BluSync"
	    tput cup 11 20
	    echo "2. BluVault"
	    tput cup 12 20
	    echo "3. Server Backup"
	    tput cup 13 20
            echo "Enter your choice number:"
            tput cup 13 50
            read producttype
            echo $producttype
          
 ###########logic which checks if input is 0 or any other value################
	echo $producttype | grep 0
        if [ $? -eq 0 ]; then
           product_count=$(echo $producttype | wc -w)
           found_zero="yes"
        fi
        if [[ $found_zero -eq "yes" ]] && [[ $product_count -gt 1 ]]; then
           echo "Incorrect values... 0 already include all Product types. Enter proper value"
           sleep 5
           select_product_type
        fi
	product_info

	sed -i "s|PRODUCT_TYPE.*| PRODUCT_TYPE=\"$producttype\" |" $PARABLU_CONFIG_SCRIPT_PATH
}

function select_storage_type ()
 {
            storagetype=""
             found_zero=""
            storage_count=""

            tput clear
            tput el
 #          tput cup 8 20
 #          echo "0. All Storage Type"
            tput cup 9 20
            echo "1. Local"
            tput cup 10 20
            echo "2. Azure"
            tput cup 11 20
             echo "3. One Drive for Business"
            tput cup 12 20
            echo "4. Google Drive"
             tput cup 13 20
            echo "Enter your choice number:"
            tput cup 13 50
            read storagetype

            storage_count=$(echo $storagetype | wc -w)
             if [[ $storage_count -gt 1 ]]; then
                    echo "Incorrect values... Select Single Storage"
                    sleep 3
                    select_storage_type
            fi
         ########## Multiple storage logic, currently disabling############################
 #      echo $storagetype | grep 0
 #       if [ $? -eq 0 ]; then
 #             storage_count=$(echo $storagetype | wc -w)
 #             found_zero="yes"
 #        fi
 #        if [[ $found_zero -eq "yes" ]] && [[ $storage_count -gt 1 ]]; then
 #           echo "Incorrect values.. 0 already includes all storage types. Enter Proper values"
 #           sleep 1
 #           select_storage_type
 #        fi
        ##################################################################################
         storage_info

        sed -i "s|STORAGE_TYPE.*| STORAGE_TYPE=$storagetype |" $PARABLU_CONFIG_SCRIPT_PATH
        tput clear

 }
function product_info ()
{
           product_name=$(echo $producttype |
                        sed -e "s|0|Blusync Bluvault ServerBackup|" |
                        sed -e "s|1|Blusync|" |
                        sed -e "s|2|Bluvault|" |
                        sed -e "s|3|ServerBackup|")

}

function storage_info ()
{
	
        storage_name=$(echo $storagetype |
                        sed -e "s|0|Local Azure ODB GoogleDrive|" |
                        sed -e "s|1|Local|" |
                        sed -e "s|2|Azure|" |
                        sed -e "s|3|ODB|" |
                        sed -e "s|4|GoogleDrive|")
}

function select_credentials ()
{
	tput clear
	tput cup 7 15
	echo "Access Credentials"
	
	tput cup 8 15
	echo "Unique name of this installation (Alphanumeric, same for Primary database and Paracloud):"
	tput cup 8 110
	read cloudname
	sed -i "s|CLOUD_NAME.*| CLOUD_NAME='"$cloudname"' |" $PARABLU_CONFIG_SCRIPT_PATH
	
	tput cup 10 15
	echo "Enter Admin Email ID:"
	tput cup 10 50
	read email
	sed -i "s|ADMIN_EMAIL_ID.*| ADMIN_EMAIL_ID='"$email"' |" $PARABLU_CONFIG_SCRIPT_PATH

	tput cup 12 15
	echo "Installation for POC[y/n]:"
	tput cup 12 50
	read choice
	case "$choice" in 
  		y|Y ) echo "POC Installation"
			validity=`date --date="15 days" +%s%3N`;;
  		n|N ) echo "Live Installation"
			validity=`date --date="2 month" +%s%3N`;;
  		* ) echo "Live Installation"
			validity=`date --date="2 month" +%s%3N`;;
	esac
	
	sed -i "s|CLOUD_VALIDITY.*| CLOUD_VALIDITY='"$validity"' |" $PARABLU_CONFIG_SCRIPT_PATH
	sed "s/^[ \t]*//" -i $PARABLU_CONFIG_SCRIPT_PATH
	tput clear
	tput sgr0
	source $PARABLU_CONFIG_SCRIPT_PATH
}

function display_selected_product_details ()
{
	tput clear
	tput bold
        tput cup 14 15
        echo "Storage Selected: "$storage_name
	tput cup 15 15
        echo "Product Selected: "$product_name
	tput cup 16 15
	echo "Unique name of this installation : "$CLOUD_NAME""
	tput cup 17 15
	echo "Admin Email Id : "$ADMIN_EMAIL_ID"" 
	tput cup 18 15
	echo "Cloud Validity : `date -d @$(  echo "($CLOUD_VALIDITY + 500) / 1000" | bc)`"
	sleep 5

	tput clear
}

function download_installer()
{
	BASE_PATH=$BACKUP_PATH_WITH_TIME
	BACKUP_NEW=$BASE_PATH/new
	BACKUP_OLD=$BASE_PATH/old
	mkdir -p $BACKUP_NEW
	mkdir -p $BACKUP_OLD
	#####JKMOUNT FLAG is used to insert value to jk.con file only during installation################
        JK_MOUNT_CONF=true
	NEW_INSTALL=true

	if [ "$version" == "" ]; then
		echo "Enter installation version"
		read -p "Enter the correct version number[mandatory] :" version
	fi

	zipFilename="$version"
	zipFilePath=$BACKUP_PATH/$version.zip
	if [ ! -f $zipFilePath ]; then
 		echo "Downloading patch version $version"
		wget --user=$DNS_USERNAME --password=$DNS_PASS https://dns.parablu.com/parablu_installables/release/$version.zip -P $BACKUP_PATH 2> /dev/null
	else 
		echo "$version.zip file already present in local directory"
	fi

	apt-get -y install zip
  	unzip -o $BACKUP_PATH/$version.zip -d $BACKUP_NEW 
	NEW_FILE_LOCATION="local"
	NEW_FILE_PATH=$BACKUP_NEW
}

function deploy_patch()
{
	FLAG=false
  PATCH_INSTALL=true

	if [  ! -f "/parablu/installed_version" ]; then
		echo "Installation is not completed successfully. Please uninstall and install the application once again"
		exit
	fi
	CURRENT_VERSION=`cat /parablu/installed_version`
	echo "Current Version is $CURRENT_VERSION"
	BASE_PATH=$BACKUP_PATH_WITH_TIME
	BACKUP_NEW=$BASE_PATH/new
	BACKUP_OLD=$BASE_PATH/old
	mkdir -p $BACKUP_NEW
	mkdir -p $BACKUP_OLD
	
	tput clear
                tput cup 7 20
                echo "What do you want to do?"
                tput cup 8 20
                echo "1. Download patch.csv from DNS and deploy patch "
                tput cup 9 20
                echo "2. Patch.csv is already locally present in this system, so proceed with patch deployment"

                tput cup 11 20
                echo "Enter your choice number:"
                tput cup 11 50
                read csvoption

                if [[ $csvoption == 1 ]]; then

                        echo "Downloading Patch from dns"
                        wget --user=$DNS_USERNAME --password=$DNS_PASS  $DNS_LINK_PATCHCSV_FOLDER/$DNS_PATCHCSV_FILENAME -P $BACKUP_PATH 2> /dev/null
                        echo "Downloaded csv file from DNS"
                        mv $BACKUP_PATH/$DNS_PATCHCSV_FILENAME $CSVFILE 2> /dev/null
                        tput clear
                        echo "=================================== Patch.csv Contents ==========================="
                        echo ""
                        echo ""
                        cat $CSVFILE 2> /dev/null
                        if [ $? -ne 0 ]; then
				echo "Patch.csv not found. Aborting the process....."
                                exit 1
                        fi

                        echo ""
                        echo ""
                        read -p "Do you want to proceed with patch deployment? [y / n]:" patchconfirm
                        if [[ $patchconfirm = y ]] || [[ $patchconfirm = Y ]]; then
                                echo "Initiating Patch Deployment"
                        else
                                echo "Aborting the process."
				rm $CSVFILE
                                exit 1
                        fi
		
		elif [[ $csvoption == 2 ]]; then

                        echo "Patch.csv locally present"        
                        tput clear
                        echo "=================================== Patch.csv Contents ==========================="
                        echo ""
                        echo ""
                        cat $CSVFILE 2> /dev/null
                        if [ $? -ne 0 ]; then
                                echo "Patch.csv not found. Aborting the process....."
                                exit 1
                        fi

                        echo ""
                        echo ""
                        read -p "Do you want to proceed with patch deployment? [y / n]:" patchconfirm
                        if [[ $patchconfirm = y ]] || [[ $patchconfirm = Y ]]; then
                                echo "Initiating Patch Deployment"
                        else
                                echo "Aborting the process."
                                exit 1
                        fi
                else
                        echo "Invalid Input"
                fi


	while IFS="," read -r version filepath filename createdOn
	do
        	#continue if the line starts with #
        	if [[ $version = \#* ]] ; then
                	continue;
        	fi

        	version="$(echo -e "${version}" | sed -e 's/^[[:space:]]*//')"
        	if [[ $version == $CURRENT_VERSION ]] ; then
                	FLAG=true;
                	echo "Current Version is        : $version and skipping the patch"
			lastversion=$version
                	continue;
        	fi

        	if [[ $FLAG == true ]]; then
                	filepath="$(echo -e "${filepath}" | sed -e 's/^[[:space:]]*//')"
                	filename="$(echo -e "${filename}" | sed -e 's/^[[:space:]]*//')"

			if [ ! -e "$BACKUP_PATH/$filename" ] ; then
 				echo "Downloading patch version $filename"
				wget --user=$DNS_USERNAME --password=$DNS_PASS $filepath/$filename -P $BACKUP_PATH 2> /dev/null
			fi
			if [ ! -f "$BACKUP_PATH/$filename" ] ; then
        			echo "Unable to read patch"
				exit 1
			fi
  			unzip -o $BACKUP_PATH/$filename -d $BACKUP_NEW 
			if [ $? -ne 0 ]; then
                                echo "Unable to unzip patch $filename . File not properly  downloaded or corrupted"
                                exit 1
                        fi
 			echo "Downloaded patch version $filename"
			echo "Applying Patch...."
			lastversion=$version
        	else
                	echo "Already Installed Version : $version and skipping the patch"
        	fi
	done < $CSVFILE

	FILE_LOCATION="local"
        FILE_PATH=$BACKUP_NEW
	for b in ${SERVER_TYPE[@]};do
        case $b in
                0) release_bluvault 2>&1 >> install.log
		   release_blukrypt 2>&1 >> install.log ;;
                1) release_bluvault 2>&1 >> install.log ;;
                2) release_blukrypt 2>&1 >> install.log ;;
                
        esac
     done
	if [ $? -eq 0 ]; then
    		echo $lastversion > /parablu/installed_version
	fi

	if [[ "$SERVER_TYPE" == "3" ]];then
                mv $CSVFILE $BACKUP_PATH/mongo_patch.csv
        else
                mv $CSVFILE $BACKUP_PATH/patch_$date_time.csv
        fi

	if [[ "$IS_PG1" == "true" ]]; then
                bash wipro_pg_replace.sh
        fi
}

function particular_patch ()
{

	FLAG=false
        PATCH_INSTALL=true

        if [  ! -f "/parablu/installed_version" ]; then
                echo "Installation is not completed successfully. Please uninstall and install the application once again"
                exit
        fi
	TEMP_CURRENT_VERSION=`cat /parablu/installed_version`
        if [[ "$SERVER_TYPE" == "3" ]]; then
                if [[ $TEMP_CURRENT_VERSION == "2.2.83_0" ]] || [[ $TEMP_CURRENT_VERSION == "2.2" ]] || [[ $TEMP_CURRENT_VERSION == "2.2.54_6" ]]; then
                        tput clear

                        tput cup 8 20
                        echo "1. Patch Upgrade in New Mongo Server "
                        tput cup 9 20
                        echo "2. Patch Upgrade in Existing Mongo Server"

                        tput cup 11 20
                        echo "Enter your choice number:"
                        tput cup 11 50
                        read mongopatchoption

                        if [[ $mongopatchoption == 1 ]]; then

                                echo "New Installation"

                        elif [[ $mongopatchoption == 2 ]]; then

                                tput clear
                                read -p "Enter the same installed version present in paracloud/blukrypt machine before you applied new patches in those environments?" confirminstalledversion

                                echo $confirminstalledversion > /parablu/installed_version
                        fi

                else

                        echo "No Action"
                fi


        fi
        CURRENT_VERSION=`cat /parablu/installed_version`
        FULL_PATCH_LINE=$CURRENT_VERSION
        echo "Current Version is $CURRENT_VERSION"
        if [ $CURRENT_VERSION == "$patchversion" ]; then
                echo "Patch $patchversion is the current installed patch, hence terminating the patch deployment"
                exit
        fi

        BASE_PATH=$BACKUP_PATH_WITH_TIME
        BACKUP_NEW=$BASE_PATH/new
        BACKUP_OLD=$BASE_PATH/old
        mkdir -p $BACKUP_NEW
        mkdir -p $BACKUP_OLD
        rm -rf pre-release/*
        rm -rf post-release/*
        mkdir -p pre-release
        mkdir -p post-release
        tput clear
                tput cup 7 20
                echo "What do you want to do?"
		tput cup 8 20
                echo "1. Download patch.csv from DNS and deploy patch "
                tput cup 9 20
                echo "2. Patch.csv is already locally present in this system, so proceed with patch deployment"

                tput cup 11 20
                echo "Enter your choice number:"
                tput cup 11 50
                read csvoption

                if [[ $csvoption == 1 ]]; then

                        echo "Downloading Patch from dns"
                        wget --user=$DNS_USERNAME --password=$DNS_PASS  https://dns.parablu.com/parablu_installables/release/patch.csv -P $BACKUP_PATH 2> /dev/null
                        echo "Downloaded csv file from DNS"
#                        mv $BACKUP_PATH/$DNS_PATCHCSV_FILENAME $CSVFILE 2> /dev/null
                        tput clear
                        echo "=================================== Patch.csv Contents ==========================="
                        echo ""
                        echo ""
                        cat $CSVFILE 2> /dev/null
                        if [ $? -ne 0 ]; then
                                echo "Patch.csv not found. Aborting the process....."
                                exit 1
                        fi

                        echo ""
                        echo ""
                        read -p "Do you want to proceed with patch deployment? [y / n]:" patchconfirm
                        if [[ $patchconfirm = y ]] || [[ $patchconfirm = Y ]]; then
                                echo "Initiating Patch Deployment"
                        else
                                echo "Aborting the process."
                                rm $CSVFILE
                                exit 1
			fi

                elif [[ $csvoption == 2 ]]; then

                        echo "Patch.csv locally present"        
                        tput clear
                        echo "=================================== Patch.csv Contents ==========================="
                        echo ""
                        echo ""
                        cat $CSVFILE 2> /dev/null
                        if [ $? -ne 0 ]; then
                                echo "Patch.csv not found. Aborting the process....."
                                exit 1
                        fi

                        echo ""
                        echo ""
                        read -p "Do you want to proceed with patch deployment? [y / n]:" patchconfirm
                        if [[ $patchconfirm = y ]] || [[ $patchconfirm = Y ]]; then
                                echo "Initiating Patch Deployment"
                        else
                                echo "Aborting the process."
                                exit 1
                        fi
                else
                        echo "Invalid Input"
                fi

         PATCH_VERSION_LINE=$(grep -wn $patchversion $CSVFILE | sed -e 's/:.*//')
        CURRENT_VERSION_LINE=$(grep -wn $CURRENT_VERSION $CSVFILE | sed -e 's/:.*//')

        #### Check patch Version is present in CSV
        grep -w "$patchversion" $CSVFILE >/dev/null 2>&1
        if [ $? -ne 0 ]; then
                echo "Patch $patchversion you are trying to install is not present in CSV. Hence Aborting the process.."
                if [[ $csvoption == 1 ]]; then
                        rm $CSVFILE
                fi
	exit
        fi

        #### Downgrading Server
        if [ "${PATCH_VERSION_LINE}" -lt "$CURRENT_VERSION_LINE" ]; then
                read -p "Trying to downgrade the Server, strictly not recommended. Proceed at your own risk [y / n]:" serverdowngrade
                        if [[ $serverdowngrade = y ]] || [[ $serverdowngrade = Y ]]; then
                                echo "Downgrade Initiated.."
				##Check Full Patch
                                grep -wn fullpatch $CSVFILE >/dev/null 2>&1
                                if [ $? -eq 0 ]; then
                                        full_patch_flag=true
                                        FULLPATCH_VERSION_LINE=$(grep -wn fullpatch $CSVFILE | sed -e 's/:.*//')
                                for fp in ${FULLPATCH_VERSION_LINE[@]}; do

                                        if [ $fp -le $PATCH_VERSION_LINE ];
                                        then
                                                CURRENT_VERSION_LINE=$fp
                                        fi
                                done
                                fi
                        else
                                echo "Aborting the process."
                                rm $CSVFILE
                                exit 1
                        fi
        fi

        ## Check Current Version is present in CSV
        grep -w "$CURRENT_VERSION" $CSVFILE >/dev/null 2>&1
        if [ $? -ne 0 ]; then
                read -p "Currently Installed Patch $CURRENT_VERSION not present in CSV .Do you want to proceed with patch deployment? [y / n]:" curvermis
                        if [[ $curvermis = y ]] || [[ $curvermis = Y ]]; then
                                echo "Patch Initiated.."
				##Check Full Patch
			        grep -wn fullpatch $CSVFILE >/dev/null 2>&1
			        if [ $? -eq 0 ]; then
				        full_patch_flag=true
			        	FULLPATCH_VERSION_LINE=$(grep -wn fullpatch $CSVFILE | sed -e 's/:.*//')
			        for fp in ${FULLPATCH_VERSION_LINE[@]}; do

			                if [ $fp -le $PATCH_VERSION_LINE ];
			                then
                        			CURRENT_VERSION_LINE=$fp
			                fi
			        done
       				fi
                        else
				echo "Aborting the process."
                                rm $CSVFILE
                                exit 1
                        fi
        fi


	if [ "$PATCH_VERSION_LINE" -gt "$CURRENT_VERSION_LINE" ]; then
        	##Check Full Patch
	        grep -wn fullpatch $CSVFILE >/dev/null 2>&1
        	if [ $? -eq 0 ]; then

	        full_patch_flag=true
        	FULLPATCH_VERSION_LINE=$(grep -wn fullpatch $CSVFILE | sed -e 's/:.*//')
	        for fp in ${FULLPATCH_VERSION_LINE[@]}; do

        	        if [ $fp -le $PATCH_VERSION_LINE ];
                	then
                        	FINAL_FULL_PATCH_LINE=$fp
	                fi
	        done

		if [ $FINAL_FULL_PATCH_LINE -gt $CURRENT_VERSION_LINE ]; then
			CURRENT_VERSION_LINE=$FINAL_FULL_PATCH_LINE
		fi

        	fi
	fi

        while IFS="," read -r version filepath filename createdOn
        do
                #continue if the line starts with #
                if [[ $version = \#* ]] ; then
                        continue;
                fi

                version="$(echo -e "${version}" | sed -e 's/^[[:space:]]*//')"


                if [[ $version == $CURRENT_VERSION ]] ; then
			FLAG=true;
                        echo "Current Version is        : $version and skipping the patch"
                        lastversion=$version
                        continue;
                elif [[ $full_patch_flag == true ]]; then
                        FLAG=true;
                fi


                if [[ $FLAG == true ]]; then
                        filepath="$(echo -e "${filepath}" | sed -e 's/^[[:space:]]*//')"
                        filename="$(echo -e "${filename}" | sed -e 's/^[[:space:]]*//')"

                        if [ ! -e "$BACKUP_PATH/$filename" ] ; then
                                echo "Downloading patch version $filename"
                                wget --user=$DNS_USERNAME --password=$DNS_PASS $filepath/$filename -P $BACKUP_PATH 2> /dev/null
                        fi
                        if [ ! -f "$BACKUP_PATH/$filename" ] ; then
                                echo "Unable to read patch"
                                exit 1
                        fi
                        unzip -o $BACKUP_PATH/$filename -d $BACKUP_NEW
			if [ $? -ne 0 ]; then
				echo "Unable to unzip patch $filename . File not properly  downloaded or corrupted"
				exit 1
			fi

                        ## Copying Pre-release script to target Location
			if [ -f $BACKUP_NEW/pre-commands/$version-prerelease.sh ];then
                                cp -r $BACKUP_NEW/pre-commands/* pre-release/
                                PRERELEASEARRAY+=("$version-prerelease.sh")
                        fi

                        ## Copying Post-release script to target location
                        if [ -f $BACKUP_NEW/post-commands/$version-postrelease.sh ];then
                                cp -r $BACKUP_NEW/post-commands/* post-release/
                                POSTRELEASEARRAY+=("$version-postrelease.sh")
                        fi

                        echo "Downloaded patch version $filename"
#                        echo "Applying Patch...."
                        lastversion=$version
                        if [ $version == $patchversion ]; then
                                break;
                        else
                                continue;
                        fi
                else
                        echo "Already Installed Version : $version and skipping the patch"
                fi
        done < <(tail -n "+$CURRENT_VERSION_LINE" $CSVFILE)
        PRESENT_DIR=`pwd`
        ##RUN PRE RELEASE SCRIPT
        for pre_script in ${PRERELEASEARRAY[@]}; do
                cd pre-release && bash $pre_script
                cd $PRESENT_DIR
        done


        FILE_LOCATION="local"
	FILE_PATH=$BACKUP_NEW
        for b in ${SERVER_TYPE[@]};do
        case $b in
		0) echo "Release Bluvault..."
                   release_bluvault 2>&1 >> install.log
                   echo "Release Blukrypt..."
                   release_blukrypt 2>&1 >> install.log ;;
                1) echo "Release Bluvault..."
                   release_bluvault 2>&1 >> install.log ;;
                2) echo "Release Blukrypt..."
                   release_blukrypt 2>&1 >> install.log ;;
        esac
     done
        if [ $? -eq 0 ]; then
                echo $lastversion > /parablu/installed_version
        fi

        mv $CSVFILE $BACKUP_PATH/patch_$date_time.csv

        if [[ "$IS_PG1" == "true" ]]; then
                bash wipro_pg_replace.sh
        fi

        ## RUN POST RELEASE SCRIPT
        for post_script in ${POSTRELEASEARRAY[@]}; do
                cd post-release && bash $post_script
                cd $PRESENT_DIR >/dev/null 2>&1
        done

}

function get_ip_address ()
{
	if [[ $current_ip == '' ]]; then
	    current_ip=$(ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}')
            if grep -q unknown-245 /var/lib/dhcp/dhclient.eth0.leases; then
       		current_ip=$(curl ipinfo.io/ip)
       		echo “Running in an Azure VM, hence changing the IP to public IP:$current_ip”
	    fi
       fi
}

# Make sure only root can run our script
if [[ $EUID -ne 0 ]]; then
   echo "This script must be run with root"
   exit 1
fi

function release_watchdog ()
{
       if [ $IS_WATCHDOG_ENABLED == "true" ]; then
	        #apt-get -y install mailutils
	        watchdog_path=`pwd`
	        croncmd="cd $watchdog_path/health_check && ./health_check.sh"
	        cronjob="*/30 * * * * $croncmd"
		croncmd1="cd $watchdog_path/health_check && ./statistics_collector.sh"
                cronjob1="*/15 * * * * $croncmd1"
	        ( crontab -l | grep -v -F "$croncmd" ; echo "$cronjob" ) | crontab -

		if [[ "$SERVER_TYPE" == "0" ]] || [[ "$SERVER_TYPE" == "3" ]]; then
                        ( crontab -l | grep -v -F "$croncmd1" ; echo "$cronjob1" ) | crontab -
                fi
	fi
}

function release_liteversion ()
{
	if [ $IS_LITEVERSION_ENABLED == "true" ]; then
    		INSTALLABLES_SCRIPT_PATH=../installables
		liteversion_script=$INSTALLABLES_SCRIPT_PATH/js/lite_version.js

		sudo mongo localhost:27017 -u "neil" -p "parablu" --authenticationDatabase "admin" < $liteversion_script

		sed -i "s|define('PORTAL_LIGHT_VERSION'.*|define('PORTAL_LIGHT_VERSION', true);|" /var/www/portal/app/Core/Config.php
	fi

}

function add_mount_points ()
{
        mp=("/")
        echo "Mount points to be monitored for disk unmount[ Give space as a seperator between each mount points ]"
        read -p "Enter Mount Points:" mountps

        mp+=("$mountps")

        sed -i "s|MOUNT_POINTS.*|MOUNT_POINTS=\"${mp[*]}\"|" $PARABLU_COMPONENT_CONFIG_SCRIPT_PATH

}

setup $@



