#!/usr/bin/perl
###############################################################################
# Copyright (c) 2005-2020 Way to the Web Limited - all rights reserved.
# Without explicit prior consent from Way to the Web Limited this script:
#	may not be altered in any way, apart from the initial variable setting
#	may not be redistributed
#	may not be copied in part or in its entirety
# For more information, please contact sales@waytotheweb.com
###############################################################################
use strict;
use Fcntl qw(:DEFAULT :flock);

my $isrh = 0;
my $isub = 0;
my $version;
my $conf;
my $ipv = "ipv4";
if (lc($ARGV[0]) eq "ipv6") {$ipv = "ipv6"}
my $server = "mirror.cpanelseller.com/syslic/proxy.php";

if (-e "/etc/redhat-release") {
	open (my $IN, "<", "/etc/redhat-release");
	flock ($IN, LOCK_SH);
	$conf = <$IN>;
	close ($IN);
	chomp $conf;
	$isrh = 1;
	if ($conf =~ /release (\d+)/i) {$version = $1}
}
elsif (-e "/etc/os-release") {
	open (my $IN, "<", "/etc/os-release");
	flock ($IN, LOCK_SH);
	my @dbconf = <$IN>;
	close ($IN);
	chomp @dbconf;
	foreach my $line (@dbconf) {
		if ($line =~ /(\w+)="(.+)"/) {
			my $name = $1;
			my $value = $2;
			if ($name eq "NAME" and $value eq "Ubuntu") {
				$isub = 1;
				$conf = $value;
			}
			if ($name eq "VERSION_ID") {
				$version = $value;
			}
		}
	}
}
if (($isrh and $version > 0 and $version < 7) or ($isub and $version < 20.04)) {
	if ($isrh) {
		print "ERROR: Unsupported OS: [Redhat] [$conf] [$ipv]\n";
	} else {
		print "ERROR: Unsupported OS: [Ubuntu] [$version] [$ipv]\n";
	}
	exit
} else {
	print "OS: [$conf] [$ipv]\n";
#	system ("rm -f /usr/src/cxsdata* ; cd /usr/src ; wget -q -O /usr/src/cxsdata http://$server/cgi-bin/cxs/index.cgi");
	system ("rm -f /usr/src/cxsdata* ; cd /usr/src ; curl -o /usr/src/cxsdata https://$server/cgi-bin/cxs/index.cgi");}

my $fileinfo = `/usr/bin/file -i /usr/src/cxsdata`;
if ($fileinfo =~ /text/) {
	print "Unable to install: ";
	print `cat /usr/src/cxsdata`;
	system ("rm -f /usr/src/cxsdata");
} else {
	print "Unpacking new cxs package...\n";
	system ("cd /usr/src ; tar -xzf cxsdata 2>&1");
	system ("cd /usr/src/cxs ; sh install.sh 2>&1");
	print "Tidying up...\n";
	system ("rm -Rf /usr/src/cxs*");
	print "...All done.\n";
}
