#!/usr/bin/env herodo
// Pre-flight check: Ensure Kubernetes cluster is accessible
try {
    if !run("kubectl cluster-info").execute().success {
        print("SKIPPED: Kubernetes cluster is not accessible");
        exit(0);
    }
} catch(e) {
    print("SKIPPED: Kubernetes cluster is not accessible: " + e);
    exit(0);
}

//! Simple Registry and Build Example
//!
//! Demonstrates the key features:
//! 1. Deploy a Docker Registry on Kubernetes
//! 2. Build a container image using Buildah in a Kubernetes pod
//! 3. Push the image to the registry
//!
//! Key concept: Same Buildah API for local and Kubernetes execution

let k = kubernetes();
print("=== Registry and Build Example ===");

// Create namespace
let ns = k.namespace("build-demo");

// Deploy registry
let registry = ns.registry("local-registry")
    .storage_size(10)           // GB
    // .node_port(30500)         // Optional: expose on node port
    // .timeout(120)             // Optional: wait time in seconds
    .deploy();

print("Registry ready: " + registry.connection_string());

// Provision build machine
let build_pod = ns.build_machine("builder")
    .image("quay.io/buildah/stable:latest")
    .privileged(true)           // Required for buildah
    // .memory(512, 2048)        // Optional: MB request, limit
    // .cpu(500, 2000)           // Optional: millicores request, limit
    .provision();

print("Build pod ready: " + build_pod.pod_name());

// Build image using Buildah (in Kubernetes pod)
let builder = buildah("myapp", "alpine:latest")
    .kubernetes(build_pod.namespace(), build_pod.pod_name())
    .build();

// Configure image
builder.run("apk add --no-cache curl");
builder.cmd(`["echo", "Hello from Kubernetes"]`);
// .label("version", "1.0")    // Optional: add labels
// .workdir("/app")            // Optional: set working directory
// .env("DEBUG", "true")       // Optional: set env vars

// Commit and push
let image_name = registry.image_prefix() + "/myapp:latest";
builder.commit(image_name);
builder.push(image_name).destination("docker://" + image_name).apply();

print("Image built and pushed: " + image_name);

// Cleanup
builder.remove();
build_pod.destroy();
ns.registry_delete("local-registry");
print("Done!");
