# Image Registry Configuration
REGISTRY ?= git.pengzhan.dev/haopengzhan/k8s-ds-secret-injection
WEBHOOK_IMAGE = $(REGISTRY)/webhook:latest
CLIENT_IMAGE = $(REGISTRY)/test-client:latest
NAMESPACE = gps-system

.PHONY: all build build-images push deploy clean certs

all: build

build:
	go build -o bin/webhook ./cmd/webhook
	go build -o bin/test-client ./cmd/test-client
	go build -o bin/secret-manager ./cmd/secret-manager

build-images:
	docker build -f Dockerfile.webhook -t $(WEBHOOK_IMAGE) .
	docker build -f Dockerfile.test-client -t $(CLIENT_IMAGE) .

push: build-images
	docker push $(WEBHOOK_IMAGE)
	docker push $(CLIENT_IMAGE)

certs:
	@echo "Generating self-signed certificates..."
	kubectl apply -f deploy/namespace.yaml
	openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 -nodes \
		-subj "/CN=inject-ds-webhook.$(NAMESPACE).svc" \
		-addext "subjectAltName = DNS:inject-ds-webhook.$(NAMESPACE).svc"
	kubectl create secret tls inject-ds-webhook-certs --cert=cert.pem --key=key.pem -n $(NAMESPACE) --dry-run=client -o yaml | kubectl apply -f -
	@echo "Updating CA Bundle in webhook configuration..."
	@CA_BUNDLE=$$(cat cert.pem | base64 | tr -d '\n') && \
	sed -i "s/caBundle: .*/caBundle: $$CA_BUNDLE/" deploy/webhook.yaml

deploy:
	kubectl apply -f deploy/namespace.yaml
	kubectl apply -f deploy/rbac.yaml
	# Ensure images in manifests match our registry
	sed -i "s|image: .*/webhook:latest|image: $(WEBHOOK_IMAGE)|" deploy/webhook.yaml
	sed -i "s|image: .*/test-client:latest|image: $(CLIENT_IMAGE)|" deploy/test-ds.yaml
	kubectl apply -f deploy/webhook.yaml
	@echo "Waiting for webhook to be ready..."
	kubectl wait --for=condition=available --timeout=60s deployment/inject-ds-webhook -n $(NAMESPACE)
	kubectl apply -f deploy/test-ds.yaml

clean:
	kubectl delete -f deploy/test-ds.yaml --ignore-not-found
	kubectl delete -f deploy/webhook.yaml --ignore-not-found
	kubectl delete -f deploy/rbac.yaml --ignore-not-found
	kubectl delete namespace $(NAMESPACE) --ignore-not-found
	rm -rf bin/ key.pem cert.pem