export REGISTRO=harbor.reymota.es\/reymota
#export REGISTRO=registry.reymota.es
export NAMESPACE = finanzas
# Kubeconfig configuration
KUBECONFIG_DIR ?= $(CURDIR)/.kube
KUBECONFIG ?= $(KUBECONFIG_DIR)/config
export KUBECONFIG
VERSION_FILE = .version

# Get current version or default to alpine-1
IMG_VERSION := $(shell cat $(VERSION_FILE) 2>/dev/null || echo "alpine-1")
# Get built version for deployment targets
BUILT_VERSION := $(shell cat .current_version 2>/dev/null || echo "$(IMG_VERSION)")
export IMG_VERSION

help:
	@echo ""
	@echo "Comandos disponibles:"
	@echo ""
	@grep "^[[:lower:]]" Makefile | grep -v "^\." | grep "##" | awk -F':.*## ' '{printf "  \033[1m%-20s\033[0m %s\n", $$1, $$2}'
	@echo ""
	@echo "Kubeconfig actual: $(KUBECONFIG) en `grep server $(KUBECONFIG) |cut -c13-`"

KUBECONFIG_HOME ?= $(HOME)/.kube

kubeconfig-list: ## Lista los kubeconfig disponibles en $HOME/.kube
	@ls -1 $(KUBECONFIG_HOME)/config* 2>/dev/null | while read f; do \
		echo "   $$f"; \
	done

kubeconfig-set: ## Selecciona un kubeconfig de forma interactiva
	@mkdir -p $(KUBECONFIG_DIR)
	@if [ -n "$(KUBECONFIG_SOURCE)" ]; then \
		if [ -f "$(KUBECONFIG_HOME)/$(KUBECONFIG_SOURCE)" ]; then \
			cp $(KUBECONFIG_HOME)/$(KUBECONFIG_SOURCE) $(KUBECONFIG_DIR)/config; \
			echo "Kubeconfig copiado de $(KUBECONFIG_HOME)/$(KUBECONFIG_SOURCE) a $(KUBECONFIG)"; \
		elif [ -f "$(KUBECONFIG_SOURCE)" ]; then \
			cp $(KUBECONFIG_SOURCE) $(KUBECONFIG_DIR)/config; \
			echo "Kubeconfig copiado de $(KUBECONFIG_SOURCE) a $(KUBECONFIG)"; \
		else \
			echo "Error: No se encontró el kubeconfig '$(KUBECONFIG_SOURCE)'"; \
			echo "Usa 'make kubeconfig-list' para ver los disponibles"; \
			exit 1; \
		fi; \
	else \
		bash -c '\
			configs=($$(ls -1 $(KUBECONFIG_HOME)/config* 2>/dev/null)); \
			if [ $${#configs[@]} -eq 0 ]; then \
				echo "No se encontraron kubeconfigs en $(KUBECONFIG_HOME)"; \
				exit 1; \
			fi; \
			echo ""; \
			echo "Selecciona un kubeconfig:"; \
			for i in "$${!configs[@]}"; do \
				echo "  $$((i+1))) $${configs[$$i]}"; \
			done; \
			echo ""; \
			read -p "Introduce el número (1-$${#configs[@]}): " num; \
			if [[ "$$num" =~ ^[0-9]+$$ ]] && [ "$$num" -ge 1 ] && [ "$$num" -le "$${#configs[@]}" ]; then \
				idx=$$((num-1)); \
				cp "$${configs[$$idx]}" $(KUBECONFIG_DIR)/config; \
				echo "Kubeconfig copiado de $${configs[$$idx]} a $(KUBECONFIG)"; \
			else \
				echo "Error: Selección inválida"; \
				exit 1; \
			fi; \
		'; \
	fi

# limpia todo
all: imagen clean install

imagen: ## Crea la imagen
	@echo "Building image with version: $(IMG_VERSION)"
	@# Store current version for other targets to use
	@echo "$(IMG_VERSION)" > .current_version
	cd ../; make
	@# Increment version for next build
	@echo "$(IMG_VERSION)" | sed 's/alpine-\([0-9]*\)/alpine-\1/' | awk -F'-' '{print "alpine-" $$2+1}' > $(VERSION_FILE)
	@echo "Next version will be: $$(cat $(VERSION_FILE))"

ns: ## Crea el namespace
	-cat namespace.yaml | sed -e "s/<NS>/${NAMESPACE}/" |kubectl --kubeconfig=$(KUBECONFIG) create -f -

install: ## Instala todo (meno las claims)
	-cat reg-secret.yaml| sed -e "s/<NS>/${NAMESPACE}/" | kubectl --kubeconfig=$(KUBECONFIG) create -f -
	-cat env-prod-configmap.yaml | sed -e "s/<NS>/${NAMESPACE}/" | kubectl --kubeconfig=$(KUBECONFIG) create -f -
	-cat secreto-db.yaml| sed -e "s/<NS>/${NAMESPACE}/" | kubectl --kubeconfig=$(KUBECONFIG) create -f -

	-cat finanzas-deployment.yaml | sed -e "s/<NS>/${NAMESPACE}/" | sed -e "s/<TAG>/${BUILT_VERSION}/" | sed -e "s/<REGISTRO>/${REGISTRO}/" | kubectl --kubeconfig=$(KUBECONFIG) create -f -
	-cat finanzas-service.yaml | sed -e "s/<NS>/${NAMESPACE}/" | kubectl --kubeconfig=$(KUBECONFIG) create -f -

clean: ## Borra todo (meno las claims)


	-cat finanzas-deployment.yaml | sed -e "s/<NS>/${NAMESPACE}/" | sed -e "s/<TAG>/${BUILT_VERSION}/" | sed -e "s/<REGISTRO>/${REGISTRO}/" | kubectl --kubeconfig=$(KUBECONFIG) delete -f -

	-cat finanzas-service.yaml | sed -e "s/<NS>/${NAMESPACE}/" | kubectl --kubeconfig=$(KUBECONFIG) delete -f -

	-cat secreto-db.yaml| sed -e "s/<NS>/${NAMESPACE}/" | kubectl --kubeconfig=$(KUBECONFIG) delete -f -
	-cat env-prod-configmap.yaml  | sed -e "s/<NS>/${NAMESPACE}/" | kubectl --kubeconfig=$(KUBECONFIG) delete -f -
	-cat reg-secret.yaml | sed -e "s/<NS>/${NAMESPACE}/" | kubectl --kubeconfig=$(KUBECONFIG) delete -f -

borraclaims: ## Borra las claims
	-cat pvc-finanzas.yaml | sed -e "s/<NS>/${NAMESPACE}/" | kubectl --kubeconfig=$(KUBECONFIG) delete -f -
	-cat pvc-static.yaml | sed -e "s/<NS>/${NAMESPACE}/" | kubectl --kubeconfig=$(KUBECONFIG) delete -f -

claims: ## Crea las claims
	-cat pvc-finanzas.yaml | sed -e "s/<NS>/${NAMESPACE}/" | kubectl --kubeconfig=$(KUBECONFIG) create -f -
	-cat pvc-static.yaml | sed -e "s/<NS>/${NAMESPACE}/" | kubectl --kubeconfig=$(KUBECONFIG) create -f -

app: ## Borra y vuelve a crear el deployment
	-cat finanzas-deployment.yaml | sed -e "s/<NS>/${NAMESPACE}/" | sed -e "s/<TAG>/${BUILT_VERSION}/" | sed -e "s/<REGISTRO>/${REGISTRO}/" | kubectl --kubeconfig=$(KUBECONFIG) delete -f -
	-cat finanzas-deployment.yaml | sed -e "s/<NS>/${NAMESPACE}/" | sed -e "s/<TAG>/${BUILT_VERSION}/" | sed -e "s/<REGISTRO>/${REGISTRO}/" | kubectl --kubeconfig=$(KUBECONFIG) create -f -

status: ## Muestra el estado del deployment
	kubectl --kubeconfig=$(KUBECONFIG) get deployments,pods,services -n $(NAMESPACE)

db: ## Crea la base de datos en el cluster
	-kubectl --kubeconfig=$(KUBECONFIG) create -f finanzas-db.yaml
