.PHONY: backend build tidy test-api clean prune-dev-data install-cron uninstall-cron

REPO_ROOT := $(abspath $(dir $(lastword $(MAKEFILE_LIST))))
WATCHDOG := $(REPO_ROOT)/scripts/rcs-watchdog.sh
CRON_MARK := \# RCS watchdog
CRON_LINE := * * * * * $(WATCHDOG)

# Run the backend from the repo root (data/ next to Makefile).
backend:
	cd backend && RCS_DATA_DIR=../data RCS_ADDR=127.0.0.1:8080 go run ./cmd/rcs

build:
	cd backend && go build -o ../bin/rcs ./cmd/rcs

tidy:
	cd backend && go mod tidy

test-api:
	curl -sS http://127.0.0.1:8080/api/health | tee /dev/stderr | grep -q '"ok":true'

# Remove local seed/test SQLite rows; keep real Reddit captures.
prune-dev-data:
	bash scripts/prune-dev-data.sh

# Install a user crontab entry that runs the watchdog every minute.
install-cron: build
	@mkdir -p "$(REPO_ROOT)/data"
	@test -f "$(REPO_ROOT)/data/rcs.env" || cp "$(REPO_ROOT)/data/rcs.env.example" "$(REPO_ROOT)/data/rcs.env"
	@chmod +x "$(WATCHDOG)"
	@tmp="$$(mktemp)"; \
	(crontab -l 2>/dev/null || true) > "$$tmp"; \
	if grep -Fq "$(CRON_MARK)" "$$tmp"; then \
		echo "crontab already has RCS watchdog entry"; \
	else \
		printf '%s\n%s\n' "$(CRON_MARK)" "$(CRON_LINE)" >> "$$tmp"; \
		crontab "$$tmp"; \
		echo "installed: $(CRON_LINE)"; \
	fi; \
	rm -f "$$tmp"

# Remove the RCS watchdog block from the user crontab.
uninstall-cron:
	@tmp="$$(mktemp)"; \
	(crontab -l 2>/dev/null || true) > "$$tmp"; \
	if ! grep -Fq "$(CRON_MARK)" "$$tmp"; then \
		echo "no RCS watchdog crontab entry"; \
		rm -f "$$tmp"; \
		exit 0; \
	fi; \
	awk -v mark="$(CRON_MARK)" -v line="$(CRON_LINE)" '\
		$$0 == mark { skip=1; next } \
		skip && $$0 == line { skip=0; next } \
		skip { skip=0 } \
		{ print }' "$$tmp" > "$$tmp.out"; \
	crontab "$$tmp.out"; \
	rm -f "$$tmp" "$$tmp.out"; \
	echo "removed RCS watchdog crontab entry"

clean:
	rm -rf bin/ data/*.db data/*.db-* data/screenshots/*
	# keep screenshots/.gitkeep
	mkdir -p data/screenshots
	touch data/screenshots/.gitkeep
