#!/bin/bash

USAGE=`cat << EOF
usage: 
update.sh [otpions]   
where  otpions is:
 --dir  <HES_DIR>               path to HES bin directory. Default  /opt/HES
 --service  <HES-SERVICE>       name of HES-service. Default HES
 --url <URL>                    url of update file.  if empty, then url  will be taken from https://update.hideez.com/hes/build.json 
 --urlLogin <URL_LOGIN>         if the update url requires access by login, password, then you can specify the login here
 --urlPassword <URL_PASSWORD>   if the update url requires access by login, password, then you can specify the password here
EOF
`

LOG_FILE="/tmp/update.log"
echo $(date -R) " Start update" | tee $LOG_FILE


HES_DIR="/opt/HES"
HESSERVICE="HES"
HES_UPDATE_URL=""
URL_LOGIN=""
URL_PASSWORD=""


while [ -n "$1" ]
do
        if [ -z "$2" ] 
        then
            echo "ERROR! no values specified after "$1" !" | tee -a $LOG_FILE
            echo "$USAGE" 
            exit 1
        fi
        param="$2"

        case "$1" in

                --dir)
                        HES_DIR=$param
                        shift ;;
                --service)
                        HESSERVICE=$param
                        shift ;;
                --url)   
                        HES_UPDATE_URL=$param
                        shift ;;
                --urlLogin)
                        URL_LOGIN=$param
                        shift ;;
                --urlPassword)
                        URL_PASSWORD=$param
                        shift ;;
                --) shift
                break ;;
                *) echo "ERROR! $1 is not an option"  | tee -a $LOG_FILE
                   echo "$USAGE"
                   exit 1
        esac
        shift
done


echo "dir = $HES_DIR" | tee -a $LOG_FILE
echo "service = $HESSERVICE" | tee -a $LOG_FILE 
#################################################


if [ "$HES_UPDATE_URL" = "" ] ; then
    JSON_URL=https://update.hideez.com/hes/build.json
    HES_UPDATE_URL=$(curl -s curl -s $JSON_URL  | jq --raw-output '.linux')
    #echo "HES_UPDATE_URL = $HES_UPDATE_URL"
fi

echo "url = $HES_UPDATE_URL" | tee -a $LOG_FILE 

#parsing json for create dump of database

JSON_FILE=$HES_DIR/appsettings.Production.json

DATABASE_SERVER=""
DATABASE_PORT=""
DATABASE_NAME=""
DATABASE_USER=""
DATABASE_PASSWORD=""

function getctedentials_jq {

   DEFAULTCONNECTION=$(jq -r '.ConnectionStrings.DefaultConnection' $1)
   PROVIDER=$(jq -r '.ConnectionStrings.Provider' $1)
   if [[ "$PROVIDER" == "null" ]]; then
      PROVIDER="MySql"
   fi

   if [[ "$PROVIDER" == "MySql" ]]; then

      #echo "DEFAULTCONNECTION = $DEFAULTCONNECTION"
      IFS=';' read -a arr <<< "$DEFAULTCONNECTION"
      for s in "${arr[@]}"; do 

         if [[ "${s^^}" == *"SERVER="* ]]; then
            IFS='=' read -a db_arr <<< "$s"
            DATABASE_SERVER=${db_arr[1]}
         fi
         if [[ "${s^^}" == *"PORT="* ]]; then
            IFS='=' read -a db_arr <<< "$s"
            DATABASE_PORT=${db_arr[1]}
         fi
         if [[ "${s^^}" == *"DATABASE="* ]]; then
            IFS='=' read -a db_arr <<< "$s"
            DATABASE_NAME=${db_arr[1]}
         fi
         if [[ "${s^^}" == *"UID="* ]]; then
            IFS='=' read -a user_arr <<< "$s"
            DATABASE_USER=${user_arr[1]}
         fi
         if [[ "${s^^}" == *"PWD="* ]]; then
            #  the password is expected to be the last parameter, 
            #  so let's take all the values
            #  except the first four characters
            DATABASE_PASSWORD="${s:4}"
            # IFS='=' read -a pass_arr <<< "$s"
            # DATABASE_PASSWORD=${pass_arr[1]}
         fi
      done
   fi    

   if [[ "$PROVIDER" == "MsSql" ]]; then
      #echo "DEFAULTCONNECTION = $DEFAULTCONNECTION"
      IFS=';' read -a arr <<< "$DEFAULTCONNECTION"
      for s in "${arr[@]}"; do 
         if [[ "${s^^}" == *"SERVER="* ]]; then
            IFS='=' read -a server_arr <<< "$s"
            SERVER_ARR=${server_arr[1]}
            IFS=',' read -a s_arr <<< "$SERVER_ARR"
            DATABASE_SERVER=${s_arr[0]}
            DATABASE_PORT=${s_arr[1]}
         fi
         if [[ "${s^^}" == *"CATALOG="* ]]; then
            IFS='=' read -a db_arr <<< "$s"
            DATABASE_NAME=${db_arr[1]}
         fi
         if [[ "${s^^}" == *"ID="* ]]; then
            IFS='=' read -a user_arr <<< "$s"
            DATABASE_USER=${user_arr[1]}
         fi
         if [[ "${s^^}" == *"PASSWORD="* ]]; then
            IFS='=' read -a user_arr <<< "$s"
            DATABASE_PASSWORD=${user_arr[1]}
         fi
      done
   fi

}


function getctedentials_sed {

    # name of database between "database="  and  ";uid"
    DATABASE_NAME=$(sed -n 's:.*database=\(.*\);uid.*:\1:pgI' $1)
    #   alternative with grep:
    #  DATABASE_NAME=$(grep -o -P '(?<=database=).*(?=;uid)' $JSON_FILE)
    # name of user between "uid="  and  ";pwd"
    DATABASE_USER=$(sed -n 's:.*uid=\(.*\);pwd.*:\1:pgI' $1)
    # password  of user between "pwd="  and  '"'
    DATABASE_PASSWORD=$(sed -n 's:.*pwd=\(.*\)".*:\1:pgI' $1)
    # name of pfx-file between ""SigningCertificateFile":"  and  ','
    #PFX_FILE=$(grep -o -P '(?<="SigningCertificateFile":).*(?=,)' $JSON_FILE)
    #  deleting quote's
    #PFX_FILE=$(echo $PFX_FILE | tr -d \")

}


#cat $JSON_FILE

if command -v jq &> /dev/null
then
    getctedentials_jq $JSON_FILE
else
    echo "jq not found in you server!" | tee -a $LOG_FILE
    exit 1
    # getctedentials_sed $JSON_FILE
fi


echo "PROVIDER = $PROVIDER"  | tee -a $LOG_FILE
echo "DATABASE_SERVER = $DATABASE_SERVER"  | tee -a $LOG_FILE
echo "DATABASE_PORT = $DATABASE_PORT"  | tee -a $LOG_FILE
echo "DATABASE_NAME = $DATABASE_NAME"  | tee -a $LOG_FILE
echo "DATABASE_USER = $DATABASE_USER" | tee -a $LOG_FILE
echo "DATABASE_PASSWORD = $DATABASE_PASSWORD" | tee -a $LOG_FILE

#################################################

## real upgrade:

# stoping  service
systemctl stop $HESSERVICE
if [ $? -eq 0 ]; then
        echo "HES service is stopped" | tee -a $LOG_FILE
else
    echo "HES service stop error" | tee -a $LOG_FILE
    exit 1
fi

# Create backup HES directory
BACKUP_HES_DIR=$HES_DIR-$(date +%Y-%m-%d-%H-%M-%S).Old

if [ -d $HES_DIR ]; then
        mv $HES_DIR $BACKUP_HES_DIR
fi

if [ $? -eq 0 ]; then
        echo "move to backup HES folder was compiled successfully" | tee -a $LOG_FILE
else
    echo "move HES foler to backup error" | tee -a $LOG_FILE
    exit 1
fi


if [ "$PROVIDER" = "MySql" ] ; then
    # Create dump of database
    mysqldump -h "$DATABASE_SERVER" -P "$DATABASE_PORT"  -u"$DATABASE_USER"  -p"$DATABASE_PASSWORD"  --no-tablespaces  "$DATABASE_NAME" > "$BACKUP_HES_DIR/$DATABASE_NAME.sql"
    if [ $? -eq 0 ]; then
    echo "database dump completed successfully" | tee -a $LOG_FILE
    else
    echo "the database dump was performed with an error" | tee -a $LOG_FILE
    exit 1
    fi
fi  #MySql


if [ "$PROVIDER" = "MsSql" ] ; then
   # Create backup of database
   /opt/mssql-tools/bin/sqlcmd -S "$DATABASE_SERVER","$DATABASE_PORT" -U "$DATABASE_USER" -P "$DATABASE_PASSWORD" -Q "BACKUP DATABASE ["$DATABASE_NAME"] TO DISK = N'/var/opt/mssql/data/db.bak' WITH NOFORMAT, NOINIT, NAME = 'db-full', SKIP, NOREWIND, NOUNLOAD, STATS = 10"
   if [ $? -eq 0 ]; then
     echo "database dump completed successfully" | tee -a $LOG_FILE
   else
     echo "the database dump was performed with an error" | tee -a $LOG_FILE
     exit 1
   fi
fi   # MsSql


################################

# create temporary directory
TMPDIR=$(mktemp -d)
 
cd "$TMPDIR"
curl -H "Cache-Control: no-cache" -u "$URL_LOGIN":"$URL_PASSWORD"  -o "$TMPDIR/hes.tar.gz" $HES_UPDATE_URL

if [ $? -eq 0 ]; then
        echo "file  hes.tar.gz to $TMPDIR  file uploaded successfull  from $HES_UPDATE_URL" | tee -a $LOG_FILE
else
        echo "Download error file from $HES_UPDATE_URL  to $TMPDIR" | tee -a $LOG_FILE
        exit 1
fi

tar -xf hes.tar.gz
mv $TMPDIR/HES $HES_DIR

if [ $? -eq 0 ]; then
        echo "folder $TMPDIR/HES to folder $HES_DIR  has been moved successfully" | tee -a $LOG_FILE
else
        echo  "Error moved folder $TMPDIR/HES to folder $HES_DIR!!!" | tee -a $LOG_FILE
        exit 1
fi

rm -rf "$TMPDIR"

################################

# copying an old json file 

BACKUP_JSON_FILE=$BACKUP_HES_DIR/appsettings.Production.json
cp $BACKUP_JSON_FILE  $JSON_FILE
if [ $? -eq 0 ]; then
        echo "backup appsettings.Production.json to appsettings.Production.json successfully copied" | tee -a $LOG_FILE
else
        echo "Error copying backup of appsettings.Production.json" | tee -a $LOG_FILE
        exit 1
fi

## copying an old update.sh file 
#UPDATE_FILE=$HES_DIR/update.sh
#BACKUP_UPDATE_FILE=$BACKUP_HES_DIR/update.sh
#if [ -f $BACKUP_UPDATE_FILE ]; then
#    cp $BACKUP_UPDATE_FILE $UPDATE_FILE
#    if [ $? -eq 0 ]; then
#        echo "old update script file successfully copied" | tee -a $LOG_FILE
#    else
#       echo "Error copying backup update script file" | tee -a $LOG_FILE
#       exit 1
#    fi
#fi

# startiing  service
systemctl start $HESSERVICE
if [ $? -eq 0 ]; then
        echo "HES service is started" | tee -a $LOG_FILE
else
    echo "HES service start error" | tee -a $LOG_FILE
    exit 1
fi

echo $(date -R) " Finish" | tee -a $LOG_FILE
#that's all ..