#!/usr/bin/perl

use Fcntl qw(F_GETFD F_SETFD FD_CLOEXEC);
use Getopt::Std;
my %opt;
getopts("", \%opt) or usage();

my $command = shift @ARGV
  or usage();
my $pat = '\.gz$';

my @fh;

for my $file (@ARGV) {
  if ($file =~ /$pat/o && -f $file) {
    my $fh;
    unless (open($fh, "-|", "gzip", "-cd", $file)) {
      warn "Couldn't open file '$file': $!; skipping\n";
      next;
    }
    push @fh, $fh;
    my $fd = fileno $fh;
    my $flags = fcntl($fh, F_GETFD, 0);
    fcntl($fh, F_SETFD, $flags & ~FD_CLOEXEC);
    my $oldfile = $file;
    $file = "/proc/self/fd/$fd";
#    warn "$oldfile -> $file\n";
  }
}

# warn "running $command @ARGV\n";
exec $command, @ARGV;
die "Couldn't run '$command': $!.\n";

sub usage {
  print STDERR "Usage: $0 command args...\n";
  exit 1;
}





