#!/usr/bin/env perl
use strict;
use warnings;
use v5.16;

use English;
use File::Basename;
use File::Slurp;
use IPC::Open3;
use POSIX;
use Symbol 'gensym';

my %stdout_status;
my %stderr_status;

undef $INPUT_RECORD_SEPARATOR;  # slurp whole file handle contents

for my $f (glob('/usr/bin/*')) {
    my $bnf = basename($f);
    next if $bnf =~ m{(
        sh$|                    # ignore shells; they tend to go interactive
        ^byobu|tmux|screen|     # ditto terminal managers
        nano|pico|^vi|          # ditto text editors
        nslookup|               # enters a command shell
        ^snmp|                  # ditto; macOS specific
        doas|sudo|              # these assume all args are shell commands
        purge-old-kernels|      # calls sudo
        debconf-apt-progress|   # takes over terminal
        yes                     # runs forever spamming "yes" at us
    )}x;
    waitpid(open3(undef, my $out, my $err = gensym,
            'timeout', 1, $f, '--help'), 0);
    if (<$out> =~ /(options|usage)/i) {
        $stdout_status{WEXITSTATUS($CHILD_ERROR)}++;
    }
    elsif (<$err> =~ /(options|usage)/i) {
        $stderr_status{WEXITSTATUS($CHILD_ERROR)}++;
    }
    else {
        say STDERR "$bnf --help gives no usage message!"
    }
}

say "STDOUT Status\tCount";
for my $s (sort(keys(%stdout_status))) {
    say $s, "\t\t", $stdout_status{$s};
}
say "\nSTDERR Status\tCount";
for my $s (sort(keys(%stderr_status))) {
    say $s, "\t\t", $stderr_status{$s};
}
