#!/usr/bin/perl
# cPanel password update
# v.01 - Perk 11/23/10
# v.02 - Rewrite - Matthew Feinberg 8-5-2011
#	added -r switch to generate randon password
#	ie. chpass -r USERNAME
# v.03 - added root user check Matthew Feinberg 8-7-2011
# v.04 - added back logic to create access hash if does not exist. will exit if not a cpanel server
# v.05 - complete re-write - mkarr - using Cpanel::ChangePasswd instead of xmlapi removing need to use access hash.
# HostGator.com LLC

use strict;
use warnings;

use lib '/usr/local/cpanel';

use Cpanel::ChangePasswd (); # internal cPanel pw change routines (it does not really export anything)

# globals

my $passlength = 12; # length for random passwords
my @passchars = ("a".."z","A".."Z","0".."9"); # characters to include in random passwords

# begin main program code

my ($user, $password) = @ARGV;

if ($user) {
    if ($user eq 'root') { # are we root
        print "[-] ERROR! I will not change the root password.\n";
    } else {
        unless ($password) { # if they did not give us a password, make one up
            print "[+] You did not give me a password. I'm gonna make one up.\n";
            $password = randtext($passlength, @passchars);
        }
        
        
        my ($status, $msg) = Cpanel::ChangePasswd::change_password(user => $user, new_password => $password, optional_services => {mysql => 1});
        
        if ($status) {
            print "[+] Success: $msg\n";
	print "[+] Processing Password Change\n";
        print "[+] Username: $user\n";
        print "[+] Password: $password\n\n";
        } else {
            print "[-] ERROR!: $msg\n";
        }
    }
} else {
    print "[-] ERROR! No user provided.\n";
    usage();
}

exit;

# end main program code

sub usage {
    print "[-] Usage: $0 USERNAME [PASSWORD]\n";
    print "[-] Password will be randomly generated if omitted.\n";
}

sub randtext {
    my $length = shift;
    return join("",@_[map{rand @_} (1..$length)]); 
}
