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 leftoverdata {
    my $user = shift;
    my $homedir = shift;
    my $fail = 0;
    my $cpuserfile = "/var/cpanel/users/$user";
    my ($name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell) = getpwnam ($user);

    # Common files that are leftover during removeacct.
    my @dbfiles = (
        "/var/cpanel/databases/$user.json", 
        "/var/cpanel/databases/$user.cache", 
        "/var/cpanel/databases/grants_$user.yaml", 
        "/var/cpanel/databases/grants_$user.cache"
    );

    # Make sure the user doesn't exist in cPanel, to an extent. This should have already been checked by userexists(), 
    # which was called before ths subroutine is ran. This is just an extra check to make sure it still doesn't exist.
    if (! -s $cpuserfile) {
        if ($name) {
            print "[!] User still exists in /etc/passwd! Removing with userdel.\n";

            if (-d $homedir) {
                system("userdel -r $user &>/dev/null");
            } else {
                system("userdel $user &>/dev/null");
            }

            if (($? >> 8) > 0) {
                # If userdel failed then we log a separate message and set $fail to indicate that it failed and removeacct was not 100% successful.
                print "[!] Something went wrong and userdel failed. Please look into this and remove the extraneous data from /etc/passwd and /etc/shadow.\n";
                $fail = 1;
            }
        }

        if (-d $homedir) {
            print "[!] $user home directory still exists and was not removed by removeacct. This could indicate a TOS violation. Please look into this.\n";
            $fail = 1;
        }

        foreach my $dbfile (@dbfiles) {
            if (-f $dbfile) {
                print "[!] Found $dbfile after removeacct. Removing.\n";
                unlink $dbfile or print "[!] Failed to remove $dbfile\n";
            }
        }
    }

    return $fail;
}

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 @homedirs = File::Find::Rule->maxdepth(1)->directory->name("home*")->in("/");
        for (File::Find::Rule->maxdepth(1)->file->name("cpmove-$user.tar.gz")->in(@homedirs)) {
            my ($source, $dest) = ($_, "$_.moved.$$.1");
            $dest++ while -e $dest;  # increment the number at .1 until no such file exists
            rename $source, $dest and print "[!] Moved potentially clobbered backup $source to $dest\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";    
            my (undef, undef, undef, undef, undef, undef, undef, $homedir) = getpwnam($user); # Get homedir before we remove account; UN-12802
            killacct();
            clearudb();
            if(leftoverdata($user, $homedir)){  # Remove potential remnants; UN-12802
                print "[!] While the account was removed in cPanel, some data was not fully removed by removeacct. Please review the information above to ensure all remnants of \"$user\" are removed.\n";
                exit;
            }
            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
