package SI::tools;

use if $ENV{DEBUG} ~~ /tools|all/ => "Smart::Comments";

use strict;
use warnings;
use File::Find;
use Data::Dumper;
use base "Exporter";

our @EXPORT = qw(&run &verbose &find_by_devid &cat &barf &def);

sub run(@) {
    system(@_);
    die "$_[0] failed with exit code " . ($? >> 8) . "\n"
      if $?;
}

sub def($$) {
    return defined $_[1] ? $_[1] : $_[0];
}

sub barf(@) { die Dumper @_ }

sub cat($) {
    my $fh = new IO::File $_[0]
      or die "Can't open $_[0]: $!\n";
    return (<$fh>) if wantarray;
    return join "", <$fh>;
}

my $last = "\n";

sub verbose(@) {
    print $last eq "\n" ? "" : " "
      if not(@_ == 1 and length($_[0]) == 1);
    print @_;
    $last = substr($_[-1], -1, 1);
}

sub find_by_devid($$) {
    my ($dir, $id) = @_;
    my @found;
    find(
        sub {
            push @found, $File::Find::name if (stat)[6] == $id;
            return;
        },
        $dir
    );
    die "ERR: found more than one alias (@found) for $id\n" if @found > 1;
    die "ERR: found no alias for $id\n" if not @found;
    return $found[0];
}

1;

# vim:sts=4 sw=4 aw ai si:
