PYTHON ?= python3
BASE_URL ?= https://localhost:8443
CA_FILE ?= secrets/pki/ca.crt
ACTION_SCRIPT ?=
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)

.PHONY: help check validate test load test-persistence test-failover test-security \
	up down destroy wait ps restore tls-audit security-http leak-check hardening bao-policy rehash \
	rotate-db-password rotate-lb-cert rotate-secret-id revoke-identity bao-sealed login-budget scan \
	test-student test-storage test-expiry all

help:
	@echo "skeleton: check validate test load test-persistence test-failover test-security"
	@echo "stand:    up down destroy wait ps restore      (Windows: powershell -File run.ps1)"
	@echo "lab7:     tls-audit security-http leak-check hardening bao-policy rehash"
	@echo "          rotate-db-password rotate-lb-cert rotate-secret-id revoke-identity bao-sealed login-budget scan"
	@echo "all:      make all = up + test + security + resilience + lifecycle"

check:
	$(PYTHON) scripts/check_contract.py

validate:
	$(PYTHON) scripts/validate_openapi.py

test:
	$(PYTHON) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS)

load:
	$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)

test-persistence:
	@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT=scripts/restart.sh"; exit 2)
	$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)

test-failover:
	@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT=scripts/stop-one.sh"; exit 2)
	$(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)

test-security:
	$(PYTHON) tests/security.py --base-url "$(BASE_URL)" $(TLS_ARGS)

# ---------------------------------------------------------------- стенд (scripts/ops.py)
up:
	$(PYTHON) scripts/ops.py up
down:
	$(PYTHON) scripts/ops.py down
# НАМЕРЕННОЕ удаление данных стенда (volumes)
destroy:
	$(PYTHON) scripts/ops.py destroy
wait ps restore tls-audit security-http leak-check hardening bao-policy bao-sealed login-budget scan rotate-lb-cert:
	$(PYTHON) scripts/ops.py $@
rehash:
	$(PYTHON) scripts/ops.py rehash-demo
rotate-db-password:
	$(PYTHON) scripts/ops.py rotate-db-password api
rotate-secret-id:
	$(PYTHON) scripts/ops.py rotate-secret-id api
revoke-identity:
	$(PYTHON) scripts/ops.py revoke-identity worker
test-student:
	CA_FILE="$(CA_FILE)" $(PYTHON) student-tests/run_all.py --base-url "$(BASE_URL)"
test-storage:
	$(PYTHON) scripts/ops.py in-network storage
test-expiry:
	$(PYTHON) scripts/ops.py in-network expiry

all: check up test test-security tls-audit security-http bao-policy hardening rehash leak-check test-expiry
	$(MAKE) test-persistence ACTION_SCRIPT=scripts/restart.sh
	$(MAKE) test-failover ACTION_SCRIPT=scripts/stop-one.sh && $(MAKE) restore
	$(MAKE) rotate-db-password rotate-lb-cert rotate-secret-id revoke-identity bao-sealed test
