#!/usr/bin/env bash

API_SERVER="http://ronquil.swamp.alex:5080"
STPC_IMAGE="/tmp/stpc-image/image.img.gz"
STPC_IMAGE_CHECKSUM="/tmp/stpc-image/checksum"
STPC_IMAGE_VERSION="/tmp/stpc-image/version"

function info() {
	echo -e "\033[33m$1\033[0m"
}

function error() {
	echo -e "\033[31m$1\033[0m"
}

function get_latest_version() {
	wget -qO- "${API_SERVER}/api/stpc/image/versions/" | jq -r .latest
}

function get_checksum() {
	version="$1"
	wget -qO- "${API_SERVER}/api/stpc/image/${version}/checksum/" | jq -r .checksum
}

function download_version() {
	version="$1"
	dest="$2"
	mkdir -p "/tmp/stpc-image"
	rm -f "${STPC_IMAGE_CHECKSUM}"
	rm -f "${dest}"
	wget --progress=bar -O "${dest}" "${API_SERVER}/api/stpc/image/${version}/download/"
	echo "`get_checksum \"${version}\"`" > "${STPC_IMAGE_CHECKSUM}"
}

function verify_checksum() {
	checksum="$1"
	filename="$2"
	if [ "${checksum}" = "`md5sum \"${filename}\" | awk '{print $1}'`" ]; then
		return 0
	else
		return 1
	fi
}

function has_version() {
	version="$1"

	if [ -f "${STPC_IMAGE_CHECKSUM}" ]; then
		if [ "`cat \"${STPC_IMAGE_CHECKSUM}\"`" = "`get_checksum \"${version}\"`" ]; then
			return 0
		else
			return 1
		fi
	else
		return 1
	fi
}

function get_disks() {
	__disks=()
	for device in /sys/block/*; do
		if udevadm info --query=property --path="${device}" | grep -q ^ID_BUS=usb; then
			disk="/dev/`basename \"${device}\"`"
			__disks+=("${disk}")
		fi
	done

	echo "${__disks[@]}"
}

# ensure the latest version is downloaded
latest_version="`get_latest_version`"
if ! has_version "${latest_version}" || ! verify_checksum "`cat \"${STPC_IMAGE_CHECKSUM}\"`" "${STPC_IMAGE}"; then
	echo "${latest_version}" > "${STPC_IMAGE_VERSION}"
	download_version "${latest_version}" "${STPC_IMAGE}"
fi
info "Using version: ${latest_version}"

# get disks to select from
disks="`get_disks`"
if [ -z "${disks}" ]; then
	error "No available disks to flash, please insert a disk and try again"
	exit 1
fi

while [ true ]; do
	echo "Select a disk:"
	for disk in ${disks}; do
		echo "  ${disk}"
	done

	# get user input
	read -p '> ' selected_disk

	# make sure disk is valid
	use_disk=""
	for disk in ${disks}; do
		if [ "${disk}" = "${selected_disk}" ]; then
			use_disk="${disk}"
			break
		elif [ "`basename \"${disk}\"`" = "${selected_disk}" ]; then
			use_disk="${disk}"
			break
		fi
	done

	if [ -z "${use_disk}" ]; then
		echo "Invalid disk: ${disk}"
	else
		break
	fi
done

# make sure that the user wants to continue
echo -e "Flashing \033[33m${use_disk}\033[0m with STPC Version \033[33m${latest_version}\033[0m"
read -p "Continue (Y/n)? " continue_flashing
if [ "${continue_flashing}" != "Y" ]; then
	info "Exiting on user command..."
	exit 1
fi

info "Creating Disk [${use_disk}]"
pv "${STPC_IMAGE}" | gunzip -c | dd of="${use_disk}" bs=1M
dd if="${STPC_IMAGE}" | pv | dd of=/dev/null count=100000

info "Synching Disk [${use_disk}"
sync

partprobe "${use_disk}"
sync

info "You may now remove the drive"
info "Please test the SD Flasher to certify"
exit 0
