# Makefile for OpenBoatmobile
# Convenience commands for common operations

# Auto-detect infrastructure-as-code binary: OpenTofu preferred, Terraform fallback.
# Override with: make TERRAFORM=terraform <target>
TERRAFORM ?= $(shell command -v tofu 2>/dev/null || command -v terraform 2>/dev/null || echo tofu)

.PHONY: help init plan apply destroy ssh logs health clean

# Default target
help:
	@echo "OpenBoatmobile - deployment commands"
	@echo ""
	@echo "Binary: $(TERRAFORM) (OpenTofu preferred, Terraform fallback)"
	@echo "Override: make TERRAFORM=terraform <target>"
	@echo ""
	@echo "Usage: make <target>"
	@echo ""
	@echo "Targets:"
	@echo "  init      Initialize $(TERRAFORM)"
	@echo "  plan      Show deployment plan"
	@echo "  apply     Deploy infrastructure"
	@echo "  destroy   Destroy infrastructure"
	@echo "  output    Show deployment outputs"
	@echo "  ssh       SSH into server"
	@echo "  tunnel    Create SSH tunnel to gateway"
	@echo "  logs      Show gateway logs"
	@echo "  health    Run health check"
	@echo "  clean     Clean IaC state"
	@echo ""
	@echo "Prerequisites:"
	@echo "  source .env   # Load secrets before running"
	@echo ""

# Initialize
init:
	$(TERRAFORM) init

# Show deployment plan
plan:
	$(TERRAFORM) plan

# Deploy infrastructure
apply:
	$(TERRAFORM) apply

# Destroy infrastructure
destroy:
	$(TERRAFORM) destroy

# Show outputs
output:
	$(TERRAFORM) output

# SSH into server (extracts command from output)
ssh:
	@SSH_CMD=$$($(TERRAFORM) output -raw ssh_command); \
	echo "$$SSH_CMD"; \
	$$SSH_CMD

# Create SSH tunnel to gateway (extracts command from output)
tunnel:
	@SSH_CMD=$$($(TERRAFORM) output -raw ssh_command); \
	IP=$$($(TERRAFORM) output -raw server_ip); \
	echo "Creating tunnel to gateway..."; \
	$$SSH_CMD -L 18789:localhost:18789

# Show gateway logs (requires SSH)
logs:
	@SSH_CMD=$$($(TERRAFORM) output -raw ssh_command); \
	$$SSH_CMD "journalctl -u openclaw-gateway -f"

# Run health check (requires SSH)
health:
	@SSH_CMD=$$($(TERRAFORM) output -raw ssh_command); \
	$$SSH_CMD "sudo /usr/local/bin/openclaw-health-check.sh"

# Clean state
clean:
	rm -rf .terraform/
	rm -f .terraform.lock.hcl
	rm -f terraform.tfstate*
	@echo "State cleaned. Run 'make init' to reinitialize."

# Validate configuration
validate:
	$(TERRAFORM) validate

# Format code
fmt:
	$(TERRAFORM) fmt

# Show workspace status
status:
	@echo "=== Workspace ==="
	@$(TERRAFORM) workspace show 2>/dev/null || echo "default"
	@echo ""
	@echo "=== State Resources ==="
	@$(TERRAFORM) state list 2>/dev/null || echo "No resources in state"
	@echo ""
	@echo "=== Outputs ==="
	@$(TERRAFORM) output 2>/dev/null || echo "No outputs defined"