from test/more import *;

requires_capability( "fs" );

from std/archive import Archive;
from std/io import Path;
from std/proc import Env;
from std/proc import Proc;
from std/zuzuzoo import Zuzuzoo;

function ensure_dir ( path ) {
	return true if path.exists();
	let parent := path.parent();
	ensure_dir(parent) if not parent.exists();
	path.mkdir();
	return true;
}

function root () {
	let dir := Path.tempdir();
	let lib := dir.child("lib");
	let bin := dir.child("bin");
	let meta := dir.child("meta");
	ensure_dir(lib);
	ensure_dir(bin);
	ensure_dir(meta);
	return {
		dir_obj: dir,
		lib_obj: lib,
		meta_obj: meta,
		lib_dir: lib.to_String(),
		bin_dir: bin.to_String(),
		meta_dir: meta.to_String(),
	};
}

let archive := Path.tempfile();
Archive.dump(
	archive,
	{
		entries: [
			{
				path: "atomic-app-1.0.0/zuzu-distribution.json",
				data: to_binary(
					"{\"name\":\"atomic-app\",\"version\":\"1.0.0\"," _
					"\"author\":\"Example\",\"license\":\"MIT\"}\n",
				),
			},
			{
				path: "atomic-app-1.0.0/modules/good.zzm",
				data: to_binary("// good\n"),
			},
			{
				path: "atomic-app-1.0.0/modules/block/path.zzm",
				data: to_binary("// blocked\n"),
			},
		],
	},
	"zip",
);

let target := root();
target{lib_obj}.child("block").spew_utf8("not a directory\n");

let child := Path.tempfile();
child.spew_utf8(
	"from std/zuzuzoo import Zuzuzoo;\n" _
	"( new Zuzuzoo(\n" _
	"  lib_dir: \"" _ target{lib_dir} _ "\",\n" _
	"  bin_dir: \"" _ target{bin_dir} _ "\",\n" _
	"  meta_dir: \"" _ target{meta_dir} _ "\",\n" _
	"  home: \"" _ Path.tempdir().to_String() _ "\"\n" _
	") ).install( \"" _ archive.to_String() _ "\", { no_test: true } );\n",
);

let argv := __system__{inc}.map( fn d -> "-I" _ d );
argv.push( child.to_String() );

let run := Proc.run(
	( new Path( path: Env.get( "ZUZU", "./bin/zuzu" ) ) ).to_String(),
	argv,
	{
		capture_stdout: true,
		capture_stderr: true,
	},
);

ok( not Proc.is_success(run), "blocked install process fails" );
like(
	run{stderr} _ run{stdout},
	/block/,
	"install failure reports blocked destination",
);
ok(
	not target{meta_obj}.child("atomic-app-1.0.0.json").exists(),
	"metadata is not written after an install file failure",
);

done_testing();
