#!/usr/local/bin/perl
# desc{ simple wrapper around ungzipping-untarring or tarring/gzipping, with sanity checking }
#
# Simple glue for tarring-gzipping, or ungz-untarring,
#  with some nice sanity checking

use strict;

#die "Where is tar?"  unless -e (my $TAR  = '/usr/bin/tar');
#die "Where is gzip?" unless -e (my $GZIP = '/usr/bin/gzip');
my $TAR = 'tar';
my $GZIP = 'gzip';

my $Debug = 0;

unless(@ARGV == 1) {
  print <<'EOU'; exit;
Usage:
  tgz foo         : creates foo.tar.gz out of foo
  tgz foo.tar.gz  : uncompresses and untars foo.tar.gz into this directory
EOU
}

my $it = $ARGV[0];
die "argument can't be null-string!"
  unless defined $it and length $it;
die "argument \"$it\" must be all alphanumeric!\n"
  unless $it =~ m<^[-\/.a-z0-9A-Z_]+$>s;
die "$it does not exist" unless -e $it;

if(-f $it) {
  my $out = $it;
  unless($out =~ s<\.tar(\.gz)?$><>s) {
    die "$it doesn't end in .tar.gz!"
  }
  
  die "$out already exists!\n" if -e $out;
  my $cl = "$GZIP -d < $it | $TAR xf -";
  print "Running: ", $cl, "\n" if $Debug;
  exec $cl;
} elsif(-d $it) {
  die "$it is not readable!" unless -r $it;
  die "you can't tar the root" if $it eq '/'; # sanity
  $it =~ s</+$><>g;
  die "$it.tar.gz already exists!\n" if -e "$it.tar.gz";
  my $cl = "$TAR cf - $it | $GZIP -9 > $it.tar.gz";
  print "Running: ", $cl, "\n" if $Debug;
  exec $cl;
} else {
  die "$it is neither file nor directory!!\n";
  exit;
}

