#!/usr/bin/perl

use warnings;
use strict;

# Force locale to C since tar may output utf-8 filenames differently
# depending on the locale.
$ENV{LANG} = 'C';

# Don't let environment change tar's behavior.
delete $ENV{TAR_OPTIONS};
delete $ENV{TAPE};

my $tar_program = "tar";

sub unquote_filename {
  my $filename = shift;
  
  my %tar_escapes = (
    'a' => "\a",
    'b' => "\b",
    'f' => "\f",
    'n' => "\n",
    'r' => "\r",
    't' => "\t",
    'v' => "\x11",
    '\\' => '\\',
  );
  $filename =~ s/\\([abfnrtv\\]|[0-9]{3})/$tar_escapes{$1} or chr(oct($1))/ge;

  return $filename;
}

sub genmanifest {
  my $tarball  = shift;
  my $manifest = shift;

  open(IN, "$tar_program --quoting-style=escape -tf $tarball |") || die "tar tf: $!";
  open(OUT, ">", $manifest) || die "$!";
  while (<IN>) {
    chomp;
    # ./ or / in the manifest just confuses tar
    s/^\.?\/+//;
    print OUT unquote_filename($_) . "\0" if length $_;
  }
  close IN;
  close OUT;
}

genmanifest("hazard.tar.gz", "haz_zero");