#!/usr/bin/perl
# Targz Unpack
#
# This script will convert a legacy tarball into an unpacked source
# directory and pristine-tar metafile that can be used to recreate the
# original tarball (with the same MD5 signature).
#
# This is meant to be a one-time process for converting the file; this
# script is *not* part of the build process.
#
# Usage:
#   --help          Print out a usage message
#   --verbose       Print out extra progress and status messages
#

use strict;
use warnings;

use File::Path   ();
use Getopt::Long ();

my $opt_help;
my $opt_verbose;
my $result = Getopt::Long::GetOptions(
    'help'    => \$opt_help,
    'verbose' => \$opt_verbose,
);

if ($opt_help) {
    print_usage();
    exit;
}

if ( !@ARGV ) {
    print "You must specify a tarball to unpack.\n";
    print_usage();
    exit 1;
}

for my $tgz (@ARGV) {
    process_tgz($tgz);
}

sub process_tgz {
    my ($tarball_path) = @_;
    if ( !-e $tarball_path ) {
        die "No such tarball: $tarball_path\n";
    }
    if ( !-f $tarball_path or $tarball_path !~ /\.pm(?:\.patch)?\.tar\.gz/ ) {
        die "Does not appear to be a tarball: $tarball_path\n";
    }

    print "Processing $tarball_path...\n";

    # Clean up the existing pristine-tar file, if any
    my $ptar = $tarball_path . '.ptar';
    if ( -e $ptar && !unlink $ptar ) {
        die "Pristine-tar file $ptar exists and cannot be removed\n";
    }

    # Clean up the existing unpacked-source directory, if any
    my $dir = $tarball_path . '.d';
    if ( -e $dir && !File::Path::remove_tree($dir) ) {
        die "Directory $dir exists and cannot be removed\n";
    }

    system( 'pristine-tar', 'gendelta', $tarball_path, $ptar ) == 0
      or die "Failed to create pristine-tar file";

    mkdir $dir
      or die "Failed to create unpacked source directory: $!\n";
    my $cwd = Cwd::cwd();
    chdir $dir
      or die "Cannot use directory $dir: $!";
    ( my $tarball_file = $tarball_path ) =~ s{^.*/}{};
    system( 'tar', 'xzf', "../$tarball_file" ) == 0
      or die "Failed to extract contents of tarball $tarball_path\n";
    chdir $cwd
      or die "Cannot use directory $cwd: $!";
}

sub print_usage {
    print <<"USAGE";

$0 [ --help ] [ --verbose ]
    --help          Print out a usage message
    --verbose       Print progress messages during processing

USAGE
}
