#!/bin/sh
eval 'if [ -x /usr/local/cpanel/3rdparty/bin/perl ]; then exec /usr/local/cpanel/3rdparty/bin/perl -x -- $0 ${1+"$@"}; else exec /usr/bin/perl -x $0 ${1+"$@"}; fi;'
if 0;
#!/usr/bin/perl

# WebSite:  http://www.rvglobalsoft.com
# Unauthorized copying is strictly forbidden and may result in severe legal action.
# Copyright (c) 2013 RV Global Soft Co.,Ltd. All rights reserved.
# 
# =====YOU MUST KEEP THIS COPYRIGHTS NOTICE INTACT AND CAN NOT BE REMOVE =======
# Copyright (c) 2006 RV Global Soft Co.,Ltd. All rights reserved.
# This Agreement is a legal contract, which specifies the terms of the license
# and warranty limitation between you and RV Global Soft Co.,Ltd. and RV Site Builder.
# You should carefully read the following terms and conditions before
# installing or using this software.  Unless you have a different license
# agreement obtained from RV Global Soft Co.,Ltd., installation or use of this software
# indicates your acceptance of the license and warranty limitation terms
# contained in this Agreement. If you do not agree to the terms of this
# Agreement, promptly delete and destroy all copies of the Software.
#
# =====  Grant of License =======
# The Software may only be installed and used on a single host machine.
#
# =====  Disclaimer of Warranty =======
# THIS SOFTWARE AND ACCOMPANYING DOCUMENTATION ARE PROVIDED "AS IS" AND
# WITHOUT WARRANTIES AS TO PERFORMANCE OF MERCHANTABILITY OR ANY OTHER
# WARRANTIES WHETHER EXPRESSED OR IMPLIED.   BECAUSE OF THE VARIOUS HARDWARE
# AND SOFTWARE ENVIRONMENTS INTO WHICH RV SITE BUILDER MAY BE USED, NO WARRANTY OF
# FITNESS FOR A PARTICULAR PURPOSE IS OFFERED.  THE USER MUST ASSUME THE
# ENTIRE RISK OF USING THIS PROGRAM.  ANY LIABILITY OF RV GLOBAL SOFT CO.,LTD. WILL BE
# LIMITED EXCLUSIVELY TO PRODUCT REPLACEMENT OR REFUND OF PURCHASE PRICE.
# IN NO CASE SHALL RV GLOBAL SOFT CO.,LTD. BE LIABLE FOR ANY INCIDENTAL, SPECIAL OR
# CONSEQUENTIAL DAMAGES OR LOSS, INCLUDING, WITHOUT LIMITATION, LOST PROFITS
# OR THE INABILITY TO USE EQUIPMENT OR ACCESS DATA, WHETHER SUCH DAMAGES ARE
# BASED UPON A BREACH OF EXPRESS OR IMPLIED WARRANTIES, BREACH OF CONTRACT,
# NEGLIGENCE, STRICT TORT, OR ANY OTHER LEGAL THEORY. THIS IS TRUE EVEN IF
# RV GLOBAL SOFT CO.,LTD. IS ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. IN NO CASE WILL
# RV GLOBAL SOFT CO.,LTD.'S LIABILITY EXCEED THE AMOUNT OF THE LICENSE FEE ACTUALLY PAID
# BY LICENSEE TO RV GLOBAL SOFT CO.,LTD.
# =====================================================================

if(!isCpanel()){
    print 'This script support only cPanel.' . "\n";
    exit(0);
}

BEGIN {
    push(@INC,"/usr/local/cpanel");
    push(@INC,"/usr/local/cpanel/Cpanel");
}

use strict;
use warnings;
use Carp;
use Cwd;
use Cwd 'realpath';
use Socket;
use POSIX;
use IO::Handle;
use IPC::Open3;
use Digest::MD5::File ();

use File::Basename;
use File::Basename qw(&basename &dirname);
use Cpanel::Version ();
use Cpanel::Version::Compare;
use Cpanel::ProcessCheck ();

use vars qw($DEBUG $WHMCGI);

#================== Configuration ================
$DEBUG = 0;
if(-f '/usr/local/rvglobalsoft/registerapp.debug'){
    $DEBUG = 1;
}
$WHMCGI = '/usr/local/cpanel/whostmgr/docroot/cgi';
my $rvAppConfig = getAppConfig();
my $appProduct = getProduct();
my $cmdCp = whichCmd('cp');
my $cmdMv = whichCmd('mv');
my $cmdMkdir = whichCmd('mkdir');
my $cmdChmod = whichCmd('chmod');

#=============== Install RVmanager ===============
if( (!isInstallRVManager() && !isProcessInstallRVManager() )
   || (getRvMLatestVersion() ne getRvMCurrentVersion() && !isProcessInstallRVManager())){
    installRVManager();
    $appProduct->{rvmanager} = 1;
}

#================== main Process =================
if (Cpanel::Version::Compare::compare(Cpanel::Version::getversionnumber(), '<', '11.37')){
    
    #make addon_rvmanager.cgi from rvmanager/index.cgi
#    if(defined $rvAppConfig->{rvmanager}->{addonfile} && $rvAppConfig->{rvmanager}->{addonfile} ne ''
#       && -e $WHMCGI . '/' . $rvAppConfig->{rvmanager}->{product} ){
#        print "Make Link for " . $rvAppConfig->{rvmanager}->{fullname} . "\n";
#        symlink($WHMCGI . '/' . $rvAppConfig->{rvmanager}->{addonfile} . '/index.cgi', $WHMCGI . '/' . $rvAppConfig->{rvmanager}->{addonfile}) if(!-e $WHMCGI . '/' . $rvAppConfig->{rvmanager}->{addonfile});
#    }
    
    #make rvskinmanager/index.cgi from addon_rvskinmanager.cgi
    if(defined $rvAppConfig->{rvskin}->{addonfile} && $rvAppConfig->{rvskin}->{addonfile} ne ''
       && -e $WHMCGI . '/rvskinmanager' ){
        print "Make Plugin For " . $rvAppConfig->{rvskin}->{fullname} . "\n";
        system($cmdMkdir .' -p /usr/local/cpanel/whostmgr/docroot/cgi/rvskinmanager') if(!-e '/usr/local/cpanel/whostmgr/docroot/cgi/rvskinmanager');
        system('"' . $cmdMv .'" -f /usr/local/cpanel/whostmgr/docroot/cgi/addon_rvskinmanager.cgi /usr/local/cpanel/whostmgr/docroot/cgi/rvskinmanager/index.cgi') if(-f '/usr/local/cpanel/whostmgr/docroot/cgi/addon_rvskinmanager.cgi');
        system("$cmdChmod 755 /usr/local/cpanel/whostmgr/docroot/cgi/rvskinmanager/index.cgi");
    }
    
    #make rvsitebuilder/index.cgi from addon_rvsitebuilder.cgi
    if(defined $rvAppConfig->{rvsitebuilder}->{addonfile} && $rvAppConfig->{rvsitebuilder}->{addonfile} ne ''){
        print "Make Plugin For " . $rvAppConfig->{rvsitebuilder}->{fullname} . "\n";
        system($cmdMkdir .' -p /usr/local/cpanel/whostmgr/docroot/cgi/rvsitebuilder') if(!-e '/usr/local/cpanel/whostmgr/docroot/cgi/rvsitebuilder');
        #create new
        if(!-f '/usr/local/cpanel/whostmgr/docroot/cgi/rvsitebuilder/index.cgi'){
            system('"' . $cmdMv .'" -f /usr/local/cpanel/whostmgr/docroot/cgi/rvsitebuilderinstaller/index.cgi /usr/local/cpanel/whostmgr/docroot/cgi/rvsitebuilder/index.cgi') if (-f '/usr/local/cpanel/whostmgr/docroot/cgi/rvsitebuilderinstaller/index.cgi');
        }
        system('"' . $cmdMv .'" -f /usr/local/cpanel/whostmgr/docroot/cgi/addon_rvsitebuilder.cgi /usr/local/cpanel/whostmgr/docroot/cgi/rvsitebuilder/index.cgi') if(-f '/usr/local/cpanel/whostmgr/docroot/cgi/addon_rvsitebuilder.cgi');
        system("$cmdChmod 755 /usr/local/cpanel/whostmgr/docroot/cgi/rvsitebuilder/index.cgi") if(-f '/usr/local/cpanel/whostmgr/docroot/cgi/rvsitebuilder/index.cgi');
    }
    
    print "Complete\n";
    exit(1);
}

#register appconf for cpanel 11.38.++
if (-x '/usr/local/cpanel/bin/register_appconfig') {
    foreach my $appKey (keys %{$appProduct}){
        if( defined $rvAppConfig->{$appKey} && $rvAppConfig->{$appKey} ne ''
        && defined $rvAppConfig->{$appKey}->{file} && $rvAppConfig->{$appKey}->{file} ne ''
        && -e $rvAppConfig->{$appKey}->{installerpath} . '/appconfig/'. $rvAppConfig->{$appKey}->{file}){
            if (defined $rvAppConfig->{$appKey}->{addonfile} && $rvAppConfig->{$appKey}->{addonfile} ne ''
                && -e '/usr/local/cpanel/whostmgr/docroot/cgi/' . $rvAppConfig->{$appKey}->{addonfile}
                && $appKey ne 'rvmanager' ){
                unlink('/usr/local/cpanel/whostmgr/docroot/cgi/' . $rvAppConfig->{$appKey}->{addonfile} ) ;
            }
            my $filePath = $rvAppConfig->{$appKey}->{installerpath} . '/appconfig/'. $rvAppConfig->{$appKey}->{file};
            my $fileCpanelConf = '/var/cpanel/apps/'.$rvAppConfig->{$appKey}->{file};
            
            #fixed cpanel 11.40
            if ( defined $rvAppConfig->{$appKey}->{cpanelfile} ) {
                my $cpanelFilePath = $rvAppConfig->{$appKey}->{installerpath} . '/appconfig/'. $rvAppConfig->{$appKey}->{cpanelfile};
                my $cpanelFileCpanelConf = '/var/cpanel/apps/'.$rvAppConfig->{$appKey}->{cpanelfile};
                if(getMdSum($cpanelFilePath) ne getMdSum($cpanelFileCpanelConf)){
                    print 'Register Appconfig to cPanel: ' . $rvAppConfig->{$appKey}->{fullname} . "\n";
                    print '/usr/local/cpanel/bin/register_appconfig ' . $rvAppConfig->{$appKey}->{installerpath} . '/appconfig/'. $rvAppConfig->{$appKey}->{cpanelfile} . "\n" if($DEBUG);
                    system('/usr/local/cpanel/bin/register_appconfig ' . $rvAppConfig->{$appKey}->{installerpath} . '/appconfig/'. $rvAppConfig->{$appKey}->{cpanelfile});
                } else {
                    print $rvAppConfig->{$appKey}->{fullname} . " has been installed into cPanel. [Skip]\n" if(-f $fileCpanelConf);
                }
            }
            
            if(getMdSum($filePath) ne getMdSum($fileCpanelConf)){
                print 'Register Appconfig : ' . $rvAppConfig->{$appKey}->{fullname} . "\n";
                print '/usr/local/cpanel/bin/register_appconfig ' . $rvAppConfig->{$appKey}->{installerpath} . '/appconfig/'. $rvAppConfig->{$appKey}->{file} . "\n" if($DEBUG);
                system('/usr/local/cpanel/bin/register_appconfig ' . $rvAppConfig->{$appKey}->{installerpath} . '/appconfig/'. $rvAppConfig->{$appKey}->{file});
                print $rvAppConfig->{$appKey}->{fullname} . " installed into WHM.\n";
            }else{
                print $rvAppConfig->{$appKey}->{fullname} . " has been installed into WHM. [Skip]\n" if(-f $fileCpanelConf);
            }
            
        }
        
        #Fix rvsitebuilder
        if($appKey eq 'rvsitebuilder'
            && -e $rvAppConfig->{$appKey}->{installerpath} ){
            system("$cmdMkdir -p " . $rvAppConfig->{$appKey}->{productpath}) if(!-e $rvAppConfig->{$appKey}->{productpath});
            system("$cmdChmod 755 " . $rvAppConfig->{$appKey}->{installerpath} . '/index.cgi');
            system("\"$cmdCp\" -a " . $rvAppConfig->{$appKey}->{installerpath} . '/index.cgi ' . $rvAppConfig->{$appKey}->{productpath} . '/index.cgi') if(!-e $rvAppConfig->{$appKey}->{productpath} . '/index.cgi');
        }
    }
    
} else {
    print "Permission Deny : /usr/local/cpanel/bin/register_appconfig\n";
    exit(1);
}

exit(0);

#=========== Subroutine =================
sub getAppConfig {
    my $rvAppConfig = {
        'rvskin' => {
            'product' => 'rvskin',
            'fullname' => 'RVskinmanager',
            'installerpath' => '/root/rvadmin',
            'file' => 'rvskinmanager.conf',
            'addonfile' => 'addon_rvskinmanager.cgi',
            'cpanelfile' => 'rvskin_cpanel.conf',  
        },
        'rvsitebuilder' => {
            'product' => 'rvsitebuilder',
            'fullname' => 'RVsitebuilder',
            'installerpath' => '/usr/local/cpanel/whostmgr/docroot/cgi/rvsitebuilderinstaller',
            'file' => 'rvsitebuilder.conf',
            'cpanelfile' => 'rvsitebuilder_cpanel.conf',
            'addonfile' => 'addon_rvsitebuilder.cgi',
            'productpath' => '/usr/local/cpanel/whostmgr/docroot/cgi/rvsitebuilder',
        },
        'rvmanager' => {
            'product' => 'rvmanager',
            'fullname' => 'RVmanager',
            'installerpath' => '/usr/local/rvglobalsoft/rvmanager/auto',
            'file' => 'rvmanager.conf',
            'addonfile' => 'addon_rvmanager.cgi',
            'productpath' => '/usr/local/rvglobalsoft/rvmanager',
        },
        'rvglobalsoft' => {
            'product' => 'rvglobalsoft',
            'fullname' => 'RVglobalsoft',
            'installerpath' => '/usr/local/rvglobalsoft/rvglobalsoft/auto',
            'file' => 'rvglobalsoft.conf',
            'addonfile' => 'addon_rvglobalsoft.cgi',
            'productpath' => '/usr/local/rvglobalsoft/rvglobalsoft',
        },
        'rvsubversion' => {
            'product' => 'rvsubversion',
            'fullname' => 'RVsubversion',
            'installerpath' => '/usr/local/rvglobalsoft/rvsubversion/auto',
            'file' => 'rvsubversion.conf',
            'addonfile' => 'addon_rvsubversion.cgi',
            'productpath' => '/usr/local/rvglobalsoft/rvsubversion',
        },
        'sslproduct' => {
            'product' => 'sslproduct',
            'fullname' => 'SSLproduct',
            'installerpath' => '/usr/local/rvglobalsoft/sslproduct/auto',
            'file' => 'sslproduct.conf',
            'addonfile' => 'addon_sslproduct.cgi',
            'productpath' => '/usr/local/rvglobalsoft/sslproduct',
        },
        'symantecvip' => {
            'product' => 'symantecvip',
            'fullname' => 'symantecVIP',
            'installerpath' => '/usr/local/rvglobalsoft/symantecvip/auto',
            'file' => 'symantecvip.conf',
            'addonfile' => 'addon_symantecvip.cgi',
            'productpath' => '/usr/local/rvglobalsoft/symantecvip',
        },
    };
    return $rvAppConfig;
}

sub getProduct {
    my $appProduct = getProductFromArgument();
        
    my $currentFileDir = dirname(realpath(__FILE__));
    my $rvAppConfig = getAppConfig();
    
    foreach my $appKey (keys %{$rvAppConfig}){
        if($DEBUG){
            print "==========================\n";
            print $appKey . "\n";
            print $currentFileDir . ' eq ' . $rvAppConfig->{$appKey}->{installerpath} . '/appconfig' . "\n";
            print $rvAppConfig->{$appKey}->{installerpath} . '/appconfig/'. $rvAppConfig->{$appKey}->{file} . "\n";
        }
        if( defined $rvAppConfig->{$appKey} &&  $rvAppConfig->{$appKey} ne '' 
            && -e $rvAppConfig->{$appKey}->{installerpath} . '/appconfig/registerapp'
            && -e $rvAppConfig->{$appKey}->{installerpath} . '/appconfig/'. $rvAppConfig->{$appKey}->{file} ){
            $appProduct->{$appKey} = 1;
        }
    }
    
    if(!scalar (keys %{$appProduct})){
        print "The product was not found\n";
        exit(1);
    }

    return $appProduct;
}

#===Get from cli===
sub getProductFromArgument {
    my $appProduct = {};
    my $num = $#ARGV;
    my $rvAppConfig = getAppConfig();
    for(my $iArg=0;$iArg<=$num;$iArg++){
        my $argKey = $ARGV[$iArg];
        if( $argKey && $rvAppConfig->{$argKey}){
            next if(!-e $rvAppConfig->{$argKey}->{installerpath} . '/appconfig/'. $rvAppConfig->{$argKey}->{file});
            $appProduct->{$argKey} = 1;
        }
        if($argKey eq '--help'){
            my $fileName = __FILE__;
            my $printHelp = <<EOF;

Usage: $fileName [Product Name]
List information about product name
    rvskin             Rvskin,Rvskin Manager
    rvsitebuilder      RVsitebuilder
    rvmanager          RVmanager
    rvglobalsoft       RVglobalsoft
    rvsubversion       RVsubversion
    sslproduct         SSLproduct
    symantecvip        symantecVIP

EOF
            print $printHelp;
            exit(0);
        }
    }
    return $appProduct;
}

sub whichCmd{
    my ($cmd) = $_[0];
    return if ($cmd eq '');
    return if ($cmd =~/\//);
    
    my $whichCmd = '';
    my $binpath = '';
    my @binpathList = (
        '/bin',
        '/usr/bin',
        '/usr/local/bin',
        '/sbin',
        '/usr/sbin',
        '/usr/local/sbin'
    );
    
    foreach my $path(@binpathList) {
        if ( -x $path . '/' . 'which') {
            $whichCmd = $path . '/' . 'which';
            last;
        }  
    }
    
    $binpath = callBackticks("$whichCmd $cmd");
    chomp ($binpath);
    $binpath =~s/\n|\r//gi;
    
    if ($binpath eq '' || $binpath=~/null/) {
        foreach my $path(@binpathList) {
            if ( -x $path . '/' . $cmd) {
                $binpath = $path . '/' . $cmd;
                last;
            }
        }                
    }
        
    return $binpath;
}

sub callBackticks{
    my $cmd = $_[0];
    if (-f '.rvsBackticks') {
        system('rm -f .rvsBackticks');
    }
    
    system("$cmd > .rvsBackticks");
    my ($resuft);
    if (-f '.rvsBackticks') {
        my ($fd);
        open($fd, '<', '.rvsBackticks');
        $resuft = join('',<$fd>);
        close($fd);
        system('rm -f .rvsBackticks');
    } else {
        $resuft = `$cmd`;
    }
    return $resuft;
}

sub isInstallRVManager {
    my $rvAppConfig = getAppConfig();
    if(defined $rvAppConfig->{rvmanager}->{productpath} && $rvAppConfig->{rvmanager}->{productpath} ne ''){
        if(-e $rvAppConfig->{rvmanager}->{productpath} . '/rvmanagerversion.txt'){
            print "RVmanager is installed\n" if($DEBUG);
            return 1;
        }
    }
    print "RVmanager is not install\n" if($DEBUG);
    return 0;
}

sub installRVManager {
    
    print "Install RVmanager\n";
    my $rvAppConfig = getAppConfig();
    my $cmdWget = whichCmd('wget');
    my $cmdTar = whichCmd('tar');
    
    if(defined $rvAppConfig->{rvmanager}->{productpath} && $rvAppConfig->{rvmanager}->{productpath} ne ''){
        if (!-e $rvAppConfig->{rvmanager}->{productpath} ) {
            system("$cmdMkdir -p " . $rvAppConfig->{rvmanager}->{productpath} );
            chmod 0755, $rvAppConfig->{rvmanager}->{productpath};
        }
        chmod(0755, $rvAppConfig->{rvmanager}->{productpath}) if(-d $rvAppConfig->{rvmanager}->{productpath});
        chdir($rvAppConfig->{rvmanager}->{productpath});
        unlink($rvAppConfig->{rvmanager}->{productpath} . '/rvmanagerauto.tar.bz2');
        system($cmdWget . ' http://download.rvglobalsoft.com/download.php/download/rvmanager-upgrade -O rvmanagerauto.tar.bz2');
        system($cmdTar . ' -jxvf rvmanagerauto.tar.bz2');
        if(-e $rvAppConfig->{rvmanager}->{installerpath} . '/autorvmanager.cgi'){
            chmod 0755, $rvAppConfig->{rvmanager}->{installerpath} . '/autorvmanager.cgi';
            system($rvAppConfig->{rvmanager}->{installerpath} . '/autorvmanager.cgi');
        }
    }
    return 1;
}

sub isCpanel {
    if(-e '/usr/local/cpanel/cpkeyclt'){
        return 1;
    }
    return 0;
}

sub isProcessInstallRVManager {
    my ($parent) = POSIX::getppid();
    my (%PPIDS) = Cpanel::ProcessCheck::previouspids( 'process' => 'autorvmanager.cgi' );
    delete $PPIDS{$parent};
    delete $PPIDS{$$};
    my ($upcppidcount) = scalar keys %PPIDS;
    
    if ($upcppidcount) {
        return 1;
    }
    return 0;
}

sub getRvMLatestVersion {
    my($request) = "latestversion.php?program=rvmanager";
    my($host) = 'http://download.rvglobalsoft.com/';
    
    my $response = LWP_get_contents($host.$request);
    my @resp = split(/\n+/, $response);
    my $content = '';
    foreach my $line (@resp) {
        $line =~ s/<br>$//;
        $content = $content . trim($line);
    }
    my $versionNo = '1.0.1';
    if( $content =~/^(.*?)\s*:\s*(.*?)$/){
        $versionNo = $2;
        $versionNo = trim($versionNo);
    }
    print "getRvMLatestVersion=$versionNo\n"if($DEBUG);
    return $versionNo; 
}

sub LWP_get_contents {
    my ($host, $params, $type) = @_;
    if (!defined $type || $type eq '') {
        $type = 'get';
    }
    use LWP::UserAgent;
    
    $host = 'http://'.$host if ($host !~ m/^http/i);
    my ($obj) = LWP::UserAgent->new;
    $obj->agent('Perl - RV Get Content');
    my $response = {};
    if ($type eq 'post') {
        $response = $obj->post($host, $params);
    } else {
        $response = $obj->get($host);
    }
    
    my $output = '';
    if ($response->is_success) {
        $output = $response->decoded_content;
    } else {
        print STDERR "LWP_get_contents error: ".$response->status_line."\n";
    }

    return $output;
}

sub trim {
    my $string = $_[0];
    $string =~ s/^\s+//;
    $string =~ s/\s+$//;
    if ($string =~/^['|"]/gi && $string =~/['|"]$/gi) {
        $string =~ s/^['|"]//;
        $string =~ s/['|"]$//;
    }
    return $string;
}


sub parseFile {
    my $file = $_[0];
    my @aLines = ();
    if( open(my $FILERead, '<', $file) ) {
        @aLines = <$FILERead>;
        close($FILERead);
    }
    for (my $i = 0; $i < @aLines; $i++) {
        $aLines[$i] =~ s/\r|\n//g;
    }
    return @aLines;
}

sub getRvMCurrentVersion{
    my $rvAppConfig = getAppConfig();
    if(defined $rvAppConfig->{rvmanager}->{productpath} && $rvAppConfig->{rvmanager}->{productpath} ne ''){
        if(-f $rvAppConfig->{rvmanager}->{productpath} . '/rvmanagerversion.txt'){
            my @aLine = parseFile($rvAppConfig->{rvmanager}->{productpath} . '/rvmanagerversion.txt');
            if(defined $aLine[0]){
                print "getRvMCurrentVersion=$aLine[0]\n"if($DEBUG);
                return $aLine[0];
            }
        }
    }
    print "getRvMCurrentVersion=0\n"if($DEBUG);
    return '1.0.1';
}

sub getMdSum {
    my $fileName = $_[0];
    return 0 if(!-f $fileName);
    return Digest::MD5::File::file_md5_hex($fileName);
}
1;