#!/usr/bin/perl

=head1 NAME

pristine-gz - regenerate pristine gz files

=head1 SYNOPSIS

B<pristine-gz> [OPTIONS] gendelta I<file.gz> I<delta>

B<pristine-gz> [OPTIONS] gengz I<delta> I<file>

=head1 DESCRIPTION

This is a complement to the pristine-tar(1) command. Normally you don't
need to run it by hand, since pristine-tar calls it as necessary to handle
.tar.gz files.

pristine-gz gendelta takes the specified I<gz> file, and generates a
small binary I<delta> file that can later be used by pristine-gz gengz
to recreate the original file.

pristine-gz gengz takes the specified I<delta> file, and compresses
the specified input I<file> (which must be identical to the contents
of the original gz file). The resulting file will be identical to
the original gz file used to create the delta.

The approach used to regenerate the original gz file is to figure out how
it was produced -- what compression level was used, whether it was built
with GNU gzip(1) or with a library or BSD version, whether the --rsyncable
option was used, etc, and to reproduce this build environment when
regenerating the gz.

This approach will work for about 99.5% of cases. One example of a case it
cannot currently support is a gz file that has been produced by appending
together multiple gz files.

For the few where it doesn't work, a binary diff will be included in the
delta between the closest regneratable gz file and the original. In
the worst case, the diff will include the entire content of the original
gz file, resulting in a larger than usual delta. If the delta is much
larger than usual, pristine-gz will print a warning.

If the delta filename is "-", pristine-gz reads or writes it to stdio.

=head1 OPTIONS

=over

=item -v

=item --verbose

Verbose mode, show each command that is run.

=item -d

=item --debug

Debug mode.

=item -k

=item --keep

Don't clean up the temporary directory on exit.

=back

=head1 ENVIRONMENT

=over

=item B<TMPDIR>

Specifies a location to place temporary files, other than the default.

=back

=head1 AUTHOR

Joey Hess <joeyh@debian.org>,
Faidon Liambotis <paravoid@debian.org>
Josh Triplett <josh@joshtriplett.org>

Licensed under the GPL, version 2.

=cut

use warnings;
use strict;
use Pristine::Tar;
use Pristine::Tar::Delta;
use Pristine::Tar::Formats;
use Pristine::Tar::DeltaTools;
use File::Basename qw/basename/;

delete $ENV{GZIP};

use constant {
  NODELTA => "2.0",
  XDELTA  => "3.0",
  XDELTA3 => "4",
};

my $genversion =
  version_from_env(XDELTA3, "xdelta" => XDELTA, "xdelta3" => XDELTA3);

# consider deltas < 10KB as small enough to be used immediately
my $good_enough_delta = 10 * 1024;

dispatch(
  commands => {
    usage    => [ \&usage ],
    gendelta => [ \&gendelta, 2 ],
    gengz    => [ \&gengz, 2 ],
  },
);

sub usage {
  print STDERR "Usage: pristine-gz [OPTIONS] gendelta file.gz delta
       pristine-gz [OPTIONS] gengz delta file
Options:
       -d, --debug            Turn on debugging output
       -v, --verbose          Turn on verbose output
       -k, --keep             Don't delete temporary files
       -h, --help             Display usage information
"
}

sub readgzip {
  my $filename = shift;

  if (!is_gz($filename)) {
    error "This is not a valid GZip archive.";
  }

  open(GZIP, "< $filename")
    or die("Could not open '$filename' for reading: $!\n");

  my $chars;
  if (read(GZIP, $chars, 10) != 10) {
    die("Unable to read 10 bytes from input\n");
  }

  my ($id1, $id2, $method, $flags, $timestamp, $level, $os, $name) =
    (unpack("CCCb8VCC", $chars), '');

  my @flags = split(//, $flags);

  if ($flags[ $fconstants{GZIP_FLAG_FNAME} ]) {
    # read a null-terminated string
    $name .= $chars while (read(GZIP, $chars, 1) == 1 && ord($chars) != 0);
  }
  close(GZIP);

  return (\@flags, $timestamp, $level, $os, $name);
}

sub predictgzipargs {
  my ($flags, $timestamp, $level) = @_;
  my @flags = @$flags;

  my @args;
  unless ($flags[ $fconstants{GZIP_FLAG_FNAME} ]) {
    push @args, '-n';
    push @args, '-M' if $timestamp;
  }

  if ($level == $fconstants{GZIP_COMPRESSION_BEST}) {
    push @args, '-9';
  } elsif ($level == $fconstants{GZIP_COMPRESSION_FAST}) {
    push @args, '-1';
  }

  return @args;
}

sub reproducegz {
  my ($orig, $tempdir, $tempin) = @_;
  my $tempout = "$tempdir/test.gz";
  doit_redir($orig, $tempin, "gzip", "-dc");

  # read fields from gzip headers
  my ($flags, $timestamp, $level, $os, $name) = readgzip($orig);
  debug("flags: ["
      . join(", ", @$flags)
      . "] timestamp: $timestamp level: $level os: $os name: $name");

  # try to guess the gzip arguments that are needed by the header
  # information
  my @args = predictgzipargs($flags, $timestamp, $level);
  my @extraargs = ("-F", $name, "-T", $timestamp);

  debug("args = " . join(" ", @args));
  debug("extraargs = " . join(" ", @extraargs));

  my @try;

  push @try, [ '--gnu', @args ];
  push @try, [ '--gnu', @args, '--rsyncable' ];
  push @try, [ '--gnu', @args, '--new-rsyncable' ];
  push @try, [ '--gnu', @args, '--16-rsyncable' ];

  if ($name =~ /\//) {
    push @args, "--original-name", $name;
    @extraargs = ("-T", $timestamp);
    $name = basename($name);
  }

  # set the Operating System flag to the one found in the original
  # archive
  push @args, ("--osflag", $os) if $os != $fconstants{GZIP_OS_UNIX};

  # many of the .gz out there are created using the BSD version of
  # gzip which is using the zlib library; try with our version of
  # bsd-gzip with added support for the undocumented GNU gzip options
  # -m and -M
  push @try, [@args];

  # Perl's Compress::Raw::Zlib interfaces directly with zlib and
  # apparently is the only implementation out there which tunes a very
  # specific parameter of zlib, memLevel, to 9, instead of 8 which is
  # the default. The module is used, among others, by Compress::Gzip
  # which in turn is used by IO::Zlib. It was found on the real world on
  # tarballs generated by Perl 5.10's Module::Build (cf. #618284)
  push @try, [ @args, '--quirk', 'perl' ];
  push @try, [ @args, '--quirk', 'perl', '-1' ];

  # apparently, there is an old version of bsd-gzip (or a similar tool
  # based on zlib) that creates gz using maximum compression (-9) but
  # does not indicate so in the headers. surprisingly, there are many
  # .gz out there.
  push @try, [ @args, '--quirk', 'buggy-bsd' ];

  # Windows' NTFS gzip implementation; quirk is really really evil
  # it should be the last test: it can result in a corrupted archive!
  if ($os == $fconstants{GZIP_OS_NTFS}) {
    pop @args;
    pop @args;    # ntfs quirk implies NTFS osflag
    push @try, [ @args, '--quirk', 'ntfs' ];
  }

  my $origsize = (stat($orig))[7];
  my ($bestvariant, $bestsize);

  foreach my $variant (@try) {
    debug("Trying: " . join(", ", @$variant));
    doit_redir($tempin, $tempout, 'zgz', @$variant, @extraargs, '-c');
    if ($genversion == XDELTA && !comparefiles($orig, $tempout)) {
      # TODO: Remove when xdelta is phased out.
      # only generate NODELTA files when XDELTA would be used otherwise
      return $name, $timestamp, undef, NODELTA, @$variant;
    } else {
      # generate a binary delta and see if this is the best variant so far
      my $ret;
      if ($genversion == XDELTA3) {
        $ret = try_xdelta3_diff($tempout, $orig, "$tempdir/tmpdelta");
      } elsif ($genversion == XDELTA) {
        $ret = try_xdelta_diff($tempout, $orig, "$tempdir/tmpdelta");
      } else {
        die "Unknown delta version $genversion. Internal error.";
      }
      if ($ret == 0) {
        my $size = (stat("$tempdir/tmpdelta"))[7];
        if (!defined $bestsize || $size < $bestsize) {
          $bestvariant = $variant;
          $bestsize    = $size;
          rename("$tempdir/tmpdelta", "$tempdir/bestdelta") || die "rename: $!";
        }
        # TODO: investigate #871938: zgz fails to reproduce its output.
        # if ($size <= $good_enough_delta) {
        #  last;
        # }
      }
    }
  }

  # Nothing worked perfectly, so use the delta that was generated for
  # the best variant
  my $percentover = 100 - int(($origsize - $bestsize) / $origsize * 100);
  debug("Using delta to best variant, bloating $percentover%: @$bestvariant");
  if ($percentover > 10 && $bestsize > $good_enough_delta) {
    print STDERR "warning: pristine-gz cannot reproduce build of $orig; ";
    if ($percentover >= 100) {
      print STDERR "storing entire file in delta!\n";
    } else {
      print STDERR
        "storing $percentover% size diff in delta ($bestsize bytes)\n";
    }
    print STDERR
"(Please consider filing a bug report so the delta size can be improved.)\n";
  }
  return $name, $timestamp, "$tempdir/bestdelta", $genversion, @$bestvariant;
}

sub gengz {
  my $deltafile = shift;
  my $file      = shift;

  my $delta = Pristine::Tar::Delta::read(Tarball => $deltafile);
  Pristine::Tar::Delta::assert(
    $delta,
    type       => "gz",
    maxversion => XDELTA3,
    fields     => [qw{params filename timestamp}]
  );

  my @params = split(' ', $delta->{params});
  while (@params) {
    $_ = shift @params;
    next if /^(--gnu|--rsyncable|--new-rsyncable|--16-rsyncable|-[nmM1-9])$/;
    if (/^(--original-name|--quirk|--osflag)$/) {
      shift @params;
      next;
    }
    die "paranoia check failed on params from delta ($_)";
  }
  @params = split(' ', $delta->{params});

  my $filename = $delta->{filename};
  $filename =~ s/^.*\///;    # basename isn't strong enough

  my @zgz = ("zgz", @params, "-T", $delta->{timestamp});
  if (!grep { $_ eq "--original-name" } @params) {
    push @zgz, "-F", $filename;
  }
  push @zgz, "-c";

  my $version = $delta->{version};
  if (!exists $delta->{delta}) {
    die "Unknown format: $version!" if !($version eq NODELTA);
    doit_redir($file, "$file.gz", @zgz);
  } else {
    my $tempdir = tempdir();
    my $tfile   = "$tempdir/" . basename($file) . ".gz";
    doit_redir($file, $tfile, @zgz);
    if ($version eq XDELTA3) {
      do_xdelta3_patch($tfile, $delta->{delta}, "$file.gz");
    } elsif ($version eq XDELTA) {
      do_xdelta_patch($tfile, $delta->{delta}, "$file.gz");
    } else {
      die "Unknown format: $version!";
    }
  }
  doit("rm", "-f", $file);
}

sub gendelta {
  my $gzfile    = shift;
  my $deltafile = shift;

  my $tempdir = tempdir();
  my ($filename, $timestamp, $xdelta, $version, @params) =
    reproducegz($gzfile, $tempdir, "$tempdir/test");

  Pristine::Tar::Delta::write(
    Tarball => $deltafile,
    {
      version   => $version,
      type      => 'gz',
      params    => "@params",
      filename  => basename($filename),
      timestamp => $timestamp,
      (defined $xdelta ? (delta => $xdelta) : ()),
    }
  );
}
