#!/bin/perl --
# run-parts: run a bunch of scripts in a directory

sub version {
    print STDERR <<'END';
Debian GNU/Linux run-parts script, version 0.2.
Distributed with Debian's base system.  Copyright (C) 1994 Ian Jackson.
This is free software; see the GNU General Public Licence version 2
or later for copying conditions.  There is NO warranty.
END
}

sub usage {
    print STDERR
        "usage: run-parts [--test|--help|--version] [--umask=umask] directory\n";
}

$cmd=$0;  $cmd =~ s:^.*/::;  $dir= '';
umask(022);

while ($ARGV[0] =~ m/^-/) {
    $_= shift(@ARGV);
    if (m/^--test$/) { $test=1; }
    elsif (m/^--help$/) { &usage; exit(0); }
    elsif (m/^--version$/) { &version; exit(0); }
    elsif (m/^--umask=0*([0-7]{1,3})$/) { umask(oct($1)); }
    elsif (m/^--$/) { last; }
    else { &usage; exit(3); }
}

if ($#ARGV) { &usage; exit(3); }

$dir= shift(@ARGV);  $dir =~ s:^\s:./$&:;  $exitstatus=0;

opendir(D,$dir) || &quit("failed to open directory $dir: $!");
for $f (sort readdir(D)) {
    next unless $f =~ m/^[-a-zA-Z0-9_]+$/;
    $path= $dir.'/'.$f;
    stat($path) || &quit("failed to stat component $path: $!");
    if (!-f _ || !-x _) {
        warn "$cmd: component $path is not an executable plain file\n";
        $exitstatus= 1;
    } elsif ($test) {
        print("$cmd would run $path\n") || &quit("$cmd: output error: $!");
    } else {
        $!=0; system($path $f);
        if ($? && $!) {
            warn "$cmd: running $path gave exit status $?, error $!\n";
            $exitstatus= 1;
        }
    }
}
closedir(D);

exit($exitstatus);

sub quit {
    print STDERR "$cmd: $_[0]\n";
    exit(2);
}
