#!/bin/sh
#

# Tehama DIA  Linux Agent Installer
#

AGENTURL=https://downloads.dia.tehama.io/avaceesipagent-linux

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 $AGENTURL"
rm -f /tmp/sipagent
wget -q -O "/tmp/sipagent" $AGENTURL >/dev/null 2>&1 || curl -s -o "/tmp/sipagent" $AGENTURL >/dev/null 2>&1
if [ ! -f "/tmp/sipagent" ]; then
  echo "Failed to download agent binary - do you have curl or wget installed? Do you have an Internet connection?"
  exit 1
fi

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

# 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
else
  /usr/local/avacee/sipagent tenant=$1 devregcode=$2 proxy=$3 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
