### ----------------------------------------------------
### -- XDG::GuaranteedResources
### -- Licenses: MIT
### -- Authors: masukomi <masukomi@masukomi.org>
### -- File: t/01-basic.rakutest
### ----------------------------------------------------
use Test;
use File::Directory::Tree;
use lib 'lib';
use XDG::GuaranteedResources;
use XDG::GuaranteedResources::InternalTestResourcer;

sub create-base-dir() returns IO::Path {
	my $base = $*CWD.child(".test_" ~ $*PID);
	$base.mkdir;
	return $base;
}


my $resourcer = XDG::GuaranteedResources::InternalTestResourcer;
my $base = create-base-dir();
# Only supports CONFIG and DATA
%*ENV<XDG_CONFIG_HOME> = $base.child('.config').Str;
%*ENV<XDG_DATA_HOME> = $base.child($*SPEC.catfile('.local', 'share')).Str;

# sanity check...
is(%*ENV<XDG_CONFIG_HOME>.IO.e, False, (%*ENV<XDG_CONFIG_HOME> ~ " shouldn't exist yet"));
is(%*ENV<XDG_DATA_HOME>.IO.e, False, (%*ENV<XDG_DATA_HOME> ~ " shouldn't exist yet"));

# test that it copies things
is(guarantee-resource("config/xdg-gr/config_file.test", $resourcer).IO.e, True, "top level config file");
is(guarantee-resource("data/xdg-gr/data_file.test", $resourcer).IO.e, True, "top level data file");
is(guarantee-resource("data/xdg-gr/data_subdir/data_subdir_file.test", $resourcer).IO.e, True, "data file in subdirectory");
dies-ok({guarantee-resource("data/xdg-gr/non_existent_file.test", $resourcer)});
#ok(guarantee-resource("data/xdg-gr/non_existent_file.test"));

# test that it doesn't overwrite existing things
my $pre_existing_file_path = IO::Spec::Unix.catpath($, %*ENV<XDG_CONFIG_HOME>,  "config_file.test");
my $fh = open ($pre_existing_file_path), :w;
$fh.print("existing_stuff");
$fh.close;

is(guarantee-resource("config/xdg-gr/config_file.test", $resourcer).IO.e, True, "top level config file");
$fh = open $pre_existing_file_path, :r;
my $contents = $fh.slurp;
$fh.close;
is($contents, "existing_stuff", "contents overwritten");

rmtree($base) if $base.e;

$base = create-base-dir();
my @paths = guarantee-resources(<config/xdg-gr/config_file.test data/xdg-gr/data_subdir/data_subdir_file.test>, $resourcer);
for @paths -> $path {
	ok($path.IO.e);
}


shell("tree $base");
END {
	rmtree($base) if $base.e
}

done-testing;


