#!/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


function create_local_package ()
{

	FLAG=false
        PATCH_INSTALL=true
	BASE_PATH=$BACKUP_PATH_WITH_TIME
        BACKUP_NEW=$BASE_PATH/new
        BACKUP_OLD=$BASE_PATH/old
        mkdir -p $BACKUP_NEW
	rm -rf createlocalpackage
        mkdir -p createlocalpackage
        CSVFILE=createlocalpackage/patch.csv

	tput clear
        tput el
        echo "        =========================================OFFLINE SERVER PACKAGE====================================="

        tput cup 8 20
        echo "1. NEW INSATLLATION PATCHES"
        tput cup 9 20
        echo "2. ONLY UPGRADE PATCHES"

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

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

        	echo "New Installation"
                echo "#VersionNumber, DnsPath, FileName, CreatedOn" >> createlocalpackage/testpatch.csv
                echo "2.2.83_0, https://dns.parablu.com/parablu_installables/release/, 2.2.83_0.zip, 28-Feb-2017" >> createlocalpackage/testpatch.csv
		read -p "Enter Patch Version:" patchtoinstall
                CURRENT_VERSION=2.2.83_0

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

                 read -p "Enter Installed Version:" installedpatchversion
                 read -p "Enter Patch Version:" patchtoinstall
		 CURRENT_VERSION=$installedpatchversion
        fi

        patchversion=$patchtoinstall
        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

        
                        wget --user=$DNS_USERNAME --password=$DNS_PASS  $DNS_LINK_PATCHCSV_FOLDER/$DNS_PATCHCSV_FILENAME -P createlocalpackage 2> /dev/null
                        
         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
				##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
				##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

	if [[ $patchtype == 2 ]]; then
		echo "#VersionNumber, DnsPath, FileName, CreatedOn" >> createlocalpackage/testpatch.csv
		echo "$installedpatchversion, https://dns.parablu.com/parablu_installables/release/, patch-$installedpatchversion.zip, 28-Feb-2017" >> createlocalpackage/testpatch.csv
	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
#			echo "$version, $filepath, $filename, $createdOn" >> createlocalpackage/testpatch.csv
                        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 "createlocalpackage/$filename" ] ; then
                                echo "Downloading patch version $filename"
                                wget --user=$DNS_USERNAME --password=$DNS_PASS $filepath/$filename -P createlocalpackage 2> /dev/null
				echo "$version, $filepath, $filename,$createdOn" >> createlocalpackage/testpatch.csv
                        fi
                        if [ ! -f "createlocalpackage/$filename" ] ; then
                                echo "Unable to read patch"
                                exit 1
                        fi
                        unzip -l createlocalpackage/$filename >/dev/null 2>&1
			if [ $? -ne 0 ]; then
				echo "Unable to unzip patch $filename . File not properly  downloaded or corrupted"
				exit 1
			else 
				echo "Downloaded patch version $filename"
				echo ""
			fi

                        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)
mv  createlocalpackage/testpatch.csv $CSVFILE        
cd createlocalpackage
#zip -jr ParabluServerPatches.zip createlocalpackage/*
zip -r ParabluServerPatches.zip *
sleep 2s
rm -rf patch*

}

create_local_package
