#!/usr/bin/env herodo
// Buildah Fluent API Example
// Demonstrates how to build an image using the fluent API spec

// Helper function to check if buildah is available
fn is_buildah_available() {
    try {
        let result = run("buildah --version").execute();
        return result.success;
    } catch(err) {
        return false;
    }
}

print("=== Buildah Fluent API Example ===");

// Check if buildah is available
let buildah_available = is_buildah_available();
if !buildah_available {
    print("Buildah is not available. Skipping Buildah example.");
    return;
}

print("✓ Buildah is available");

// Cleanup any existing container/image first
try {
    run("buildah rm webserver").execute();
} catch(e) {}

try {
    run("buildah rmi my-webserver:latest").execute();
} catch(e) {}

print("Building a web server image...");

// Build a web server image - FLUENT API EXAMPLE
let nginx_conf = "server {\n    listen 80;\n    root /var/www/html;\n}\n";

let b = bah("webserver", "alpine:latest")
    .run("apk update")
    .run("apk add --no-cache nginx")
    .run("mkdir -p /var/www/html")
    .write(nginx_conf, "/etc/nginx/conf.d/default.conf")
    .write("<h1>Hello World</h1>", "/var/www/html/index.html")
    .entrypoint("/usr/sbin/nginx")
    .cmd("-g 'daemon off;'")
    .commit("my-webserver:latest");

// Check if commit succeeded
if b.success {
    print("✓ Image built successfully!");
    print("  Image ID: " + b.stdout);
} else {
    print("✗ Image build failed!");
    print("  Error: " + b.stderr);
}

// Clean up
print("Cleaning up...");
b.remove();

// Remove the test image
try {
    run("buildah rmi my-webserver:latest").execute();
} catch(e) {}

print("\n=== Buildah Fluent API Example Complete ===");
