# curb viewer — on-device dashboard for a Curb Energy Monitor hub.
# This is the redistributable viewer: our code only, no Curb proprietary
# firmware. It installs over SSH onto a running hub you already have access to.
#
# You supply SSH access via CURB_SSH. Key-based is preferred; for a freshly
# recovered hub you can use password auth, e.g.:
#   make deploy HUB=root@192.168.1.215 CURB_SSH="sshpass -p PW ssh -o ..."

HUB     ?= root@192.168.1.215
KEY     ?= $(HOME)/.ssh/curb_hub_rsa
METHOD  ?= rsync
# Old Dropbear on the lamarr hub needs the legacy algorithms.
CURB_SSH ?= ssh -i $(KEY) -o PubkeyAcceptedAlgorithms=+ssh-rsa -o HostKeyAlgorithms=+ssh-rsa -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10
export CURB_SSH
export METHOD

.DEFAULT_GOAL := help
.PHONY: help deploy deploy-scp deploy-viewer-only test verify revert reboot

help:  ## List targets
	@echo "curb viewer — on-device dashboard (redistributable)"
	@echo
	@echo "Usage: make <target> [HUB=user@ip] [METHOD=rsync|scp]"
	@echo
	@grep -hE '^[a-zA-Z_-]+:.*?## ' $(MAKEFILE_LIST) \
	  | awk 'BEGIN{FS=":.*?## "} {printf "  \033[1m%-16s\033[0m %s\n", $$1, $$2}'
	@echo
	@echo "Vars: HUB=$(HUB)  METHOD=$(METHOD)  KEY=$(KEY)"

deploy:  ## Install the viewer on a running hub (HUB=user@ip; rsync, scp fallback)
	@test -n "$(HUB)" || { echo "set HUB=user@ip"; exit 1; }
	sh local-viewer/deploy.sh "$(HUB)"

deploy-scp:  ## Same as deploy but force scp transport
	@test -n "$(HUB)" || { echo "set HUB=user@ip"; exit 1; }
	METHOD=scp sh local-viewer/deploy.sh "$(HUB)"

deploy-viewer-only:  ## Install viewer AND disable the streamer (no cloud upload / SD buffering)
	@test -n "$(HUB)" || { echo "set HUB=user@ip"; exit 1; }
	VIEWER_ONLY=1 sh local-viewer/deploy.sh "$(HUB)"

test:  ## Test the viewer off-device against the hub's ARM luajit under qemu
	sh local-viewer/test/run.sh

verify:  ## Check the viewer is serving on the hub (:80)
	@test -n "$(HUB)" || { echo "set HUB=user@ip"; exit 1; }
	@host=$$(echo "$(HUB)" | sed 's/.*@//'); \
	 echo "GET http://$$host/api/health"; \
	 curl -fsS "http://$$host/api/health" | head -c 240 && echo " ..." \
	   || echo "not serving yet (still booting? give it a moment)"

revert:  ## Remove the viewer from a hub and restore its backups (HUB=user@ip)
	@test -n "$(HUB)" || { echo "set HUB=user@ip"; exit 1; }
	sh local-viewer/revert.sh "$(HUB)"

reboot:  ## Reboot the hub to activate a deploy (HUB=user@ip)
	@test -n "$(HUB)" || { echo "set HUB=user@ip"; exit 1; }
	-$(CURB_SSH) "$(HUB)" '/sbin/reboot || reboot'
	@echo "rebooting — give it ~1-2 min, then: make verify"
