#!/usr/local/bin/perl6
use Shell::Command;
use Panda;
use Panda::Ecosystem;
use Panda::App;

# default opts for MAIN
if %*ENV<PANDA_DEFAULT_OPTS> {
    @*ARGS = %*ENV<PANDA_DEFAULT_OPTS> ~ (@*ARGS ?? ' ' ~ @*ARGS !! '');
}

# initialize the Panda object
my $panda;
{
    my $pandadir;
    my $destdir = %*ENV<DESTDIR>;
    $destdir = "{cwd}/$destdir" if defined($destdir) &&  $*OS ne 'MSWin32' && $destdir !~~ /^ '/' /;
    for grep(*.defined, $destdir, %*CUSTOM_LIB<site home>) -> $prefix {
        $destdir  = $prefix;
        $pandadir = "$prefix/panda";
        try mkpath $pandadir unless $pandadir.IO ~~ :d;
        last if $pandadir.path.w
    }
    unless $pandadir.path.w {
        die "Found no writable directory into which panda could be installed";
    }

    my $ecosystem = Panda::Ecosystem.new(
        statefile    => "$pandadir/state",
        projectsfile => "$pandadir/projects.json",
    );

    $panda = Panda.new(:$ecosystem);
}

# allow switches after positionals
@*ARGS = @*ARGS.grep(/^ '-'/), @*ARGS.grep(/^ <-[-]>/);

#= Install the specified modules
multi MAIN ('install', *@modules, Bool :$notests, Bool :$nodeps) {
    for @modules -> $x {
        #try {
            $panda.resolve($x, :$notests, :$nodeps);
        #    CATCH { when X::Panda { say $_.message } }
        #};
    }
}

#= List all available modules
multi MAIN ('list', Bool :$installed, Bool :$verbose) {
    listprojects($panda, :$installed, :$verbose);
}

#= Update the module database
multi MAIN ('update') {
    $panda.ecosystem.update;
}

#= Display information about specified modules
multi MAIN ('info', *@modules) {
    projectinfo($panda, @modules);
}

#= Search the name/description
multi MAIN ('search', $pattern) {
    search-projects($panda, $pattern);
}

END {
    rm_rf '.work' if '.work'.IO.e;
}

# vim: ft=perl6
