#!/bin/bash

#
# Description : This is used to configure the Secure Gateway Server details on the Agent machine..
#
# Usage       : configureDcAgentServerCommunication_linux.sh [sgs_fqdn/sgs_ip]
#
# Returns     : (Nothing)
#

if [ $# -eq 1 ]
  then
    # Set the provided argument as server_ip
    #
    server_ip=$1
  else
    # Number of arguments not equal to 1
    #
    echo "Usage : [sudo] ./configureDcAgentServerCommunication_linux.sh [sgs_fqdn/sgs_ip]"
    exit 2
fi

# Server Protocal is set as HTTPS
#
server_protocol="https"


# Ensure the Script is Run as Root.
#
if [ "$EUID" -ne 0 ]
  then
  echo "Failed to configure DC Agent - Server Communication! - Retry with \"Root Permission\""
  exit 1
fi


# Checking if DC Agent is installed
#
if [ -e /usr/bin/dcservice ]
  then
    echo "DC Agent Installed in this machine. Configuring Server Communication."
  else
    echo "DC Agent Not Installed in this machine. Exiting script."
    exit 1
fi


# Determine the agent installed directory
#
if [ -e /etc/desktopcentralagent/dcagentsettings.json ]
  then
  agent_install_directory=$(cat /etc/desktopcentralagent/dcagentsettings.json | grep "DIRECTORY_PATH" | cut -f 2 -d ":" | cut -f 2 -d "\"" | rev | cut -f 1 -d "/" --complement | rev)
fi

if [[ ! -e $agent_install_directory ]]
  then
  if [ -e /usr/bin/dcservice ]
    then
    agent_install_directory=$(ls -l /usr/bin/ | grep dcservice | cut -d ">" -f 2 | rev | tail -c +35 | rev | cut -d " " -f 2)
  fi
fi

if [[ ! -e $agent_install_directory ]]
  then
  agent_install_directory="/usr/local"	# Default Agent Install Directory
fi

server_info_file="$agent_install_directory/desktopcentralagent/conf/ServerInfo.json"
meta_data_file="$agent_install_directory/desktopcentralagent/data/meta-data.json"

dcservice -p

echo "Server File           : $server_info_file"


echo "New Server IP         : $server_ip"
sed -i "s/\"serversecipaddress\":.*/\"serversecipaddress\": \"${server_ip}\",/" $server_info_file


echo "New Server Protocol   : $server_protocol"
sed -i "s/\"serverprotocol\":.*/\"serverprotocol\": \"${server_protocol}\",/" $server_info_file

sed -i "s/\"serverlastaccessname\":.*/\"serverlastaccessname\": \"${server_ip}\",/" $server_info_file

echo "$meta_data_file"
rm -f $meta_data_file
echo "Restarting DC Agent"

systemctl restart dcservice.service

if [ $? -ne 0 ]
then
  dcservice -p
  sleep 2
  dcservice -t &
fi

if [ $? -eq 0 ]
  then
    echo "Successfuly configured DC Agent Server Communication. And, agent restarted"
  else
    echo "Failed to restart the Agent."
fi
