#!/bin/bash
#
# ha-destroy-cluster - Destroy the Nyquist cluster configuration and resources
#
# (C) Copyright 2020-2024, Bogen Communications LLC. All rights reserved.
#

SCRIPT_DEBUG=0

if [ $SCRIPT_DEBUG -eq 1 ]; then
	CMD_OUTPUT="/dev/stdout"
	function debug_out { echo $@; }
else
	CMD_OUTPUT="/var/log/nyquist_af_setup.log"
	function debug_out { echo $@ &>> $CMD_OUTPUT; }
fi

echo $(date) Started: $0 $@ >> $CMD_OUTPUT

# The following { encapsulates output to CMD_OUTPUT (see bottom of script)
{

# Make sure PATH includes /sbin
if [[ $PATH != *"/sbin"* ]]; then
	export PATH="$PATH:/sbin:/usr/sbin"
fi

#
# Start mysql if it's not running (slave will be stopped by master)
#
MYSQL_ACTIVE=$(systemctl is-active mysql 2>/dev/null)

if [ "$MYSQL_ACTIVE" != "active" ]; then
	systemctl start mysql
fi

#
# Call ha-get-config to get the following variables:
#
#   CLUSTER_NAME                "Nyquist"
#   CLUSTER_PWD                 hacluster user's password
#   CLUSTER_MODE                Clusters current mode
#   CLUSTER_SHARED_IP           The shared Nyquist Server IP address
#   CLUSTER_MASTER_IP           Master node's IP Address
#   CLUSTER_SLAVE_IP            Slave (standby) node's IP Address
#   CLUSTER_MASTER_HOST         Master node's hostname
#   CLUSTER_SLAVE_HOST          Slave node's hostname
#   THIS_NODES_IPADDR           Current node's IP Address
#   THIS_NODES_HOSTNAME         Current node's hostname
#   SERVER_IPADDR               Nyquist Server IP Address
#
. /usr/local/bin/ha-get-config

debug_out "Destroy cluster"

pcs resource unmanage p_mariadb-clone --monitor

pcs resource unmanage p_apache-clone --monitor

pcs --all cluster stop

pcs --all cluster disable

pcs --all cluster destroy

systemctl stop pcsd.service

systemctl disable pcsd.service

systemctl stop rsync

systemctl disable rsync

systemctl stop lsyncd

systemctl disable lsyncd

/usr/sbin/asterisk -rx "core stop now"

sleep 5

/usr/bin/killall -s 9 -r "^asterisk"

rm -f /var/opt/nyquist/ha/*

if [ -e /etc/cron.daily/nyquist ]; then
  rm -f /etc/cron.daily/nyquist
fi

if [ -e /etc/asterisk/aflicense.dat ]; then
  rm -f /etc/asterisk/aflicense.dat
fi

#
# Update pjsip.conf transports to use the default bind address
#
awk "
/^\[transport-tls\]/ { transport=\"tls\" }
/^\[transport-ws\]/ { transport=\"ws\" }
/^\[transport-wss\]/ { transport=\"wss\" }
/^\[transport-udp\]/ { transport=\"udp\" }
/^\[transport-tcp\]/ { transport=\"tcp\" }

transport==\"ws\" && /^bind=/ { print \"bind=0.0.0.0:8088\"; next }
transport==\"wss\" && /^bind=/ { print \"bind=0.0.0.0:8089\"; next }
( transport==\"tls\" || transport==\"udp\" || transport==\"tcp\" ) && /^bind=/ { print \"bind=0.0.0.0\"; next }

{ print }
" /etc/asterisk/pjsip.conf > /tmp/tmp && mv /tmp/tmp /etc/asterisk/pjsip.conf;

# Restore saved init.d scripts
cp -f /var/opt/nyquist/etc/init.d/* /etc/init.d

if [ $? -eq 0 ]; then
	systemctl disable mysql
	systemctl stop mysql
	rm -f /etc/mysql/mariadb.conf.d/50-nyquist.cnf
	update-rc.d mysql defaults
	systemctl daemon-reload
	systemctl enable mysql

	systemctl disable safe_asterisk
	update-rc.d safe_asterisk defaults
	systemctl daemon-reload
	systemctl enable safe_asterisk

	systemctl disable asterisk
	update-rc.d asterisk defaults
	systemctl daemon-reload
	systemctl enable asterisk

	systemctl disable nyquist
	update-rc.d nyquist defaults
	systemctl daemon-reload
	systemctl enable nyquist

	systemctl disable queue-manager
	update-rc.d queue-manager defaults
	systemctl daemon-reload
	systemctl enable queue-manager

	systemctl disable device-monitor
	update-rc.d device-monitor defaults
	systemctl daemon-reload
	systemctl enable device-monitor

	systemctl disable isc-dhcp-server
	update-rc.d isc-dhcp-server defaults
	systemctl daemon-reload
fi

systemctl start mysql
systemctl start apache2
systemctl start safe_asterisk
systemctl start nyquist
systemctl start queue-manager
systemctl start device-monitor
systemctl start asterisk
systemctl enable update-mqtt-pwd
systemctl start update-mqtt-pwd
systemctl disable mosquitto
systemctl enable mosquitto
systemctl start mosquitto
systemctl disable nyquist-status
systemctl enable nyquist-status
systemctl start nyquist-status

export MYSQL_PWD=BogenNyq1

mysql -e "STOP SLAVE"
mysql -e "RESET SLAVE"
mysql -e "RESET SLAVE ALL"
mysql -e "USE asterisk;UPDATE automatic_failover_config SET mode='setup'"
mysql -e "USE asterisk;UPDATE automatic_failover_setup SET completed_master=0, completed_standby=0"

rm -f /var/lib/mysql/master1-bin*
rm -f /var/lib/mysql/master1-relay-bin*

DHCP_SERVER_ENABLED=$(/usr/local/bin/nysql -q dhcp_server.enabled)

if [ "$DHCP_SERVER_ENABLED" = "1" ]; then

	systemctl enable isc-dhcp-server
	systemctl start isc-dhcp-server
fi

/usr/local/bin/update-nqsched-crontab

rm -f /etc/sudoers.d/nyquist-ha

rm -f /var/log/nyquist_af_alerts.log

rm -f /etc/logrotate.d/nyquist-ha

rm -f /etc/rsync.passwd

cp -f /dev/null /etc/rsyncd.secrets

echo "DELETE from dashboard_msg WHERE popup_title LIKE 'AF-%'" | mysql --user=root asterisk

if [ "$THIS_NODES_HOSTNAME" = "$CLUSTER_MASTER_HOST" ]; then
	sed -i "/$CLUSTER_SLAVE_HOST/d" /etc/hosts
	sed -i "/Nyquist Secondary Automatic Failover Host/d" /etc/hosts
else
	sed -i "/$CLUSTER_MASTER_HOST/d" /etc/hosts
	sed -i "/Nyquist Primary Automatic Failover Host/d" /etc/hosts
fi

} &>> $CMD_OUTPUT

#
# If the node's current IP address is already equal to the server IP address, we are done and can exit.
# If this is the slave node, we need to update the server IP address to match the salve's IP address.
#
if [ "$THIS_NODES_IPADDR" = "$SERVER_IPADDR" ] || [ "$THIS_NODES_HOSTNAME" = "$CLUSTER_SLAVE_HOST" ]; then

	if [ "$SERVER_IPADDR" != "$CLUSTER_SLAVE_IP" ]; then

		export MYSQL_PWD=BogenNyq1

		debug_out "Updating system.server_ipaddr to $CLUSTER_SLAVE_IP"

		echo "UPDATE system SET server_ipaddr=INET_ATON('$CLUSTER_SLAVE_IP');" | mysql --user=root asterisk &>> $CMD_OUTPUT

		if [ $? -ne 0 ]; then

			echo "0:Error updating Server IP Address in database"

			exit 1
		fi

		/usr/local/bin/change-server-ipaddr $CLUSTER_SLAVE_IP &>> $CMD_OUTPUT

		ADD_TO_SAN_LIST=$(/usr/local/bin/nysql -q system.include_ip_addresses_in_ssl_san_list)

		/usr/local/bin/ha-update-ssl-cert $CLUSTER_SLAVE_IP $ADD_TO_SAN_LIST &>> $CMD_OUTPUT
	fi

	echo $(date) Finished: $0 $@ >> $CMD_OUTPUT

	echo "1:Success"

	exit 0
fi


#
# Need to restore the Server's standalone IP Address; schedule a job to do the
# work so that the script does not get killed when the IP address changes.
#
# Execute ha-update-ssl-cert after ha-update-ipaddr to remove cluster IP's
# added by ha-update-ipaddr.
#
# Tell the web interface that we are changing the IP address.
#
ADD_TO_SAN_LIST=$(/usr/local/bin/nysql -q system.include_ip_addresses_in_ssl_san_list)
at -M now >/dev/null 2>&1 <<EOF
sleep 20
/usr/local/bin/ha-update-ipaddr $THIS_NODES_IPADDR $SERVER_IPADDR > /dev/null 2>&1
sleep 10
/usr/local/bin/ha-update-ssl-cert $SERVER_IPADDR $ADD_TO_SAN_LIST
sleep 10
/usr/local/bin/run_server_cmd kill > /dev/null 2>&1
EOF

echo $(date) Finished: $0 $@ >> $CMD_OUTPUT

echo "1:Changing IP Address to $SERVER_IPADDR"

exit 0
