use crate::core::types::Resource;
pub fn check_script(resource: &Resource) -> String {
let deploy_path = resource.target.as_deref().unwrap_or("/dev/null");
let mut script =
format!("test -x '{deploy_path}' && echo 'installed:build' || echo 'missing:build'");
if let Some(ref check) = resource.completion_check {
script = format!(
"if {check} >/dev/null 2>&1; then echo 'installed:build'; else echo 'missing:build'; fi"
);
}
script
}
pub fn apply_script(resource: &Resource) -> String {
let command = resource.command.as_deref().unwrap_or("true");
let artifact = resource.source.as_deref().unwrap_or("/dev/null");
let deploy_path = resource.target.as_deref().unwrap_or("/tmp/build-artifact");
let build_machine = resource.build_machine.as_deref().unwrap_or("localhost");
let mut script = String::from("set -euo pipefail\n");
let build_cmd = if let Some(ref dir) = resource.working_dir {
format!("cd '{dir}' && {command}")
} else {
command.to_string()
};
if build_machine == "localhost" {
script.push_str(&format!("# Phase 1: build locally\n{build_cmd}\n"));
} else {
script.push_str(&format!(
"# Phase 1: build on {build_machine}\n\
ssh -o BatchMode=yes -o ConnectTimeout=10 '{build_machine}' '{build_cmd}'\n"
));
}
if build_machine != "localhost" {
script.push_str(&format!(
"# Phase 2: transfer artifact\n\
mkdir -p \"$(dirname '{deploy_path}')\"\n\
scp -o BatchMode=yes '{build_machine}:{artifact}' '{deploy_path}'\n\
chmod +x '{deploy_path}'\n"
));
} else {
script.push_str(&format!(
"# Phase 2: copy artifact locally\n\
mkdir -p \"$(dirname '{deploy_path}')\"\n\
cp '{artifact}' '{deploy_path}'\n\
chmod +x '{deploy_path}'\n"
));
}
if let Some(ref check) = resource.completion_check {
script.push_str(&format!("# Phase 3: verify\n{check}\n"));
}
script
}
pub fn state_query_script(resource: &Resource) -> String {
let deploy_path = resource.target.as_deref().unwrap_or("/dev/null");
format!(
"if [ -f '{deploy_path}' ]; then \
sha256sum '{deploy_path}' | awk '{{print $1}}'; \
else echo 'MISSING'; fi"
)
}