#!/bin/sh
#

# Tehama DIA -  Linux Agent Installer
# v 1.1 - 2024-05-08

 
TARURL=https://downloads.sip.controlup.com/avaceesipagent-linux.tar

if ! [ $(id -u) = 0 ]; then
   echo "This script must be run with root privilege"
   exit 1
fi

if [ $# -eq 0 ]; then
  echo
  echo "Syntax:"
  echo "   sip-install.sh <tenant> <registration code> [proxy address]"
  echo
  exit 1
fi

# download the agent and make sure it was successful
#
echo "Downloading the latest Linux x64 agent from ${TARURL}"
rm -f /tmp/sipagent.tar
wget -q -O "/tmp/sipagent.tar" ${TARURL} >/dev/null 2>&1 || curl -s -o "/tmp/sipagent.tar" ${TARURL} >/dev/null 2>&1

if [ -f \"/tmp/sipagent.tar\" ]; then
  echo "Failed to download agent binary - do you have curl or wget installed? Do you have an Internet connection?"
  exit 1
fi

rm -rf /tmp/sipagentextract
mkdir /tmp/sipagentextract
tar -xf /tmp/sipagent.tar -C /tmp/sipagentextract


# stop and remove existing service
#
echo "Removing existing agent if present"
service avaceesip stop
pkill sipagent
rm -f /usr/local/avacee/sipagent
rm -rf /var/log/avacee
mkdir -p /usr/local/avacee
cp /tmp/sipagentextract/sipagent /usr/local/avacee/sipagent
chmod +x /usr/local/avacee/sipagent
cp /tmp/sipagentextract/RCNotifications /usr/local/avacee/.
chmod +x /usr/local/avacee/RCNotifications

# register agent settings
#
echo "Registering agent settings"
if [ -z "$3" ]; then
    /usr/local/avacee/sipagent tenant=$1 devregcode=$2 store_settings_only=1 >/dev/null 2>&1
elif [ -z "$4" ]; then
    /usr/local/avacee/sipagent tenant=$1 devregcode=$2 proxy=$3 store_settings_only=1 >/dev/null 2>&1
else
    /usr/local/avacee/sipagent tenant=$1 devregcode=$2 proxy=$3 proxy_test_ip=$4 store_settings_only=1 >/dev/null 2>&1  
fi

# create service file
#
echo "Creating service"
cat <<EOF > /etc/systemd/system/avaceesip.service
[Unit]
Description=ControlUp Edge DX Service
[Service]
ExecStart=/usr/local/avacee/sipagent
WorkingDirectory=/usr/local/avacee/
[Install]
WantedBy=multi-user.target
EOF

# register service
#
echo "Registering service"
systemctl daemon-reload
systemctl enable avaceesip
service avaceesip start
