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

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_domains = check_ssl();
if ( @{$ssl_domains} > 0 ) {
    foreach my $domain ( @{$ssl_domains} ) {
        print "[*] SSL found for $domain\n";
        print "[*] Saving SSL data...\n";
        mkdir "/tmp/hg_save_ssl/";
        cp_ssl($domain);
    }
}

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 @ssl_domains;
    open(my $fh, '<', '/etc/userdomains');
        while(<$fh>) {
            if ( /^([a-z0-9\-\.]+):\s$user$/ ) {
                my $domain = $1;
                if ( -f "/var/cpanel/ssl/apache_tls/$domain/certificates" ) {
                    push(@ssl_domains, $domain);
                }
            }
        }
    close($fh);
    return(\@ssl_domains);
}

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/json-api/accountsummary?user=$user" );
    $request->header( Authorization => $auth );
    my $response = $ua->request($request);
    my $data = JSON->new->utf8->decode($response->content);
    my $size = $data->{'acct'}[0]->{'diskused'};
    $size =~ s/M//g;
    $size =~ s/none/0/g;
    my $suspend = $data->{'acct'}[0]->{'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_domains} > 0 ) {
                installssl($ssl_domains);
            }
            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/json-api/removeacct?user=$user" );
    $request->header( Authorization => $auth );
    my $response = $ua->request($request);
    my $data = JSON->new->utf8->decode($response->content);

    if ( $data->{'result'}[0]->{'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/json-api/createacct?username=$user&domain=$domain&plan=$plan&contactemail=$contact&password=$password");
    } else {
        $request = HTTP::Request->new( GET => "https://127.0.0.1:2087/json-api/createacct?username=$user&domain=$domain&plan=$plan&password=$password");
    }
    $request->header( Authorization => $auth );
    my $response = $ua->request($request);
    my $data = JSON->new->utf8->decode($response->content);
    if ( $data->{'result'}[0]->{'status'} ) {
        print "[*] Account $user successfully created with password $password\n";
    } else {
        print "[!] Unable to create $user on the server.\n";
        print "Error: ". $data->{'result'}[0]->{'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/json-api/setsiteip?user=$user&ip=$ip" );
    $request->header( Authorization => $auth );
    my $response = $ua->request($request);
    my $data = JSON->new->utf8->decode($response->content);
    if ( $data->{'result'}[0]->{'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 $ssl_domains = shift;
    print "Please install SSL certificate manually.";
    foreach my $domain ( @{$ssl_domains} ) {
        print "$domain - /tmp/hg_save_ssl/$domain:\n";
        open(my $fh, '<', '/tmp/hg_save_ssl/' . $domain);
            while(<$fh>) {
                print;
            }
        close($fh);
        print("\n\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 $ssl_domain = shift;
    my $ssl_file;
    my $save_path = '/tmp/hg_save_ssl';
    if ( -f "/var/cpanel/ssl/apache_tls/$ssl_domain/combined" ) {
        $ssl_file = "/var/cpanel/ssl/apache_tls/$ssl_domain/combined";
    } else {
        $ssl_file = "/var/cpanel/ssl/apache_tls/$ssl_domain/certificates";
    }
    if ( ! $ssl_file ) {
        die "Unable to find SSL certificate, check this and reset manually.";
    }
    copy($ssl_file, $save_path . '/' . $ssl_domain);
    chmod(0400, $save_path . '/' . $ssl_domain);
    if ( ! -f $save_path . '/' . $ssl_domain ) {
        die "Saving of certificate failed. Reset manually";
    }
}

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
