#! /nix/store/3vpjybwkizvyqp0pif5x91lzsha0189v-perl-5.24.3/bin/perl -w -I/nix/store/y9mfv3sx75mbfibf1zna1kq9v98fk2nb-nix-1.11.16/lib/perl5/site_perl/5.24.3/aarch64-linux-thread-multi -I/nix/store/0hzl2h5v2giwakz6livcvjffh5s235gh-perl-DBI-1.636/lib/perl5/site_perl -I/nix/store/1jjwnyfb277hk2cg4m5nyi0qkv6hy4af-perl-DBD-SQLite-1.54/lib/perl5/site_perl -I/nix/store/7zsxk1bk62hzav0r6nxc8nwkg39l0pl1-perl-WWW-Curl-4.17/lib/perl5/site_perl

use strict;
use Nix::Manifest;
use Nix::GeneratePatches;
use Nix::Utils;

if (scalar @ARGV != 5) {
    print STDERR <<EOF;
Usage: nix-generate-patches NAR-DIR PATCH-DIR PATCH-URI OLD-MANIFEST NEW-MANIFEST

This command generates binary patches between NAR files listed in
OLD-MANIFEST and NEW-MANIFEST.  The patches are written to the
directory PATCH-DIR, and the prefix PATCH-URI is used to generate URIs
for the patches.  The patches are added to NEW-MANIFEST.  All NARs are
required to exist in NAR-DIR.  Patches are generated between
succeeding versions of packages with the same name.
EOF
    exit 1;
}

my $narPath = $ARGV[0];
my $patchesPath = $ARGV[1];
my $patchesURL = $ARGV[2];
my $srcManifest = $ARGV[3];
my $dstManifest = $ARGV[4];

my (%srcNarFiles, %srcLocalPaths, %srcPatches);
readManifest $srcManifest, \%srcNarFiles, \%srcPatches;

my (%dstNarFiles, %dstLocalPaths, %dstPatches);
readManifest $dstManifest, \%dstNarFiles, \%dstPatches;

my $tmpDir = mkTempDir("nix-generate-patches");

generatePatches \%srcNarFiles, \%dstNarFiles, \%srcPatches, \%dstPatches,
    $narPath, $patchesPath, $patchesURL, $tmpDir;

propagatePatches \%srcPatches, \%dstNarFiles, \%dstPatches;

# Optionally add all new patches to the manifest in $NIX_ALL_PATCHES.
my $allPatchesFile = $ENV{"NIX_ALL_PATCHES"};
if (defined $allPatchesFile) {
    my (%dummy, %allPatches);
    readManifest("$patchesPath/all-patches", \%dummy, \%allPatches)
        if -f $allPatchesFile;
    copyPatches \%dstPatches, \%allPatches;
    writeManifest($allPatchesFile, {}, \%allPatches, 0);
}

writeManifest $dstManifest, \%dstNarFiles, \%dstPatches;
