#!/bin/bash
# ========================================================================== #
#                                                                            #
#    KVMD - The main PiKVM daemon.                                           #
#                                                                            #
#    Copyright (C) 2018-2024  Maxim Devaev <mdevaev@gmail.com>               #
#                                                                            #
#    This program is free software: you can redistribute it and/or modify    #
#    it under the terms of the GNU General Public License as published by    #
#    the Free Software Foundation, either version 3 of the License, or       #
#    (at your option) any later version.                                     #
#                                                                            #
#    This program is distributed in the hope that it will be useful,         #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of          #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           #
#    GNU General Public License for more details.                            #
#                                                                            #
#    You should have received a copy of the GNU General Public License       #
#    along with this program.  If not, see <https://www.gnu.org/licenses/>.  #
#                                                                            #
# ========================================================================== #

die() {
	echo >&2 "E: $*"
	exit 1
}

set -eo pipefail

if (( $# == 1 )) && [[ $1 =~ ^([0-9]+)/([0-9]+)$ ]]; then
	_usb_bus="${BASH_REMATCH[1]}"
	_usb_addr="${BASH_REMATCH[2]}"
else
	die "Invalid invocation: $0 ${*@Q}"
fi

_fw_info=$(picotool info --bus "$_usb_bus" --address "$_usb_addr")
_fw_name=$(<<<"$_fw_info" sed -nE 's/^ name: *(.+)$/\1/p')
case "$_fw_name" in
	"org.pikvm.switch.v1.rp2040") ;;
	"org.pikvm.hid.v1.rp2040") ;;
	"switch") _fw_name="org.pikvm.switch.v1.rp2040" ;;
	"hid") _fw_name="org.pikvm.hid.v1.rp2040" ;;
	*) die "Unknown Pico-based device: $_fw_name" ;;
esac

_uf2="/usr/share/kvmd/firmware/$_fw_name/firmware.uf2"
if [[ ! -f "$_uf2" ]]; then
	die "Can't find firmware $_uf2"
fi

set -x
picotool load \
		--bus "$_usb_bus" \
		--address "$_usb_addr" \
		--update \
		--verify \
		--execute \
	"$_uf2"
