#!/usr/bin/perl
# Make Targz
#
# This script will create the EasyApache tarballs from their unpacked source, and
# generate the targz.yaml file containing all the MD5 checksums for the tarballs.
#
# Usage:
#   --help          Print out a usage message
#   --verbose       Print progress messages during processing
#

use strict;
use warnings;

use Cwd          ();
use Digest::MD5  ();
use Digest::SHA  ();
use File::Find   ();
use Getopt::Long ();
use YAML         ();

{
    no warnings 'once';
    $YAML::SortKeys = 2;
}

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

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

if ( !-d '.git' or !-d 'targz' ) {
    print "This script must be run from the root directory of an EasyApache git repo.\n";
    exit 1;
}

my $cwd        = Cwd::cwd();
my $targz_dir  = "$cwd/targz";
my $targz_file = "$cwd/targz.yaml";

gen_targz_file();

exit;

sub gen_targz_file {
    my %md5    = ( '_hashref' => 1 );
    my %sha512 = ( '_hashref' => 1 );

    my $find_sub = sub {
        if ( $_ =~ /\.pm/ && $_ =~ /\.tar\.gz/ && -f $_ ) {
            my $path = $File::Find::name;
            $path =~ s{^$targz_dir/}{};
            my $tarball_path     = "/var/cpanel/perl/easy/$path";
            my $tarball_contents = get_file_contents($File::Find::name);
            my $tarball_md5      = Digest::MD5::md5_hex($tarball_contents);
            my $tarball_sha512   = Digest::SHA::sha512_hex($tarball_contents);
            $md5{$tarball_path}    = $tarball_md5;
            $sha512{$tarball_path} = $tarball_sha512;
        }
    };

    File::Find::find( $find_sub, $targz_dir );

    # Write new targz.yaml
    if ( open( my $targz_fh, '>', $targz_file ) ) {
        print {$targz_fh} "# Entry looks like: /var/cpanel/perl/easy/Cpanel/Easy/Test.pm.tar.gz: f5806f5059ef7bd4d3fcf36cf116d1ef\n" . "# And will be fetched from: http://{httpupdate}/cpanelsync/{httpupdate_uri}/targz/Cpanel/Easy/Test.pm.tar.gz\n";
        print {$targz_fh} YAML::Dump( \%md5, \%sha512 );
        close $targz_fh;
    }
    else {
        die "Failed to open '$targz_file' for writing: $!";
    }
}

sub get_file_contents {
    my ($filename) = @_;

    if ( open my $fh, '<', $filename ) {
        my $contents = do { local $/; <$fh> };
        close $fh;
        return $contents;
    }
    else {
        die "Failed to open '$filename' for reading: $!";
    }
}

sub print_usage {
    print <<"USAGE";

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

USAGE
}
