#!/bin/sh
#

#  Tehama DIA -  Linux Agent Reinstaller
#  v1.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] [proxy test IP]"
  echo
  exit 1
fi

# Stop and unregister existing service, remove all associated files
echo "Removing existing agent if present"
service avaceesip stop
systemctl disable avaceesip
systemctl daemon-reload
pkill sipagent
rm -f /usr/local/avacee/sipagent
rm -f /usr/local/avacee/RCNotifications
rm -rf /usr/local/avacee/sip_agent/cachefiles
rm -rf /var/log/avacee
rm -rf /usr/local/sipagent
rm -rf /tmp/sipagentextract
rm -rvf /var/log/sipagent
rm -rvf /usr/local/avacee
mkdir -p /usr/local/avacee

# Download the agent and verify the download 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

# Extract the downloaded tar
rm -rf /tmp/sipagentextract
mkdir /tmp/sipagentextract
tar -xf /tmp/sipagent.tar -C /tmp/sipagentextract
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 and register the service
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

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

