perl <<'EOF'
use File::Find::Rule;
use File::Basename;
use File::Copy;
use LWP::UserAgent;
use XML::Simple;

my $user = "user_placeholder";
if ( ! $user ) {
	print "[!] User not provided.\n";
	exit;
}
if ( ! -f "/var/cpanel/users/$user" ) {
	print "[!] User does not exist.\n";
	exit;
}
check_reseller();

my($domain, $plan, $ip, $contact) = get_data();
if ( ! $ip && ! $domain && ! $plan ) {
	print "[!] Unable to get data for $user.\n";
	exit;
}

my $ssl = check_ssl();
my($hgcsr,$hgkey);
if ( $ssl ) {
	print "[*] SSL found for $ssl\n";
	print "[*] Saving SSL data...\n";
	mkdir "/tmp/hg_save_ssl/";
	($hgcsr,$hgkey) = cp_ssl($ssl);
}

my $size = check_size();

sub get_data {
	my($d, $p, $i, $c);
	open my $fh, '<', "/var/cpanel/users/$user";
	while ( my $line = <$fh> ) {
		if ( $line =~ /ip=(\S+)/i ) {
			$i = $1;
		}
		if ( $line =~ /plan=(.*)/i ) {
			$p = $1;
		}
		if ( $line =~ /dns=(\S+)/i ) {
			$d = $1;
		}
		if ( $line =~ /contactemail=(\S+)/i ) {
			$c = $1;
		}
	}
	return($d, $p, $i, $c);
}

sub check_ssl {
	my $rule = File::Find::Rule->new;
	$rule->file;
	$rule->name('*_SSL');
	my @files = $rule->in("/var/cpanel/userdata/$user");
	my $count = @files;
	if ( $count ) {
		$files[0] =~ s/_SSL$//;
		my $ssl_domain = basename($files[0]);
		return $ssl_domain;
	} else {
		return 0;
	}
}

sub check_size {
	my $hash = get_accesshash();
	my $auth = "WHM root:" . $hash;
	$ENV{PERL_LWP_SSL_VERIFY_HOSTNAME}=0;
	my $ua = LWP::UserAgent->new(SSL_verify_mode => 'SSL_VERIFY_NONE');
	my $request =
      		HTTP::Request->new(
        		GET => "https://127.0.0.1:2087/xml-api/accountsummary?user=$user" );
	$request->header( Authorization => $auth );
	my $response = $ua->request($request);
	my $data = $response->content;
	my $xml = XML::Simple->new;	
	$data = $xml->XMLin($data);
	my $size = $data->{'acct'}->{'diskused'};
	$size =~ s/M//g;
	$size =~ s/none/0/g;
	my $suspend = $data->{'acct'}->{'suspended'};
	if ( $suspend ) {
		print "[!] User $user is suspended.\n";
		exit;
	}
	# Imposing 1G limit for chatshell
	if ( $size > 1000 ) {
		print "[!] Total disk space is above automated limit for $user. Disk Usage: $size Mb\n";
		exit;
	} else {
		print "[*] Preparing backup for $user. Disk Usage: $size Mb\n";
		my $backup = `/scripts/pkgacct $user`;
		my $backup_file;
		if ( $backup =~ /pkgacctfile\sis:\s(\S+)/ ) {
			$backup_file = $1;
		}
		if ( $backup_file ) {
			print "[*] Backup complete at $backup_file\n";	
			killacct();
			clearudb();
			sleep(10);
			createacct();
			change_ip();
			if ( $ssl ) {
				installssl();
			}
			move($backup_file, "/home/$user/" . basename($backup_file));
			my(undef,undef,$uid,$gid) = getpwnam($user);
			chown $uid, $gid, "/home/$user/" . basename($backup_file);
			chmod 0644, "/home/$user/" . basename($backup_file);
			print "[*] Done.\n";
		} else {
			print "[!] Backup failed. Please manually reset.\n";
			exit;
		}
	}
}

sub clearudb {
	my $content;
	open my $fh, '<', "/var/cpanel/databases/users.db";
	while ( my $line = <$fh> ) {
		next if $line =~ /$user:/;
		next if $line =~ /$user\_/;
		$content .= $line;
	}
	close $fh;
	open $fh, '>', "/var/cpanel/databases/users.db";
	print {$fh} $content;
	close $fh;
}

sub killacct {
	my $hash = get_accesshash();
        my $auth = "WHM root:" . $hash;
	$ENV{PERL_LWP_SSL_VERIFY_HOSTNAME}=0;
        my $ua = LWP::UserAgent->new(SSL_verify_mode => 'SSL_VERIFY_NONE');
        my $request =
                HTTP::Request->new(
                        GET => "https://127.0.0.1:2087/xml-api/removeacct?user=$user" );
        $request->header( Authorization => $auth );
	my $response = $ua->request($request);
        my $data = $response->content;
        my $xml = XML::Simple->new;
        $data = $xml->XMLin($data);
	if ( $data->{'result'}->{'status'} ) {
		print "[*] Account $user removed successfully.\n";
	} else {
		print "[!] Unable to delete $user from the server.\n";
		exit;
	}
}

sub createacct {
	my $hash = get_accesshash();
        my $auth = "WHM root:" . $hash;
        $ENV{PERL_LWP_SSL_VERIFY_HOSTNAME}=0;
        my $ua = LWP::UserAgent->new(SSL_verify_mode => 'SSL_VERIFY_NONE');
	my $password = passgen();
        my $request;
	if ( $contact ) {
		$request =
        	        HTTP::Request->new(
                        GET => "https://127.0.0.1:2087/xml-api/createacct?username=$user&domain=$domain&plan=$plan&contactemail=$contact&password=$password");
	} else {
		$request =
                        HTTP::Request->new(
                        GET => "https://127.0.0.1:2087/xml-api/createacct?username=$user&domain=$domain&plan=$plan&password=$password");
	}
        $request->header( Authorization => $auth );
        my $response = $ua->request($request);
        my $data = $response->content;
        my $xml = XML::Simple->new;
        $data = $xml->XMLin($data);
        if ( $data->{'result'}->{'status'} ) {
                print "[*] Account $user successfully created with password $password\n";
        } else {
                print "[!] Unable to create $user on the server.\n";
		print "Error: ". $data->{'result'}->{'statusmsg'} . "\n\n";
		print "Please manually create the account with the following settings:\n";
		print "\tUsername: $user\n";
		print "\tDomain: $domain\n";
		print "\tIP: $ip\n";
		if ( $contact ) {
			print "\tContact Email: $contact\n";
		}
                exit;
        }
}

sub change_ip {
	my $hash = get_accesshash();
        my $auth = "WHM root:" . $hash;
        $ENV{PERL_LWP_SSL_VERIFY_HOSTNAME}=0;
        my $ua = LWP::UserAgent->new(SSL_verify_mode => 'SSL_VERIFY_NONE');
        my $request =
                HTTP::Request->new(
                        GET => "https://127.0.0.1:2087/xml-api/setsiteip?user=$user&ip=$ip" );
        $request->header( Authorization => $auth );
        my $response = $ua->request($request);
        my $data = $response->content;
        my $xml = XML::Simple->new;
        $data = $xml->XMLin($data);
	if ( $data->{'result'}->{'status'} ) {
                print "[*] Account $user IP updated to $ip.\n";
        } else {
                print "[!] Unable to set IP for $user to $ip. Please manually set.\n";
                exit;
        }
}

sub installssl {
	my $crt = open_file($hgcsr);
	my $key = open_file($hgkey);
	print "Please install SSL certificate manually...\n\n";
	print "CRT:\n$crt\n\n";
	print "KEY:\n$key\n\n";
}

sub get_accesshash{
        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;
    }
}

sub cp_ssl {
	my $domain = shift;
	my $ssl_domain = $domain;
	$ssl_domain =~ s/\./_/g;
	my @dirs = ("/etc/ssl/certs/", "/usr/share/ssl/certs/", "/var/cpanel/ssl/installed/certs");	
	my @crts;
	foreach my $d ( @dirs ) {
		if ( -d $d ) {
			my $rule = File::Find::Rule->new;
			$rule->file;
			$rule->name("$ssl_domain*crt");
			my @files = $rule->in("$d");
			
			push @crts, @files;
		}
	}
	my $count = @crts;
	if ( $count > 1 ) {
		print "[!] More than one SSL for $domain. Please manually reset.\n";
		exit;
	} elsif ( $count == 1 ) { 
		my $save_path = '/tmp/hg_save_ssl/' . basename($crts[0]);
		copy($crts[0], $save_path) or die "Unable to save SSL. Please manually reset.\n";
		print "[*] " . $crts[0] . " saved.\n";
		my $ssl_hash = basename($crts[0]);
		$ssl_hash =~ s/$ssl_domain//g;
		$ssl_hash =~ s/^_(\S+?_\S+?)_\S+_\S+\.crt/$1/g;
		if ( $ssl_hash ) {
			my $rule = File::Find::Rule->new;
			$rule->file;
			$rule->name("$ssl_hash*key");
			my @files = $rule->in("/var/cpanel/ssl/installed/keys");
			my $key_count = @files;
			if ( $key_count ) {
				my $key = $files[0];
				my $key_save_path = '/tmp/hg_save_ssl/' . basename($key);
				copy($key, $key_save_path) or die "Unable to save SSL key. Please manually reset.\n";
				print "[*] $key saved.\n";
				return($save_path, $key_save_path);
			} else {
				print "[!] No SSL key was found for $domain. Please manually reset.\n";
				exit;
			}
		} else {
			print "[!] Unable to determine SSL key hash. Please manually reset.\n";
			exit;
		}
	} else {
		print "[!] No SSL crt was found for $domain. Please manually reset.\n";
		exit;
	}
}

sub check_reseller {
	open my $fh, '<', "/var/cpanel/resellers";
	while ( my $line = <$fh> ) {
		if ( $line =~ /^$user:/ ) {
			print "[!] This user is a reseller. Please manually reset.\n";
			exit;
		}
	}
	close $fh;
}

sub open_file {
	my $file = shift;
	my $content;
	open my $fh, '<', $file;
	while ( my $line = <$fh> ) {
		$content .= $line;
	}
	close $fh;
	return $content;
}

sub passgen {
        my @chars = ('A'..'Z','a'..'z','0'..'9');
        my $num = scalar(@chars);
        my ( $i, $x, $string );
        for ( $i = 12; $i >= 1; $i-- ) {
                $string .= @chars[rand($num)];
        }
        return ( $string );
}
EOF
