#!/bin/bash

#
# Description : This is used to check the DC server ip is reachable or not. .
#
# Usage       : ./WFHcheck.sh 0.0.0.0 
#
# OS : Linux
#
# Returns     : True / False

# Ensure the Script is Run as Root.
#
if [ "$EUID" -ne 0 ]
  then
  echo "Retry with \"Root Permission\""
  exit 1
fi

# Usage validation, ie, arguments
#
if [ $# -ne 1 ]
  then
    # Number of arguments not equal to 8
    #
    echo "Usage : [sudo] ./WFHcheck.sh [server_ip] "
    exit -1
fi

# Checking if DC Agent is installed
#
if [ ! -e /usr/bin/dcservice ]
  then
    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"

ip=$1

serveripaddress=$(cat $server_info_file | grep "\"serverflatname\"" | cut -f 2 -d ":" | cut -f 2 -d "\"" | rev | cut -f 2 -d "\"" | rev)
serverflatname=$(cat $server_info_file | grep "\"serverflatname\"" | cut -f 2 -d ":" | cut -f 2 -d "\"" | rev | cut -f 2 -d "\"" | rev)
servername=$(cat $server_info_file | grep "\"servername\"" | cut -f 2 -d ":" | cut -f 2 -d "\"" | rev | cut -f 2 -d "\"" | rev)
serversecipaddress=$(cat $server_info_file | grep "\"serversecipaddress\"" | cut -f 2 -d ":" | cut -f 2 -d "\"" | rev | cut -f 2 -d "\"" | rev)

value="False"
value1="False"

ping -w 5 $ip 2>&1 >/dev/null
if [ $? -eq 0 ]
  then
   value="True"
fi 

if [[ "$ip" != "$serveripaddress" ]]; then
      ping -w 5 $serveripaddress 2>&1 >/dev/null
      if [ $? -eq 0 ]
        then
         value1="True"
      fi 
fi

if [[ "$ip" != "$serverflatname" ]]; then
      ping -w 5 $serverflatname 2>&1 >/dev/null
      if [ $? -eq 0 ]
        then
         value1="True"
      fi 
fi

if [[ "$ip" != "$servername" ]]; then
      ping -w 5 $servername 2>&1 >/dev/null
      if [ $? -eq 0 ]
        then
         value1="True"
      fi 
fi

if [[ "$ip" != "$serversecipaddress" ]]; then
      ping -w 5 $serversecipaddress 2>&1 >/dev/null
      if [ $? -eq 0 ]
        then
         value1="True"
      fi 
fi

if [[ $value = "True" && $value1 = "False" ]]
then
	echo "WFH status: True"
else
	echo "WFH status: False"
fi

