#!/bin/bash
#

caller=$1
operation=$2
PWD_CORE=$PWD
PRODUCT_NAME=appliance
BOGEN_ROOT=/opt/bogen
BOGEN_INCOMING_DIR=$BOGEN_ROOT/incoming
BOGEN_PREV_VER_DIR=$BOGEN_ROOT/previous
BOGEN_FACT_DEF_DIR=$BOGEN_ROOT/default
BOGEN_LOG_DIR=$BOGEN_ROOT/logs
BOGEN_ARCHIVE_DIR=$BOGEN_ROOT/archive

if [ -e "${BOGEN_ROOT}/${PRODUCT_NAME}/VERSION.config" ]; then
	CURRENT_NYQUIST_VERSION=$(cat $BOGEN_ROOT/$PRODUCT_NAME/VERSION.config)
else
	CURRENT_NYQUIST_VERSION=0.0.0
fi

MAIN_TAR_LOC=$PWD_CORE
MAIN_TAR_NAME=$PRODUCT_NAME-$NYQUIST_VERSION

PRODUCT_ROOT=$BOGEN_ROOT/$PRODUCT_NAME

NYQUIST_SCRIPTS=$BOGEN_ROOT/scripts
HTML_ROOT=$BOGEN_ROOT/root/var/www/html
BACKUPS_DIR=/var/opt/$PRODUCT_NAME/backups
UPDATE_LOG=$BOGEN_LOG_DIR/Update-log-`date +%F-%R`.txt

#date >> $UPDATE_LOG
#echo "Current Nyquist Version: $CURRENT_NYQUIST_VERSION" | tee -a $UPDATE_LOG
echo " -- Restoring to factory defaults from version $CURRENT_NYQUIST_VERSION"
echo "<br>"
TARGET_DIRECTORY=$BOGEN_ROOT/$PRODUCT_NAME

restore_config() {
	# Remove everything except the asound file(s)
	sudo find /etc/nyquist -type f -not -name "*\.txt" -not -path "*backup/*" -exec rm -f {} +
	sudo create_default_standalone_config

	# Restore factory default config settings
	sudo cat <<- END > /etc/nyquist/SIP.config
		# Autogenerated - File contains all of the default configuration information for
		# Web interface access on the device
		AUTO_GENERATED = yes
		
		DEVICE_NAME = Nyquist Appliance
		
		WEB_USERNAME = admin
		
		WEB_PASSWORD = bogen
	END
	sudo cat <<- END > ${TARGET_DIRECTORY}/network.config
		TFTP Server:
		TFTP Source: Option 66
	END
}

sudo find /var/log -type f  \( -name "*.gz" -o -name "*.1" \) -exec rm -f {} +
sudo find /var/log -type f -exec truncate -s 0 -c {} +

restore_config


CURRENT_NYQUIST_VERSION=$(cat $BOGEN_ROOT/$PRODUCT_NAME/VERSION.config)

echo " --  Now at version $CURRENT_NYQUIST_VERSION" #| tee -a $UPDATE_LOG
# Reset network configuration to factort default DHCP, it is assumed that this 
# script is only called from webui or the reset button!!!
sudo /usr/local/bin/restart_application 2>&1 | logger -p user.info -t "$0[$$]"
sudo /usr/local/bin/network_set webui dhcp 2>&1 | logger -p user.info -t "$0[$$]"
sudo sync
sudo systemd-run --no-block --service-type=idle bash -c "sleep 5;/usr/local/bin/reboot_now ${caller}"
#date >> $UPDATE_LOG