perl <<'EOF'
use strict;
use lib qw( /usr/local/cpanel /usr/local/cpanel/3rdparty/perl/514/lib64/perl5/cpanel_lib );
use cPanel::PublicAPI;

sub main {
	my ($domain, $phpversion) = @_;
	my $user = _getuser($domain);
	my $docroot = _getdoc($user, $domain);
	if ( ! -x '/usr/local/cpanel/bin/update_php_handler_hg' ) {
		print "[!] Update script was not found!\n";
		next;
	}
	if ( -f $docroot . '/.htaccess' ) {
		system("cp -pv $docroot/.htaccess $docroot/.htaccess.phphandler.". time());
	}
	if ( $phpversion eq 'strip' ) {
		system('/usr/local/cpanel/bin/update_php_handler_hg','--verbose','--recurse=0',"--strip","--user=$user","--directory=$docroot","\n");
	} else {
		system('/usr/local/cpanel/bin/update_php_handler_hg','--verbose','--recurse=0',"--force=$phpversion","--user=$user","--directory=$docroot","\n");
	}
}

sub _getuser {
	my $domain = shift;
	chomp(my $user = `egrep ^$domain:.+\$ /etc/userdomains | cut -d: -f2`);
	$user =~ s/^\s+//;
	if ( ! $user ) {
		print "[!] User not found.\n";
		next;
	}
	return($user);
}


sub _getdoc {
	my ($user, $domain) = @_;
	my $accesshash = _getah();
	my $cp = cPanel::PublicAPI->new( 'user' => 'root', 'accesshash' => $accesshash );
	my $docroot = $cp->cpanel_api2_request('whostmgr', { 'module' => 'DomainLookup', 'func' => 'getdocroot', 'user' => "$user" },
		{
	        	'domain' => "$domain",
		}
	);
	$docroot = $docroot->{cpanelresult}{data}[0]{docroot};
	if ( ! $docroot ) {
		print "[!] Docroot not found.\n";
		next;
	}
	return $docroot;
}

sub _getah {
	my $accesshash;
	if ( ! -f '/root/.accesshash' ) {
		$ENV{REMOTE_USER} = 'root';
		system('/usr/local/cpanel/bin/realmkaccesshash');
	}
	if ( -f '/root/.accesshash' ) {
	       	open my $hash, "<", "/root/.accesshash";
	        	my @accesshash = <$hash>;
	        close $hash;
	        foreach(@accesshash){
	                $accesshash .= $_
	        }
	        $accesshash =~ s/\n//g;
	        return $accesshash;
	}
}

main('domain_placeholder', 'php_placeholder');
EOF
