// File: /root/code/git.threefold.info/herocode/sal/src/virt/nerdctl/health_check_script.rs

use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;

/// Handles health check scripts for containers
///
/// This module provides functionality to create and manage health check scripts
/// for containers, allowing for more complex health checks than simple commands.

/// Converts a health check command or script to a usable command
///
/// If the input is a single-line command, it is returned as is.
/// If the input is a multi-line script, it is written to a file in the
/// /root/hero/var/containers directory and the path to that file is returned.
///
/// # Arguments
///
/// * `cmd` - The command or script to convert
/// * `container_name` - The name of the container, used to create a unique script name
///
/// # Returns
///
/// * `String` - The command to use for the health check
pub fn prepare_health_check_command(cmd: &str, container_name: &str) -> String {
    // If the command is a multiline script, write it to a file
    if cmd.contains("\n") {
        // Create the directory if it doesn't exist
        let dir_path = "/root/hero/var/containers";
        if let Err(_) = fs::create_dir_all(dir_path) {
            // If we can't create the directory, just use the command as is
            return cmd.to_string();
        }

        // Create a unique filename based on container name
        let script_path = format!("{}/healthcheck_{}.sh", dir_path, container_name);

        // Write the script to the file
        if let Err(_) = fs::write(&script_path, cmd) {
            // If we can't write the file, just use the command as is
            return cmd.to_string();
        }

        // Make the script executable
        if let Ok(metadata) = fs::metadata(&script_path) {
            let mut perms = metadata.permissions();
            perms.set_mode(0o755);
            if let Err(_) = fs::set_permissions(&script_path, perms) {
                // If we can't set permissions, just use the script path with sh
                return format!("sh {}", script_path);
            }
        } else {
            // If we can't get metadata, just use the script path with sh
            return format!("sh {}", script_path);
        }

        // Use the script path as the command
        script_path
    } else {
        // If it's a single line command, use it as is
        cmd.to_string()
    }
}

/// Cleans up health check scripts for a container
///
/// # Arguments
///
/// * `container_name` - The name of the container whose health check scripts should be cleaned up
pub fn cleanup_health_check_scripts(container_name: &str) {
    let dir_path = "/root/hero/var/containers";
    let script_path = format!("{}/healthcheck_{}.sh", dir_path, container_name);

    // Try to remove the script file if it exists
    if Path::new(&script_path).exists() {
        let _ = fs::remove_file(script_path);
    }
}
