PYTHON ?= python3
BASE_URL ?= https://localhost:8443
CA_FILE ?= certs/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 init up down

help:
	@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running HTTPS API; load: synthetic writes"
	@echo "init: локальная PKI и секреты; up/down: запуск и остановка Compose"
	@echo "audit-transport/audit-api/audit-passwords/audit-telemetry/audit-hardening/audit-replicas: проверки lab7"
	@echo "audit-openbao/rotate-lb/rotate-valkey/scan: 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 to your implemented executable restart hook"; 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 to your implemented executable stop-one hook"; 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)

init:
	./scripts/init-secrets.sh

up: init
	docker compose up -d openbao
	$(PYTHON) scripts/manage_openbao.py bootstrap
	docker compose up -d --build --wait

down:
	docker compose --profile expiry down

EXPIRY_BASE_URL ?= https://localhost:8444

.PHONY: audit-transport audit-api audit-openbao rotate-lb rotate-valkey scan
audit-transport:
	./scripts/audit_transport.sh

audit-api:
	docker compose --profile expiry up -d --no-deps --wait api-short-ttl
	$(PYTHON) scripts/check_security_api.py --base-url "$(BASE_URL)" $(TLS_ARGS) --expiry-url "$(EXPIRY_BASE_URL)"; \
		result=$$?; docker compose --profile expiry stop api-short-ttl; exit $$result

audit-openbao:
	$(PYTHON) scripts/check_secret_lifecycle.py --url "$(BASE_URL)"

rotate-lb:
	$(PYTHON) scripts/rotate_security.py lb --url "$(BASE_URL)"

rotate-valkey:
	$(PYTHON) scripts/rotate_security.py valkey --url "$(BASE_URL)"

scan:
	./scripts/scan_lab7.sh

GRAFANA_URL ?= https://localhost:3007

.PHONY: audit-passwords audit-telemetry
audit-passwords:
	$(PYTHON) scripts/check_passwords.py --base-url "$(BASE_URL)" $(TLS_ARGS)

audit-telemetry:
	$(PYTHON) scripts/check_telemetry.py --base-url "$(BASE_URL)" --grafana-url "$(GRAFANA_URL)" $(TLS_ARGS)

.PHONY: audit-hardening
audit-hardening:
	$(PYTHON) scripts/check_hardening.py

.PHONY: audit-replicas
audit-replicas:
	$(PYTHON) scripts/check_replicas.py --base-url "$(BASE_URL)" $(TLS_ARGS)
