#!/usr/bin/perl
#-------------------------------------------------------------------------------
# cpanel - updaterc.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/updaterc.pl
#
#------------------------------------------------------------------------------

die "No arguments specified" if !@ARGV;

my $runtype      = $ARGV[0];
my $program      = $ARGV[1];
my $programver   = $ARGV[2];
my $installerver = $ARGV[3] || '';
my $dir          = undef;

if ( $runtype =~ m/^publish$/i ) {
    $dir = "/home/cpanel/cpanelsync/addons/modules";
}
elsif ( $runtype =~ m/^qa$/i ) {
    $dir = "/home/qabuild/cpanelsync/addons/modules";
}
elsif ( $runtype =~ m/^test$/i ) {
    print "\"$0\" has been invoked. No further action is performed with runtype \"$runtype\".\n";
    exit;
}
else {
    die "ERROR: Encountered unexpected runtype \"$runtype\". Valid values are \"publish\", \"qa\", or \"test\".\n";
}

chdir "$dir" or die "Unable to chdir to \"$dir\": $!";

if ( !$program || !$programver ) {
    die "Invalid arguments specified, nothing will be updated!";
}

my $version_text = $installerver ? $programver . '-' . $installerver : $programver;
print "Updating nthemes.rc for $program to $version_text\n";

if ( open my $nthemes_fh, '+<', 'nthemes.rc' ) {
    my @lines;
    while (<$nthemes_fh>) {
        chomp;
        if (m/^\Q${program}\E/) {
            my @line = split( /\|/, $_ );
            if ($installerver) {
                $line[5] = $programver . '-' . $installerver;
            }
            else {
                $line[5] = $programver;
            }
            push @lines, join( '|', @line );
        }
        else { push @lines, $_; }
    }
    seek( $nthemes_fh, 0, 0 );
    print {$nthemes_fh} join( "\n", @lines );
    truncate( $nthemes_fh, tell($nthemes_fh) );
    close $nthemes_fh;
}
else {
    die "Unable to update themes file \"nthemes.rc\": $!";
}

