#!/bin/bash
#
# Nyquist C4000 11.0.0.652 Patch 1 update script
#
# (C) Copyright 2026, Bogen Communications LLC. All rights reserved.
#
NYQUIST_RELEASE=11.0.0
NYQUIST_VERSION=$NYQUIST_RELEASE.652
BOGEN_ROOT=/opt/bogen
UPDATE_LOG=$BOGEN_ROOT/nyquist/c4000-$NYQUIST_VERSION-patch1-log-$(date +%F-%R).txt

unset LICINFO_DEBUG
export RLM_ACT_TIMEOUT=300
export PATH=/usr/bin:/bin:/sbin/:/usr/sbin:/usr/local/bin

#
# The following { encapsulates output to log file (see last line of script)
#
{

rm -f /usr/lib/sysctl.d/protect-links.conf
echo "fs.protected_regular = 0" > /etc/sysctl.d/99-protect-links.conf
sysctl -w fs.protected_regular=0

# Exit if patch is not for the installed Nyquist release
read -r -d : VERNUM < /etc/asterisk/version
if [ "$VERNUM" != "$NYQUIST_VERSION" ]; then
   if [ "$VERNUM" != "$NYQUIST_RELEASE" ]; then
      exit 1
   fi
fi

# Update SipTrunkController.php
cp $BOGEN_ROOT/SipTrunkController.php /var/www/html/laravel/app/Http/Controllers/SipTrunkController.php

# Update form_create.blade.php
cp $BOGEN_ROOT/form_create.blade.php /var/www/html/laravel/resources/views/sip_trunks/form_create.blade.php


# Make sure trunk_keys folder exists
mkdir -p --mode=770 /etc/asterisk/trunk_keys
chown root:www-data /etc/asterisk/trunk_keys

# Update update-siptrunks-conf
cp $BOGEN_ROOT/update-siptrunks-conf /usr/local/bin/update-siptrunks-conf
chmod 550 /usr/local/bin/update-siptrunks-conf
chown root:www-data /usr/local/bin/update-siptrunks-conf

# Update sip trunks
sudo /usr/local/bin/update-siptrunks-conf update

# Copy release notes
cp $BOGEN_ROOT/Release-Notes-11.0.0.652-patch1.txt /srv/tftp
chown www-data:www-data /srv/tftp/Release-Notes-11.0.0.652-patch1.txt
chmod 664 /srv/tftp/Release-Notes-11.0.0.652-patch1.txt

VERSTR=$(< /etc/asterisk/version)
if [ -z "$VERSTR" ]; then
   exit
fi

PATCHSTR=$(grep Patch /etc/asterisk/version)
if [ -z "$PATCHSTR" ]; then
	echo "$VERSTR - Patch numbers applied: 1" > /etc/asterisk/version
else
	if [ "$VERSTR" = "$NYQUIST_VERSION - Patch numbers applied: 1" ]; then
		touch /etc/asterisk/version
	fi
fi

echo "Update RLM info"

trycount=1
while [ $trycount -le 5 ]
do
   ARET=$(/usr/local/bin/licinfo -U 2>/dev/null)
   if [ "$ARET" = "0" ]; then
      ((trycount++))
      sleep 15
      /bin/ping -c 1 -W 60 hostedactivation.com > /dev/null 2>&1
   else
		trycount=6
	fi
done

} > $UPDATE_LOG 2>&1

exit 0
