#!/usr/bin/env herodo
// 08__web_server.rhai
// Demonstrates a complete workflow to set up a web server using 
// Note: This script requires  to be installed and may need root privileges

if which("nerdctl") == "" || which("runc") == "" || which("buildah") == "" {
    print("SKIPPED: nerdctl/runc/buildah are required");
    exit(0);
}
println("Starting  web server workflow...");

// Create and use a temporary directory for all files
let work_dir = "/tmp/";
mkdir(work_dir);
chdir(work_dir);
println(`Working in directory: ${work_dir}`);


println("\n=== Creating custom nginx configuration ===");
let config_content = `
server {
    listen 80;
    server_name localhost;

    location / {
        root /usr/share/nginx/html;
        index index.html;
    }
}
`;

let config_file = `${work_dir}/custom-nginx.conf`;
// Use file_write instead of run command
file_write(config_file, config_content);
println(`Created custom nginx configuration file at ${config_file}`);

// Step 3: Create a custom index.html file
println("\n=== Creating custom index.html ===");
let html_content = `
<!DOCTYPE html>
<html>
<head>
    <title>Demo</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 40px;
            line-height: 1.6;
            color: #333;
        }
        h1 {
            color: #0066cc;
        }
    </style>
</head>
<body>
    <h1>Hello from HeroScript !</h1>
    <p>This page is served by an Nginx container.</p>
</body>
</html>
`;

let html_file = `${work_dir}/index.html`;
// Use file_write instead of run command
file_write(html_file, html_content);
println(`Created custom index.html file at ${html_file}`);

println("\n=== Creating nginx container ===");
let container_name = "nginx-demo";

let env_map = #{}; // Create an empty map
env_map["NGINX_HOST"] = "localhost";
env_map["NGINX_PORT"] = "80";
env_map["NGINX_WORKER_PROCESSES"] = "auto";

// Create a container with a rich set of options using batch methods
let container = nerdctl_container_from_image(container_name, "nginx:latest")
    .reset()
    .with_detach(true)
    .with_ports(["8080:80"])                // Add multiple ports at once
    .with_volumes([`${work_dir}:/usr/share/nginx/html`, "/var/log:/var/log/nginx"])  // Mount our work dir
    .with_envs(env_map)               // Add multiple environment variables at once
    .with_cpu_limit("1.0")
    .with_memory_limit("512m")
    .start();


println("\n web server workflow completed successfully!");
println("The web server is running at http://localhost:8080");

"Web server script completed successfully!"
