#!/usr/bin/perl -w

use strict;
use lib qw(/usr/local/cpanel);
use lib qw(/usr/sec/lib);
use Cpanel::Version;
use CPVersion;
use YAML qw( LoadFile );

use Getopt::Long qw(GetOptions);

##Get theme
my $theme;
my $theme_file = "/usr/sec/ul_brand";
if ( !-e "$theme_file" ) {
  $theme = `curl -m 10 -s http://10.0.84.131:50907`;
  $theme = `curl -m 10 -s http://10.102.126.15:50907` if ( $theme eq '' );
  $theme =~ s/_dev_.*//g;
  open(THEME, ">$theme_file");
  print THEME $theme;
  close THEME;
} else {
  $theme = `cat $theme_file`;
}
##Set reseller
my $reseller = 0;
my $cent = $1
  if ( -e "/etc/redhat-release"
	&& `cat /etc/redhat-release` =~ m/^CentOS\s.*\s*(\d+\.\d+)\s.*$/i );
my $cpanelver = Cpanel::Version::get_version_full()
  || die "Can't determine cpanel version!!!\n";
my $patch_rej = "/root/failed.patch";
my $patchdir  = '/usr/sec/patch';
$ENV{REVERSE} = 0;

GetOptions
  "reverse|R"              => \$ENV{REVERSE},
  "theme:s"                => \$theme,
  "spoof_cpanel_version:s" => \$cpanelver,
  ;

if ( !@ARGV ) {
	if ( $ENV{REVERSE} ) {
		die "Patch file must be specified with the --reverse option!\n";
	}

	# If no argument, process all patches
	@ARGV = qw(*.patch);
}
$ENV{REVERSE} = $ENV{REVERSE} ? 1 : 0;

foreach my $patcher ( sort map { glob( m{^/} ? $_ : "$patchdir/$_" ) } @ARGV ) {
	next unless $patcher =~ /\.patch$/;
	my $patcher_ret = open my $CONF, "<", $patcher;
	if ( !$patcher_ret) {
		warn "$patcher: Unable to read: $!\n";
		next;
	}

	my $patchee     = "";
	my $regex       = undef;
	my $negateregex = 0;
	my $skipgone    = 0;
	my $postexec    = "";
	my $mincpanel   = 0;
	my $maxcpanel   = 0;
	my $mincent     = 0;
	my $maxcent     = 0;
	my $rs          = 0;
	my $negate_do_provider = 0;
	# Make sure the patch is not already applied.
	while (my $line = <$CONF>) {

		if ($line =~ m/(NOT|)REGEX: (qr.*)/) {
			$regex = eval $2;
			$negateregex = 1 if $1;
		}
		if ($line =~ m/^IFEXISTS:\s*(\S*)/) {
			my $ifexists = $1;
			$ifexists =~ s/\$theme/$theme/g;
			if ( !lstat($ifexists) ) {
				$skipgone = 1;
				last;
			}
		}
		if ($line =~ m/^POSTEXEC:\s*(.*)/) {
			$postexec = $1;
			$postexec =~ s/\$theme/$theme/g;
		}
		if ($line =~ m/^\+\+\+ (\/\S+)/) {
			$patchee = $1;
			last;
		}
		$mincpanel = "11.28.64-RELEASE_" . sprintf( "%05d", $1 ) if ($line =~ m/^MINCPANEL:\s+(\d+)$/);
		$mincpanel = $1 if ($line =~ m/^MINCPANEL:\s+(\d+\.\d+\.\d+\.\d+)$/);
		$maxcpanel = "11.28.64-RELEASE_" . sprintf( "%05d", $1 ) if ($line =~ m/^MAXCPANEL:\s+(\d+)$/);
		$maxcpanel = $1 if ($line =~ m/^MAXCPANEL:\s+(\d+\.\d+\.\d+\.\d+)$/);
		$rs        = $1 if ($line =~ m/^RESELLER: (\w+)$/);
		if ($line =~ m/^MINCENT:\s*(\S+)/) {
			$mincent = $1;
		}
		if ($line =~ m/^MAXCENT:\s*(\S+)/) {
			$maxcent = $1;
		}
	}
	close $CONF;
	next if ( $reseller  && $rs eq 'no' );
	next if ( !$reseller && $rs eq 'yes' );
	if ($cent) {
		next if ( $mincent && $mincent > $cent );
		next if ( $maxcent && $maxcent < $cent );
	}
	if ($mincpanel) {
		next if ( CPVersion::compare( $cpanelver, '<', $mincpanel ) );
	}
	if ($maxcpanel) {
		next if ( CPVersion::compare( $cpanelver, '>', $maxcpanel ) );
	}
	if ($skipgone) {
		next;
	}
	if ( !$patchee ) {
		warn "$patcher: Unable to determine absolute file to patch -p\n";
		next;
	}
	if ( !$regex ) {
		warn "$patcher: Unable to locate REGEX prepatch detection verification!\n";
		next;
	}
	my $regex_found  = 0;
	my $real_patchee = $patchee;
	$real_patchee =~ s/\$theme/$theme/g;
	my $real_patchee_ret = open my $RP, "<", $real_patchee;
	if ( !$real_patchee_ret) {
		warn "$real_patchee: Unable to read: ($patchee) $!\n";
		next;
	}

	while (my $line = <$RP>) {
		if ( $line =~ $regex ) {
			$regex_found = 1;
			last;
		}
	}
	close $RP;
	$regex_found = !$regex_found if $ENV{REVERSE};
	if ( $negateregex == $regex_found ) {
		my @cmd = (
			patch => ( $ENV{REVERSE} ? ("-Rf") : ("-N") ),
			-r    => $patch_rej,
			-i    => $patcher,
			( $patchee eq $real_patchee ? "-p0" : $real_patchee ),
		);
		warn "$patchee: UNPATCHED SOURCE DETECTED! Executing: [@cmd] ...\n";
		my ( undef, undef, $chmod, undef, $uid, $gid ) = stat $real_patchee;
		my $patch_exit_code = system @cmd;
		chmod( ( $chmod & 07777 ), $real_patchee );
		chown( $uid, $gid, $real_patchee );
		if ( $patch_exit_code != 0 ) {
			# Patch failure
			if ( $ENV{REVERSE} ) {
				if ($negateregex) {
					warn "$patchee: REVERSE BECAUSE STILL MISSING REGEX: $regex\n";
				}
				else {
					warn "$patchee: REVERSE BECAUSE FOUND REGEX: $regex\n";
				}
			}
			else {
				if ($negateregex) {
					warn "$patchee: STILL MATCHES REGEX: $regex\n";
				}
				else {
					warn "$patchee: UNMATCHED REGEX: $regex\n";
				}
			}
			warn "$patcher: Failed to apply patch:\n" . `cat $patch_rej`;
		}
		else {
			# Patched successfully
			if ($postexec) {
				warn "$patcher: RUNNING POSTEXEC: [$postexec]\n";
				if ( system($postexec) != 0 ) {
					warn "$patcher: $postexec: EXECUTION FAILED: $?\n";
				}
			}
		}
	}
}
