#!/bin/bash
#

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_ARCHIVE_DIR=$BOGEN_ROOT/archive

UPDATE_FILE=appliance_update.cfg
ULBIN=/usr/local/bin
CONFIG_DIR=/etc/nyquist
SF=SIP.config

caller=${1:-webui}

trim() {
    local var="$*"
    var="${var#"${var%%[![:space:]]*}"}"   # remove leading whitespace characters
    var="${var%"${var##*[![:space:]]}"}"   # remove trailing whitespace characters
    echo -n "$var"
}

# Make sure we don't run multiple times and the first to execute survives
cmd_string=(${0//// })
cmd=${cmd_string[${#cmd_string[*]} - 1]}

tmp_ifs="$IFS"
IFS=$'\n'

ps_list=(`ps -C ${cmd} -o pid --no-header`)
num_copies=${#ps_list[*]}
if [ $num_copies -gt 1 -a ${ps_list[0]:-0} -ne $$ ]; then
	logger -p user.warning "$0[$$] Running $num_copies copies viz ${ps_list[*]}"
	exit 0
fi

IFS="$tmp_ifs"

SERVER_ADDR=$($ULBIN/find_tftp_server)

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

check_updates_webui() {
	#Get the update file
	sudo $ULBIN/get_file_from_server $SERVER_ADDR $UPDATE_FILE > /dev/null

	#If no update file, then no updates available
	if [ ! -f "$UPDATE_FILE" ]
	then
		echo "No updates available"
		exit 0
	else
		#echo "$UPDATE_FILE found"

		FIRMWARE_FILE=$(grep ".tar.gz" $UPDATE_FILE)
		#echo "Firmware File:  $FIRMWARE_FILE"

		TMP_NYQUIST_VERSION=$(echo $FIRMWARE_FILE | cut -d'-' -f2)
		NEW_NYQUIST_VERSION=$(echo $TMP_NYQUIST_VERSION | cut -f1,2,3 -d'.')
		#echo " -- Update to version $NEW_NYQUIST_VERSION is waiting to be installed"

		#If update available is <= current firmware version, no update is available
		#echo "Current Firmware Version: $CURRENT_NYQUIST_VERSION"
		if [ $NEW_NYQUIST_VERSION == $CURRENT_NYQUIST_VERSION ]; then
			echo "<br>"
			echo " -- Nyquist version $NEW_NYQUIST_VERSION is already installed"
			exit 0
		elif [ "$NEW_NYQUIST_VERSION" \< "$CURRENT_NYQUIST_VERSION" ]; then
			echo "<br>"
			echo " -- Nyquist version $NEW_NYQUIST_VERSION is older than current version ($CURRENT_NYQUIST_VERSION) already installed"
			exit 0
		else
			echo "<br>"
			echo " -- Nyquist version $NEW_NYQUIST_VERSION is newer than current version ($CURRENT_NYQUIST_VERSION) already installed"
			echo "<br>"
			# We can get the new version
			sudo $ULBIN/get_file_from_server $SERVER_ADDR $FIRMWARE_FILE
			sudo mv $FIRMWARE_FILE $BOGEN_INCOMING_DIR
		fi
	fi

	#Cleanup update file
	sudo rm $UPDATE_FILE
}

check_updates_config() {
	# Find out if we have FW_FILENAME information set in from the asterisk server
	while read config_line; do
		declare -g $config_line
	done <<- END
		`sed -e "/\(^#\|^$\)/d" -e "s/\s*//g" $CONFIG_DIR/$SF`
	END

	if [ "${FW_FILENAME:-unset}" != "unset" ]; then
		# Hack to make existing parts of the upgrade happy
		FW_FILENAME_HACK=NyqUpdate${FW_FILENAME#NyqUpdate}
		if [ ! -f /opt/bogen/archive/${FW_FILENAME_HACK} ]; then
			sudo $ULBIN/get_file_from_server $SERVER_ADDR $FW_FILENAME
			sudo mv $FW_FILENAME $BOGEN_INCOMING_DIR/${FW_FILENAME_HACK}
		elif [ "${FW_FILENAME_HACK/$CURRENT_NYQUIST_VERSION/}" == "${FW_FILENAME_HACK}" ]; then
			sudo mv /opt/bogen/archive/${FW_FILENAME_HACK} $BOGEN_INCOMING_DIR/
		fi

		if [ -f $BOGEN_INCOMING_DIR/${FW_FILENAME_HACK} ]; then
			logger -p user.info -t "$0" "Upgrading firmware with ${FW_FILENAME_HACK}"
			sudo /opt/bogen/nyq_update
		fi
	fi
}

if [ "$caller" == "webui" ]; then
	check_updates_webui
else
	check_updates_config
fi