# Makefile for OpenBoatmobile
# Convenience commands for common operations

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

# Default target
help:
	@echo "OpenBoatmobile - Terraform deployment commands"
	@echo ""
	@echo "Usage: make <target>"
	@echo ""
	@echo "Targets:"
	@echo "  init      Initialize Terraform"
	@echo "  plan      Show deployment plan"
	@echo "  apply     Deployinfrastructure"
	@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 Terraform state"
	@echo ""
	@echo "Prerequisites:"
	@echo "  source .env   # Load secrets before running"
	@echo ""

# Initialize Terraform
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 Terraform 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 Terraform state
clean:
	rm -rf .terraform/
	rm -f .terraform.lock.hcl
	rm -f terraform.tfstate*
	@echo "Terraform state cleaned. Run 'make init' to reinitialize."

# Validate configuration
validate:
	terraform validate

# Format code
fmt:
	terraform fmt

# Show workspace status
status:
	@echo "=== Terraform 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"