# Configuration defaults (please use Makefile.env to override these, see Makefile.env.example)
LIGHTBAR_HOST = 192.168.13.12
LIGHTBAR_URL = http://$(LIGHTBAR_HOST)
WEBREPL_CLI = webrepl_cli.py
WEBREPL_HOST = $(LIGHTBAR_HOST)
WEBREPL_PASSWORD = secret-pw
REPL_TTY_PATH = /dev/ttyUSB0

# Include local config
-include Makefile.env

# Directory for saving timestamps of when files were last uploaded
UPLOAD_CACHE_DIR := .upload_cache

# Auto-detect all .py files that should be uploaded
SRC_UPLOAD_TARGETS := $(patsubst %.py,$(UPLOAD_CACHE_DIR)/%.py.timestamp,$(wildcard src/*.py src/**/*.py src/**/**/*.py))
LIB_UPLOAD_TARGETS := $(patsubst %.py,$(UPLOAD_CACHE_DIR)/%.py.timestamp,$(wildcard lib/*.py))

# Default target
.DEFAULT_GOAL := upload-reboot

# Make password variable available to the environment so that it doesn't appear in the output
export WEBREPL_PASSWORD

# -- Device control

# Reboot the ESP32 via REST API
.PHONY: reboot
reboot:
	curl -X POST $(LIGHTBAR_URL)/api/reboot

# Shutdown the HTTP server via REST API, allowing access to the WebREPL
.PHONY: shutdown
shutdown:
	curl -X POST $(LIGHTBAR_URL)/api/shutdown

# -- Deployment

# Upload all files (or only /src, or only /lib) to the ESP32 via WebREPL
.PHONY: upload upload-all upload-src upload-lib
upload: upload-all
upload-all: upload-src upload-lib
upload-src: $(SRC_UPLOAD_TARGETS)
upload-lib: $(LIB_UPLOAD_TARGETS)

# Upload all files via WebREPL and reboot
.PHONY: upload-reboot
upload-reboot: upload-all reboot

# Pattern rules for uploading files to the ESP32 via WebREPL if they were changed since the last upload
$(UPLOAD_CACHE_DIR)/%.py.timestamp :: %.py
	$(WEBREPL_CLI) -p $$WEBREPL_PASSWORD $*.py $(WEBREPL_HOST):/$(subst src/,,$*).py >/dev/null
	@mkdir -p $(@D) && touch $@

# Create necessary directories on the ESP32 filesystem via REPL (not WebREPL!)
# TODO: This cannot be done via webrepl_cli.py, so you either need to use REPL over USB, or create the directories manually
.PHONY: repl-create-directories
repl-create-directories:
	@echo "(Note: If the directory already exists, rshell will print \"Unable to create [DIR]\")"
	@echo
	rshell -p $(REPL_TTY_PATH) mkdir /pyboard/lib /pyboard/lightbar /pyboard/lightbar/endpoints

# Clear the .upload_cache directory that contains the last upload timestamps
.PHONY: clear-upload-cache clear-upload-cache-src
clear-upload-cache-all:
	rm -rf $(UPLOAD_CACHE_DIR)
clear-upload-cache-src:
	rm -rf $(UPLOAD_CACHE_DIR)/src/

# Clear the upload timestamp cache and re-upload all files
.PHONY: reupload-all reupload-src
reupload-all: clear-upload-cache-all upload-all
reupload-src: clear-upload-cache-src upload-src
