package util;

require Exporter;
@ISA = qw( Exporter );
@EXPORT = qw( system_ dolog getkeys loadList selfdir );
use Cwd 'abs_path';
use File::Basename;

use strict;
use warnings;

my $SELFDIR = dirname( abs_path( $0 ) );

my $verbose = $ENV{ VERBOSE };

sub dolog {
    print STDERR @_ if $verbose;
}

sub system_ {
    dolog( "+ @_\n" );
    if ( system( @_ ) != 0 ) {
        print STDERR "ERROR: system: @_\n";
        return 0;
    }
    return 1;
}

sub getkeys {
    my ( $hostname ) = @_;
    my @keys = ( "all" );

    push( @keys, "server" ) if ( $hostname =~ m/^a/ );
    push( @keys, "graphical" ) if ( $hostname =~ m/^(pythia|pandora)/ );
    push( @keys, "workers" ) if ( $hostname =~ m/^(pythia|pandora|pheme)/ );
    push( @keys, $hostname =~ s/^([a-z]*).*$/$1/r ) if $hostname =~ /[0-9]$/;
    push( @keys, $hostname );
    return @keys;
}

sub loadList {
    my ( $type, $list ) = @_;

    dolog( "loadList $type/$list\n" );
    open( my $f, "<", "$SELFDIR/$type/$list" ) or return ();
    my @pkgs;
    while ( <$f> ) {
        chomp;
        s/#.*$//;
        chomp;
        next if $_ eq "";
        push( @pkgs, $_ );
    }
    return @pkgs;
}

sub selfdir {
    return $SELFDIR;
}

1;
