#!/bin/bash
BOGEN_DIR=/opt/bogen
PRODUCT_NAME=appliance
ULBIN=/usr/local/bin
NC_FILE=$BOGEN_DIR/$PRODUCT_NAME/network.config
CONFIG_DIR=/etc/nyquist
SF=SIP.config

touch /etc/nyquist/config_update_button_press
sync

caller=${1:-WebOrServer}
ppid=$2
cmd_string=(${0//// })
cmd=${cmd_string[${#cmd_string[*]} - 1]}
temp_path="/run"
filename="${cmd}.poll"

# Verify that we are not running in background
tmp_ifs="$IFS"
IFS=$'\n'

ps_list=(`ps -C ${cmd} -o args --no-header`)
[ -n "${ps_list[1]}" -a -z "$ppid" ] && exit 0

# See if we are low/out of disk space over 80% cut off
du=($(df --output=pcent /))
if [ "${du[1]//[!0-9]/}" -gt "80" ]
then
	sudo find /var/log -type f  \( -name "*.gz" -o -name "*.1" \) -exec rm -f {} +
	du=($(df --output=pcent /))
	[ "${du[1]//[!0-9]/}" -gt "80" ] && sudo find /var/log -type f -exec truncate -s 0 -c {} +
fi

IFS="$tmp_ifs"

SERVER_ADDR=$($ULBIN/find_tftp_server)

echo "SERVER_ADDR: $SERVER_ADDR"

# Get the MAC address of this appliance
MAC_ADDR=$(sudo ifconfig eth0 | grep 'HWaddr' | awk '{print $5}' | sed -e 's/://g')
pushd ${temp_path}
FILE_TO_GET=$MAC_ADDR.cfg



reset_sip_config() {
	#   echo "Copying Default $BOGEN_DIR/$PRODUCT_NAME/etc/nyquist/$SF to $CONFIG_DIR/$SF"
	cat <<- END > ${temp_path}/$SF.default
		# 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 diff ${temp_path}/$SF.default $CONFIG_DIR/$SF &> /dev/null
	res=$?
	if [ $res -ne 0 ]; then
		sudo chown root:www-data ${temp_path}/$SF.default
		sudo chmod 664 ${temp_path}/$SF.default
		sudo cp -p ${temp_path}/$SF.default $CONFIG_DIR/$SF
		sudo $ULBIN/network_set server default &> /dev/null
	fi
}

server_mode_setup() {
	sudo $ULBIN/get_file_from_server $SERVER_ADDR $FILE_TO_GET > /dev/null
	if [ $? -eq 0 ]; then
		$ULBIN/led_controller status green on yes
		sudo $ULBIN/get_file_from_server $SERVER_ADDR audio_status > /dev/null
		if [ $? -eq 0 ]; then
			read audio < audio_status
			unlink audio_status
			if [ "${audio/#disable}" != "${audio}" ]; then
				touch mute 
			elif [ -f mute ]; then
				unlink mute
			fi
		fi

		sudo $ULBIN/transfer_device_config FromServer $SERVER_ADDR $MAC_ADDR
		[ $? -ne 0 ] && sudo $ULBIN/transfer_device_config ToServer $SERVER_ADDR $MAC_ADDR
		# Gear up the rollback engine for this config
		$ULBIN/config_rollback
		[ -e ${temp_path}/${filename} ] && unlink ${temp_path}/${filename}
		#   echo "Moving $FILE_TO_GET to $CONFIG_DIR/$SF"
		sudo chown root:www-data $FILE_TO_GET
		sudo chmod 664 $FILE_TO_GET
		sudo cp -p $FILE_TO_GET $CONFIG_DIR/$SF
		sudo $ULBIN/network_set server default
	else
		sudo $ULBIN/push_device_info_to_server $SERVER_ADDR $MAC_ADDR
		rc=$?

		# if there is no network error we are in discovery
		[ $rc -ne 2 ] && $ULBIN/led_controller status blue on

		if [ ! -f ${temp_path}/${filename} ]; then
			# start a background poll
			touch ${temp_path}/${filename}
			systemd-run --no-block --service-type=idle $0 "$caller" "$$"
			# No need to follow through cleanup as the background instance would do that
			popd
			exit 0
		else
			retry=1
			[ $rc -eq 1 ] && logger -p user.warning -t "$0[$$]" "Failed to TFTP device info to ${SERVER_ADDR}"
			SERVER_ADDR=$($ULBIN/find_tftp_server)
			sleep 5
		fi
		reset_sip_config
	fi
}

fetch_scheduled_tones() {
	SCH_TONES_FILE="scheduled_tones"
	TONE_FILE="backup_tone.wav"
        echo "Getting $SCH_TONES_FILE from $SERVER_ADDR"
	#echo "sudo $ULBIN/get_file_from_server $SERVER_ADDR $SCH_TONES_FILE"
	sudo $ULBIN/get_file_from_server $SERVER_ADDR $SCH_TONES_FILE > /dev/null
        if [ $? -eq 0 ]; then
		sudo chown root:www-data $SCH_TONES_FILE
		sudo chmod 664 $SCH_TONES_FILE
		sudo cp -p $SCH_TONES_FILE $CONFIG_DIR/$SCH_TONES_FILE
	fi
	echo "Getting $TONE_FILE from $SERVER_ADDR"
	sudo $ULBIN/get_file_from_server $SERVER_ADDR $TONE_FILE > /dev/null
        if [ $? -eq 0 ]; then
		sudo chown root:www-data $TONE_FILE
		sudo chmod 664 $TONE_FILE
		sudo cp -p $TONE_FILE $CONFIG_DIR/$TONE_FILE
	fi
}

retry=1
while [ $retry -eq 1 ]
do
	# what we need was a do { }while; loop
	retry=0
	# Now we get the configuration file from the server
	#echo "Fetching $FILE_TO_GET from $SERVER_ADDR"
	#echo "<br>"
	
	if [ -e /etc/nyquist/standalone.config ]; then
		reset_sip_config
		$ULBIN/led_controller status green on
		[ -e mute ] && unlink mute
		[ -e ${temp_path}/${filename} ] && unlink ${temp_path}/${filename}
	else
		server_mode_setup
                fetch_scheduled_tones
	fi
done

ps_list=(`ps -C restart_application -o args --no-header`)
[ -z "${ps_list[*]}" ] && sudo $ULBIN/restart_application no_update

sudo rm $FILE_TO_GET
popd



echo "Configuration update complete"
