#!/bin/bash
IP_COUNT=0
ONE_AGENT_OPTIONS=""
IS_USER_SET_IP=0
ENCODED_STRING=""
INSIDE_DOCKER_CONTAINER=0
OLD_DB=0
PUBLIC_KEY="-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAwMvtvkyHO7R3EU0jjaok
X9bsBWGzUxV9dSLcNqmTAl3LGifM2OEKMLr3NdP2nq0ZzU09Ds5wF12smOlt9hI4
W7x2be6L5fKME4iszDK2yWZBZYhTDBCcAIAkibbCO35enxOvLUBDWTHrFmFLpkrx
OutVIAuC5vM4IYSZGaPtqMbBTpIFc5ecLA8vYVlIytFM9p/in3sf1dgibojcqJPA
ZXX4pIt80+/mo4W9xGoCJw0oBjOGU/FEg+X79fp85F67G2ZrafvsU+urYJ/MNIz9
iRuDUZnPYn4OlGUAOLCkf+H0D2VxHNv0/IiSmNQwOkqvef7es6J47YiHZIKVmNyW
eNIa4hs0n/yfJG2mUUZmt80EcFzDFIp5yCx19igot4MZlMMCK699IyDBni/EIMLf
oOq8Ygv9sq7i97zfmqx7R2P5VQ63Q2lTgxNfHFCGZ7TOsgbu4n+sqYp9cB9p1caI
joAF5dITCdHMfBDrLlTBSpxsGIOcxgc3MT4FZyhzdCEh2TAInk0sDv9NgwxuLsB5
qq+qh9upeuoH76vTWzRm5XCX1QMTOOiCHb9xhq30j0uESCtAba58d1SgwFMgcGsl
DcZrlnFymkMfmCHgl5lw8zmK9czp2EctjjDMPpxXfhaTI/GHgN8XacY4VzxRZLr+
ke+Gmcny4WRWTyTh+kspiu8CAwEAAQ==
-----END PUBLIC KEY-----"

SERVER_INSTALLER_JSON=""
CAVBIN_URL="http://10.10.30.16:8992/others/CAVBIN"
RBU_URL="http://10.10.30.16:8992/others/RBU"
release_build="*"

#TODO: shuold we validate here

declare -A product_name

product_name["1"]="Observability <End to End monitoring>"
product_name["2"]="Infra monitoring"
product_name["3"]="Application monitoring"
product_name["4"]="Chaos Testing"
product_name["5"]="Synthetic monitoring"
product_name["6"]="UI/UX monitoring"
product_name["7"]="Log monitoring"
product_name["8"]="Load Testing"
product_name["9"]="Service Virtualization"
product_name["10"]="Generator Only"

get_ip(){
  # Get the list of network interfaces that are UP
  interfaces=$(ip -br a | awk '$2 == "UP" {print $1}')

  # Loop through the interfaces and get the IP address of wireless and weird interfaces only
  for interface in $interfaces; do
      ip_address=$(ip addr show $interface | grep -oP '(?<=inet\s)\d+(\.\d+){3}')
      if [ -n "$ip_address" ] && [ "$ip_address" != "127.0.0.1" ]; then
        #IP_COUNT=`expr $COUNT + 1`
        IP_LIST_WITH_SPACE="$IP_LIST_WITH_SPACE `echo "$ip_address" | tr '\n' ' '`"
      fi
  done

  ip_addresses=(`echo "$IP_LIST_WITH_SPACE"`)
   IP_COUNT=${#ip_addresses[@]}  
  if [ $IP_COUNT == 0 ]; then
    echo  "WARNING: Unable to find IP Address for this machine, So continuing with 127.0.0.1"
    ONE_AGENT_OPTIONS+="--Mgmt-Interface-IP=127.0.0.1 "
  elif [ $IP_COUNT == 1 ]; then
    ONE_AGENT_OPTIONS+="--Mgmt-Interface-IP=${ip_addresses[0]} "
  elif [ $IP_COUNT -ge 2 ]; then
    ONE_AGENT_OPTIONS+="--Mgmt-Interface-IP=${ip_addresses[0]} "
    ONE_AGENT_OPTIONS+="--Ext-Interface-IP=${ip_addresses[1]} "
  fi
}

# Check if /proc/1/cgroup file exists && /.dockerenv file is exists
check_inside_docker_container_or_not(){
  if [ -f "/.dockerenv" ] && [ -f "/proc/1/cgroup" ] && grep -q "docker" "/proc/1/cgroup"; then
    INSIDE_DOCKER_CONTAINER=1
  else
    INSIDE_DOCKER_CONTAINER=0
  fi
}

connectivity(){

curl -I https://www.google.com > /dev/null 2>&1

if [ $? != 0 ]; then
    echo "Error: No Internet connectivity, Hence exiting."
    exit 1
fi

yum --version > /dev/null 2>&1
if [ $? != 0 ];then 
    echo "Error: Package repository not found, Hence exiting."
    exit 1
fi
}


createConfigFileAndWirteConfig(){
  CAV_INSTALL="$INSTALLATION_PATH/cavissonInstallation.config"
  rm $CAV_INSTALL >>/dev/null 2>&1
  touch $CAV_INSTALL
  chmod 777 $CAV_INSTALL
  chown cavisson:cavisson $CAV_INSTALL >>/dev/null 2>&1  
  echo "LITEIMAGE=$liteImage" >> $CAV_INSTALL
  echo "INSIDE_DOCKER_CONTAINER=$INSIDE_DOCKER_CONTAINER" >> $CAV_INSTALL
  echo "CAVISSONKERNEL=$cavissonkernel" >> $CAV_INSTALL
  echo "ENABLE_OS_HARDNING=$enableoshardning" >>$CAV_INSTALL
  echo "OLD_DB=$OLD_DB" >>$CAV_INSTALL
 
  # Iterate over the array and print the values
  for sub_feature in "${sub_feature_array[@]}"; do
    
   echo "$sub_feature=1" >> $CAV_INSTALL
  done

}

compare_licence(){
  licence_dir="/home/cavisson/.licence"
  ls "$licence_dir/cav_licence" 1>/dev/null 2>&1 
  if [ $? == 0 ]; then 
    old_licence=`cat "$licence_dir/cav_licence" | sed -n '/BEGIN SIGN B64/,/END SIGN B64/p' | sed '1d;$d'`
    new_licence=`cat "$licence_path" | sed -n '/BEGIN SIGN B64/,/END SIGN B64/p' | sed '1d;$d'`
    if [ "$old_licence" == "$new_licence" ]; then
      echo "Licence is similar to existing licence"
      exit 1 
    fi
  fi
  echo "Upgrading licence"
}


create_cavisson_user()
{
  HOME_DIR="/home/cavisson"
  NS_WDIR="/home/cavisson/work"
  #create  user  cavisson
  #echo "Creating  user  cavisson"
  USRSTORM=`cat /etc/passwd|grep "^cavisson:"|wc -l`
  if [ $USRSTORM -ne 1 ];then
        echo "going to be creating user cavisson"
            useradd -m -s /bin/bash cavisson && echo -e "cavisson\ncavisson" | passwd cavisson >> /dev/null 2>&1
            if [ $? -ne 0 ];then
                echo "User cavisson could not be created successfully"
                exit 1
            fi
  else
    #echo "user already created"
    return 
  fi

  ## systemctl added on 11-10-2022 by Sandeep Raghav in 4.10.0
  chown cavisson:cavisson $HOME_DIR
  sed -i "/cavisson*/d" /etc/sudoers >/dev/null 2>&1
  echo "cavisson ALL=(ALL) NOPASSWD: /usr/sbin/service, /usr/bin/systemctl, /sbin/setcap, /home/cavisson/bin/cav_service, /bin/netstat, /sbin/iptables, /sbin/iptables-save, /sbin/ip, /sbin/route, /usr/bin/du, /usr/bin/strace, /usr/bin/gdb, /usr/bin/ltrace, /sbin/ldconfig, /usr/sbin/iotop, /usr/sbin/tcpdump, /sbin/tc, $JAVA_HOME/bin/jmap" >>/etc/sudoers
  echo 'Defaults  env_keep += "NS_WDIR"' >> /etc/sudoers

  chmod +x $HOME_DIR/
  #Make directory "work" under "$HOME_DIR"
  #echo "Creating $NS_WDIR and work, upgrade, etc and .rel directories"
  su cavisson -c "mkdir -p $HOME_DIR/etc"
  su cavisson -c "mkdir -p $HOME_DIR/users"
  su cavisson -c "mkdir -p $NS_WDIR/etc"
  su cavisson -c "mkdir -p $NS_WDIR/upgrade"
  su cavisson -c "mkdir -p $NS_WDIR/.rel"

 #create bash_profile and call bashrc from bash_profile
  echo -e "if [ -f /.bashrc ]; then\n\t. /.bashrc\nfi\n. $HOME_DIR/bin/nsi_controller_selection_profile" > $HOME_DIR/.bash_profile
  echo -e "if [ -f /.bashrc ]; then\n\t. /.bashrc\nfi\n. $HOME_DIR/bin/nsi_controller_selection_profile" > /root/.bash_profile
}

rootPrivilages(){
  if [ "$(id -u)" != "0" ]; then
    return 1
  else
    #echo "User is root"
    return 0
  fi
}


change_dir(){
 
  cav_libs_dir="$INSTALLATION_PATH"
  cur_dir=`pwd`
  #Store the old Logs and remove the old Cavbin file if it is present in the default execution path
  if [ "$cur_dir" == "$cav_libs_dir" ]; then
    if [ ! -z "$(ls -A $cav_libs_dir)" ]; then
      if [ "$controller_name" == "work" ]; then
        mkdir -p $cav_libs_dir/oldlogs
        mv $cav_libs_dir/*.log $cav_libs_dir/logs/* $cav_libs_dir/cavissonInstallation.config $cav_libs_dir/oldlogs 2>/dev/null
      fi
    fi
    return	
  fi 
  
  if [ ! -d $cav_libs_dir ]; then
    mkdir -p $cav_libs_dir 
  else
    if [ ! -z "$(ls -A $cav_libs_dir)" ]; then
      mkdir -p $cav_libs_dir/oldlogs
      mv $cav_libs_dir/*.log $cav_libs_dir/logs/* $cav_libs_dir/cavissonInstallation.config $cav_libs_dir/oldlogs 2>/dev/null
      rm $cav_libs_dir/Cav.* 2>/dev/null
    fi
  fi
  
  # check if files matching the pattern exist in the specified path
  if [ -f "$server_package" ]; then
    cav_name=$(basename "$server_package")
    rm "$cav_libs_dir/$cav_name" 1>/dev/null 2>&1
    ln -s $server_package $cav_libs_dir 1>/dev/null 2>&1
    if [ $? != 0 ]; then 
      echo "Error in creating soft link for cavBin"
    fi
  fi

  # check if files matching the pattern exist in the current directory
  ls $file_name 1>/dev/null 2>&1 
  if [ $? == 0 ]; then 
    cav_name=`ls $file_name | head -1`
    rm "$cav_libs_dir/$cav_name" 1>/dev/null 2>&1
    ln -s "$cur_dir/$cav_name" $cav_libs_dir 1>/dev/null 2>&1
    if [ $? != 0 ]; then
      echo "Error in creating soft link for cavBin"
    fi
  fi
    
  rm "$cav_libs_dir/cav_licence" 1>/dev/null 2>&1 
  echo $licence_path | grep "/" 1>/dev/null 2>&1
  if [ $? == 0 ]; then
    ln -s "$licence_path" $cav_libs_dir 1>/dev/null 2>&1
    if [ $? != 0 ]; then
      echo "Error in creating soft link for cav_licence"
    fi
  else
    ln -s "$cur_dir/$licence_path" $cav_libs_dir 1>/dev/null 2>&1 
    if [ $? != 0 ]; then
      echo "Error in creating soft link for cav_licence"
    fi
  fi

  rm "$cav_libs_dir/ServerInstaller.sh" 1>/dev/null 2>&1 
  ln -s "$cur_dir/ServerInstaller.sh" $cav_libs_dir 1>/dev/null 2>&1 
  if [ $? != 0 ]; then
    echo "Error in creating soft link for ServerInstaller.sh"
  fi
  
  ls rbu_setup.*.bin 1>/dev/null 2>&1
  if [ $? == 0 ]; then
    rbu_name=`ls rbu_setup.*.bin | head -1`
    rm "$cav_libs_dir/$rbu_name" 1>/dev/null 2>&1
    ln -s "$cur_dir/$rbu_name" $cav_libs_dir 1>/dev/null 2>&1
    if [ $? != 0 ]; then
      echo "Error in creating soft link for cavBin"
    fi
    rbu_flag=1
  fi
    
  cd $cav_libs_dir
}

installRbu(){
#If already Rbu file is present in the installation path then rbu_flag=1 and skip the download process, if not rbu_flag is null and will download RBU
if [ -z "$rbu_flag" ]; then
  #if we installing NVSM as sub-module we have to download rbu_setup.4.1.13.2_Ubuntu1604_64.bin  
  IFS=', ' read -r -a product_suite_array <<< "$product_suite"
  
  for product in "${product_suite_array[@]}" 
  do
    if [ $product == 5 ]; then
      nohup wget $RBU_URL 1>/dev/null 2>&1 
      rbu_file_name="rbu_setup.*.${distrib}.*.bin"
      # Run the command and store the output in an array
      readarray -t output_array < <(grep -oP '(?<=href="/others/RBU/)[^"]+' RBU | grep "$rbu_file_name" | sort -t '.' -k2,2n -k3,3n -k4,4n -k5,5n -k6,6n)
      output_array=($(printf "%s\n" "${output_array[@]}" | tac))
      # Print the array elements
      for element in "${output_array[@]}"; do
	rbu_release_build=`echo $element | grep -oP '(\d+\.){3}\d+'`
        if [[ "$(printf "%s\n%s" "$rbu_release_build" "$release_build" | sort -V | head -n1)" == "$rbu_release_build" ]]; then
	  break
        fi
      done
      RBU_URL="$RBU_URL/$element"
      echo "For config sub-module as NVSM need to download RBU"
      wget $RBU_URL
      break
    fi
  done
fi
}  
  
install_cavbin(){

  installRbu
  new_version=$(echo $file_name | sed 's/^.*\.\([0-9]*\.[0-9]*\.[0-9]*\)\.\([0-9]*\)\..*$/\1.\2/') 
  present_version="$VERSION.$BUILD"
   
  if [ "X$present_version" != "X." ]; then 
    if [[ "$new_version" == "$present_version" ]]; then
      echo "Version provided is similar to installed version. So checking licence"
      compare_licence
    elif [ "$new_version" \< "$present_version" ]; then
      echo "Downgrading to version ${new_version}"
      ONE_AGENT_OPTIONS+="--Install " 
    else
      echo "Upgrading Cavisson Product Suite to version ${new_version}"
      ONE_AGENT_OPTIONS+="--Install " 
    fi
  else	 
    echo "Installing Cavisson Product Suite release $release_build"
    ONE_AGENT_OPTIONS+="--Install " 
  fi
  
  encode_one_agent_options 
  bash $file_name $ENCODED_STRING
  status=$?
}

check_user_give_path() {
  # check if files matching the pattern exist in the specified path
  if [ -f "$server_package" ]; then
    #echo "Files $server_package is exsit starting installation"
    file_name=$server_package
    release_build=`echo $file_name | grep -oP '(\d+\.){3}\d+'`
    install_cavbin
    return ;
  fi
  
  # check if files matching the pattern exist in the current directory
  ls $file_name 1>/dev/null 2>&1
  if [ $? == 0 ]; then
    #echo "Files matching pattern $file_name exist in the current directory starting installation"   
    file_name=`ls $file_name | head -1`
    release_build=`echo $file_name | grep -oP '(\d+\.){3}\d+'`
    install_cavbin
    return ;
  fi
  
  #No files matching pattern $file_name found
  if [ "$release_build" == "*" ]; then
    #find the latest build from http://10.10.30.16:8992/others/CAVBIN
    nohup wget "$CAVBIN_URL" 1>/dev/null 2>&1
    #<tr><td><i class="icon icon-_page"></i></td><td class="perms"><code>(-rwxr-xr-x)</code></td><td class="file-size"><code>4.7G</code></td><td class="display-name"><a href="/others/CAVBIN/Cav.4.12.0.13.Ubuntu2004_64.bin">Cav.4.12.0.13.Ubuntu2004_64.bin</a></td></tr>
    #from this string we grep "href="/others/CAVBIN/" then find the name
    file_name=`grep -oP '(?<=href="/others/CAVBIN/)[^"]+' CAVBIN | grep "Cav.*.$distrib*" | sort -t '.' -k2,2n -k3,3n -k4,4n -k5,5n -k6,6n | tail -n1`
    CAVBIN_URL="http://10.10.30.16:8992/others/CAVBIN/$file_name"
    release_build=`echo $file_name | grep -oP '(\d+\.){3}\d+'`
  else
    if [ "$distrib" == "Red" ]; then
      file_name="Cav.$release_build.Redhat_64.bin"
    else
      file_name="Cav.$release_build.Ubuntu2004_64.bin"    
    fi 
    CAVBIN_URL="http://10.10.30.16:8992/others/CAVBIN/$file_name"
  fi

  echo "Downloading Cavisson Product Suite Version $release_build from Cavisson Build Repository"
  wget $CAVBIN_URL
  if [ $? != 0 ]; then
    echo "Release Build $release_build not found kindly specify the correct relase build"
    exit 1
  fi
  
 
  install_cavbin
}


#change the name of version file
check_cavbin_version(){

  if [ -f /etc/.version ];then
    local VERSION=$(grep ^VERSION /etc/.version | awk '{print $2}')
    local BUILD=$(grep ^BUILD /etc/.version | awk '{print $2}')
    if [ ! -z "${VERSION}" -a ! -z "${BUILD}" ];then
      echo "Installed Cavisson Product Suite Version $VERSION.$BUILD"
    fi
  fi

  check_user_give_path
}

detect_linux_distribution(){

    if [ -f /etc/redhat-release ]; then
        cat /etc/redhat-release
    elif [ -f /etc/os-release ]; then
        (
        . /etc/os-release
        local distrib="${NAME}"
        if [ -z "${distrib}" ]; then
            distrib="${ID}"
        fi
        local version="${VERSION_ID}"
        if printf "%s" "${distrib}" | grep -iq "debian"; then
            version="$(cat /etc/debian_version)"
        fi
        printf "%s %s" "${distrib}" "${version}"
        )
    elif [ -f /etc/SuSE-release ]; then
        head -1 /etc/SuSE-release
    elif [ -f /etc/lsb-release ]; then
        (
        . /etc/lsb-release
        printf "%s %s" "${DISTRIB_ID}" "${DISTRIB_RELEASE}"
        )
    elif ls /etc/*release* >/dev/null 2>&1; then
        # Generic fallback
        cat /etc/*release*
    else
        printf "AIX %s" "$(oslevel -s)"
    fi

}

detect_cavbin_and_installed(){

    POSTGRESQL_VERSION=12
    DISTRO=`grep ^NAME /etc/os-release | cut -d '=' -f2 |tr -d '""'`
    RELEASE=`cat /etc/os-release |sed -n '/VERSION_ID=/ s/[^0-9]//g p'`
    if [[ "$DISTRO" == "Ubuntu" &&  $RELEASE == "16.04" ]];then
      POSTGRESQL_VERSION=9.5
    fi


    #echo  "Distribution: $(detect_linux_distribution)"
    distrib=$(detect_linux_distribution | awk '{print $1}')
    if [ "X$distrib" == "XCentOS" ];then
      distrib="Red"
      POSTGRESQLCONF=/var/lib/pgsql/$POSTGRESQL_VERSION/data/postgresql.conf
    else
      POSTGRESQLCONF=/etc/postgresql/$POSTGRESQL_VERSION/main/postgresql.conf
    fi
    #Cav.4.11.0.46.Ubuntu2004_64.bin 
    file_name="Cav.$release_build.${distrib}*.bin"    
    change_dir 
    createConfigFileAndWirteConfig 
    check_cavbin_version
}

usage(){

  echo "-----------------------------------------------------------------------------------------------------------------------------------------------------------
-s|--Single-Node
Use this value when the installation is done on one node. This is the default
-S|—Multi-Node
Use this value when you need to create a cluster having multiple nodes.
-C|--Cert-path
Use this value in case you want to install your own SSL certificate.
-a|--Env-name
Provide an Environment name. Default is NetD
-t|--Tier
Provide an Application Tier name.
-p|--Server-package
Use this to specify the path where your server package is kept. This is needed in case machine does not have internet connectivity.
-R|--Release-build
Provide this value in case you want to install specific release. Default is the latest release available on Cavisson repository
-c|--Licence-path
Use this to specify the licence file path provided by Cavisson
-d|--Domain
Use this to specify domain name for SSL certificate
-M|--Mgmt-Interface-IP
IP address of the interface which will be used to access GUI
-E|--Ext-Interface-IP
IP address of the interface which will be used to connect to  cavisson agents
-i|--Uninstall
For uninstalling the installer
-h|--help
Use this value for parameter help

------------------------------------------------------------------------------------------------------------------------------------------------------------"
  exit 0
}
  
ParseCommandLineArguments(){
  OPT=`getopt -o hsSCa:t:P:R:l:c:p:O:d:M:E:i --long help,Single-Node,Multi-Node,Cert-File:,Env-name:,Tier:,Server-package:,Release-build:,Licence-path:,Controller-name:,Base-port:,old-db:,Domain:,Mgmt-Interface-IP:,Ext-Interface-IP:,uninstall -- "$@"`

  eval set -- "$OPT"

  while true; do
    case "$1" in
      -h|--help) usage ; shift 2;; 
      -s|--Single-Node) single_node=true; ONE_AGENT_OPTIONS+="--Single-Node " ;shift;;
      -S|--Multi-Node) multi_node=true; ONE_AGENT_OPTIONS+="--Multi-Node " ;shift;;
      -C|--Cert-File) cert_path="$2"; ONE_AGENT_OPTIONS+="--Cert-File=$cert_path " ;shift 2;;
      -a|--Env-name) env_name="$2"; shift 2;;
      -t|--Tier) tier="$2"; shift 2;;
      -P|--Server-package) server_package="$2"; shift 2;;
      -R|--Release-build) release_build="$2"; shift 2;; #TODO : do validation 4.12.0.39 this sting 
      -l|--Licence-path) licence_path="$2"; shift 2;;
      -c|--Controller-name) controller_name="$2"; ONE_AGENT_OPTIONS+="--Controller-name=$controller_name " ;shift 2;;
      -p|--Base-port) base_port="$2"; ONE_AGENT_OPTIONS+="--Base-port=$base_port " ;shift 2;;
      -O|--old-db) OLD_DB="$2"; shift 2;;
      -d|--Domain) domain="$2"; shift 2;;
      -M|--Mgmt-Interface-IP) mgmt_ip="$2"; ONE_AGENT_OPTIONS+="--Mgmt-Interface-IP=$mgmt_ip "; IS_USER_SET_IP=1; shift 2;;
      -E|--Ext-Interface-IP) ext_ip="$2"; ONE_AGENT_OPTIONS+="--Ext-Interface-IP=$ext_ip "; IS_USER_SET_IP=1; shift 2;;
      -i|--uninstall) uninstall=1; shift;;
      --) shift; break;;
      *) echo "Error: Invalid command-line argument: $1, specify correct argument and re-run the script"; exit ;;
    esac
  done
}

encode_one_agent_options (){
  ENCODED_STRING=$(echo -n $ONE_AGENT_OPTIONS | base64)
  ENCODED_STRING=$(echo -n "$ENCODED_STRING" | tr -d '[:space:]') #why this requerd
}

verifySignature(){
  JSON_FILE="/home/cavisson/${controller_name}/sys/controllerConfig.json"
  if [ "$licence_path" == "cav_licence.json" ]; then	
     cat $licence_path > .serv_inst_json
  else
    licence_json_sign_b64=$(cat $licence_path | sed -n '/BEGIN SIGN B64/,/END SIGN B64/p' | sed '1d;$d')
    licence_json_b64=$(cat $licence_path | sed -n '/BEGIN B64/,/END B64/p' | sed '1d;$d')
    
    #TODO : change file location 
    echo "$licence_json_sign_b64" > .sign_b64
    echo "$licence_json_b64" > .b64
    echo "$PUBLIC_KEY" > .key
  
    openssl base64 -d -in .sign_b64 -out .out_licence
    if [ $? != 0 ]; then
      echo "openssl base64 -d -in .sign_b64 -out .out_licence Command faild"
      exit 1
    fi
  
    openssl dgst -sha256 -verify .key -signature .out_licence .b64 1>/dev/null 2>&1
    if [ $? != 0 ]; then
      echo "Licence validation faild. Kindly contact cavisson cutomer support"
      exit 1
    fi
  
    echo "Licence verification done"
    
    #Decode JSON
    openssl base64 -d -in .b64 -out .serv_inst_json
  fi
  
  SERVER_INSTALLER_JSON=`cat .serv_inst_json`
  licenceForDays=`grep "licenceForDays" .serv_inst_json | grep -o '[0-9]*'` 
  liteImage=`grep "lite-image" .serv_inst_json | grep -o '[0-9]*'` 
  cavissonkernel=`grep "cavisson-kernel" .serv_inst_json | grep -o '[0-9]*'`
  enableoshardning=`grep "enable-os-hardning" .serv_inst_json | grep -o '[0-9]*'` 
   
  # Extract the "lite-image-SubFeature" array value from the JSON
  sub_features=$(cat .serv_inst_json | sed -n 's/.*"lite-image-SubFeature": \[\(.*\)\]/\1/p')
 
  # Remove the square brackets and double quotes from the extracted value
  sub_features=${sub_features//\"/}
  sub_features=${sub_features//[/}
  sub_features=${sub_features//]/}
 
  # Create an array from the extracted values
  IFS=', ' read -ra sub_feature_array <<< "$sub_features"
  
  rm -f .sign_b64 .b64 .key .out_licence .serv_inst_json
  
  product_suite=$(echo "$SERVER_INSTALLER_JSON" | grep -o '"productSuite": \[[^]]*\]' | sed 's/.*\[//;s/\].*//;s/,//g')
  
  #IFS=', ' read -r -a product_suite_array <<< "$product_suite"
  #ONE_AGENT_OPTIONS+="--Module=${product_suite_array[@]}"
 
  #Here we are updating purpose field in json.
  if [[ "$controller_name" != "Xwork" ]];then
    sed -i 's/"purpose":"[^"]*"/"purpose":"'"${product_name[$product_suite]}"'"/' "$JSON_FILE" 1>/dev/null 2>&1
  fi

  ONE_AGENT_OPTIONS+="--Module=${product_suite} "
  ONE_AGENT_OPTIONS+="--LicenceForDays=${licenceForDays} "
}

read_licence_file(){
  if [ -f "$licence_path" ]; then
    verifySignature
  else
    echo "Neither licence file is provided as argument nor present in current directory, specify licence file in argument"
    exit 1
  fi
}

copy_licence(){
  licence_dir="/home/cavisson/.licence"
  if [ -f "$licence_path" ]; then
    mkdir $licence_dir 1>/dev/null 2>&1
    cp $licence_path /home/cavisson/.licence
  fi 
}

Get_OS_release()
{
  if [[ -f /etc/lsb-release ]] ;then
    DISTRO=`cat /etc/lsb-release |grep -w DISTRIB_ID|cut -d '=' -f2`
    RELEASE=`cat /etc/lsb-release |sed -n '/DISTRIB_RELEASE=/ s/[^0-9]//g p'`
    if [ "X$DISTRO" == "XUbuntu" -a "X$RELEASE" == "X2004" ] || [ "X$DISTRO" == "XUbuntu" -a "X$RELEASE" == "X1604" ];then
      stat="1"
    fi
  elif [[ -f /etc/redhat-release ]] ;then
    if grep "Red Hat" /etc/redhat-release >/dev/null 2>&1 || grep "CentOS" /etc/redhat-release >/dev/null 2>&1; then
      RELEASE=`cat /etc/redhat-release |sed -n 's/[^0-9]//g p'|cut -c 1-2`
      if [ $RELEASE -eq 79 -o $RELEASE -eq 77 ];then
        stat="0"
      else
        DISTRO=`cat /etc/redhat-release`
        echo "Cavisson Installer is not supported for OS $DISTRO."
      exit 0
      fi
    fi
  fi
}

main(){

  #OS_TYPE=`cat /etc/os-release | head -n 1| cut -d '"' -f2`
  Get_OS_release
  if [ $stat -eq 0 ];then
    connectivity
  fi
  #JSON is passed in case of docker, as openssl is not present to decrypt licence file, in other case cav_licence will be present
  if [ -f cav_licence.json ]; then
    licence_path="cav_licence.json"
  else
    licence_path="cav_licence"
  fi

  ParseCommandLineArguments "$@"
  #Checking if cavbin file is passed as argument or not and also only one Cavbin should present in path before starting the installtion
  if [ -z "$server_package" ]; then
    cavcount=`ls Cav.*.bin 2>/dev/null | wc -l`
      if [ "$cavcount" -gt "1" ]; then
        echo "There are more Cavbin files .Please use only one Cavbin"
        exit 1
      fi
    fi

  if [ ! -z $controller_name ];then
    USER=$(whoami)
    if [ $USER != "cavisson" ];then
      echo "Cavisson privileges are required to run this script. Login with cavisson and re-run the script."
      exit 1
    fi
  else
    controller_name="work"
    if ! rootPrivilages; then
      echo "Root privileges are required to run this script. Login with root and re-run the script."
      exit 1
    fi
  fi

  if [ $IS_USER_SET_IP == 0 ]; then
    get_ip 
  fi
   
  read_licence_file
  #TODO : from here only single node will work need to support multi node
  ONE_AGENT_OPTIONS+="--Single-Node "
  #TODO : Due to Vulnerabilities issue in mongo 4.4.0 we are upgrading mongo 6.0.7.For this version we need avx flag support,So we check Avx is present or not. 
  #check_preinstallation_process
  
  check_inside_docker_container_or_not
  if [ "X$controller_name" != "Xwork" ];then
    INSTALLATION_PATH="/home/cavisson/installer/$controller_name"
    createConfigFileAndWirteConfig 
    echo "Going to create New Controller $controller_name"
    ONE_AGENT_OPTIONS+="--Configure "
    encode_one_agent_options
    change_dir 
    bash $INSTALLATION_PATH/CavissonServerInstaller.sh $ENCODED_STRING
    status=$?
    echo "New Controller Creation Done"
    exit $status
  else
    create_cavisson_user
    INSTALLATION_PATH="/home/cavisson/installer/work"
    detect_cavbin_and_installed
    sudo chown cavisson:cavisson /home/cavisson/installer
  fi

  if [ $status == 0 ]; then
   copy_licence
   if [ $liteImage == 0 ]; then 
      echo "In order to finish the installation, a system reboot is necessary. Reboot will start in 1min"
      sleep 60
      if [[ "X$controller_name" == "Xwork" ]];then
        reboot
      fi
    else
      #As in docker the shell nsi_on_upgrade_and_reboot is not running for setting the value of  cat /proc/sys/fs/suid_dumpable to 1 so we running the shell here to set the value
      bash /home/cavisson/work/bin/nsi_on_upgrade_and_reboot
      #for lite image we dont want enable query plan for postgrase by defult so reverting it here
      sed -i 's/auto_explain.log_min_duration/#auto_explain.log_min_duration/g' $POSTGRESQLCONF 
      sed -i 's/auto_explain.log_format/#auto_explain.log_format/g' $POSTGRESQLCONF 
      sed -i 's/auto_explain.log_nested_statements/#auto_explain.log_nested_statements/g' $POSTGRESQLCONF 
    fi
    su cavisson -c "bash /home/cavisson/work/bin/cav_post_install_cleanup.sh"
    bash /home/cavisson/work/bin/cav_post_install_cleanup.sh   
  fi
}

main "$@"

