#!/bin/bash
#

function BLUE {
	local COLOR='\033[1;34m'
	local NC='\033[0m'
	echo "${COLOR}$@${NC}"
}

function RED {
	local COLOR='\033[1;31m'
	local NC='\033[0m'
	echo "${COLOR}$@${NC}"
}

function PURPLE {
	local COLOR='\033[0;35m'
	local NC='\033[0m'
	echo "${COLOR}$@${NC}"
}

function YELLOW {
	local COLOR='\033[0;33m'
	local NC='\033[0m'
	echo "${COLOR}$@${NC}"
}

function GREEN {
	local COLOR='\033[0;32m'
	local NC='\033[0m'
	echo "${COLOR}$@${NC}"
}

function init {
	[ "" == "${RELEASE_SECRET}" ] && export RELEASE_SECRET=$1
	[ "" == "${RELEASE_SERVER}" ] && export RELEASE_SERVER="https://releases.vespy.tech"
	[ "" == "${RELEASE_SECRET_FILE}" ] && export RELEASE_SECRET_FILE="/opt/toe/config/ttt/secret.txt"

	if [ ! -f ${RELEASE_SECRET_FILE} ]; then
		if [ "" == "${RELEASE_SECRET}" ]; then
			echo "ERROR: RELEASE_SECRET is not defined."
			exit 1
		else
			sudo mkdir -vp $(dirname ${RELEASE_SECRET_FILE})
			sudo chown -v pi:pi $(dirname ${RELEASE_SECRET_FILE})
			echo "${RELEASE_SECRET}" > ${RELEASE_SECRET_FILE}
		fi
	else
		if [ "" == "${RELEASE_SECRET}" ]; then
			export RELEASE_SECRET=$(cat ${RELEASE_SECRET_FILE})
		else
			if [ "${RELEASE_SECRET}" != "$(cat ${RELEASE_SECRET_FILE})" ]; then
				echo "overwrite secret file ..."
				echo "${RELEASE_SECRET}" > ${RELEASE_SECRET_FILE}
			fi
		fi
	fi

	export WGET_AUTH="--user agent --password ${RELEASE_SECRET}"
	export OS_ARCH=$(uname -m)

	# test if auth is working
	#
	local TEST_URL="${RELEASE_SERVER}/firmware/scripts/provisioning/pkg-update"
	if ! wget ${WGET_AUTH} -q -O- ${TEST_URL} > /dev/null; then
		echo "ERROR: Failed to access ${TEST_URL} with provided credentials."
		exit 1
	fi
}

function download_from_server {
	local REMOTE_PATH=$1
	local LOCAL_PATH=$2
	if [ -z "${REMOTE_PATH}" ] || [ -z "${LOCAL_PATH}" ]; then
		echo "ERROR: Remote and local paths must be specified."
		return 1
	fi
	mkdir -p "$(dirname ${LOCAL_PATH})"

	wget ${WGET_AUTH} -O ${LOCAL_PATH} ${RELEASE_SERVER}${REMOTE_PATH}
	if [ $? -ne 0 ]; then
		echo "ERROR: Failed to download ${REMOTE_PATH} to ${LOCAL_PATH}."
		return 1
	fi
	if [ ! -f ${LOCAL_PATH} ]; then
		echo "ERROR: Downloaded file ${LOCAL_PATH} does not exist."
		return 1
	fi
	echo "Downloaded ${REMOTE_PATH} to ${LOCAL_PATH} successfully."
	return 0
}


function process_armv7l {
	echo "Processing armv7l architecture..., updating RDS agent and TOE startup script."
	if [ ! -f "/home/pi/venahub-fw/bin/node" ]; then
		echo "Node.js runtime not found at /home/pi/venahub-fw/bin/node. Please check the installation (very old version)."
		return 1
	fi

	local RDS_AGENT_DIR="/opt/rds-agent2"
	if [ ! -d "${RDS_AGENT_DIR}" ]; then
		download_from_server /firmware/runtime/rds-agent/armv7l/rds-agent2.tar.gz /tmp/rds.tar.gz
		if [ $? -ne 0 ]; then
			echo "Failed to download RDS agent archive."
			return 1
		fi
		echo "RDS agent directory not found at ${RDS_AGENT_DIR}. Creating directory."
		sudo mkdir -p ${RDS_AGENT_DIR}
		sudo chown -R pi:pi ${RDS_AGENT_DIR}
		tar -xzf /tmp/rds.tar.gz -C /opt/
	fi

	local RDS_STARTUP_SCRIPT="/home/pi/vt-rfid/cli/venahub/rootfs/etc/init.d/20-rds-agent"
	if [ ! -f ${RDS_STARTUP_SCRIPT} ]; then
		echo "RDS startup script not found at ${RDS_STARTUP_SCRIPT}. Please check the path."
		return 1
	fi

	echo "Checking RDS startup script at ${RDS_STARTUP_SCRIPT} ... => $(cat ${RDS_STARTUP_SCRIPT} | grep vena-rds)"

	if [ -z "$(cat ${RDS_STARTUP_SCRIPT} | grep rds-agent2)" ]; then
		echo "RDS startup script is not updated, downloading new version..."
		download_from_server /firmware/os/rootfs/${OS_ARCH}${RDS_STARTUP_SCRIPT} ${RDS_STARTUP_SCRIPT}
		if [ $? -ne 0 ]; then
			echo "Failed to download RDS startup script."
			return 1
		fi
	else
		echo "RDS startup script is updated."
	fi

	local TOE_STARTUP_SCRIPT="/opt/toe/startup.sh"
	if [ ! -f ${TOE_STARTUP_SCRIPT} ]; then
		echo "TOE startup script not found at ${TOE_STARTUP_SCRIPT}. Please check the path."
		return 1
	fi

	sudo chown pi:pi ${TOE_STARTUP_SCRIPT}
	if [ ! -f ${TOE_STARTUP_SCRIPT}.bak ]; then
		echo "Creating backup of TOE startup script."
		cp ${TOE_STARTUP_SCRIPT} ${TOE_STARTUP_SCRIPT}.bak
	fi
	download_from_server /firmware/os/rootfs/${OS_ARCH}${TOE_STARTUP_SCRIPT} ${TOE_STARTUP_SCRIPT}
	if [ $? -ne 0 ]; then
		echo "Failed to download TOE startup script."
		return 1
	fi
	echo "TOE startup script updated successfully."
	return 0
}

function generate_pm2_startup_script {
cat <<__EOF__
#!/bin/bash
pm2 stop rds-agent
pm2 delete rds-agent
pm2 start /opt/toe-framework/services/rds-agent/index.js \
	--name rds-agent \
	--node-args="--expose-gc" \
	-- \
		-s 'wstty-client.url=https://rds.vespy.tech' \
		-i 'wstty-client.restart_timeout=28800' \
		-i 'system-info.ttt_max_read_attempts=30'
pm2 save
__EOF__
}

function process_aarch64 {
	echo "Processing aarch64 architecture..., updating RDS agent and TOE startup script."
	cd /opt/toe-framework/services/rds-agent/
	git pull
	echo "RDS agent updated successfully."

	local TMP_FILE="/tmp/rds-agent-startup.sh"
	generate_pm2_startup_script > ${TMP_FILE}
	echo "RDS agent is not running or not configured correctly, needs to be upgraded."
	cat ${TMP_FILE}
	sudo su - root -c "bash ${TMP_FILE}"
	if [ $? -ne 0 ]; then
		echo "Failed to start RDS agent with PM2."
		return 1
	fi

	local PROFILE_CONFIG_FILE="/opt/toe/config/ttt/profile.txt"
	local CONTENT=$(cat ${PROFILE_CONFIG_FILE} 2>/dev/null)
	if [ "${CONTENT}" == "${OS_ARCH}" ]; then
		echo "Profile configuration file already contains the correct architecture: ${OS_ARCH}"
	else
		echo ${OS_ARCH} > ${PROFILE_CONFIG_FILE}
		echo "Updated profile configuration file at ${PROFILE_CONFIG_FILE} with content: ${OS_ARCH} (old: ${CONTENT})"
	fi
	return 0
}

init $@
case "${OS_ARCH}" in
	"armv7l")
		echo "Processing armv7l architecture..."
		process_armv7l
		;;
	"aarch64")
		echo "Processing aarch64 architecture..."
		process_aarch64
		;;
	*)
		echo "Unsupported architecture: ${OS_ARCH}"
		exit 1
		;;
esac
exit 0