use super::helpers::{extract_absolute_binary, service_rid};
use crate::core::shell_escape::sh_squote;
use crate::core::types::{Resource, TaskMode};
use crate::resources::verdict;
pub fn check_script(resource: &Resource) -> String {
if resource.task_mode.as_ref() == Some(&TaskMode::Service) {
let rid = service_rid(resource);
let pidfile = sh_squote(&format!("/tmp/forjar-svc-{rid}.pid"));
let ldd_check = extract_absolute_binary(resource.command.as_deref().unwrap_or(""))
.map(|bin| {
let b = sh_squote(bin);
format!(
"if command -v ldd >/dev/null 2>&1 && [ -f {b} ]; then \
if ldd {b} 2>&1 | grep -q 'not found'; then \
echo 'task=ldd-fail'; exit 1; fi; fi; "
)
})
.unwrap_or_default();
return format!(
"{ldd_check}{}",
verdict::single(
&format!("[ -f {pidfile} ] && kill -0 \"$(cat {pidfile})\" 2>/dev/null"),
"task=completed",
"task=pending",
)
);
}
if let Some(ref check) = resource.completion_check {
return verdict::single(check, "task=completed", "task=pending");
}
if !resource.output_artifacts.is_empty() {
let base = crate::core::task::probe::probe_base_dir(resource);
let assertions: Vec<String> = resource
.output_artifacts
.iter()
.map(|a| {
let resolved = crate::core::task::probe::resolve_under(&base, a);
let path = if base == std::path::Path::new(".") {
a.clone()
} else {
resolved.to_string_lossy().into_owned()
};
verdict::assert_that(
&format!("[ -e {} ]", sh_squote(&path)),
&format!("task=completed:{a}"),
&format!("task=pending:{a}"),
)
})
.collect();
return verdict::check_script_from(&assertions);
}
verdict::check_script_from(&[verdict::always_diverged("task=pending")])
}
pub(super) fn pipeline_script(resource: &Resource) -> String {
let mut script = String::from("set -euo pipefail\n");
if let Some(ref dir) = resource.working_dir {
script.push_str(&format!("cd {}\n", sh_squote(dir)));
}
script.push_str("FORJAR_PIPELINE_OK=0\n");
for (i, stage) in resource.stages.iter().enumerate() {
let cmd = stage.command.as_deref().unwrap_or("true");
let name = if stage.name.is_empty() {
format!("stage-{i}")
} else {
stage.name.clone()
};
script.push_str(&format!(
"echo {}\n",
sh_squote(&format!("=== Stage: {name} ==="))
));
if stage.gate {
script.push_str(&format!(
"if ! bash -c '{cmd}'; then\n echo {}\n exit 1\nfi\n",
sh_squote(&format!("GATE FAILED: {name}"))
));
} else {
script.push_str(&format!("{cmd}\n"));
}
}
script
}