#!/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);
}

// basic_kubebuilder.rhai
// Basic example demonstrating how to use KubeBuilder to build container images in Kubernetes

println("KubeBuilder Basic Example");
println("=========================");
println("");
println("This example shows how to:");
println("1. Provision a builder pod in Kubernetes");
println("2. Execute commands in the pod");
println("3. Use buildah to create container images");
println("4. Clean up resources");
println("");

// Configuration
let namespace = "build";
let builder_name = "example-builder";

println(`Namespace: ${namespace}`);
println(`Builder name: ${builder_name}`);
println("");

// Step 1: Create a build machine
println("Step 1: Creating build machine configuration...");
let machine = kube_build_machine(namespace, builder_name);

// Configure the build machine using property setters
machine.image = "ubuntu:24.04";   // Base image
machine.cpu = "1";                 // CPU limit (keep low for small clusters)
machine.memory = "2Gi";            // Memory limit
machine.debug_mode = true;         // Enable debug output

println(`  Image: ubuntu:24.04`);
println(`  CPU: 2`);
println(`  Memory: 4Gi`);
println("");

// Step 2: Provision the build machine
println("Step 2: Provisioning build machine in Kubernetes...");
println("(This creates a pod with buildah installed)");
println("");

let handle = provision(machine);

println(`Pod created: ${handle.pod_name}`);
println(`Namespace: ${handle.namespace}`);
println("");

// Step 3: Execute commands in the build machine
println("Step 3: Executing commands in the builder...");

// Check OS info
let os_result = exec(handle, ["cat", "/etc/os-release"]);
println("OS Info (property access):");
println(os_result.stdout);
println("OS Info (index access):");
println(os_result["stdout"]);

// Check buildah version
let buildah_result = exec(handle, ["buildah", "--version"]);
println(`Buildah version (property): ${buildah_result.stdout}`);
println(`Buildah version (index): ${buildah_result["stdout"]}`);
// Test Rhai trim in different ways
let raw_stdout = buildah_result["stdout"];
println(`Type of stdout: ${type_of(raw_stdout)}`);
println(`Raw length: ${raw_stdout.len()}`);
let trimmed = raw_stdout.trim();
println(`Trimmed value: ${trimmed}`);
// Alternative: use sub_string to remove last char if it's a newline
if raw_stdout.ends_with("\n") {
    let clean = raw_stdout.sub_string(0, raw_stdout.len() - 1);
    println(`Clean value: ${clean}`);
}
println("");

// Step 4: Build a simple container image using the fluent bah() API
println("Step 4: Building a simple container image with fluent API...");

// Use the new fluent kube_bah() API for building container images
// This creates a Bah builder that runs buildah commands in the Kubernetes pod
let image = kube_bah(handle, "mycontainer", "alpine:latest")
    .run("apk add --no-cache curl")     // Install curl
    .set_entrypoint("/usr/bin/curl")    // Set entrypoint
    .commit("my-curl-image:latest");    // Commit to image

// Check the result of the last operation
if image.success {
    println("Successfully built image: my-curl-image:latest");
    println(`Container ID: ${image.container_id}`);
} else {
    println(`Build failed: ${image.stderr}`);
}

// List images using the old-style buildah command (for comparison)
let images_result = buildah(handle, ["images"]);
println("");
println("Images in builder:");
println(images_result.stdout);

// Clean up the container
image.remove();
println("Cleaned up build container");

println("");

// Step 5: Clean up
println("Step 5: Destroying build machine...");
destroy(handle);
println("Build machine destroyed");
println("");

println("=========================");
println("Example completed!");
println("=========================");

"KubeBuilder basic example completed successfully"
