#!/bin/bash
#
# Nyquist Troubleshooter (C4000 11.0.0 / E7000 11.0.0) for Debian 12
#
# (C) Copyright 2019-2026, Bogen Communications LLC. All rights reserved.
#
# Usage: nqts [options...]
#
# [options]:
#
# -a - Check activation readiness (before activation)
# -A - Display amplifier config file (select from list)
# -d - Dial plan CLI debug
# -e - Check everything
# -E [<extension>] - Display station configuration file from list or for specified <extension>
# -f - Fix issues
# -G - Display ASB config file (select from list)
# -i - Check installation (post install)
# -m - Check and fix MySQL tables
# -n - Automatically answer 'no' to all prompts
# -o - Check operation (running system)
# -s - Force System Controller processing
# -S - Get SMART temp errors from syslog
# -w - Filter for www-data access
#
#set -x
#
function checksbits() {
   RETURNVAL=0
   for i in /usr/local/bin/run_dahdi_genconf /usr/local/bin/run_system_setup /usr/local/bin/run_server_cmd /usr/local/bin/run_sysupdate /usr/local/bin/run_system_backup /usr/local/bin/run_update_outsideline_status /usr/local/bin/getlog /usr/local/bin/licinfo /usr/local/bin/run_ifreset_check
   do
      if [ ! -u $i ]; then
         if [ $RETURNVAL = 0 ]; then
            echo ""
         fi
         echo "$i does not have set-user-ID bit set, fixing!"
         chmod +s "$i"
         RETURNVAL=1
      fi
      if [ ! -g $i ]; then
         if [ $RETURNVAL = 0 ]; then
            echo ""
         fi
         echo "$i does not have set-group-ID bit set, fixing!"
         chmod +s "$i"
         RETURNVAL=1
      fi
   done
   return $RETURNVAL
}

PRODUCT=nyquist
ASTERISK_VERSION=22.4.1
BOGEN_ROOT=/opt/bogen
VERSION_SRC=$BOGEN_ROOT/version
VERSION_DST=/etc/asterisk/version
NYQUIST_CORE=$BOGEN_ROOT/$PRODUCT
NYQUIST_SCRIPTS=$NYQUIST_CORE/scripts
DATABASE=$BOGEN_ROOT/$PRODUCT/database
DATABASE_SQL=$DATABASE/sql
DATABASE_CORE=$DATABASE_SQL/core
DATABASE_PRODUCT=$DATABASE_SQL/$PRODUCT
ASTERISK_DIR=$NYQUIST_CORE/asterisk-$ASTERISK_VERSION

CHECK_ACTIVATION=0
CHECK_INSTALL=0
CHECK_OPERATION=0
CHECK_FIX_MYSQL=0
DISPLAY_CONFIG=
DISPLAY_AMP_CFG=0
DISPLAY_GW_CFG=0
FIX_ISSUES=0
NYQ_SYSCTL=0
REPLY_NO=0
RESET_PASSWORD=0
WWW_ACCESS=0
DISPLAY_LICINFO_ERRORS=0
SHOW_TLS=0
SMART_TEMP_LOG=0
VERBOSE=0

#
# Get Automatic Failure configuration data
#
CLUSTER_SHARED_IP=
if [ -e /var/opt/nyquist/ha/shared_ip ]; then
	CLUSTER_SHARED_IP=$(</var/opt/nyquist/ha/shared_ip)
fi

export PATH=/usr/bin:/bin:/sbin/:/usr/sbin:/usr/local/bin

read -d . DEBIAN_VERSION < /etc/debian_version

DEB_VER=""
if [ "$DEBIAN_VERSION" = "10" ] || [ "$DEBIAN_VERSION" = "11" ] || [ "$DEBIAN_VERSION" = "12" ]; then
   DEB_VER="_deb10"
fi

while getopts "aAdEefGilmnorsStvw?" opt; do
   case "$opt" in
      a) CHECK_ACTIVATION=1;;
      A) DISPLAY_AMP_CFG=1;;
      d) /usr/sbin/asterisk -rvvvv
	 exit;;
      e) CHECK_ACTIVATION=1;
         CHECK_INSTALL=1;
         CHECK_OPERATION=1;;
      E)
	 # check for optional <extension>
         nextopt=${!OPTIND}
	 if [[ -n $nextopt && $nextopt != -* ]] ; then
            OPTIND=$((OPTIND + 1))
	    DISPLAY_CONFIG=$nextopt
	 else
            DISPLAY_CONFIG=List
	 fi
	 ;;
      f) FIX_ISSUES=1;;
      G) DISPLAY_GW_CFG=1;;
      i) CHECK_INSTALL=1;;
      l) DISPLAY_LICINFO_ERRORS=1;;
      m) CHECK_FIX_MYSQL=1;;
      n) REPLY_NO=1;;
      o) CHECK_OPERATION=1;;
      r) RESET_PASSWORD=1;;
      s) NYQ_SYSCTL=1;;
      S) SMART_TEMP_LOG=1;;
      t) SHOW_TLS=1;;
      v) VERBOSE=1;;
      w) WWW_ACCESS=1;;
      ?) cat <<EOF
Options:
-a - Check activation readiness (before activation)
-A - Display amplifier config file (select from list)
-d - Start Asterisk CLI debug session
-e - Check everything
-E [<extension>] - Display Station configuration file from list or for specified <extension>
-f - Fix issues (includes change password to default)
-G - Display ASB config file (select from list)
-i - Check installation (post install)
-l - Display licinfo error codes and descriptions.
-m - Check and fix MySQL database tables
-n - Automatically answer 'no' to all prompts
-o - Check operation (running system)
-r - Allow Admin Web-UI password reset by adding new web admin station via user wizard
-s - Force System Controller processing
-S - Get SMART Temp errors from syslog, store in /tmp/smartd.log
-t - Show TLS setup
-v - Enable verbose output
-w - Filter for www-data access
EOF
exit;;
   esac
done

if [ $DISPLAY_LICINFO_ERRORS = 1 ]; then
   cat<<EOF
RLM_EH_READ_NOLICENSE     -102   Can't read license data
RLM_EH_NET_INIT           -103   Network (msg_init()) error
RLM_EH_NET_WERR           -104   Error writing to network
RLM_EH_NET_RERR           -105   Error reading from network (try: export RLM_ACT_TIMEOUT=120)
RLM_EH_CONN_REFUSED       -111   Connection refused at server
RLM_EH_WRITE_LF           -120   Can't write new license file
RLM_EH_ACT_BADLICKEY      -135   Bad license key in activation binary
RLM_EH_CANT_GET_REHOST    -149   Cannot get rehost hostid
RLM_EH_CANT_DEL_REHOST    -150   Cannot delete rehost hostid
RLM_EH_CANT_CREATE_REHOST -151   Cannot create rehostable hostid
RLM_EH_REHOST_TOP_DIR_EXISTS -152 Rehostable top dir exists
RLM_EH_REHOST_EXISTS      -153   Rehostable hostid exists
RLM_EH_NO_FULFILLMENTS    -154   No fulfillments to revoke
RLM_ACT_KEY_USED          -1005  Activation key already used
RLM_ACT_BAD_HOSTID        -1006  Missing hostid
RLM_ACT_BAD_HOSTID_TYPE   -1007  Invalid hostid type
RLM_ACT_NO_KEY_MATCH      -1021  No matching activation key in database
EOF
   exit
fi

if [ $SMART_TEMP_LOG = 1 ]; then
   LOGFILE="/tmp/smartd.log"
   find /var/log -maxdepth 1 -type f -name 'syslog*' -mtime +365 -delete
   /bin/sed -n '/smartd/p' /var/log/syslog > $LOGFILE

   for i in $(find /var/log -type f -regex '.*/syslog-[0-9]+$')
   do
      /bin/sed -n '/smartd/p' $i >> $LOGFILE
   done

   for i in $(find /var/log -type f -name 'syslog*.gz')
   do
      zcat $i | /bin/sed -n '/smartd/p' - >> $LOGFILE
   done

   chown www-data:www-data $LOGFILE
   chmod 0660 $LOGFILE
   exit
fi

if [ $SHOW_TLS = 1 ]; then
	asterisk -rx "pjsip show transport transport-tls"
	echo "Supported Ciphers:"
	if [ $VERBOSE = 1 ]; then
	   openssl ciphers -s -V
	else
	   openssl ciphers -s -v
	fi
	echo "PJSIP Supported Ciphers:"
	asterisk -rx "pjsip list ciphers"
	if [ $VERBOSE = 1 ]; then
		echo "Enpoints using TLS:"
		asterisk -rx "pjsip show contacts" |grep -i tls
	fi
	exit
fi

if [ "$DISPLAY_CONFIG" != "" ]; then
   if [ "$DISPLAY_CONFIG" = "List" ]; then
      export MYSQL_PWD=A1B7N0Q0GEN00Z9
      /usr/bin/mysql --user="asterisk" asterisk -e "select extension,mac_address,name from station where extension != 0"
      read -r -p "Enter extension: "
      if  [ "$REPLY" != "" ]; then
         DEV_MAC=$(nysql -q station.mac_address -w extension="$REPLY" 2>/dev/null)
         if [ "$DEV_MAC" = "" ]; then
            echo "Can't find MAC address for extension $REPLY"
            exit
         fi
         cat /srv/tftp/"$DEV_MAC.cfg"
      fi
      exit
   fi

   STATION_MAC=$(nysql -q station.mac_address -w extension="$DISPLAY_CONFIG" 2>/dev/null)
   if [ "$STATION_MAC" = "" ]; then
      echo "Station extension $DISPLAY_CONFIG does not exist"
      exit
   fi
   cat /srv/tftp/"$STATION_MAC.cfg"
   exit
fi

if [ $DISPLAY_GW_CFG = 1 ]; then
   /usr/bin/mysql --user="asterisk" --password="A1B7N0Q0GEN00Z9" asterisk -e "select id,mac_address,name from gateway"
   read -r -p "Enter id: "
   if  [ "$REPLY" != "" ]; then
      GW_MAC=$(nysql -q gateway.mac_address -w id="$REPLY" 2>/dev/null)
      if [ "$GW_MAC" = "" ]; then
         echo "Can't find MAC address for id $REPLY"
	 exit
      fi
      cat /srv/tftp/"$GW_MAC.cfg"
   fi
   exit
fi

if [ $DISPLAY_AMP_CFG = 1 ]; then
   /usr/bin/mysql --user="asterisk" --password="A1B7N0Q0GEN00Z9" asterisk -e "select id,mac_address,name from amplifier"
   read -r -p "Enter id: "
   if  [ "$REPLY" != "" ]; then
      AMP_MAC=$(nysql -q amplifier.mac_address -w id="$REPLY" 2>/dev/null)
      if [ "$AMP_MAC" = "" ]; then
         echo "Can't find MAC address for id $REPLY"
	 exit
      fi
      cat /srv/tftp/"$AMP_MAC.cfg"
   fi
   exit
fi

if [ $CHECK_FIX_MYSQL = 1 ]; then
   export MYSQL_PWD=BogenNyq1;mysqlcheck --user=root --all-databases --extended --auto-repair
   systemctl enable mariadb
   exit
fi


if [ $RESET_PASSWORD = 1 ]; then
   /usr/local/bin/nysql << EOF
UPDATE setup SET visited='0' WHERE name='station';
UPDATE setup SET visited='0' WHERE name='user';
EOF
   echo "A new Web Admin station can now be added via user wizard"
   exit
fi

if [ -e /opt/bogen/activate_nyquist_e7000 ]; then
   NYQ_SYSCTL=1
fi

licinfo -p > /dev/null 2>&1

if [ $? -gt 1 ]; then
   echo -e "\nlicinfo has an issue with current keys, one or more keys may be invalid, see below:\n"
   if [ -e /etc/asterisk/nyquist.lic ]; then
      cat /etc/asterisk/nyquist.lic
   fi
   cat /etc/asterisk/licenses/*.akey 2>/dev/null
   if [ $REPLY_NO = 1 ]; then
      exit
   fi
   read -p "continue? (y/n): "
   if [ "$REPLY" != "y" ]; then
      exit
   fi
fi

NQPROD="$(licinfo -p)"
case "$NQPROD" in
   nq-c4000) NQPROD="C4000";;
   nq-e7000) NQPROD="E7000";;
          *) NQPROD="Unknown Nyquist Product: ";;
esac

echo "$NQPROD $(/usr/local/bin/nyquist-version)"

################################################################################
# CHECK ACTIVATION
################################################################################
if [ $CHECK_ACTIVATION = 1 ];
then
echo "Checking Activation:"

if [ -e /tmp/activation_error.txt ]; then
   echo -e "\nActivation Error:\n$(cat /tmp/activation_error.txt)\n"
fi

if [ -e /opt/bogen/customerinfo.txt ]; then
   if [ "$(find /opt/bogen/customerinfo.txt -group www-data)" = "" ]; then
      chown root:www-data /opt/bogen/customerinfo.txt
      echo "customerinfo.txt group was wrong: fixed"
   fi
   if [ "$(find /opt/bogen/customerinfo.txt -perm -0660)" = "" ]; then
      chmod 0660 /opt/bogen/customerinfo.txt
      echo "customerinfo.txt permission was wrong: fixed"
   fi
fi

if [ -e /home/bogen/serial_number ]; then
   echo "Serial Number: $(cat /home/bogen/serial_number)"
   NYQ_SYSCTL=1
else
   if [ $NYQ_SYSCTL = 1 ]; then
      echo "Missing Serial Number file (/home/bogen/serial_number)"
   fi
fi

if [ -e /home/bogen/nyquist.akey ]; then
   NYQ_SYSCTL=1
   NQPROD="$(licinfo -p)"
   if [ "$NQPROD" = "nq-e7000" ]; then
	   NLK_USED="(Not used)"
   else
	   NLK_USED=""
   fi
   echo "Node Lock Key: $(cat /home/bogen/nyquist.akey) $NLK_USED"
else
   if [ $NYQ_SYSCTL = 1 ]; then
      echo "Missing Node Lock Key file (/home/bogen/nyquist.akey)"
   fi
fi

echo -n "checking tables..."
/usr/local/bin/nysql <<EOF |grep -v "Tables_in_asterisk" > /tmp/nqtables.txt
show tables
EOF

NQTABLES="$(awk 'END{print NR}' /tmp/nqtables.txt)"

if [ $NQTABLES -lt 187 ]; then
   echo "Possibly missing tables, current count: $NQTABLES"
   if [ $REPLY_NO = 0 ]; then
      read -p "View Table list (y/n)? "
      if [ "$REPLY" = "y" ]; then
         more /tmp/nqtables.txt
      fi
   fi
fi

echo "done"

echo -n "checking license keys..."
HAVE_LICENSE_KEY=0

if [ ! -e /etc/asterisk/licenses/nyquist.akey ]; then
   if [ "$NQPROD" = "C4000" ]; then
      echo "No C4000 license key"
   fi
else
   HAVE_LICENSE_KEY=1
fi

if [ $HAVE_LICENSE_KEY = 0 ]; then
   if [ ! -e /etc/asterisk/nyquist.akey ]; then
      echo "No E7000 license key"
   else
      HAVE_LICENSE_KEY=1
   fi
fi

if [ "$(licinfo -m)" != "VALID" ]; then
   echo "No valid license"
   licinfo -l
fi

echo "done"

if [ $HAVE_LICENSE_KEY = 1 ]; then
   echo "License keys ($(licinfo -p)):"
   licinfo -a
fi

echo -n "Checking set-user-ID bits..."
checksbits
echo "done"

echo "Setup Status:"
/usr/local/bin/nysql << EOF
select name, visited FROM setup
EOF

if [ $CHECK_INSTALL = 0 ]; then
   if [ $CHECK_OPERATION = 0 ]; then
      if [ $REPLY_NO = 0 ]; then
         read -p "Check Site Access (y/n)? "
         if [ "$REPLY" = "y" ]; then
            /usr/local/bin/check-site-access
         fi
      fi
   fi
fi

if [ ! -z "$(ls /opt/bogen/nyquist/Activation-log-* 2>/dev/null)" ]; then
      if [ $REPLY_NO = 0 ]; then
         read -p "View Activation Log (y/n)? "
         if [ "$REPLY" = "y" ]; then
            more /opt/bogen/nyquist/Activation-log-*
         fi
      fi
fi

fi # END OF CHECK_ACTIVATION

################################################################################
# CHECK INSTALLATION
################################################################################

if [ $CHECK_INSTALL = 1 ];
then
   echo "Checking Installation:"

if [ -e /opt/bogen/nyquist/scripts/check-packages$DEB_VER ]; then
   /opt/bogen/nyquist/scripts/check-packages$DEB_VER
fi

echo -n "Checking Asterisk version..."
CHECK_VER="$(strings /usr/sbin/asterisk |grep -c asterisk-22.4.1/include/asterisk)"
if [ "$CHECK_VER" = "0" ]; then
   echo ""
   echo -n "   Asterisk version not correct, expected 22.4.1, got "
   strings /usr/sbin/asterisk |grep asterisk-22.4.1/include/asterisk|head -1|awk -F- '{print $2}' -|awk -F/ '{print $1}' -
else
   echo "done"
fi

echo -n "Checking set-user-ID bits..."
checksbits
echo "done"

echo -n "Checking sudoers..."
CHECKSUDO="$(grep "root\sALL=(ALL:ALL) ALL" /etc/sudoers)"
if [ "$CHECKSUDO" = "" ]; then
   echo -e "\n/etc/sudoers does not include correct root entry"
   CHECKSUDO="$(grep "^root\s" /etc/sudoers)"
   if [ "$CHECKSUDO" != "" ]; then
      echo "Found: $CHECKSUDO"
   fi
   if [ $REPLY_NO = 0 ]; then
      read -p "Add entry now (y/n)? "
      if [ "$REPLY" = "y" ]; then
         sed -i "/\broot\b/d" /etc/sudoers
         echo -e "root\tALL=(ALL:ALL) ALL" >> /etc/sudoers
      fi
   fi
fi

if [ "$CLUSTER_SHARED_IP" != "" ]; then
   if [ ! -e /etc/sudoers.d/nyquist-ha ]; then
	   echo "Missing /etc/sudoers.d/nyquist-ha for hacluster user"
   fi
fi

echo "done"

echo -n "Checking fstab entries..."
CHECK_MSG="$(grep /srv/tftp/msg /etc/fstab)"
if [ "$CHECK_MSG" = "" ]; then
   echo -e "\nMissing /srv/tftp/msg in /etc/fstab!"
else
   echo "done"
fi

echo -n "Checking MySQL configuration..."
if [ "$DEBIAN_VERSION" = "10" ] || [ "$DEBIAN_VERSION" = "11" ] || [ "$DEBIAN_VERSION" = "12" ]; then
   CHECK_MYSQL="$(grep event_scheduler=ON /etc/mysql/mariadb.conf.d/50-server.cnf)"
else
   CHECK_MYSQL="$(grep event_scheduler=ON /etc/mysql/my.cnf)"
fi

if [ "$CHECK_MYSQL" = "" ]; then
   echo -e "\nMissing event_scheduler entry"
   if [ $REPLY_NO = 0 ]; then
      read -p "Add entry now (y/n)? "
      if [ "$REPLY" = "y" ]; then
         if [ "$DEBIAN_VERSION" = "10" ] || [ "$DEBIAN_VERSION" = "11" ] || [ "$DEBIAN_VERSION" = "12" ]; then
	    sed -i 's/^\[mysqld\]$/[mysqld]\nevent_scheduler=ON/' /etc/mysql/mariadb.conf.d/50-server.cnf
         else
            sed -i 's/^\[mysqld\]$/[mysqld]\nevent_scheduler=ON/' /etc/mysql/my.cnf
         fi
      fi
   fi
   echo ""
else
   echo "done"
fi

echo -n "Checking dpkg status..."
dpkg -C
echo "done"

if [ $CHECK_OPERATION = 0 ]; then
   if [ $REPLY_NO = 0 ]; then
      read -p "Check Site Access (y/n)? "
      if [ "$REPLY" = "y" ]; then
         /usr/local/bin/check-site-access
      fi
   fi
fi

if [ ! -z "$(ls /opt/bogen/nyquist/Install-log-* 2>/dev/null)" ]; then
   if [ $REPLY_NO = 0 ]; then
      read -p "View Installation Log (y/n)? "
      if [ "$REPLY" = "y" ]; then
         more /opt/bogen/nyquist/Install-log-*
      fi
   fi
fi

if [ ! -z "$(ls /opt/bogen/nyquist/Update-log-* 2>/dev/null)" ]; then
   if [ $REPLY_NO = 0 ]; then
      read -p "View Update Log (y/n)? "
      if [ "$REPLY" = "y" ]; then
         more /opt/bogen/nyquist/Update-log-*
      fi
   fi
fi

fi # END OF CHECK_INSTALLATION

################################################################################
# CHECK OPERATION
################################################################################
if [ $CHECK_OPERATION = 1 ];
then
   echo "Checking Operation:"

if [ $WWW_ACCESS = 0 ]; then

echo -n "Checking crontab entries..."

CRON_MISSING=0
NQSSU_MISSING=0

for i in nqssu add-mcast-route routine-trigger check-ast-log check-iax-connections cdr_prune schedule_events sync-ldap request-callback update-device-status
do
   if [ -z "$(crontab -l | grep $i)" ]; then
      if [ $CRON_MISSING = 0 ]; then
         CRON_MISSING=1
         echo ""
      fi
      echo "   missing: $i"
      if [ "$i" = "nqssu" ]; then
         NQSSU_MISSING=1;
      fi
   fi
done

for i in create-backup purge-recordings purge-backups
do
   if [ -z "$(crontab -l -u www-data | grep $i)" ]; then
      if [ $CRON_MISSING = 0 ]; then
         CRON_MISSING=1
         echo ""
      fi
      echo "   missing: $i"
   fi
done

if [ $CRON_MISSING = 0 ]; then
   echo "done"
fi

if [ $NQSSU_MISSING = 1 ]; then
   echo "* It's ok for nqssu to be missing if software update checking disabled"
fi

fi

echo -n "Checking swap configuration..."
SWAPSTAT=$(/sbin/swapon -s)
if [ "$SWAPSTAT" = "" ]; then
   echo '<p style="color:red;">WARNING: Swap not enabled, please enable swap!</p>'
fi
echo "done"

echo -n "Checking set-user-ID bits..."
checksbits
echo "done"

if [ $WWW_ACCESS = 0 ]; then

echo -n "Checking sudoers..."
CHECKSUDO="$(grep "root\sALL=(ALL:ALL) ALL" /etc/sudoers)"
if [ "$CHECKSUDO" = "" ]; then
   echo -e "\n/etc/sudoers does not include correct root entry"
   CHECKSUDO="$(grep "^root\s" /etc/sudoers)"
   if [ "$CHECKSUDO" != "" ]; then
      echo "Found: $CHECKSUDO"
   fi
   if [ $REPLY_NO = 0 ]; then
      read -p "Add entry now (y/n)? "
      if [ "$REPLY" = "y" ]; then
         sed -i "/\broot\b/d" /etc/sudoers
         echo -e "root\tALL=(ALL:ALL) ALL" >> /etc/sudoers
      fi
   fi
else
   echo "done"
fi

fi

echo -n "Checking fstab entries..."
CHECK_MSG="$(grep /srv/tftp/msg /etc/fstab)"
if [ "$CHECK_MSG" = "" ]; then
   echo -e "\nMissing /srv/tftp/msg in /etc/fstab!"
else
   echo "done"
fi

echo -n "Checking MySQL configuration..."
if [ "$DEBIAN_VERSION" = "10" ] || [ "$DEBIAN_VERSION" = "11" ] || [ "$DEBIAN_VERSION" = "12" ]; then
   CHECK_MYSQL="$(grep event_scheduler=ON /etc/mysql/mariadb.conf.d/50-server.cnf)"
else
   CHECK_MYSQL="$(grep event_scheduler=ON /etc/mysql/my.cnf)"
fi

if [ "$CHECK_MYSQL" = "" ]; then
   echo -e "\nMissing event_scheduler entry"
   if [ $REPLY_NO = 0 ]; then
      read -p "Add entry now (y/n)? "
      if [ "$REPLY" = "y" ]; then
         if [ "$DEBIAN_VERSION" = "10" ] || [ "$DEBIAN_VERSION" = "11" ] || [ "$DEBIAN_VERSION" = "12" ]; then
	    sed -i 's/^\[mysqld\]$/[mysqld]\nevent_scheduler=ON/' /etc/mysql/mariadb.conf.d/50-server.cnf
         else
            sed -i 's/^\[mysqld\]$/[mysqld]\nevent_scheduler=ON/' /etc/mysql/my.cnf
         fi
      fi
   fi
else
   echo "done"
fi

echo -n "Checking hostname configuration..."

MY_HOSTNAME=$(hostname)
ETC_HOSTNAME=$(awk '/^127.0.1.1/ {print $2}' /etc/hosts)

if [ "$MY_HOSTNAME" != "$ETC_HOSTNAME" ]; then
	echo -e "\n\nWARNING: Hostname '$MY_HOSTNAME' does not match /etc/hosts hostname '$ETC_HOSTNAME.'"
	echo "Please install the <b>sysctrl-fix-lag</b> update on your system to resolve this issue."
else
	echo "done"
fi

if [ "$CLUSTER_SHARED_IP" != "" ]; then
	MQTT_HA_ROLE=$(</var/opt/nyquist/ha/current_mode)
else
	MQTT_HA_ROLE="master"
fi

if [ "$MQTT_HA_ROLE" = "master" ]; then
	echo -n "Checking MQTT server..."
	if [ ! -e /etc/asterisk/mqtt_pwd ]; then
		echo -e "\n\nMissing MQTT Password!"
	fi
	if [ ! -e /etc/mosquitto/conf.d/nyquist.conf ]; then
		echo -e "\n\nMissing Nyquist MQTT Config file!"
	fi
	if [ "$(/bin/systemctl is-active mosquitto)" != "active" ]; then
		if [ "$(/usr/local/bin/ha-mode)" != "slave" ]; then
			echo -e "\n\nMQTT server is not running!"
		fi
	fi
	echo "done"
fi

RECOMMEND_RESTART=0
DM_NOT_RUNNING=0
NS_NOT_RUNNING=0

NQ_STUN_ENABLED=$(systemctl is-enabled stun 2>/dev/null)
if [ "$NQ_STUN_ENABLED" = "enabled" ]; then
	NQ_STUN=" stund"
else
	NQ_STUN=""
fi

if [ "$DEBIAN_VERSION" = "10" ] || [ "$DEBIAN_VERSION" = "11" ] || [ "$DEBIAN_VERSION" = "12" ]; then
   MYSQL_DAEMON=mariadbd
else
   MYSQL_DAEMON=mysqld
fi
PROCESS_LIST="apache2 asterisk cron device-monitor in.tftpd $MYSQL_DAEMON ntpd safe_asterisk queue-manager nyquist-status mosquitto$NQ_STUN"

if [ "$CLUSTER_SHARED_IP" != "" ]; then

	echo -e "\nServices:\nName   \t\tPID"
	HA_ROLE=$(sudo /usr/local/bin/ha-current-role)

	if [ "$HA_ROLE" = "master" ]; then
		PROCESS_LIST="apache2 corosync cron in.tftpd $MYSQL_DAEMON ntpd NetworkManager pacemakerd pcsd rsync$NQ_STUN"
	fi

	if [ "$HA_ROLE" = "slave" ]; then
		PROCESS_LIST="apache2 corosync cron in.tftpd $MYSQL_DAEMON ntpd NetworkManager pacemakerd pcsd rsync"
	fi
else
	echo -e "\nLinux/Nyquist Services:\nName   \t\tPID"
fi

for i in $PROCESS_LIST
do
   if [ ${#i} -lt 7 ]; then
      EXTRATAB="\t"
   else
      EXTRATAB=""
   fi

   NQPID="$(ps -C $i -o pid=|head -n 1)"

   if [ "$NQPID" = "" ]; then
      NQPID="Not running"
      RECOMMEND_RESTART=1
      if [ "$i" = "device-monitor" ]; then
         DM_NOT_RUNNING=1
      fi
      if [ "$i" = "nyquist-status" ]; then
         NS_NOT_RUNNING=1
      fi
   fi

   echo -n -e "$i \t$EXTRATAB$NQPID\t"

   if [ "$i" = "mysqld" ]; then
      i="mysql"
   fi

   if [ "$i" = "mariadbd" ]; then
      i="mysql"
   fi

   if [ "$i" = "ntpd" ]; then
      i="ntp"
   fi

   if [ "$i" = "in.tftpd" ]; then
      i="tftpd-hpa"
   fi

   if [ "$i" = "pacemakerd" ]; then
      i="pacemaker"
   fi

   if [ "$i" = "stund" ]; then
      i="stun"
   fi

   SERVER_STATUS="$(service $i status|grep Active|awk -F: '{print $2}' -)"

   if [ "$i" = "asterisk" ] || [ "$i" = "safe_asterisk" ]; then
      if [ "$NQPID" != "Not running" ]; then
         echo $SERVER_STATUS|sed -e 's/exited/running/' -
      else
         echo $SERVER_STATUS
      fi
   else
      echo $SERVER_STATUS
   fi

   if [ "$(echo $SERVER_STATUS|grep inactive)" != "" ]; then
      RECOMMEND_RESTART=1
      if [ "$i" = "device-monitor" ]; then
         DM_NOT_RUNNING=1
      fi
   fi
done

if [ $RECOMMEND_RESTART = 1 ]; then
   echo -e "\n* One or more critical services is not running, server restart recommended."

   if [ $DM_NOT_RUNNING = 1 ]; then
      echo "If device-monitor is the only service not running and Station Supervision"
      echo "is disabled, this is normal, server restart is not required."
   fi

   if [ $NS_NOT_RUNNING = 1 ]; then
      echo "nyquist-status is not running. You may need to save the Nyquist Control Password"
      echo "again to force nyquist-status to restart."
   fi
fi

AST_VERSION="$(asterisk -rx "core show version" 2>/dev/null|awk '{print $2}' -)"

if [ "$AST_VERSION" = "" ]; then

	if [ "$CLUSTER_SHARED_IP" != "" ]; then

		if [ "$HA_ROLE" = "master" ]; then
			AST_VERSION="Down"
		else
			AST_VERSION="Standby"
		fi
	else
		AST_VERSION="Down"
	fi
fi

if [ $WWW_ACCESS = 0 ]; then

	echo -e "\nServer Status ($AST_VERSION):"

	if [ "$AST_VERSION" != "Down" ] && [ "$AST_VERSION" != "Standby" ]; then
		asterisk -rx "core show calls"
	fi
fi

# Check NTP source
if [ "$(ntpq -p|grep '*LOCAL')" != "" ]; then
   echo "NTP using LOCAL!"
   ntpq -p
fi

# Check multicast route
if [ "$(/sbin/ip route|grep '^239.0.0.0')" = "" ]; then
   echo "Missing multicast route (239.0.0.0)"
fi

echo ""

# Display audio status
if [ -e /srv/tftp/audio_status ]; then
   echo "Audio Status: $(cat /srv/tftp/audio_status)"
else
   echo "Audio Status: missing audio status file (/srv/tftp/audio_status)"
fi

# Check key directories
DIRS_MISSING=0
echo -n "Checking Nyquist directories..."
for i in /etc/asterisk /srv/tftp/backup /srv/tftp/msg /srv/tftp/msg /var/opt/nyquist /var/opt/nyquist/audio-dist /var/opt/nyquist/backups /var/opt/nyquist/demo /var/www/html/laravel/public/audio /var/www/html/laravel/public/exports /var/www/html/laravel/public/maps /var/www/html/laravel/public/updates /var/www/html/laravel/public/audio/announcements /var/www/html/laravel/public/audio/audio-dist /var/www/html/laravel/public/audio/sounds /var/www/html/laravel/public/audio/tones /var/lib/asterisk/sounds/user/announcements /var/spool/asterisk/monitor /var/lib/asterisk/sounds /var/lib/asterisk/sounds/user/tones /var/spool/asterisk/outgoing /var/log/asterisk/cdr-csv
do
   if [ ! -e $i ]; then
      if [ $DIRS_MISSING = 0 ]; then
         DIRS_MISSING=1
         echo ""
      fi
      echo "   missing dir: $i"
   fi
done
if [ $DIRS_MISSING = 0 ]; then
   echo "done"
fi

# Check key Linux programs
PROG_MISSING=0
echo -n "Checking Linux programs..."
for i in apache2 asterisk at dig ffmpeg mysql nmcli openssl php ping rsync sensors sshpass sox sudo swift tr wget mosquitto mosquitto_sub identify
do
   if [ "$(command -v $i)" = "" ]; then
      if [ $PROG_MISSING = 0 ]; then
         PROG_MISSING=1
         echo ""
      fi
      echo "   $i is missing"
   fi
done
if [ $PROG_MISSING = 0 ]; then
   echo "done"
fi

# Check Nyquist programs
PROG_MISSING=0
echo -n "Checking Nyquist programs..."
PATH=/usr/local/bin
for i in add-mcast-route airable-browser alembic announcement_manager audio_info ccm-control ccm-play cdr_check cdr_export cdr_prune cdr_to_db cdr_update change-mysql-access change-schedule change-server-ipaddr check-ast-logs check-controller-status check_cos check-for-firmware-updates check-for-system-updates check-iax-connections check-iax-server check-in check-server-status check-site-access check-table clear-data clear_table clear_user_session clock_set conf_participants continue-debian-upgrade convert-ifaces-to-nmi create-amplifier-cfg create-backup create_call create-digium-phones-conf create-gateway-cfg create_gsm create-mac-phoneprov create-nyquist-cfg create_preannounce_tone create-remote-phonebook create-spa112-cfg create-spa112-device-cfg create-syscontacts create-ta2400-cfg create-yealink-cfg create-fanvil-cfg custom-config dash-text db_credentials device-monitor display-message download-firmware-updates download-system-updates export-keys ffmpeg ffprobe file_io find-zone-overlap fix-zonesublist-dups gen_tone get-calls-info get_ip_for_station getlog get-multisite-label get-new-stations get-page-list get_public_ipaddr get_todays_schedule get_unique_stations import-file import-keys input-control ip-and-mask2cidr kick_from_conf licinfo licinfo-c4000 licinfo-e7000 mount-usb-drive night-ring notify-nyquist-amplifiers notify-nyquist-controller notify-nyquist-controllers notify-nyquist-mixer notify-nyquist-progdist nqssu nyquist-email nyquist-status nyquist-version nysql originate-emergency-call originate-webadminq-call originate-announcement pd-control pd-play pd-play-stream play_announcement play_audio prog_dist_stations program_distribution purge-backups purge-nws-alerts purge-recordings queue-manager reboot-all-devices reboot-all-snom-phones reboot-amplifier reboot-gateway remove_announcement remove_calls routine-digits routine-execute routine-export routine-import routine-trigger run_dahdi_genconf run_server_cmd run_system_backup run_system_setup run_sysupdate run_update_outsideline_status schedule_announcement schedule_events send-event set-db-timezone start_announcement start-debian-upgrade startup-cleanup stop_announcement stop_audio swift sync-nyquist-devices sync-yealink-phones sync-fanvil-phones system-backup system-setup system-update time-passed toggle-audio-dist tts-to-file update-all-nyquist-devices update-all-snom-phones update-all-spa-devices update-all-ta2400-devices update-all-yealink-phones update-all-fanvil-phones update-analog-lines update-backup-files-list update-conferences update-crontab update-dahdi-conf update-device-status update-digium-phone-conf update-digium-zones update-firmware update-iax update-nightring-stationlist update-nqsched-crontab update-outside-lines update-outsidelines-status update-paging-exclusion update-paging-extensions update-parking-lot update-phones update-recorded-files-list update-rtp-conf update-server-ipaddr update-siptrunks-conf update-siptrunks-status update-songs update-ssl-cert update-voicemail-conf update-yealink-idlescreen update-yealink-menu user-data-backup validate-date wav_to_gsm weather-alert ha-config ha-current-role ha-destroy-cluster ha-get-config ha-init-master ha-init-mysql-master ha-init-mysql-slave ha-init-resources ha-init-slave ha-init-stop-services ha-mode ha-openssl.cnf ha-restart-nyquist ha-resync-mysql-master ha-resync-mysql-slave ha-status ha-status-cleanup ha-stop-nyquist ha-sync-message-table ha-update-hostname ha-update-ipaddr ha-update-ssl-cert create-ht813-cfg web-audiodist-control update-stations-zone-volume config-dhcp-server schedule-routine remove-scheduled-routine request-callback update-calendar-control weather mcr-activate mcr-setup mcr-shutdown start-debian-upgrade continue-debian-upgrade update-debian nyquist-status nqnetcap sm-control load-fanvil-icons originate-annunciation sync-ldap update-mqtt-pwd sync-fanvil-phones update-all-fanvil-phones create-fanvil-cfg nyquist-logger download-fanvil-fw verify-checksums fix-network-route-issue nq-config-appliance nq-netscan device-status update-fail2ban-config
do
   #if [ "$(ls /usr/local/bin/$i 2>/dev/null)" = "" ]; then
   if [ -z "$(command -v $i)" ]; then
      if [ $PROG_MISSING = 0 ]; then
         PROG_MISSING=1
         echo ""
      fi
      echo "   $i is missing"
   fi
done
if [ $PROG_MISSING = 0 ]; then
   echo "done"
fi

export PATH=/usr/bin:/bin:/sbin/:/usr/sbin:/usr/local/bin

# Check nyquist service
if [ "$CLUSTER_SHARED_IP" = "" ]; then
	if [ ! -e /etc/init.d/nyquist ]; then
	   echo "Missing /etc/init.d/nyquist boot service!"
	fi
else
	if [ ! -e /lib/systemd/system/nyquist.service ]; then
	   echo "Missing /lib/systemd/system/nyquist.service service!"
	fi
fi

# Check nyquist.rules
if [ ! -e /etc/udev/rules.d/nyquist.rules ]; then
   echo "Missing /etc/udev/rules.d/nyquist.rules file!"
fi

FOUND_LOCKFILE=0
echo -n "Checking lock files..."
for i in pruneCdrRecords purgeBackups purgeRecordings routine-import-export Nyquist-crontab updateSipTrunks
do
   if [ -e /tmp/$i.lock ]; then
      echo -e "\n$i lock file exists! Reboot server to delete lock."
      FOUND_LOCKFILE=1
   fi
done
if [ $FOUND_LOCKFILE = 0 ]; then
   echo "done"
fi

if grep -Eq '^[[:space:]]*APP_DEBUG[[:space:]]*=[[:space:]]*false[[:space:]]*$' /var/www/html/laravel/.env; then
    echo "Laravel debug is disabled"
else
    echo "Laravel debug is enabled"
fi

# Check for use of bogen default password
DIDWARN=0
PWCOUNT=$(/usr/bin/mysql --user="asterisk" --password="A1B7N0Q0GEN00Z9" asterisk -e "select id from ps_auths where password='bogen' and id!='0'"|grep -cv "id")

if [ "$PWCOUNT" != "0" ]; then
   if [ "$PWCOUNT" != "" ]; then
      if [ $WWW_ACCESS = 1 ]; then
         echo -e "\n<p style=\"color:red\">WARNING: $PWCOUNT Stations are still using default bogen registration password!</p>"
      else
         echo -e "\nWARNING: $PWCOUNT Stations are still using default bogen registration password!\n"
      fi
      DIDWARN=1
   fi
fi

PWCOUNT=$(/usr/bin/mysql --user="asterisk" --password="A1B7N0Q0GEN00Z9" asterisk -e "select id from station where web_password='bogen' AND device_type IN ('10','11','13','14','15','22','23','25','26','28','29','66','67','68','69','70','71','72','73')"|grep -cv "id")

if [ "$PWCOUNT" != "0" ]; then
   if [ "$PWCOUNT" != "" ]; then
      if [ $WWW_ACCESS = 1 ]; then
         echo -e "\n<p style=\"color:red\">WARNING: $PWCOUNT Nyquist appliance web interfaces are still using default bogen password!</p>"
      else
         echo -e "\nWARNING: $PWCOUNT Nyquist appliance web interfaces are still using default bogen password!\n"
      fi
      DIDWARN=1
   fi
fi

PWCOUNT=$(/usr/bin/mysql --user="asterisk" --password="A1B7N0Q0GEN00Z9" asterisk -e "select id from station where web_password='bogen' AND device_type IN ('45','46','47')"|grep -cv "id")

if [ "$PWCOUNT" != "0" ]; then
   if [ "$PWCOUNT" != "" ]; then
      if [ $WWW_ACCESS = 1 ]; then
         echo -e "\n<p style=\"color:red\">WARNING: $PWCOUNT Analog-Telephone-Adaptor web interfaces are still using default bogen password!</p>"
      else
         echo -e "\nWARNING: $PWCOUNT Analog-Telephone-Adaptor web interfaces are still using default bogen password!\n"
      fi
      DIDWARN=1
   fi
fi

PWCOUNT=$(/usr/bin/mysql --user="asterisk" --password="A1B7N0Q0GEN00Z9" asterisk -e "select id from gateway where web_password='bogen'"|grep -cv "id")

if [ "$PWCOUNT" != "0" ]; then
   if [ "$PWCOUNT" != "" ]; then
      if [ $WWW_ACCESS = 1 ]; then
         echo -e "\n<p style=\"color:red\">WARNING: $PWCOUNT ASB appliance web interfaces are still using default bogen password!</p>"
      else
         echo -e "\nWARNING: $PWCOUNT ASB appliance web interfaces are still using default bogen password!\n"
      fi
      DIDWARN=1
   fi
fi

PWCOUNT=$(/usr/bin/mysql --user="asterisk" --password="A1B7N0Q0GEN00Z9" asterisk -e "select id from amplifier where web_password='bogen'"|grep -cv "id")

if [ "$PWCOUNT" != "0" ]; then
   if [ "$PWCOUNT" != "" ]; then
      if [ $WWW_ACCESS = 1 ]; then
         echo -e "\n<p style=\"color:red\">WARNING: $PWCOUNT Amplifier appliance web interfaces are still using default bogen password!</p>"
      else
         echo -e "\nWARNING: $PWCOUNT Amplifier appliance web interfaces are still using default bogen password!\n"
      fi
      DIDWARN=1
   fi
fi

if [ "$DIDWARN" != "0" ]; then
	echo "MySQL Status:"
else
	echo -e "\nMySQL Status:"
fi

export MYSQL_PWD=BogenNyq1;mysqlcheck --user=root --all-databases --silent
export MYSQL_PWD=A1B7N0Q0GEN00Z9
mysql --user="asterisk" asterisk -e status|grep Threads|fold -s

echo -e -n "\nDHCP Server Status: "
DHCP_ENABLED="$(echo "select enabled from dhcp_server"|mysql -f -N --user=asterisk asterisk)"
if [ "$DHCP_ENABLED" = "1" ]; then
   echo ""
   systemctl status isc-dhcp-server --no-pager -q -n 8
   DHCP_GW="$(echo "select gateway from dhcp_server"|mysql -f -N --user=asterisk asterisk)"
   if [ "$DHCP_GW" = "" ]; then
      if [ $WWW_ACCESS = 1 ]; then
         echo -e "\n<p style=\"color:red\">WARNING: DHCP Gateway is not set, paging and audio distrubution may not function!</p>"
      else
         echo -e "\nWARNING: DHCP Gateway is not set, paging and audio distrubution may not function!\n"
      fi
   fi
else
   echo "Disabled"
fi

echo ""

if [ -e /var/opt/nyquist/ha/master_host ]; then
   echo -e "-------------------------\nAutomatic Failover Status\n-------------------------"
   sudo /usr/local/bin/ha-status
fi

if [ $REPLY_NO = 0 ]; then
   read -p "Check Site Access (y/n)? "
   if [ "$REPLY" = "y" ]; then
      /usr/local/bin/check-site-access
   fi
fi

if [ ! -z "$(ls /opt/bogen/nyquist/Install-log-* 2>/dev/null)" ]; then
   if [ $REPLY_NO = 0 ]; then
      read -p "View Installation Log (y/n)? "
      if [ "$REPLY" = "y" ]; then
         more /opt/bogen/nyquist/Install-log-*
      fi
   fi
fi

if [ ! -z "$(ls /opt/bogen/nyquist/Update-log-* 2>/dev/null)" ]; then
   if [ $REPLY_NO = 0 ]; then
      read -p "View Update Log (y/n)? "
      if [ "$REPLY" = "y" ]; then
         more /opt/bogen/nyquist/Update-log-*
      fi
   fi
fi

CBR="$(export MYSQL_PWD=A1B7N0Q0GEN00Z9;/usr/bin/mysql -N --user="asterisk" asterisk -e "select * from callback_requests" 2>/dev/null)"
if [ "$CBR" != "" ]; then
   echo -e "\nActive Callback Requests:\nDCS-Ext CBR-Ext Expires\n$CBR"
fi

fi # END OF CHECK_OPERATION

################################################################################
# FIX ISSUES
################################################################################
if [ $FIX_ISSUES = 1 ];
then

ON_SYS_CONTROLLER=0

echo "
Fix issue on what system type:

1. System Controller
2. Customer Server
"

read -p "Select system type (1 or 2): "

if [ "$REPLY" = "1" ]; then
   ON_SYS_CONTROLLER=1
fi

NYQUIST_DIR=/opt/bogen/nyquist

if [ ! -d $NYQUIST_DIR/database ] || [ ! -d "$NYQUIST_DIR/laravel" ] ||
         [ ! -e "$NYQUIST_DIR/nyquist-asterisk.tar.gz" ] || [ ! -e "$NYQUIST_DIR/nyquist-files.tar.gz" ] ; then

   BASE_DIR="/opt/bogen"
   PATTERN="nyquist_*"

   MOST_RECENT_DIR=""
   MOST_RECENT_TIMESTAMP=""


   for DIR in "$BASE_DIR"/$PATTERN; do
      if [ -d "$DIR/database" ] && [ -d "$DIR/laravel" ] &&
	 [ -e "$DIR/nyquist-asterisk.tar.gz" ] && [ -e "$DIR/nyquist-files.tar.gz" ] ; then

         TIMESTAMP=$(basename "$DIR" | sed -E 's/^nyquist_([0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2})$/\1/')

         if [[ "$TIMESTAMP" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}$ ]]; then
            if [[ -z "$MOST_RECENT_TIMESTAMP" || "$TIMESTAMP" > "$MOST_RECENT_TIMESTAMP" ]]; then
                MOST_RECENT_TIMESTAMP=$TIMESTAMP
                MOST_RECENT_DIR=$DIR
            fi
         fi
      fi
   done

   if [[ -n "$MOST_RECENT_DIR" ]]; then
      NYQUIST_DIR=$MOST_RECENT_DIR
   fi


fi

NYQUIST_CORE=$NYQUIST_DIR
NYQUIST_SCRIPTS=$NYQUIST_CORE/scripts
ASTERISK_DIR=$NYQUIST_CORE/asterisk-$ASTERISK_VERSION
DATABASE=$NYQUIST_DIR/database
DATABASE_SQL=$DATABASE/sql
DATABASE_CORE=$DATABASE_SQL/core
DATABASE_PRODUCT=$DATABASE_SQL/$PRODUCT

echo "
The following can be fixed:
"

FIX_ASTERISK=0
FIX_DB=0
FIX_LARAVEL=0
FIX_MISSING_NODELOCK=0
FIX_APT=0
FIX_PACKAGES=0
FIX_SUDOERS=0
FIX_FSTAB=0
FIX_CUSTOMERINFO=0
FIX_PHP=0
FIX_PASSWD=0
FIX_FS_SIZE=0
FIX_REPAIR_DB=0
FIX_CSTATE=0;

if [ -e $NYQUIST_DIR/nyquist-asterisk.tar.gz ]; then
   echo "1 - Asterisk (compile/build/install)"
fi

if [ -e $NYQUIST_DIR/database ]; then
   echo "2 - database tables"
fi

if [ $ON_SYS_CONTROLLER = 1 ]; then
   if [ -e $NYQUIST_DIR/root/var/www/html/laravel ]; then
      echo "3 - laravel files"
   fi
fi

if [ ! -e /home/bogen/nyquist.akey ]; then
   if [ "$NQPROD" = "C4000" ]; then
      echo "4 - missing nodelock key"
   fi
fi

echo "5 - Fix apt"

if [ -e $NYQUIST_SCRIPTS/install-packages$DEB_VER ]; then
   echo "6 - Packages"
fi

CHECKSUDO="$(grep "root\sALL=(ALL:ALL) ALL" /etc/sudoers)"
if [ "$CHECKSUDO" = "" ]; then
   CHECKSUDO="$(grep "^root\s" /etc/sudoers)"
   if [ "$CHECKSUDO" != "" ]; then
      echo "7 - Fix incorrect root entry in /etc/sudoers"
   else
      echo "7 - Fix missing root entry in /etc/sudoers"
   fi
fi

CHECK_MSG="$(grep /srv/tftp/msg /etc/fstab)"
if [ "$CHECK_MSG" = "" ]; then
   echo "8 - Fix missing /srv/tftp/msg in /etc/fstab!"
fi

CUSTINFO_ERROR=0
if [ -e /opt/bogen/customerinfo.txt ]; then
   if [ "$(find /opt/bogen/customerinfo.txt -group www-data)" = "" ]; then
      CUSTINFO_ERROR=1
   fi
   if [ "$(find /opt/bogen/customerinfo.txt -perm -0660)" = "" ]; then
      CUSTINFO_ERROR=1
   fi
   if [ $CUSTINFO_ERROR = 1 ]; then
      echo "9 - Fix issues with customerinfo.txt file"
   fi
fi

echo "10 - PHP"

echo "11 - Change Nyquist User password to bogen"

echo "12 - Fix root filesystem size too small"

echo "13 - Repair Nyquist database (MySQL)"

if [ $ON_SYS_CONTROLLER = 1 ]; then
   if [ "$(grep GRUB_CMDLINE_LINUX= /etc/default/grub)" != "GRUB_CMDLINE_LINUX=\"intel_idle.max_cstate=0 processor.max_cstate=1\"" ]; then
      echo "14 - Disable CSTATE throttle"
   fi
fi

echo ""
read -p "Fix what (enter number)? "

case $REPLY in
   1) FIX_ASTERISK=1;;
   2) FIX_DB=1;;
   3) FIX_LARAVEL=1;;
   4) FIX_MISSING_NODELOCK=1;;
   5) FIX_APT=1;;
   6) FIX_PACKAGES=1;;
   7) FIX_SUDOERS=1;;
   8) FIX_FSTAB=1;;
   9) FIX_CUSTOMERINFO=1;;
   10) FIX_PHP=1;;
   11) FIX_PASSWD=1;;
   12) FIX_FS_SIZE=1;;
   13) FIX_REPAIR_DB=1;;
   14) FIX_CSTATE=1;;
   default) exit;;
esac

echo ""

if [ $FIX_ASTERISK = 1 ]; then
   echo -n "Fixing Asterisk..."
   cd $NYQUIST_CORE
   rm -rf $NYQUIST_DIR/asterisk-$ASTERISK_VERSION >/dev/null 2>&1
   echo -n "extract tar..."
   tar -x -P -f $NYQUIST_CORE/nyquist-asterisk.tar.gz > /dev/null 2>&1
   cd $ASTERISK_DIR
   echo "build..."
   make clean
   cd menuselect
   make distclean
   cd ..
   #mkdir -p /tmp/user/0
   #cp third-party/pjproject/dist/* /tmp/user/0 > /dev/null 2>&1
   #cp third-party/pjproject/dist/* /tmp > /dev/null 2>&1
   ./bootstrap.sh
   ./configure --with-pjproject-bundled --with-srtp --with-opus=yes
   make menuselect.makeopts
   make menuselect.makeopts
   menuselect/menuselect --disable chan_phone
   menuselect/menuselect --enable CORE-SOUNDS-EN-G722 --enable CORE-SOUNDS-EN-GSM --enable EXTRA-SOUNDS-EN-G722 --enable EXTRA-SOUNDS-EN-GSM --enable codec_opus menuselect.makeopts
   /bin/sync
   make
   if [ $? -ne 0 ]; then
      echo "Make failed! (server)"
      exit 1
   fi
   make install
   ldconfig
   echo "Note: ERROR 1060 (42S21) messages can be ignored..."
   export MYSQL_PWD=BogenNyq1
   mysql -f --user=root -D asterisk < $DATABASE_CORE/asterisk_update_$ASTERISK_VERSION.sql
fi

if [ $FIX_DB = 1 ]; then
   read -p "1 - Install tables (erases customer data)
2 - Update tables (preserving customer data)

Enter 1 or 2 : "

   if [ "$REPLY" = "1" ]; then
      if [ ! -e /opt/bogen/install_nyquist ]; then
         echo "Can't proceed, missing /opt/bogen/install_nyquist"
         exit
      fi

      cat <<EOF > /tmp/install_tables.$$
#!/bin/bash
#
PRODUCT=nyquist
ASTERISK_VERSION=22.4.1
BOGEN_ROOT=/opt/bogen
VERSION_SRC=\$BOGEN_ROOT/version
VERSION_DST=/etc/asterisk/version
NYQUIST_CORE=$NYQUIST_CORE
NYQUIST_SCRIPTS=$NYQUIST_SCRIPTS
DATABASE=$DATABASE
DATABASE_SQL=$DATABASE_SQL
DATABASE_CORE=$DATABASE_CORE
DATABASE_PRODUCT=$DATABASE_PRODUCT
ASTERISK_DIR=$ASTERISK_DIR
export MYSQL_PWD=BogenNyq1
cd $BOGEN_ROOT
#
# Create MySQL Database and USER
#
mysql -f --user=root < \$DATABASE_CORE/createuser.sql
mysql -f --user=root < \$DATABASE_CORE/createdb.sql
echo "SET GLOBAL event_scheduler = ON" | mysql -f --user=root -D asterisk
mysql -f --user=root -D asterisk < \$DATABASE_CORE/asterisk_\$ASTERISK_VERSION.sql
mysql -f --user=root -D asterisk < \$DATABASE_CORE/ps_endpoints.sql
cd \$DATABASE
EOF
      grep TABLES_TO_CREATE /opt/bogen/install_nyquist >> /tmp/install_tables.$$
      cat <<EOF >> /tmp/install_tables.$$
do
   source ./runsql \$DATABASE_CORE/\$i.sql
done
EOF
      grep "^TABLES_TO_UPDATE" /opt/bogen/install_nyquist >> /tmp/install_tables.$$

      cat <<EOF >> /tmp/install_tables.$$
for i in \$TABLES_TO_UPDATE
do
   source ./runsql \$DATABASE_PRODUCT/\$i.sql
done
EOF

      echo -e "\n!!!WARNING!!! Installing database tables will erase all customer data!!!\n"

      read -p "Please confirm that you want to install database tables? (y/n) :"
      if [ "$REPLY" = "y" ]; then
         chmod 770 /tmp/install_tables.$$
         /tmp/install_tables.$$
      fi

      rm /tmp/install_tables.$$
      exit
   fi

   if [ "$REPLY" = "2" ]; then
      cd $DATABASE || exit
      $BOGEN_ROOT/update_tables
      $BOGEN_ROOT/update_database
      TMP_SQL_FILE=/tmp/sessions-$$.sql
      cat <<EOF >> $TMP_SQL_FILE
USE asterisk;
DROP TABLE IF EXISTS sessions;
CREATE TABLE sessions (
 id            varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
 user_id       bigint(20) unsigned DEFAULT NULL,
 timeout       int(5) NOT NULL,
 extension     varchar(40) COLLATE utf8mb4_unicode_ci NOT NULL,
 ip_address    varchar(45) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
 user_agent    text COLLATE utf8mb4_unicode_ci DEFAULT NULL,
 payload       text COLLATE utf8mb4_unicode_ci NOT NULL,
 last_activity int(11) NOT NULL,
PRIMARY KEY (id),
KEY sessions_user_id_index (user_id),
KEY sessions_last_activity_index (last_activity)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
DROP EVENT IF EXISTS AutoDeleteSessions;
CREATE EVENT AutoDeleteSessions ON SCHEDULE EVERY 1 HOUR DO DELETE FROM sessions WHERE user_id is NULL;
EOF
      export MYSQL_PWD=BogenNyq1
      mysql -f --user=root -D asterisk < $TMP_SQL_FILE
      rm $TMP_SQL_FILE
      echo "Database tables updated"
      exit
   fi
fi

if [ $FIX_LARAVEL = 1 ]; then
   cp -rf $NYQUIST_DIR/root/var/www/html/laravel/* /var/www/html/laravel

   if [ "$NQPROD" = "C4000" ]; then
      rm -rf /var/www/html/laravel/public/help/topics/
      cp -rf $NYQUIST_CORE/laravel/help/topics_c4000/ /var/www/html/laravel/public/help/topics/
      rm -rf /var/www/html/laravel/public/help/topics_user/
      cp -rf $NYQUIST_CORE/laravel/help/topics_user_c4000/ /var/www/html/laravel/public/help/topics_user/
      rm -f /var/www/html/laravel/public/help/NyquistSystemAdministratorManual.pdf
      cp -f $NYQUIST_CORE/laravel/help/NyquistSystemAdministratorManual_c4000.pdf /var/www/html/laravel/public/help/NyquistSystemAdministratorManual.pdf
      rm -f /var/www/html/laravel/public/help/NyquistUserGuide.pdf
      cp -f $NYQUIST_CORE/laravel/help/NyquistUserGuide_c4000.pdf /var/www/html/laravel/public/help/NyquistUserGuide.pdf
      cp -f $NYQUIST_CORE/laravel/help/Nyquist-EULA_c4000.pdf /var/www/html/laravel/public/help/Nyquist-EULA.pdf
      cp -f $NYQUIST_CORE/laravel/pages/eula.blade.php /var/www/html/laravel/resources/views/pages/eula.blade.php
      cp -f $NYQUIST_CORE/laravel/images/c4000.png  /var/www/html/laravel/public/img/nyquist_logo.png
   fi

   chmod -R 777 /var/www/html/laravel/storage
   chmod -R 777 /var/www/html/laravel/bootstrap/cache

   if [ ! -e /var/www/html/laravel/public/audio/monitor ]; then
      ln -s /var/spool/asterisk/monitor  /var/www/html/laravel/public/audio
   fi

   if [ ! -e /var/www/html/laravel/public/audio/announcements ]; then
      ln -s  /var/lib/asterisk/sounds/user/announcements   /var/www/html/laravel/public/audio
   fi

   if [ ! -e /var/www/html/laravel/public/audio/tones ]; then
      ln -s  /var/lib/asterisk/sounds/user/tones   /var/www/html/laravel/public/audio
   fi

   if [ ! -e /var/www/html/laravel/public/audio/sounds ]; then
      ln -s  /var/lib/asterisk/sounds   /var/www/html/laravel/public/audio
   fi

   if [ ! -e /var/www/html/laravel/public/audio/audio-dist ]; then
      ln -s  /var/opt/nyquist/audio-dist   /var/www/html/laravel/public/audio
   fi
fi

if [ $FIX_MISSING_NODELOCK = 1 ]; then
   echo ""
   read -p "Enter nodelock key (NXXX-XXXX-XXXX-XXXX-XXXX): " akey

   if [ "$akey" != "" ]; then
       echo -n $akey > /home/bogen/nyquist.akey
   fi
fi

if [ $FIX_APT = 1 ]; then
   echo "Executing: dpkg --configure -a"
   dpkg --configure -a
fi

if [ $FIX_PACKAGES = 1 ]; then
   $NYQUIST_SCRIPTS/install-packages$DEB_VER
fi

if [ $FIX_SUDOERS = 1 ]; then
   sed -i "/\broot\b/d" /etc/sudoers
   echo -e "root\tALL=(ALL:ALL) ALL" >> /etc/sudoers
fi

if [ $FIX_FSTAB = 1 ]; then
   echo "tmpfs /srv/tftp/msg tmpfs defaults,nodev,nosuid,noexec,noatime,mode=1775,uid=root,gid=www-data,size=10m 0 0" >> /etc/fstab
   mount /srv/tftp/msg
fi

if [ $FIX_CUSTOMERINFO = 1 ]; then
   chown root:www-data /opt/bogen/customerinfo.txt
   chmod 0660 /opt/bogen/customerinfo.txt
   echo "New settings:"
   ls -l /opt/bogen/customerinfo.txt
fi

if [ $FIX_PHP = 1 ]; then
   export DEBIAN_FRONTEND="noninteractive"
   export APT_LISTCHANGES_FRONTEND=none

   debconf-set-selections <<< 'apt-listchanges apt-listchanges/frontend select none'
   debconf-set-selections <<< 'apt-listchanges apt-listchanges/confirm boolean false'

   apt-get -y --allow-releaseinfo-change update > /dev/null 2>&1

   echo "Uninstalling PHP..."

   sleep 5

   apt-get -y remove \*php\*
   apt-get -y remove \*php\*

   echo -e "\nInstalling PHP..."

   sleep 5

   apt-get -y -o Dpkg::Options::="--force-confold" install php php-common php-mysql php-curl php-cli php-fpm php-json php-zip php-gd php-mbstring php-xml php-pear php-bcmath php-readline libapache2-mod-php

   echo -e "\nConfiguring PHP and restarting Apache..."

   sleep 5

   #
   # Update php.ini
   #
   version_files=$(ls -1 /etc/php | grep -E '^[0-9]+\.[0-9]+$')
   highest_version=$(printf "%s\n" "${version_files[@]}" | sort -V | tail -n 1)
   if [ -z "$highest_version" ]; then
      highest_version=8.2
   fi
   sed -i "s/upload_max_filesize = .*/upload_max_filesize = 2G/" /etc/php/$highest_version/apache2/php.ini
   sed -i "s/post_max_size = .*/post_max_size = 4G/" /etc/php/$highest_version/apache2/php.ini
   sed -i "s/session.gc_maxlifetime = .*/session.gc_maxlifetime = 86400/" /etc/php/$highest_version/apache2/php.ini

   systemctl daemon-reload
   systemctl restart apache2

   echo -e "\n\nYou may need to restart the Nyquist server if issues are still showing up."

fi

if [ $FIX_PASSWD = 1 ]; then
	nysql -q users|awk '{print $1,$2}' -

	read -p "Change password to bogen, which user (enter number)? "

	if [ "$REPLY" != "" ]; then
		/usr/local/bin/nysql << EOF
		UPDATE users SET password='\$2y\$10\$8NwqpzycYK/d6veFT363ReO0kdKojq8U92eiMXTpC8k6LjxG0rE56' WHERE id=$REPLY
EOF
		echo "The user's password has been changed to: bogen"
	fi
fi

if [ $FIX_FS_SIZE = 1 ]; then
   if [ -e /dev/nvme0 ]; then 
      DISKNAME="nvme0n1p"
   else
      DISKNAME="sda"
   fi
	resize2fs /dev/${DISKNAME}2 > /dev/null 2>&1
	resize2fs /dev/${DISKNAME}1 > /dev/null 2>&1
	df -h
fi

if [ $FIX_REPAIR_DB = 1 ]; then
	export MYSQL_PWD=BogenNyq1;mysqlcheck --user=root --all-databases --extended --auto-repair
fi

if [ $FIX_CSTATE = 1 ]; then
   echo "Disabling CSTATE throttle via grub"
   /bin/sed -i -e 's/GRUB_CMDLINE_LINUX=""/GRUB_CMDLINE_LINUX="intel_idle.max_cstate=0 processor.max_cstate=1"/' /etc/default/grub
   /usr/sbin/update-grub
   echo "reboot required for change to take effect."
fi

fi # END OF FIX ISSUES
