#!/usr/bin/perl
#-------------------------------------------------------------------------------
# cpanel - build_plat_arch.pl                     Copyright(c) 2011 cPanel, Inc.
#                                                           All rights Reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited
#-------------------------------------------------------------------------------
# Note:
# For actual WHM plugin publishing, this script is expected to be at
# the following location:
#     httpupdate0:/home/cpanel/cpanelsync/addons/modules/build_plat_arch.pl
#
#-------------------------------------------------------------------------------

use Getopt::Long ();

my @publishing_plugin_list = (
    'pro',
    'cronconfig',
    'addonupdates',
    'spamdconf',
    'edit_com',
    'munin',
    'clamavconnector',
    'atmailopen',
);

my ( $runtype, $plugin, $base_dir ) = undef;

my $opt_result = Getopt::Long::GetOptions(
    'r|runtype=s' => \$runtype,
    'p|plugin=s'  => \$plugin,
);

if ( !$opt_result || !$runtype || !$plugin ) {
    print "Usage: $0 --runtype [publish|qa|test] --plugin <your_plugin_name> \n";
    print " e.g.: $0 --runtype publish --plugin cronconfig \n";
    die "Valid parms expected ... Exiting from \"$0\"";
}

if ( $runtype =~ m/^publish$/i ) {
    $base_dir = "/home/cpanel/cpanelsync/addons/modules";
}
elsif ( $runtype =~ m/^qa$/i ) {
    $base_dir = "/home/qabuild/cpanelsync/addons/modules";
}
elsif ( $runtype =~ m/^test$/i ) {
    $base_dir = "/home/qabuild/cpanelsync/addons/modules";
}
else {
    die "ERROR: Unexpected value \"$runtype\" for option runtype. (Valid values are \"publish\", \"qa\" or \"test\".) \n" . "Usage: $0 --runtype [publish|qa|test]\nExiting from \"$0\" ... \n";
}

if ( !grep( /^\Q$plugin\E$/, @publishing_plugin_list ) ) {
    die "ERROR: Unexpected plugin name \"$plugin\".\n" . "       Valid plugin names are \"@publishing_plugin_list\".\nExiting from \"$0\"...\n";
}

if ( !chdir $base_dir ) {
    die "ERROR: Unable to chdir to \"$base_dir\"\n. Exiting from \"$0\"...";
}

if ( !-d "$base_dir/$plugin" ) {
    die "ERROR: plugin dir \"$base_dir/$plugin\" does not exist.\n" . "       Unable to proceed further. Exiting from \"$0\"...\n";
}

my @PLATS = ( "FreeBSD", "Linux" );
my @ARCHS = ( "i386", "i486", "i586", "i686", "x86_64", "amd64" );
foreach my $plat (@PLATS) {
    foreach my $arch (@ARCHS) {
        if ( $runtype =~ /^test$/ ) {
            print "\"$0\" has been invoked for processing \"${plugin}-${plat}-${arch}\"\n";
            print "No further action is performed with runtype \"$runtype\".\n";
            next;
        }
        unlink("$base_dir/${plugin}-${plat}-${arch}");
        system( "rsync", "-av", "--delete", "$base_dir/$plugin/", "$base_dir/${plugin}-${plat}-${arch}/" );
    }
}
