#!/bin/bash
#
# Run it with Internet connection:
#
# 		wget -q -O- https://files.vespy.tech/dfu-scripts/bootstrap | bash -s - <SECRET> [dev|production]
#
# Run it with Local network connection via Service Tablet:
#
# 		cat ${TOPDIR}/tools/provisioning/bootstrap | ssh pi@${HUB_IP_ADDRESS} "bash -s -- bash -s -- <SECRET> [dev|production] http://10.42.0.1:6060"
#

#
# For DFU from Service Tablet ----
#
function output_command {
	local command_name="$1"
	shift
	local output="!\t${command_name}"
	for arg in "$@"; do
		output="${output}\t${arg}"
	done
	[ "true" == "${SERVICE_TABLET_DFU}" ] && echo -e "$output" && return 0
}

function error_exit {
	local code=$1
	local message="$2"
	output_command ERR_EXIT "$code" "$message"
	echo -e "$message"
	exit 1
}

function log_info {
	echo -e "$@"
	output_command LOG INFO VENAHUB "$@"
}

function log_warn {
	echo -e "$@"
	output_command LOG WARN VENAHUB "$@"
}

function log_error {
	echo -e "$@"
	output_command LOG ERROR VENAHUB "$@"
}

function indicate_progress {
	local progress="$1"
	local message="$2"
	output_command PROGRESS "$progress" "$message"
	echo -e "$message"
}
#
# -- Function to output a command line with TAB-separated tokens.


function run_cmd {
	local COLOR='\033[1;32m'
	local NC='\033[0m'
	echo -e "${COLOR}$@${NC}"
	${BASH} -c "$@"
}

function init_variables {
	local NAME="venahub-fw"
	local SECRET=$1
	local TARGET=$2
	local SERVER_URL=$3
	[ "" == "${SECRET}" ] && echo "please specify the secret of agent to access release server" && exit 1
	[ "pi" != "$(whoami)" ] && echo "please execute this script with user _pi_" && exit 1
	[ "" == "${TARGET}" ] && TARGET="production" 
	[ "" == "${SERVER_URL}" ] && SERVER_URL="https://releases.vespy.tech"
	export TOPDIR="/home/pi/${NAME}"
	export SCRIPT_NAME="pkg-update"
	export WGET_AUTH="--user agent --password ${SECRET}"
	export RELEASE_SECRET=${SECRET}
	export RELEASE_SERVER=${SERVER_URL}
	export RELEASE_TARGET=${TARGET}
	[ "" == "${PKG_UPDATE_SCRIPT_URL}" ] && export PKG_UPDATE_SCRIPT_URL="${SERVER_URL}/firmware/scripts/provisioning/${SCRIPT_NAME}"
	
	wget ${WGET_AUTH} -q -O- ${PKG_UPDATE_SCRIPT_URL} > /dev/null
	if [ 0 -ne $? ]; then
		error_exit 0x4001 "failed to access ${PKG_UPDATE_SCRIPT_URL}, please check the URL or secret"
	fi
	indicate_progress 30 "init_variables done"
}

function bootstrap {
	mkdir -p ${TOPDIR}
	if [ ! -d "${TOPDIR}" ]; then
		error_exit 0x4002 "failed to create ${TOPDIR}, please check the permission"
	fi
	indicate_progress 32 "successfully created ${TOPDIR}"

	local SCRIPT_PATH="${TOPDIR}/${SCRIPT_NAME}"

	echo "downloading ${SCRIPT_NAME} ..."
	run_cmd "wget ${WGET_AUTH} -q -O /tmp/${SCRIPT_NAME} ${PKG_UPDATE_SCRIPT_URL}"
	if [ 0 -ne $? ]; then
		error_exit 0x4003 "failed to download ${PKG_UPDATE_SCRIPT_URL}, please check the URL or secret"
	fi
	if [ ! -f /tmp/${SCRIPT_NAME} ]; then
		error_exit 0x4004 "failed to download ${PKG_UPDATE_SCRIPT_URL}, please check the URL or secret"
	fi
	indicate_progress 33 "successfully downloaded ${SCRIPT_NAME}"

	if [ -f "${SCRIPT_PATH}" ]; then
		local CHECKSUM1=$(sha256sum /tmp/${SCRIPT_NAME} | awk '{print $1}')
		local CHECKSUM2=$(sha256sum ${SCRIPT_PATH} | awk '{print $1}')
		if [ "${CHECKSUM1}" != "${CHECKSUM2}" ]; then
			echo "upgrading ${SCRIPT_PATH} ..."
			run_cmd "cp -vf /tmp/${SCRIPT_NAME} ${SCRIPT_PATH}"
			if [ 0 -ne $? ]; then
				error_exit 0x4005 "failed to upgrade ${SCRIPT_PATH}, please check the permission"
			fi
			indicate_progress 34 "successfully upgraded ${SCRIPT_NAME}"
		else
			indicate_progress 35 "skip upgrading ${SCRIPT_NAME}"
		fi
	else
		echo "copying ${SCRIPT_PATH} ..."
		run_cmd "cp -vf /tmp/${SCRIPT_NAME} ${SCRIPT_PATH}"
		if [ 0 -ne $? ]; then
			error_exit 0x4006 "failed to copy ${SCRIPT_PATH}, please check the permission"
		fi
		indicate_progress 35 "successfully copied ${SCRIPT_NAME}"
	fi

	shift # remove the first argument
	run_cmd "chmod +x ${SCRIPT_PATH}"
	if [ 0 -ne $? ]; then
		error_exit 0x4007 "failed to chmod ${SCRIPT_PATH}, please check the permission"
	fi
	indicate_progress 36 "successfully chmod ${SCRIPT_NAME}"
	log_info "bootstrap done, going to run ${PKG_UPDATE_SCRIPT_URL} ..."
	log_info "command: cd ${TOPDIR} && RELEASE_SECRET=${RELEASE_SECRET} RELEASE_SERVER=${RELEASE_SERVER} ${BASH} ./${SCRIPT_NAME} ${RELEASE_TARGET}"

	run_cmd "cd ${TOPDIR} && SERVICE_TABLET_DFU=${SERVICE_TABLET_DFU} RELEASE_SECRET=${RELEASE_SECRET} RELEASE_SERVER=${RELEASE_SERVER} ${BASH} ./${SCRIPT_NAME} ${RELEASE_TARGET}"
	local RET=$?
	if [ 0 -ne ${RET} ]; then
		exit ${RET}
	fi
	return 0
}

output_command BEGIN_FILE env.txt
env
output_command END_FILE

init_variables $@
bootstrap $@
