#!/bin/bash

#
# Description : This is used to update the Server details in the SeverInfo.json file.
#               In order to ensure the communication between the Agent & the Server.
#
# Usage       : bash configureDcAgentServerCommunicationWithPort_linux.sh [fqdn_server_ip] [server_secure_port] 
#               [] have to be specified by the user
#
# Returns     : (Nothing)
#


server_ip=$1
server_secure_port=$2

product_settings_file=""

# 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 /etc/systemd/system/dcservice.service ] || [ -e /etc/init.d/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
    product_settings_file="/etc/desktopcentralagent/dcagentsettings.json"
elif [ -e /etc/uems_agent/uemsagentsettings.json ];then
    product_settings_file="/etc/uems_agent/uemsagentsettings.json"
fi

agent_install_directory=$(cat $product_settings_file | grep "DIRECTORY_PATH" | cut -f 2 -d ":" | cut -f 2 -d "\"")
echo "Agent installed directory: $agent_install_directory"

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

$agent_install_directory/bin/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 Port   : $server_secure_port"
sed -i "s/\"serversecureport\":.*/\"serversecureport\": \"${server_secure_port}\",/" $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"

if [ -e /etc/systemd/system/dcservice.service ]; then
    systemctl restart dcservice.service
elif [ -e /etc/init.d/dcservice ]; then
    service dcservice restart
fi

if [ $? -ne 0 ]
then
  $agent_install_directory/bin/dcservice -p
  sleep 2
  $agent_install_directory/bin/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