#!/usr/bin/env perl6
use v6;
use JSON::Fast;
use Bailador::CLI;

multi sub MAIN(Bool :$help) {
	usage();
}

multi sub MAIN(Str :$new) {
#	if not $new -> {
#		usage("Project-Name is a required parameter");
#	}
	say "Generating $new";
	if $new.IO.e {
		say "$new already exists. Exiting.";
		exit;
	}
	mkdir $new;
	my %skeleton = skeleton();
	#say %skeleton;

	for %skeleton.keys -> $file {
		say $file;
		if $file.rindex('/')
		{
			my $sep = $file.rindex('/');
			my $dir = $file.substr(0, $sep);
			mkdir "$new/$dir";
		}
		spurt "$new/$file", %skeleton{$file};
	}
}

multi sub MAIN('version') {
	my $root = $*PROGRAM.absolute.IO.dirname;
	$root = $root.IO.dirname;
	my $meta_filename = "$root/../Bailador/META6.json";
	my $json = $meta_filename.IO.slurp: :close;
	my $version = from-json($json)<version>;
	say "Bailador " ~ $version;
}

multi sub MAIN ( Str $app, Str :$w = 'lib,bin') {
    my @watchlist = $w.split: /<!after \\> \,/;
    s/\\\,/,/ for @watchlist;

    say "Attempting to boot up the app";
    my $p = bootup-app $app;
    react {
        whenever watch-recursive(@watchlist.grep: *.IO.e) -> $e {
            if $e.path() !~~ /\.sw.$/ and $e.path() !~~ /\~$/ {
                say "Change detected [$e.path(), $e.event()]. Restarting app";
                $p.kill;
                $p = bootup-app $app;
            }
        }
    }
}
