# Download ml21-reproduce.R and ml21-source-bundle.zip together.
# Rscript ml21-reproduce.R NEW-OUTDIR [BUNDLE]
args<-commandArgs(trailingOnly=TRUE);if(length(args)<1)stop('NEW-OUTDIR required')
out<-normalizePath(args[1],winslash='/',mustWork=FALSE);bundle<-if(length(args)>1)args[2]else'ml21-source-bundle.zip'
if(dir.exists(out))stop('Choose NEW output directory')
if(!exists('sha256sum',asNamespace('tools')))stop('R4.5+ tools::sha256sum required')
if(unname(tools::sha256sum(bundle))!='d002166441d0b52588ca8181346ef477c2b6fc236bc8c30f85da27e5eb4695af')stop('Bundle SHA256 mismatch')
stage<-tempfile('ml21-source-');dir.create(stage);base<-normalizePath(tempdir(),winslash='/',mustWork=TRUE);resolved<-normalizePath(stage,winslash='/',mustWork=TRUE)
if(!startsWith(tolower(resolved),paste0(tolower(base),'/')))stop('Temporary stage outside intended root')
entries<-unzip(bundle,list=TRUE)$Name
if(any(grepl('(^/|^[A-Za-z]:|(^|/)\\.\\.(/|$))',entries)))stop('Unsafe archive paths')
unzip(bundle,exdir=stage)
status<-system2(file.path(R.home('bin'),'Rscript.exe'),c(shQuote(file.path(stage,'reproduce-causal-representation.R')),shQuote(stage),shQuote(out)))
unlink(resolved,recursive=TRUE)
if(status!=0)stop('Reproduction child failed')
