SHELL := /bin/bash
export PATH := $(PWD)/scripts:$(PATH)

IMAGE_TAG := $(shell git rev-parse --short HEAD)
IMAGE_NAME ?= bearcloud
HY_OPTS ?= --no-cache
VM_OPTS ?=

SECRET_KEYS := ssh_host_ecdsa_key ssh_host_ed25519_key ssh_host_rsa_key
KEYTYPE_ssh_host_ecdsa_key := ecdsa
KEYTYPE_ssh_host_ed25519_key := ed25519
KEYTYPE_ssh_host_rsa_key := rsa

SECRET_FILES := $(addprefix secret/,$(SECRET_KEYS))

.PHONY: all check-root check-deps validate secrets builder vm hypervisor confirm

all: vm hypervisor

check-root:
	@if [ "$$(id -u)" != "0" ]; then \
		echo "This script must be run in root."; \
		exit 2; \
	fi

check-deps:
	@if ! command -v ssh-keygen >/dev/null; then \
		echo "ssh-keygen is required for guest setup."; \
		exit 1; \
	fi

validate: check-deps
	@./scripts/validate.sh || { echo "env validation failed"; exit 1; }

confirm: check-root validate
	@echo "Image tag: $(IMAGE_NAME):$(IMAGE_TAG) and $(IMAGE_NAME):latest"
	@echo "Additional arguments for VM image: $(VM_OPTS)"
	@echo "Additional arguments for Hypervisor Image: $(HY_OPTS)"
	@echo "Missing secret files like ssh host key will be automatically created."
	@echo "Continue?"
	@read

$(SECRET_FILES):
	@echo "Creating missing secret $@"
	ssh-keygen -t "$(KEYTYPE_$(notdir $@))" -f "$@" \
		-C "automatically generated bearcloud ssh key" \
		-N ""

secrets: $(SECRET_FILES)

builder:
	@if ! docker buildx ls | grep -q "bearcloud"; then \
		docker buildx create --name bearcloud \
			--buildkitd-flags '--allow-insecure-entitlement security.insecure'; \
	fi

vm: confirm secrets builder
	@echo "BUILDING VM DISK IMAGE"
	docker build \
		--builder bearcloud \
		--allow security.insecure \
		-f vm.Dockerfile \
		--build-context host-modules=/lib/modules \
		--target export \
		--output type=local,dest=./data \
		$(VM_OPTS) .
	fallocate -d ./data/vm.raw

hypervisor: confirm secrets
	@echo "BUILDING HYPERVISOR IMAGE"
	docker build -t "$(IMAGE_NAME):$(IMAGE_TAG)" -t "$(IMAGE_NAME):latest" \
		-f hypervisor.Dockerfile $(HY_OPTS) .
