#!/usr/bin/perl
# pwtemp
# temporary password toggle
# https://gatorwiki.hostgator.com/Admin/PwTemp
# http://git.toolbox.hostgator.com/pwtemp
# Please submit all bug reports at bugs.hostgator.com
# why ask permission when you can ask forgiveness
# patrick p
# maintainer : jlavoy
# (C) 2012 - HostGator.com, LLC
# this was written in 2010. Judge not, lest ye be judged
use strict;
use Fcntl;
eval {
	require Cwd;
	require Sys::Hostname;
	require Getopt::Std;
	require File::Copy;
	require File::LckPwdF;
	require Digest::MD5;
};
if ( $@ ) {
	print "[!] Missing some perl modules. Installing...\n";
	do_modules();
	print "[*] Installation of new modules complete. Please re-run your command.\n";
	exit();
} else { 
	import Cwd;
	import Sys::Hostname;
	import Getopt::Std;
	import File::Copy;
	import File::LckPwdF;
	import Digest::MD5 qw(md5 md5_hex);;
}

my %opt;
my $opt_string = 'dilutrn';
getopts("$opt_string", \%opt );
use sigtrap 'handler' => \&handler, 'INT';

chomp(my ( $action, $targetuser ) = @ARGV);

if ( $action eq 'setjoomla' ) { $action = 'setjoom' }
if ( $action eq 'unsetjoomla' ) { $action = 'unsetjoom' }

my %actions = (
	setuser => \&setuser,
	unsetuser => \&unsetuser,
	setftp => \&setftp,
	unsetftp => \&unsetftp,
	setftpall => \&setftpall,
	setmail => \&setmail,
	unsetmail => \&unsetmail,
	setplesk => \&setplesk,
	unsetplesk => \&unsetplesk,
	setwp => \&setwp,
	unsetwp => \&unsetwp,
	setjoom => \&setjoom, 
	unsetjoom => \&unsetjoom,
	setdrupal => \&setdrupal,
	unsetdrupal => \&unsetdrupal,
	setmagento => \&setmagento,
	unsetmagento => \&unsetmagento,
	setzencart => \&setzencart,
	unsetzencart => \&unsetzencart,
	setvb => \&setvb,
	unsetvb => \&unsetvb,
	setmailman => \&setmailman,
	unsetmailman => \&unsetmailman,
	setwhmcs => \&setwhmcs,
	unsetwhmcs => \&unsetwhmcs,
	setphpbb => \&setphpbb,
	unsetphpbb => \&unsetphpbb,
	setsmf => \&setsmf,
	unsetsmf => \&unsetsmf
);

my @internal_domains = qw(accountservergroup.com
	apthost.com
	arvixe.com
	arvixeshared.com
	asoshared.com
	bigrock.com
	bluehost.com
	bluehost.in
	cloudhosted.com
	digitalcloud.com
	ehosts.com
	hostclear.com
	hostfinity.com
	hostgator.cl
	hostgator.co
	hostgator.com
	hostgator.com.br
	hostgator.com.tr
	hostgator.in
	hostgator.mx
	hou.hostgator.com
	ideahost.com
	myserverhosts.com
	mysitehosted.com
	prodns.cl
	prodns.com.br
	prodns.com.co
	prodns.mx
	site5.com
	webhostbox.net
	webhostsunucusu.com
	webserversystems.com
	websitewelcome.com
);

my $hostname = hostname();
my @cpuserlist;

open(my $DAT, '<', '/etc/trueuserowners');
	while (<$DAT>) {
		$_ =~ /^([a-z0-9\-\.]{1,16}):/;
		push(@cpuserlist, $1);
	}
close($DAT);

# check and cache if we're running on a shared/reseller/internal box
my $sharedcheck = 0;
foreach my $internal_domain ( @internal_domains ) {
	if ( $hostname =~ /$internal_domain/ ) {
		$sharedcheck = 1;
		last;
	}
}
$sharedcheck = 1 if -f '/usr/local/cpanel/Cpanel/Security/Policy/RootRestrict.pm';
push(@cpuserlist, 'root') unless $sharedcheck;

if ( ! -d '/root/.hgtogglehash' ) { 
	mkdir('/root/.hgtogglehash');
	chmod(0700, '/root/.hgtogglehash');
}

my $epoch = time();
open(my $test, '>', '/root/.hgtogglehash/test.' . $epoch);
	print $test $epoch;
close($test);
open($test, '<', '/root/.hgtogglehash/test.' . $epoch);
	my $check = <$test>;
close($test);
unlink('/root/.hgtogglehash/test.' . $epoch);
if ( $check != $epoch ) {
	die "[!] Unable to write to disk, please check if disk is full!\n";
}


my $mysqlcommand;
if ( -d '/var/cpanel' ) {
	$mysqlcommand = '/usr/bin/mysql --defaults-file=/root/.my.cnf -N';
} else {
	open(my $DAT, '<', '/etc/psa/.psa.shadow');
		my $mysqlpass = do { local $/; <$DAT> };
	close($DAT);
	chomp($mysqlpass);
	$mysqlcommand = "/usr/bin/mysql -uadmin -p\'$mysqlpass\' -N";
}

# at check
if ( ! -f '/etc/init.d/atd' ) {
	print "[!] at not installed, yumming...\n";
	system('yum install at -y');
	if ( ! -e '/etc/init.d/atd') {
		die "[!] at still missing, yum failed. check manually.\n";
	}
}
chomp(my $atdstatus = `/etc/init.d/atd status`);
if ( $atdstatus =~ /atd\sis\sstopped/ ) {
	print "[!] atd is not running, starting...\n";
	system("/etc/init.d/atd start");
}


if ( $action !~ /^(setuser|unsetuser|setftp|unsetftp|setftpall|setmail|unsetmail|setplesk|unsetplesk|setwp|unsetwp|setjoom|unsetjoom|setjoomla|unsetjoomla|setdrupal|unsetdrupal|setmagento|unsetmagento|setzencart|unsetzencart|setvb|unsetvb|setmailman|unsetmailman|setwhmcs|unsetwhmcs|setphpbb|unsetphpbb|setsmf|unsetsmf)$/ ) {
	print "Usage: $0 <action> <username|email|ftpaccount|database|maillist>\n";
	print qq(
Options:
	-i	- will display the URL using the hostname rather than the IP address.
	-d	- will reset ALL admin users, not just the primary. This tool is meant to be used by security in compromise situations. If you need to
		  reset just one user, do so manually.
	-dl	- will reset the user password and lock it using passwd.
	-du	- will reset the user password and unlock it using passwd.
	-dr	- will reset the password for a reseller and their sub accounts.
	-t	- output in a more transfers friendly format.

Actions:
	System - 
		setuser|unsetuser <user>
		setmail|unsetmail <email address>
		setftp|unsetftp <ftp\@user>
		setmailman|unsetmailman <maillist>
		setplesk|unsetplesk <user>
	CMS - 
		setwp|unsetwp <database>
		setjoom|unsetjoom <database>
		setdrupal|unsetdrupal <database>
		setmagento|unsetmagento <database>
		setzencart|unsetzencart <database>
		setvb|unsetvb <database>
		setwhmcs|unsetwhmcs <database>
		setphpbb|unsetphpbb <database>
		setsmf|unsetsmf <database>

Examples:
	pwtemp setuser bob
		# cpanel user 'bob' is given a temporary password, which is displayed to you.
		# this user's password will be reverted to the original value after 15min.
		# (useful to gain temporary access to bob's account)

	pwtemp unsetuser bob
		# cpanel user 'bob', if he still has a temporary password, will immediately
		# have his original password restored, skipping the remainder of the 15min.
		# (useful to allow bob to access his own account without waiting)

	pwtemp setuser -d alice
	pwtemp setuser -d alice\@ali.ce
		# give cPanel user 'alice' and email account 'alice\@ali.ce' new passwords,
		# permanently replacing the old passwords.
		# (useful if alice\@ali.ce (owned by alice) is currently authing lots of spam)

);
	exit;
}

if ( ( $targetuser !~ /^[A-Za-z0-9A-Z\-\.\_@\+]{1,128}$/ ) && ( $action =~ /^(setmail|unsetmail|setftp|unsetftp)$/ ) ) {
	die "[!] ERROR: Invalid character in e-mail address.\n";
}

if ( ( $targetuser !~ /^[A-Za-z0-9\_\.\-@]{1,64}$/ ) && ( $action =~ /^(setmailman|unsetmailman)$/ ) ) {
	die "[!] ERROR: Invalid character in list name.\n";
}

$actions{$action}->($targetuser);

sub do_modules {
	my %modules = (
		'Digest::MD5' => 'Digest-MD5-2.55',
		'File::LckPwdF' => 'File-LckPwdF-0.01'
	);
	chdir('/usr/src');
	foreach my $module ( keys %modules ) {
		print "[*] Installing $module\n";
		if ( -d $modules{$module} ) {
			system("rm -rf $modules{$module}");
		}
		if ( -f "$modules{$module}.tar.gz" ) {
			unlink("$modules{$module}.tar.gz");
		}
		system("wget -O $modules{$module}.tar.gz -q http://scripts.hostgator.com/~ursh/$modules{$module}.tar.gz");
		system("tar xfz $modules{$module}.tar.gz");
		chdir($modules{$module});
		system("/usr/bin/perl Makefile.PL 2>/dev/null 1>/dev/null");
		system("make -j4 2>/dev/null 1>/dev/null");
		system("make install 2>/dev/null 1>/dev/null");
		unlink("/usr/src/$modules{$module}.tar.gz");
	}
}

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

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

sub hash {
	my ( $string, $salt ) = @_;
	my $hash;
	open(my $DAT, '<', '/etc/libuser.conf');
		while(<$DAT>) {
			if ( /^crypt_style = (.*)$/ ) {
				$hash = $1;
				last;
			}
		}
	close($DAT);
	my $newpass;
	if ( $hash eq 'md5' ) {
		$newpass = crypt($string,"\$1\$" . $salt);
	} elsif ( $hash eq 'sha512' ) {
		$newpass = crypt($string, "\$6\$$salt");
	}
	chomp($newpass);
	return($newpass);
}

sub handler {
	print "[!] SIGINT captured! Continuing for safety!\n";
	return();
}

sub removedupe {
	my ( $action, $targetuser ) = @_;
	open(my $DAT, '-|', 'atq');
		while (<$DAT>) {
			if ( /^([0-9]+)\s+/ ) {
				my $atjob = $1;
				open(my $DAT, "-|", "at -c $atjob");
					while (<$DAT>) {
						if ( /$0\s+$action\s+$targetuser/ ) {
							print "[*] Removing old at job.\n";
							system("atrm $atjob");
							return;
						}
					}
				close($DAT);
			}
		}
	close($DAT);
	return;
}

sub resellerrun {
	my ( $action, $targetuser ) = @_;
	my $isreseller = 0;
	open(my $DAT, '<', '/var/cpanel/resellers');
		while(<$DAT>) {
			if ( /^$targetuser:/ ) {
				$isreseller = 1;
				last;
			}
		}
	close($DAT);
	if ( ! $isreseller ) {
		die "[!] User is not a reseller, don't use -r!\n";
	}
	my @subaccounts;
	open($DAT, '<', '/etc/trueuserowners');
		while(<$DAT>) {
			if ( /^([0-9a-z]+):\s$targetuser$/ ) {
				push(@subaccounts, $1);
			}
		}
	close($DAT);
	foreach my $user (@subaccounts) {
		system("pwtemp -dn setuser $user");
		system("/usr/local/cpanel/bin/ftpupdate $user $ 1>/dev/null 2>/dev/null 3>/dev/null &");
	}
}

sub confcheck {
	use Switch;
	my ($action) = @_;
	my ( $targetuser, $dbprefix, $foundprefix, $misc );
	my $confs = { 
			'setwp' => 'wp-config.php',
			'unsetwp' => 'wp-config.php',
			'setdrupal' => 'sites/default/settings.php',
			'unsetdrupal' => 'sites/default/settings.php',
			'setjoom' => 'configuration.php',
			'unsetjoom' => 'configuration.php',
			'setmagento' => 'app/etc/local.xml',
			'unsetmagento' => 'app/etc/local.xml',
			'setzencart' => 'includes/configure.php',
			'unsetzencart' => 'includes/configure.php',
			'setvb' => 'includes/config.php',
			'unsetvb' => 'includes/config.php',
			'setwhmcs' => 'configuration.php',
			'unsetwhmcs' => 'configuration.php',
			'setphpbb' => 'config.php',
			'unsetphpbb' => 'config.php',
			'setsmf' => 'Settings.php',
			'unsetsmf' => 'Settings.php'
	};
	if ( -f $confs->{$action} ) {
		open(my $DAT, '<', $confs->{$action});
			while(<$DAT>) {
				switch($action) {
					case /setwp/ {
						if (( /define\('DB_NAME', '([0-9a-zA-Z\-\_]+)'\);/ ) && ( $_ !~ /^#|\/\/|\*/ )) {
							$targetuser = $1;
						} elsif (( /\$table_prefix\s+=\s+'([0-9a-zA-Z\-\_]+)';/ ) && ( $_ !~ /^#|\/\/|\*/ )) {
							$dbprefix = $1;
							$foundprefix = 1;
						}
					}
					case /setdrupal/ { 
						if (( /'database' => '([0-9a-zA-Z\-\_]+)',/ ) || ( /\$db_url = 'mysqli:\/\/\S+:\S+\@\s+\/([0-9a-zA-Z\-\_]+)';/ )) {
							$targetuser = $1;
							last;
						}
					}
					case /setjoom/ {
						if ( /\$db\ =\ '([0-9a-zA-Z\-\_]+)';/ ) {
							$targetuser = $1;
						} elsif ( /\$dbprefix\s+=\s+'([a-zA-Z0-9\_\-]+)';/ ) {
							$dbprefix = $1;
							$foundprefix = 1;
						}
					}
					case /setmagento/ {
						if ( /<dbname><!\[CDATA\[([0-9a-zA-Z\-\_]+)\]\]><\/dbname>/ ) {
							$targetuser = $1;
						} elsif ( /\<frontName\>\<\!\[CDATA\[([0-9a-zA-Z\-\/]+)\]\]\>\<\/frontName\>/ ) {
							$misc = $1;
						}
					}
					case /setzencart/ {
						if ( /define\('DB_DATABASE', '([0-9a-zA-Z_]+)'\);/ ) {
							$targetuser = $1;
							last;
						}
					}
					case /setvb/ {
						if ( /\$config\['Database']\['dbname'] = '([0-9a-zA-Z\-\_]+)';/ ) {
							$targetuser = $1;
							last;
						}
					}
					case /setwhmcs/ {
						if ( /\$db_name = ["']([0-9a-zA-Z\-\_]+)["'];/ ) {
							$targetuser = $1;
							last;
						}
					}
					case /setphpbb/ {
						if ( /\$dbname = '([a-zA-Z0-9\-\_]+)';/ ) {
							$targetuser = $1;
							last;
						}
					}
					case /setsmf/ {
						if ( /\$db_name = '([a-zA-Z0-9\-\_]+)';/ ) {
							$targetuser = $1;
							last;
						}
					}
				}
			}
		close($DAT);
	} else {
		die "[!] No target specified and no configuration file found for specified action ($action)\n";
	}
	return($targetuser, $dbprefix, $foundprefix, $misc);
}
						
sub checktarget {
	use Switch;
	my ( $targetuser ) = @_;
        if ( ! $targetuser ) {
                die "[!] No database specified and unable to automatically determine target for ($action)\n";
        }
	switch ($action) {
		case /setuser|unsetuser/ {
			if ( $targetuser !~ /^([a-zA-Z0-9\.\-]{1,16})$/ ) {
				die "[!] $targetuser is not valid input for $action!\n";
			}
			$targetuser =~ tr/A-Z/a-z/;
		}
		case /setplesk|unsetplesk/ {
			if ( $targetuser !~ /^([a-zA-Z0-9]+)$/ ) {
				die "[!] $targetuser is not valid input for $action!\n";
			}
			$targetuser =~ tr/A-Z/a-z/;
		}
		case /setmailman|unsetmailman/ {
			if ( $targetuser !~ /^([A-Za-z0-9\-\_\.@]+)$/ ) {
				die "[!] $targetuser is not valid input for $action!\n";
			}
		}
		case /setmail|unsetmail/ {
			if ( $targetuser !~ /^([A-Za-z0-9\-\_]+)\@([A-Za-z0-9\-\.]+)$/ ) {
				die "[!] $targetuser is not valid input for $action!\n";
			}
		}
		else {
			if ( $targetuser !~ /^([a-zA-Z0-9\_\-]+)$/ ) {
				die "[!] $targetuser is not valid input for $action!\n";
			}
		}
	}
	my $target = $targetuser;
        if ($target =~ /^mysql$/) { die "lol nice try." }
	if (( $action !~ /^un/ ) && ( $action !~ /^setuser/ )) {
	        if ( -f "/root/.hgtogglehash/$target" ) {
			die "[!] ERROR: User already toggled!\n";
		}
	} elsif ( $action =~ /^setuser/ ) {
		if ( -f "/root/.hgtogglehash/$target" ) {
			print "[!] User is already toggled, would you like to untoggle them [y|N]?";
			chomp(my $answer = <STDIN>);
			if ( $answer =~ /y|yes/i ) {
				system("/root/bin/pwtemp unsetuser $target");
				exit();
			} else {
				exit();
			}
		}
	} else {
		if ( ! -s "/root/.hgtogglehash/$target" ) {
			die "[!] ERROR: User is not toggled!\n";
		}
	}
	return($target);
}

sub findprefix {
	my ($action, $targetdb) = @_;
	my %prefixes = (
			'setwp' => 'usermeta',
			'unsetwp' => 'usermeta',
			'setdrupal' => 'system',
			'unsetdrupal' => 'system',
			'setjoom' => 'session',
			'unsetjoom' => 'session',
			'setmagento' => 'core_config_data',
			'unsetmagento' => 'core_config_data',
			'setzencart' => 'admin',
			'unsetzencart' => 'admin',
			'setvb' => 'administrator',
			'unsetvb' => 'administrator',
			'setwhmcs' => 'admin',
			'unsetwhmcs' => 'admin',
			'setphpbb' => 'smilies',
			'unsetphpbb' => 'smilies',
			'setsmf' => 'smileys',
			'unsetsmf' => 'smileys'
	);
	chomp(my @tables = `$mysqlcommand $targetdb -e "show tables"`);
	my ( $dbprefix, $foundprefix );
	foreach my $thistable (@tables) {
		if ( $thistable =~ /^([a-zA-Z0-9_]+)$prefixes{$action}/ ) {
			$dbprefix = $1;
			$foundprefix = 1;
			last;
		} elsif ( $thistable =~ /^$prefixes{$action}$/ ) {
			$dbprefix = '';
			$foundprefix = 1;
			last;
		}
	}
	return($dbprefix, $foundprefix);
}

# start actions
sub setuser {
	my ( $targetuser ) = shift;
	if ( ! $targetuser ) {
		if ( Cwd->cwd() =~ /^\/home([0-9]+)?\/([0-9a-zA-Z\.\-]{1,16})/ ) {
			$targetuser = $2;
		} else {
			die "[!] No user specified and not in home directory!\n";
		}
	}
	$targetuser = checktarget($targetuser);
	if ( ( $opt{'d'} ) && ( $opt{'r'} ) ) {
		resellerrun($action, $targetuser);
		exit();
	}
	if ((!grep(/^$targetuser$/,@cpuserlist)) && ($sharedcheck)) {
		die "[!] ERROR: $targetuser is not a valid cPanel user on this server\n";
	}
	my ( $shadowuser, $shadowhash, $founduser );
	my $origfilesize = -s "/etc/shadow";
	(lock_passwd(15)) || (die "Can't lock password file:\n$! stopped");
	open(DAT,"/etc/shadow");
	while (<DAT>) {
		my $thisline = $_;
		($shadowuser, $shadowhash) = split(':',$thisline);
		if ($shadowuser =~ /^$targetuser$/) {
			$founduser = 1;
			last;
		}
	}
	close(DAT);
	if (!$founduser) {
		die "[!] ERROR: No user found with that username.\n";
	}
	if ((($shadowhash !~ /^.{34}$/) && ($shadowhash !~ /^.{98}$/) && ($shadowhash !~ /^.{106}$/)) && ($shadowhash ne "")) { 
		if ($shadowhash =~ /^!!/) {
			if ( ! $opt{'u'} ) {
				die "[!] FATAL ERROR: Cannot toggle suspended user! use -du to unlock first!\n";
			} else {
				print "[*] Unlocking user.\n";
				unlock_passwd();
				system("passwd -u $targetuser 3>/dev/null 2>/dev/null 1>/dev/null");
				lock_passwd(15);
			}
		} else {
			die "[!] FATAL ERROR: Invalid Length (!34|98|106) [" . length($shadowhash) . "] [$shadowhash]\nThis means that the users password hash in /etc/shadow is not what we would normally expect. Therefore we're stopping to avoid breaking anything. Set the password manually.\n";
		}
	}
	my $mysqlhash;
	if ($shadowuser ne 'root') { $mysqlhash = `$mysqlcommand mysql -e "select password from user where User=\'$shadowuser\' and host='localhost'"`; }
	chomp($mysqlhash);
	unless ( ! -d "/root/.hgtogglehash" ) {
		if ( ! $opt{'d'} ) { 
			open(WRITE, ">/root/.hgtogglehash/$shadowuser") || die "[!] ERROR: Couldn't open filehandle /root/.hgtogglehash/$shadowuser";
			print WRITE $shadowhash . "\n";
			if (($mysqlhash) && ($shadowuser ne 'root')) { print WRITE $mysqlhash; }
			close(WRITE);
			my $mode = 0400; chmod $mode, "/root/.hgtogglehash/$shadowuser";
		}
	} else { 
		die "[!] FATAL ERROR: /root/.hgtogglehash does not exist!"; 
	}
	my ( $string, $salt );
	if ( $shadowuser eq 'root' ) {
		( $string, $salt ) = rootpassgen();
	} else {
		( $string, $salt ) = passgen();
	}
	my $newpass = hash($string, $salt);
	open(DAT, "/etc/shadow") || die "[!] FATAL ERROR: Can't open shadow file";
	my @origshadow = <DAT>;
	close(DAT);
	foreach my $thisline (@origshadow) {
		($shadowuser, $shadowhash) = split(':',$thisline);
		if ($shadowuser =~ /^$targetuser$/) {
			if ( $shadowhash =~ /^$/ ) { die "[!] current hash in shadow file is blank. Please do a standard password reset.\n" }
			chomp($thisline);
			$thisline =~ s/^[a-z0-9\-]{1,16}:[a-zA-Z0-9\-\_\$\.\/\\\!]{34}:/$targetuser:$newpass:/g;
			$thisline =~ s/^[a-z0-9\-]{1,16}:[a-zA-Z0-9\-\_\$\.\/\\\!]{98}:/$targetuser:$newpass:/g;
			$thisline =~ s/^[a-z0-9\-]{1,16}:[a-zA-Z0-9\-\_\$\.\/\\\!]{106}:/$targetuser:$newpass:/g;
			$thisline .= "\n";
		}
	}
	if ( -f "/etc/shadow.pwtemp" ) { unlink("/etc/shadow.pwtemp") }
        #Bugzilla #3128, files getting chmod'd to 0644. open the file read/write, create if not exists, open with exclusive lock (probably unnecessary, but useful)
        sysopen(WRITE, "/etc/shadow.pwtemp", O_RDWR|O_CREAT|O_EXCL, 0600) || die "[!] FATAL ERROR: Can't open shadow file for writing: $!";
		print WRITE @origshadow;
	close(WRITE);
	my $newfilesize = -s "/etc/shadow.pwtemp";
	if ((( ($origfilesize - $newfilesize) >= 100 ) && ( ($newfilesize - $origfilesize) >= 100 )) || ($newfilesize == 0)) {
		print "[!] Shadow filesizes differ! Exiting for safety!\n";
		unlock_passwd();
		exit();
	} else {
		rename("/etc/shadow.pwtemp", "/etc/shadow");
	}
	(unlock_passwd()) || (die "Can't unlock password file:\n$! stopped");
	if ($mysqlhash) {
		print "[*] Updating mysql hash \n";
		system("$mysqlcommand mysql -e \"update user set password=password(\'$string\') where user=\'$targetuser\'; flush privileges\""); 
	}
	if ( ! $opt{'n'} ) {
		system("/usr/local/cpanel/bin/ftpupdate $targetuser 1>/dev/null 2>/dev/null 3>/dev/null &");
	}
	# set lang
	if (( ! $opt{'d'} ) && ( -e "/var/cpanel/users/$targetuser" )) {
		open(DAT, "<", "/var/cpanel/users/$targetuser") or die "[!] Cannot open cpanel user file for reading.";
			my @origuserfile = <DAT>;
		close(DAT);
		my ( $lang, $locale, $directive, $setting );
		foreach my $line (@origuserfile) {
			($directive, $setting) = split("=",$line);
			if ($directive =~ /^LANG$/) {
				$lang = $setting;
			}
			if ($directive =~ /^LOCALE$/) {
				$locale = $setting;
			}
		}
		if ( $lang !~ /english/ ) {   
			print "[*] Setting Language to English.\n";
			my $command = "cp -p /var/cpanel/users/$targetuser /var/cpanel/users/$targetuser.pwtempsetlang";
			system($command);
			open(DAT, "/var/cpanel/users/$targetuser.pwtempsetlang") or die "Cannot open userdata file.\n";
				open(WAT, ">/var/cpanel/users/$targetuser") or die "Cannot open userdata file.\n";
					while(<DAT>) {
						$_ =~ s/LANG=.*/LANG=english/;
						$_ =~ s/LOCALE=.*/LOCALE=en/;
						print WAT $_;
					}
				close(WAT);
			close(DAT);
			unlink("/var/cpanel/users/$targetuser.pwtempsetlang");
			open(WAT, ">/root/.hgtogglehash/$targetuser.lang");
				print WAT "$lang" . "$locale";
			close(WAT);
		}
	}
	if ( ! $opt{'d'} ) {
		my $restorecommand = "$0 unsetuser $targetuser '3>/dev/null 2>/dev/null 1>/dev/null'";
		system("echo $restorecommand | at now +15 minute 1>/dev/null 2>/dev/null 3>/dev/null");
		print "\n[*] Temporary password for $targetuser is $string\n";
		print "	note: this pw will expire in 15 minute(s).\n\n";
		chomp(my $ip = `hostname -i`);
		if ( $targetuser eq "root" ) {
			if ( $opt{'i'} ) {
				print " https://$hostname:2087/login?user=$targetuser&pass=$string \n\n";
			} elsif (( -d "/etc/psa" ) && ( -f "/usr/local/psa/bin/admin" )) {
				print " https://$ip:8443/ \n\n";
			} elsif (( ! $opt{'i'} ) && ( ! $sharedcheck )) {
				print " https://$ip:2087/login?user=$targetuser&pass=$string \n\n";
			}
		} else {
			open(my $DAT, "<", "/var/cpanel/resellers");
				while(<$DAT>) {
					if ( /^$targetuser:/ ) {
						if (( ! $opt{'i'} ) && ( ! $sharedcheck )) {
							print " https://$ip:2087/login?user=$targetuser&pass=$string \n";
						} else {
							print " https://$hostname:2087/login?user=$targetuser&pass=$string \n";
						}
						last;
					}
				}
			close($DAT);
			if ( $opt{'t'} ) {
				print " $ip\t$targetuser\t$string\n\n";
			} elsif (( ! $opt{'i'} ) && ( ! $sharedcheck )) {
				print " https://$ip:2083/login?user=$targetuser&pass=$string \n\n";
			} else {
				print " https://$hostname:2083/login?user=$targetuser&pass=$string \n\n";
			}
		}
	} else {
		my $isreseller = 0;
		open(my $DAT, '<', "/var/cpanel/resellers");
			while (<$DAT>) {
				if ( /^$targetuser:/ ) {
					$isreseller = 1;
					last;
				}
			}
		close($DAT);
		if ( $isreseller == 0 ) {
			print "\n[*] Cpanel password for $targetuser reset to $string \n";
		} else {
			print "\n[*] Cpanel password for reseller $targetuser reset to $string \n";
		}
		if ( $opt{'l'} ) {
			print "[*] Locking password.\n";
			system("passwd -l $targetuser 3>/dev/null 2>/dev/null 1>/dev/null");
		}
	}
}


sub unsetuser {
	my ( $targetuser ) = shift;
	if ( ! $targetuser ) {
		if ( Cwd->cwd() =~ /^\/home([0-9]+)?\/([0-9a-zA-Z\.\-]{1,16})/ ) {
			$targetuser = $2;
		} else {
			die "[!] No user specified and not in home directory!\n";
		}
	}
	$targetuser = checktarget($targetuser);
	removedupe($action, $targetuser);
	my $origfilesize = -s "/etc/shadow";
	(lock_passwd(15)) || (die "Can't lock password file:\n$! stopped");
	open(DAT, "<", "/root/.hgtogglehash/$targetuser");
		my @orighash = <DAT>;
	close(DAT);
	if (($orighash[0] !~ /^.{34}$/) && ($orighash[0] !~ /^.{98}$/) && ($orighash[0] !~ /^.{106}$/)) { 
		die "[!] ERROR: This is not a proper hash. [$orighash[0]]\n";
	}
	my $origuserhash = $orighash[0];
	my $myhash = $orighash[1];
	chomp($origuserhash,$myhash);
	open(DAT, "<", "/etc/shadow") || die "[!] FATAL ERROR: Can't open shadow file";
		my @origshadow = <DAT>;
	close(DAT),
	my ( $shadowuser, $shadowhash);
	foreach my $thisline (@origshadow) { 
		($shadowuser, $shadowhash) = split(':',$thisline);
		if ($shadowuser =~ /^$targetuser$/) {
			chomp($thisline);
			$thisline =~ s/^[a-z0-9\-]{1,16}:[a-zA-Z0-9\-\_\$\.\/\\\!]{34}:/$targetuser:$origuserhash:/g;
			$thisline =~ s/^[a-z0-9\-]{1,16}:[a-zA-Z0-9\-\_\$\.\/\\\!]{98}:/$targetuser:$origuserhash:/g;
			$thisline =~ s/^[a-z0-9\-]{1,16}:[a-zA-Z0-9\-\_\$\.\/\\\!]{106}:/$targetuser:$origuserhash:/g;
			$thisline .= "\n";
		}
	}
	if ( -f "/etc/shadow.pwtemp" ) { unlink("/etc/shadow.pwtemp") }
	# Bugzilla #3128, files getting chmod'd to 0644. open the file read/write, create if not exists, open with exclusive lock (probably unnecessary, but useful)
    	sysopen(WRITE, "/etc/shadow.pwtemp", O_RDWR|O_CREAT|O_EXCL, 0600) || die "[!] FATAL ERROR: Can't open shadow file for writing: $!";
		print WRITE @origshadow;
	close(WRITE);
	my $newfilesize = -s "/etc/shadow.pwtemp";
	if (( ($origfilesize - $newfilesize) >= 100 ) && ( ($newfilesize - $origfilesize) >= 100 )) {
		print "[!] Shadow filesizes differ! Exiting for safety!\n";
		unlock_passwd();
		exit();
	} else {
		rename("/etc/shadow.pwtemp", "/etc/shadow");
	}
	(unlock_passwd()) || (die "Can't unlock password file:\n$! stopped");
	# unset lang
	my @langsettings;
	if ( -e "/root/.hgtogglehash/$targetuser.lang" ) {
		print "[*] Restoring Language.\n";
		open(DAT, "<", "/root/.hgtogglehash/$targetuser.lang") or die "Cannot open language hash file.\n";
			while(<DAT>) {
				push(@langsettings, $_);
			}
		close(DAT);
		my @userfile;
		open(DAT, "/var/cpanel/users/$targetuser");
			@userfile = <DAT>;
		close(DAT);
		open(WAT, ">/var/cpanel/users/$targetuser");
			foreach my $line (@userfile) {
				chomp($langsettings[0]);
				$line =~ s/LANG=english/LANG=$langsettings[0]/;
				chomp($langsettings[1]);
				$line =~ s/LOCALE=en/LOCALE=$langsettings[1]/;
				print WAT $line;
			}
		close(WAT);
		unlink("/root/.hgtogglehash/$targetuser.lang");
	}
	if (($myhash) && ($targetuser ne 'root')) { system("$mysqlcommand mysql -e \"update user set password=\'$myhash\' where user=\'$targetuser\'; flush privileges\""); }
	system("/usr/local/cpanel/bin/ftpupdate $targetuser 1>/dev/null 2>/dev/null 3>/dev/null &");
	unlink("/root/.hgtogglehash/$targetuser");
	print "[*] Original password restored.\n";
	if ( ( $opt{'d'} ) && ( $opt{'l'} ) ) {
		print "[*] Locking user password.\n";
		system("passwd -l $targetuser 3>/dev/null 2>/dev/null 1>/dev/null");
	} elsif ( ( $opt{'d'} ) && ( $opt{'u'} ) ) {
		print "[*] Unlocking user password.\n";
		system("passwd -u $targetuser 3>/dev/null 2>/dev/null 1>/dev/null");
	}
}

sub setmail { 
	my ( $targetuser ) = shift;
	$targetuser =~ tr/A-Z/a-z/;
	if ( -s "/root/.hgtogglehash/$targetuser" ) { 
		die "[!] ERROR: User already toggled! Exiting!\n";
	}
	if ( ! -d "/usr/local/cpanel" ) {
		die "[!] This functional is only available on cPanel servers.\n";
	}
	my $shadowdomain;
	my $shadowemailuser;
	my $shadowhash;
	my $shadowuser;
	$targetuser =~ s/\+/\@/g;
	if ($targetuser =~ /^([a-zA-Z0-9\-\._]+)\@([a-zA-Z0-9\-\.]+)$/) { 
		$shadowemailuser = $1;
		$shadowdomain = $2;
	}
	if (( $shadowdomain =~ /^[a-zA-Z0-9-]+\.[a-zA-Z]+$/ ) ||
		( $shadowdomain =~ /^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+\.[a-zA-Z]+$/ ) ||
		( $shadowdomain =~ /^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+\.[a-zA-Z]+$/ ) ||
		( $shadowdomain =~ /^[a-zA-Z0-9-]+\.co.[a-zA-Z]{2}$/ ) ||
		( $shadowdomain =~ /^[a-zA-Z0-9-]+\.com.[a-zA-Z]{2}$/ ) ||
		( $shadowdomain =~ /^[a-zA-Z0-9-]+\.[a-zA-Z]{3}\.[a-zA-Z]{2}$/ ) &&
		( $shadowdomain !~ /^.*\;.*$/ )) {
		my $user;
		my $founddomain;
		my $founduser;
		open(DAT, "<", "/etc/userdomains");
			while (<DAT>) {	
				if ($_ =~ /^$shadowdomain: ([a-z0-9\-]{1,16})$/) {
					$user = $1;
					$founddomain = 1;
					last;
				}
			}
		close(DAT);
		if (!$founddomain) { 
			die "[!] ERROR: Can't locate domain.\n";
		}
		if ( ! -s "/home/$user/etc/$shadowdomain/shadow" ) {
			die "[!] ERROR: No e-mail shadow file exists for $shadowdomain at /home/$user/etc/$shadowdomain/shadow !\n";
		}
		open(DAT, "<", "/home/$user/etc/$shadowdomain/shadow");
			while (<DAT>) {
				chomp(my $thisline = $_);
				($shadowuser, $shadowhash) = split(':',$thisline);
				if ($shadowuser =~ /^$shadowemailuser$/) {
					$founduser = 1;
					last;
				}
			}
		close(DAT);
		if (!$founduser) { 
			die "[!] ERROR: Couldn't find that user.\n";
		}
		if (($shadowhash !~ /^.{13}$/) && ($shadowhash !~ /^.{34}$/) && ($shadowhash !~ /^.{98}$/) && ($shadowhash !~ /^.{106}$/) && ($shadowhash ne "")) {
			die "[!] FATAL ERROR: Invalid Length (!13-34-99-106) [$shadowhash]\n";
		}
		unless ( ! -d "/root/.hgtogglehash" ) {
			if ( ! $opt{'d'} ) {
				open(WRITE, ">/root/.hgtogglehash/$shadowemailuser\@$shadowdomain") || die "[!] ERROR: Couldn't write to /root/.hgtogglehash/$shadowemailuser\@$shadowdomain";
				print WRITE $shadowhash;
				close(WRITE);
				my $mode = 0400; chmod $mode, "/root/.hgtogglehash/$shadowemailuser\@$shadowdomain";
			}
		} else {
			die "[!] FATAL ERROR: /root/.hgtogglehash does not exist!";
		}
		if ( $opt{'u'} ) {
			system("chattr -ia /home/$user/etc/$shadowdomain/shadow");
		}
		my ( $string, $salt ) = passgen();
		my $newpass = hash($string, $salt);
		open(DAT, "<", "/home/$user/etc/$shadowdomain/shadow") || die "[!] FATAL ERROR: Can't open shadow file";
			my @origshadow = <DAT>;
		close(DAT);
		my ( $emailshadowuser, $emailshadowhash );
		#print "[*] mailuser: [$shadowemailuser]\n";
		foreach my $thisline (@origshadow) {
			($emailshadowuser, $emailshadowhash) = split(':',$thisline);
			if ($emailshadowuser =~ /^$shadowemailuser$/) {
				chomp($thisline);
				$thisline =~ s/^[a-z0-9\-\._]{1,128}:[a-zA-Z0-9\-\_\$\.\/\\\!]{13}($|:)/$shadowemailuser:$newpass$1/g;
				$thisline =~ s/^[a-z0-9\-\._]{1,128}:[a-zA-Z0-9\-\_\$\.\/\\\!]{34}($|:)/$shadowemailuser:$newpass$1/g;
				$thisline =~ s/^[a-z0-9\-\._]{1,128}:[a-zA-Z0-9\-\_\$\.\/\\\!]{98}($|:)/$shadowemailuser:$newpass$1/g;
				$thisline =~ s/^[a-z0-9\-\._]{1,128}:[a-zA-Z0-9\-\_\$\.\/\\\!]{106}($|:)/$shadowemailuser:$newpass$1/g;
				$thisline .= "\n";
			}
		}
		if ( ! open(WRITE, ">", "/home/$user/etc/$shadowdomain/shadow") ) {
			unlink("/root/.hgtogglehash/$shadowemailuser\@$shadowdomain");
			die "[!] FATAL ERROR: Can't open shadow file for writing.";
		}
		print WRITE @origshadow;
		close(WRITE);
		#print "[*] Wrote $shadowemailuser:$newpass to /home/$homedir/etc/$shadowdomain/shadow\n";
		chomp(my $ip = `hostname -i`);
		chomp(my $hostname = `hostname`);
		if ( ! $opt{'d'} ) {
			my $restorecommand = "$0 unsetmail $targetuser '3>/dev/null 2>/dev/null 1>/dev/null'";
			system("echo $restorecommand | at now +15 minute 1>/dev/null 2>/dev/null 3>/dev/null");
			print "\n[*] Temporary password for user $shadowuser\@$shadowdomain is $string\n";
			print "	note: this pw will expire in 15 minute(s).\n\n";
			if (( ! $opt{'i'} ) && ( ! $sharedcheck )) {
				print "	https://$ip:2096/login?user=$targetuser&pass=$string \n\n";
			} else {
				print " https://$hostname:2096/login?user=$targetuser&pass=$string  \n\n";
			}
		} else {
			if ( $opt{'l'} ) {
				system("chattr +ia /home/$user/etc/$shadowdomain/shadow");
				print "[*] $shadowdomain locked!\n";
			} elsif ( $opt{'u'} ) {
				system("chattr -ia /home/$user/etc/$shadowdomain/shadow");
				print "[*] $shadowdomain unlocked!\n";
			}
			print "\n Email password for $shadowuser\@$shadowdomain reset to $string \n";
		}
	} else {
		die "[!] FATAL ERROR: This domain is highly disgusting. (invalid characters)\n";
	}
}

sub unsetmail {
	my ( $targetuser ) = shift;
	$targetuser =~ tr/A-Z/a-z/;
	my $shadowdomain;
	my $shadowemailuser;
	my $shadowhash;
	my $shadowuser;
	$targetuser =~ s/\+/\@/g;
	if ($targetuser =~ /^([a-zA-Z0-9\-\._]+)\@([a-zA-Z0-9\-\.]+)$/) {
		$shadowemailuser = $1;
		$shadowdomain = $2;
	}
	if ( ! -s "/root/.hgtogglehash/$shadowemailuser\@$shadowdomain" ) {
		die "[!] ERROR: No original hash exists for that e-mail address.\n";
	}
	removedupe($action, $targetuser);
	open(DAT, "<", "/root/.hgtogglehash/$targetuser");
		my $orighash = <DAT>;
	close(DAT);
	if (($orighash !~ /^.{13}$/) && ($orighash !~ /^.{34}$/) && ($orighash !~ /^.{98}$/) && ($orighash !~ /^.{106}$/)) {
		die "[!] ERROR: This is not a proper hash. [$orighash]\n";
	}
	#print "[*] Original hash located. user: [$targetuser] hash: [$orighash]\n";
	my ( $user, $founddomain, $founduser );
	open(DAT, "<", "/etc/userdomains");
		while (<DAT>) {
			if (/^$shadowdomain: ([a-z0-9\-]{1,16})$/) {
				$user = $1;
				$founddomain = 1;
				last;
			}
		}
	close(DAT);
	if (!$founddomain) {
		die "[!] ERROR: Can't locate domain.\n";
	}
	if ( ! -s "/home/$user/etc/$shadowdomain/shadow" ) {
		die "[!] ERROR: No e-mail shadow file exists for $shadowdomain at /home/$user/etc/$shadowdomain/shadow !\n";
	}

	open(DAT, "/home/$user/etc/$shadowdomain/shadow") || die "[!] FATAL ERROR: Can't open shadow file";
		my @origshadow = <DAT>;
	close(DAT);
	foreach my $thisline (@origshadow) {
		($shadowuser, $shadowhash) = split(':',$thisline);
		if ($shadowuser =~ /^$shadowemailuser$/) {
			chomp($thisline);
			$thisline =~ s/^[a-z0-9\-\._]{1,128}:[a-zA-Z0-9\-\_\$\.\/\\\!]{13}($|:)/$shadowemailuser:$orighash$1/g;
			$thisline =~ s/^[a-z0-9\-\._]{1,128}:[a-zA-Z0-9\-\_\$\.\/\\\!]{34}($|:)/$shadowemailuser:$orighash$1/g;
			$thisline =~ s/^[a-z0-9\-\._]{1,128}:[a-zA-Z0-9\-\_\$\.\/\\\!]{98}($|:)/$shadowemailuser:$orighash$1/g;
			$thisline =~ s/^[a-z0-9\-\._]{1,128}:[a-zA-Z0-9\-\_\$\.\/\\\!]{106}($|:)/$shadowemailuser:$orighash$1/g;
			$thisline .= "\n";
		}
	}
	open(WRITE, ">", "/home/$user/etc/$shadowdomain/shadow") || die "[!] FATAL ERROR: Can't open shadow file for writing.";
		print WRITE @origshadow;
	close(WRITE);
	unlink("/root/.hgtogglehash/$targetuser");
	#print "[*] Shadow file written.\n";
	print "[*] Original password restored.\n";
}

sub setplesk {
	my ( $targetuser ) = shift;
	$targetuser = checktarget($targetuser);
	my $oldpass;
	if ( $targetuser =~ /^admin$/ ) {
		chomp($oldpass = `/usr/local/psa/bin/admin --show-password`);
	} else {
		die "[!] Non-admin users are currently not supported.\n";
	}
	my ( $string, $salt ) = passgen();
	if ( ! $opt{'d'} ) {
		if ( ! -f "/root/.hgtogglehash/$targetuser" ) {
			open(my $WAT, ">", "/root/.hgtogglehash/$targetuser");
				print $WAT $oldpass;
			close($WAT);
			my $mode = 0400; chmod($mode, "/root/.hgtogglehash/$targetuser");
		}
	}
	system("/usr/local/psa/bin/init_conf -u -passwd $string 3>/dev/null 2>/dev/null 1>/dev/null");
	if ( ! $opt{'d'} ) {
		my $restorecommand = "$0 unsetplesk $targetuser '3>/dev/null 2>/dev/null 1>/dev/null'";
		system("echo $restorecommand | at now + 15 minute 3>/dev/null 2>/dev/null 1>/dev/null");
		print "[*] Temporary Password: \n";
	}
	print "\tUsername: $targetuser\n";
	print "\tPassword: $string\n";
	if ( ! $opt{'d'} ) {
		print "\n\tnote: this password will expire in 15 minutes.\n";
	}
}

sub unsetplesk {
	my ( $targetuser ) = shift;
	$targetuser = checktarget($targetuser);
	removedupe($action, $targetuser);
	open(my $DAT, "<", "/root/.hgtogglehash/$targetuser") || die "FATAL ERROR: Could not find restore file!\n";
		my $orighash = <$DAT>;
	close($DAT);
	system("/usr/local/psa/bin/init_conf -u -passwd $orighash 3>/dev/null 2>/dev/null 1>/dev/null");
	unlink("/root/.hgtogglehash/$targetuser");
	print "[*] Original password restored.\n";
}

sub setwp {
	my ( $targetuser ) = shift;
	my ( $dbprefix, $foundprefix );
	if ( ! $targetuser ) {
		($targetuser, $dbprefix, $foundprefix) = confcheck($action);
	}
	my $targetdb = checktarget($targetuser);
	if ( ! $foundprefix ) {
		( $dbprefix, $foundprefix ) = findprefix($action, $targetdb);
	}
	if ( ! $foundprefix) {
		die "[!] ERROR: Db prefix could not be determined.\n";
	}
	if ( $dbprefix =~ /^[0-9a-zA-Z\-]+\_[0-9]+\_$/ ) {
		print "[!] Possible Multisite install detected.\n";
	}
	chomp(my @ids = `$mysqlcommand -o $targetdb --silent -e "SELECT DISTINCT user_id FROM ${dbprefix}usermeta WHERE meta_key LIKE '\%capabilities%' AND meta_value LIKE '\%admin%' ORDER BY umeta_id;"`);
        if ( $? != 0 ) {
                die "[!] Unable to determine user ID's. This most likely means that there are multiple \$PREFIX_usermeta tables, or multiple wordpress installations in the database. Try just running 'pwtemp setwp' from the installation directory with no database specified.\n";
        }
	foreach my $id (@ids) {
		chomp(my $adminuser = `$mysqlcommand -o $targetdb --silent -e "SELECT user_login FROM ${dbprefix}users WHERE ID='$id'"`);
		chomp(my $adminpass = `$mysqlcommand -o $targetdb --silent -e "SELECT user_pass FROM ${dbprefix}users WHERE ID='$id'"`);
		if ( ! $opt{'d'} ) {
			if ( ! -f "/root/.hgtogglehash/$targetdb" ) {
				open(my $WAT, ">", "/root/.hgtogglehash/$targetdb") or die "FATAL ERROR: Could not open /root/.hgtogglehash/$targetdb for writing.";
					print $WAT $adminpass;
				close($WAT);
				my $mode = 0400; chmod $mode, "/root/.hgtogglehash/$targetdb";
			}
		}
		my ( $string, $salt ) = passgen();
		my $reset = `$mysqlcommand -o $targetdb -e "UPDATE ${dbprefix}users SET user_pass=MD5(\'$string\') WHERE ID=\'$id\'"`;
		chomp(my $siteurl = `$mysqlcommand -o $targetdb -e "SELECT option_value FROM ${dbprefix}options WHERE option_name='siteurl'"`);
		if ( ! $opt{'d'} ) {
			my $restorecommand = "$0 unsetwp $targetdb '3>/dev/null 2>/dev/null 1>/dev/null'";
			system("echo $restorecommand | at now +15 minute 3>/dev/null 2>/dev/null 1>/dev/null");
			print "\n[*] Temporary Password: \n";
		}
		print "\n\tAdminURL: $siteurl/wp-admin\n";
		print "\tUsername: $adminuser\n";
		print "\tPassword: $string\n";
		if ( ! $opt{'d'} ) {
			print "\n\tnote: this password will expire in 15 minutes.\n";
			chomp(my $which = `which memcached 3>/dev/null 2>/dev/null 1>/dev/null; echo \$?`);
			if ( $which == 0 ) {
				print "\n[!] Memcached found, if toggle password doesn't work, restart memcached\n";
			}
			last;
		}
	}
}


sub unsetwp {
	my ( $targetuser ) = shift;
	my ( $dbprefix, $foundprefix );
	if ( ! $targetuser ) {
		($targetuser, $dbprefix, $foundprefix) = confcheck($action);
	}
	my $targetdb = checktarget($targetuser);
	removedupe($action, $targetdb);
	if ( ! $foundprefix ) {
		( $dbprefix, $foundprefix ) = findprefix($action, $targetdb);
	}
	if ( ! $foundprefix ) {
		die "[!] ERROR: Db prefix could not be determined.\n";
	}
	my $cmd = `$mysqlcommand $targetdb -e "select user_pass, ID from ${dbprefix}users where ID = (select user_id from ${dbprefix}usermeta where meta_key like '%capabilities%' and meta_value like '%admin%' order by umeta_id limit 1)"`;
	chomp($cmd);
	my ($adminpass, $userid) = split(' ', $cmd);

	open(DAT, "/root/.hgtogglehash/$targetdb") || die "FATAL ERROR: Couldn't find restore file!";
	my $orighash = <DAT>;
	close(DAT);
	$orighash =~ s/\$/\\\$/g;
	$orighash =~ s/\"/\\\"/g;
	$cmd = `$mysqlcommand $targetdb -e "update ${dbprefix}users set user_pass=\'$orighash\' where ID=\'$userid\'"`;
	unlink("/root/.hgtogglehash/$targetdb");
	print "[*] Original password restored.\n";
}

sub setdrupal {
	my ( $targetuser ) = shift;
	if ( ! $targetuser ) {
		($targetuser) = confcheck($action);
	}
	my $targetdb = checktarget($targetuser);
	my ( $dbprefix, $foundprefix ) = findprefix($action, $targetdb);
	# drupal hash generation requires php5.2. So we're gonna make sure it's there before doing anything.
	my $phpversion;
	open(my $DAT, "-|", "/usr/local/bin/php -v");
		while(<$DAT>) {
			if ( /^PHP\s+([0-9]+\.[0-9]+)/ ) {
				$phpversion = $1;
			}
		}
	close($DAT);
	if ( $phpversion < '5.2' ) {
		die "[!] ERROR: Cannot find php5.2 binary, which is a requirement for this toggle. Exiting.\n";
	}
	if ( ! $foundprefix ) {
	 	die "[!] ERROR: Db prefix could not be determined.\n";
	}
	chomp(my $username = `$mysqlcommand --silent $targetdb -e "SELECT name FROM ${dbprefix}users WHERE uid='1'"`);
	chomp(my $userid = `$mysqlcommand --silent $targetdb -e "SELECT uid FROM ${dbprefix}users WHERE uid='1'"`);
	chomp(my $adminpass = `$mysqlcommand --silent $targetdb -e "SELECT pass FROM ${dbprefix}users WHERE uid='1'"`);
	if ( ! $opt{'d'} ) {
		open(WRITE, ">/root/.hgtogglehash/$targetdb") || die "FATAL ERROR: Couldn't open /root/.hgtogglehash/$targetdb for writing.";
		print WRITE $adminpass;
		close(WRITE);
		my $mode = 0400; chmod $mode, "/root/.hgtogglehash/$targetdb";
	}
	my ( $string, $salt ) = passgen();
	# determine site path
	my $domain = `$mysqlcommand $targetdb --silent -e "select location from ${dbprefix}watchdog limit 1;"`;
	chomp($domain);
	$domain =~ s/http:\/\///g;
	$domain =~ s/install\.php.*//g;
	if ( $domain !~ /^[0-9a-zA-Z\.\-\/]+$/ ) { 
		unlink("/root/.hgtogglehash/$targetdb");
		die "ERROR: Could not determine site path from database. Cannot continue, will need to be reset manually.\n";
	}
	my @uri = split(/\//, $domain);
	$domain = shift(@uri);
	my $uripath;
	foreach my $piece (@uri) {
		$uripath .= '/' . $piece
	}
	my $path;
	if ( $domain !~ /^www\./ ) {
		$path = `grep -C5 -w 'www.$domain' /usr/local/apache/conf/httpd.conf |grep DocumentRoot | awk '{print \$2}'`;
	} else {
		$path = `grep -C5 -w '$domain' /usr/local/apache/conf/httpd.conf |grep DocumentRoot | awk '{print \$2}'`;
	}
	chomp($path);
	$path .= $uripath;
	chomp(my $unixuser = `/scripts/whoowns $domain`);
	# determine if drupal 7 which uses sha2 hashes
	my $drupalschema = `$mysqlcommand $targetdb --silent -e "select schema_version from ${dbprefix}system WHERE name='system'"`;
	chomp($drupalschema);
        if ($drupalschema > 6999) {
                my $shahash;
                my @output = `cd $path/ 2>/dev/null && sudo -u $unixuser /usr/local/bin/php ./scripts/password-hash.sh \"$string\" 2>/dev/null`;
		if ( $? != 0 ) {
			die "[!] Unable to generate password using drupals salt+hasher. Please toggle manually or ask customer for login information.\n";
		}
                if ( grep(/password/, @output) ) {
                        foreach(@output) {
                                if ( /hash:\s+(\S+)/ ) {
                                        $shahash = $1;
                                        last;
                                }
                        }
                } else {
                        $shahash = shift(@output);
                }
                chomp($shahash);
                $shahash =~ s/\$/\\\$/g;
                system("$mysqlcommand  $targetdb -e \"UPDATE ${dbprefix}users SET pass=\'$shahash\' WHERE uid=\'$userid\'\"");
        } else {
                system("$mysqlcommand  $targetdb -e \"UPDATE ${dbprefix}users SET pass=MD5(\'$string\') WHERE uid=\'$userid\'\"");
        }

	if ( ! $opt{'d'} ) {
		my $restorecommand = "$0 unsetdrupal $targetdb '3>/dev/null 2>/dev/null 1>/dev/null'";
		system("echo $restorecommand | at now +15 minute 1>/dev/null 2>/dev/null 3>/dev/null");
		print "\n[*] Temporary password:\n";
	}
	print "	Username: $username\n";
	print "	Password: $string\n\n";
	if ( ! $opt{'d'} ) { print "	note: this pw will expire in 15 minute(s).\n\n"; }
}

sub unsetdrupal {
	my ( $targetuser ) = shift;
	if ( ! $targetuser ) {
		($targetuser) = confcheck($action);
	}
	my $targetdb = checktarget($targetuser);
	removedupe($action, $targetdb);
	my ( $dbprefix, $foundprefix ) = findprefix($action, $targetdb);
	if ( ! $foundprefix ) {
		die "[!] ERROR: Db prefix could not be determined.\n";
	}
	my $userid = `$mysqlcommand --silent $targetdb -e "select uid from ${dbprefix}users where uid='1'"`;
	chomp($userid);
	open(DAT, "/root/.hgtogglehash/$targetdb") || die "FATAL ERROR: Couldn't find restore file!";
	my $orighash = <DAT>;
	close(DAT);
	$orighash =~ s/\$/\\\$/g;
	$orighash =~ s/\"/\\\"/g;
	system("$mysqlcommand  $targetdb -e \"UPDATE ${dbprefix}users SET pass=\'$orighash\' WHERE uid=\'$userid\'\"");
	unlink("/root/.hgtogglehash/$targetdb");
	print "[*] Original password restored.\n";
}


sub setjoom {
	my ( $targetuser ) = shift;
	my ($dbprefix, $foundprefix);
	if ( ! $targetuser ) {
		($targetuser, $dbprefix, $foundprefix) = confcheck($action);
	}
	my $targetdb = checktarget($targetuser);
	if ( ! $foundprefix ) {
		( $dbprefix, $foundprefix ) = findprefix($action, $targetdb);
	}
	if ( ! $foundprefix ) {
		die "[!] ERROR: DB prefix could not be determined.\n";
	}
	# determine version
	my $cmd = `$mysqlcommand $targetdb --silent -e "show tables like '\%assets';"`;
	chomp($cmd);
	my $jversion;
	if ( $cmd =~ /^.*assets$/ ) {
		$jversion = '1.7';
	} else {
		$jversion = '1.5';
	}
	# determine admin account
	my @admins;
	if ( $jversion == '1.7' ) {
                $cmd = `$mysqlcommand $targetdb --silent -e "select rules from ${dbprefix}assets where parent_id='0';"`;
                chomp($cmd);
                my @assets = split(/,/, $cmd);
                my @groupids;
                foreach my $line (@assets) {
                        if ( $line =~ /"core\.admin":{"([0-9]+)":1}/ ) {
                                push(@groupids, $1);
                        } elsif ( $line =~ /"core\.manage":{"([0-9]+)":1}/ ) {
                                push(@groupids, $1);
                        }
                }
                my @userids;
                foreach my $groupid (@groupids) {
                        push(@userids, split(/\n/, `$mysqlcommand $targetdb --silent -e "select user_id from ${dbprefix}user_usergroup_map where group_id='${groupid}';"`));
                }
                foreach my $userid (@userids) {
                        my $admin = `$mysqlcommand $targetdb --silent -e "select username from ${dbprefix}users where id='${userid}';"`;
                        chomp($admin);
			if ( $admin !~ /^$/ ) {
	                        push(@admins, $admin);
			}
                }
	} elsif ( $jversion == '1.5' ) {
		@admins = `$mysqlcommand $targetdb --silent -e "select username from ${dbprefix}users where usertype='Super Administrator';"`;
		chomp(@admins);
	}
	my $firstadmin = $admins[0];
	if ( ( $firstadmin =~ /^$/ ) || ( grep(/\s/, $firstadmin) ) ) {
		die "Could not determine admin user. Must be toggled manually.\n";
	}
	my $adminpass;
	if ( ! $opt{'d'} ) {
		$adminpass = `$mysqlcommand $targetdb --silent -e "select password from ${dbprefix}users where username='${firstadmin}';"`;
	}
	if ( ! $opt{'d'} ) {
		open(WAT, ">/root/.hgtogglehash/$targetdb") || die "FATAL ERROR: Could not open /root/.hgtogglehash/$targetdb for writing.";
			print WAT $firstadmin . "," . $adminpass;
		close(WAT);
		my $mode = 0400; chmod($mode, "/root/.hgtogglehash/$targetdb");
	}
	# generate password
	foreach my $admin (@admins) {
		my ( $string, $salt ) = passgen();
		my $hashed = md5_hex($string . $salt);
		my $genpass = $hashed . ':' . $salt;
		chomp($genpass);
		$cmd = `$mysqlcommand $targetdb -e "update ${dbprefix}users set password='${genpass}' where username='${admin}';"`;
		# setup restore
		if ( ! $opt{'d'} ) { 
			my $restorecommand = "$0 unsetjoom $targetdb '3>/dev/null 2>/dev/null 1>/dev/null'";
			system("echo $restorecommand | at now + 15 minute 1>/dev/null 2>/dev/null 3>/dev/null");
			print "\n[*] Temporary password:\n";
		}
		print "\tUsername: $admin\n";
		print "\tPassword: $string\n\n";
		if ( ! $opt{'d'} ) {
			print "\tnote: this password will expire in 15 minute(s).\n\n";
			last;
		}
	}
}

sub unsetjoom {
	my ( $targetuser ) = shift;
	my ( $dbprefix, $foundprefix );
	if ( ! $targetuser ) {
		($targetuser, $dbprefix, $foundprefix) = confcheck($action);
	}
	my $targetdb = checktarget($targetuser);
	removedupe($action, $targetdb);
	if ( ! $foundprefix ) {
		( $dbprefix, $foundprefix ) = findprefix($action, $targetdb);
	}
	if ( ! $foundprefix ) {
		die "[!] ERROR: Db prefix could not be determined.\n";
	}
	my ($restoreuser, $restorepass);
	open(DAT, "/root/.hgtogglehash/$targetdb");
		while(<DAT>) {
			if ( $_ =~ /^([A-Za-z0-9\.\-\@\_]+),([A-Za-z0-9\:\*\(\)\[\]\/\\\$\.]+)$/ ) {
				$restoreuser = $1;
				$restorepass = $2;
				last;
			}
		}
	close(DAT);
	if ( ( ! defined($restoreuser) ) || ( ! defined($restorepass) ) ) { 
		print "Could not parse /root/.hgtogglehash/$targetdb ... Most likely they have a goofy special character in their username. Restore manually from the hash below and report this to script maintainer including server and database.\n";
		system("/bin/cat /root/.hgtogglehash/$targetdb");
		exit();
	}
	system("$mysqlcommand $targetdb -e \"update ${dbprefix}users set password='${restorepass}' where username='${restoreuser}';\"");
	unlink("/root/.hgtogglehash/$targetdb");
	print "[*] Original password restored.\n";
}

sub setmagento {
	my ( $targetuser ) = shift;
	my $adminpath;
	if ( ! $targetuser ) {
		($targetuser, undef, undef, $adminpath) = confcheck($action);
	}
	my $targetdb = checktarget($targetuser);
	my ( $dbprefix, $foundprefix ) = findprefix($action, $targetdb);
	if ( ! $foundprefix ) {
		die "[!] ERROR: Db prefix could not be determined.\n";
	}
	chomp(my $adminuser = `$mysqlcommand $targetdb --silent -e "SELECT username FROM ${dbprefix}admin_user WHERE is_active='1' limit 1"`);
	chomp(my $adminpass = `$mysqlcommand $targetdb --silent -e "SELECT password FROM ${dbprefix}admin_user WHERE username='${adminuser}' limit 1"`);
	if (( ! $adminuser ) || ( ! $adminpass )) {
		die "[!] Unable to determine admin account. Unable to toggle. Please toggle manually or ask customer for login information.\n";
	}
	if ( ! $opt{'d'} ) {
		open(my $WAT, ">", "/root/.hgtogglehash/$targetdb") || die "FATAL ERROR: Cannot open /root/.hgtogglehash\n";
			print $WAT $adminpass;
		close($WAT);
		my $mode = 0400; chmod $mode, "/root/.hgtogglehash/$targetdb";
	}
	my ( $string, $salt ) = passgen();
	my $cmd = `$mysqlcommand $targetdb -e "UPDATE ${dbprefix}admin_user SET password=MD5(\'$string\') WHERE username='${adminuser}'"`;
	chomp(my $url = `$mysqlcommand $targetdb --silent -e "SELECT value FROM ${dbprefix}core_config_data WHERE path='web/unsecure/base_url' limit 1;"`);
	if ( ! $opt{'d'} ) {
		my $restorecommand = "$0 unsetmagento $targetdb '3>/dev/null 2>/dev/null 1>/dev/null'";
		system("echo $restorecommand | at now + 15 minutes 3>/dev/null 2>/dev/null 1>/dev/null");
		print "\n[*] Temporary Password:\n";
	}
	print "\n\tAdminurl: ${url}/${adminpath}/\n";
	print "\tUsername: $adminuser\n";
	print "\tPassword: $string\n\n";
	if ( ! $opt{'d'} ) { print " note: This pw will expire in 15 minutes.\n\n"; }
}	

sub unsetmagento {
	my ( $targetuser ) = shift;
	if ( ! $targetuser ) {
		($targetuser) = confcheck($action);
	}
	my $targetdb = checktarget($targetuser);
	removedupe($action, $targetdb);
	my ( $dbprefix, $foundprefix ) = findprefix($action, $targetdb);
        if ( ! $foundprefix ) {
                die "[!] ERROR: Db prefix could not be determined.\n";
        }
	chomp(my $adminuser = `$mysqlcommand $targetdb --silent -e "SELECT username FROM ${dbprefix}admin_user WHERE is_active='1' limit 1"`);
	open(my $DAT, "<", "/root/.hgtogglehash/$targetdb");
		my $orighash = <$DAT>;
	close($DAT);
	$orighash =~ s/\$/\\\$/g;
	$orighash =~ s/\"/\\\"/g;
	my $cmd = `$mysqlcommand $targetdb -e "UPDATE ${dbprefix}admin_user SET password='$orighash' WHERE username='${adminuser}'"`;
	unlink("/root/.hgtogglehash/$targetdb");
	print "[*] Original password restored.\n";
}


sub setzencart {
	my ( $targetuser ) = shift;
	if ( ! $targetuser ) {
		($targetuser) = confcheck($action);
	}
	my $targetdb = checktarget($targetuser);
	my ( $dbprefix, $foundprefix ) = findprefix($action, $targetdb);
	if ( ! $foundprefix ) {
		die "[!] ERROR: Db prefix could not be determined.\n";
	}
	chomp(my @ids = `$mysqlcommand -o $targetdb --silent -e "SELECT admin_id FROM ${dbprefix}admin;"`);
	foreach my $id (@ids) {
		chomp(my $adminuser = `$mysqlcommand -o $targetdb --silent -e "SELECT admin_name FROM ${dbprefix}admin WHERE admin_id='$id';"`);
		chomp(my $adminpass = `$mysqlcommand -o $targetdb --silent -e "SELECT admin_pass FROM ${dbprefix}admin WHERE admin_id='$id';"`);
		if ( ! $opt{'d'} ) {
			open(my $WAT, ">", "/root/.hgtogglehash/$targetdb" ) or die "FATAL ERROR: Cannot open /root/.hgtogglehash/$targetdb.";
				print $WAT "$adminuser|$adminpass";
			close($WAT);
			my $mode = 0400; chmod($mode, "/root/.hgtogglehash/$targetdb");
		}
		my ( $string, $salt ) = passgen();
		$salt = substr(md5_hex($string), 0, 2);
		my $hashed = md5_hex($salt . $string);
		chomp(my $newpass = $hashed . ":" . $salt);
		my $cmd = `$mysqlcommand -o $targetdb -e "UPDATE ${dbprefix}admin SET admin_pass=\'$newpass\' WHERE admin_id='$id';"`;
		if ( ! $opt{'d'} ) {
			my $restorecommand = "$0 unsetzencart $targetdb '3>/dev/null 2>/dev/null 1>/dev/null'";
			system("echo $restorecommand | at now + 15 minutes 3>/dev/null 2>/dev/null 1>/dev/null");
			print "\n[*] Temporary Password:\n";
		}
		print "\n\tUsername: $adminuser\n";
		print "\tPassword: $string\n\n";
		if ( ! $opt{'d'} ) {
			print " note: This pw will expire in 15 minutes.\n\n";
		}
		if ( ! $opt{'d'} ) { 
			last;
		}
	}
}


sub unsetzencart {
	my ( $targetuser ) = shift;
	if ( ! $targetuser ) {
		($targetuser) = confcheck($action);
	}
	my $targetdb = checktarget($targetuser);
	removedupe($action, $targetdb);
	my ( $dbprefix, $foundprefix ) = findprefix($action, $targetdb);
	if ( ! $foundprefix ) {
		die "[!] ERROR: Db prefix could not be determined.\n";
	}
	my ($adminuser, $orighash);
	open(my $DAT, "<", "/root/.hgtogglehash/$targetdb");
		while(<$DAT>) {
			if ( /^([a-zA-Z0-9\_\-]+)\|([a-zA-Z0-9\:]+)$/ ) {
				($adminuser, $orighash) = ($1, $2);
			}
		}
	close($DAT);
	$orighash =~ s/\$/\\\$/g;
	$orighash =~ s/\"/\\\"/g;
	my $cmd = `$mysqlcommand -o $targetdb -e "UPDATE ${dbprefix}admin SET admin_pass='$orighash' WHERE admin_name='$adminuser';"`;
	unlink("/root/.hgtogglehash/$targetdb");
	print "[*] Original password restored.\n";
}


sub setftp {
	my ( $targetuser ) = shift;
	$targetuser =~ /^([a-zA-Z0-9\-\@\.\_]+)$/;
	my $targetftp = $1;
	if ( -f "/root/.hgtogglehash/$targetftp" ) {
		die "[!] ERROR: User already toggled! Exiting!\n";
	}
	my ( $ftpuser, $domain ) = split(/\@/, $targetftp);
	chomp(my $cpaneluser = `/scripts/whoowns $domain`);
	open(my $DAT, "<", "/etc/proftpd/$cpaneluser") or die "[!] Cannot find cPanel user!\n";
		my ( $confuser, $confpass, $founduser );
		while (<$DAT>) {
			my $line = $_;
			( $confuser, $confpass ) = split(/:/, $line);
			if ( $confuser =~ /^$targetuser$/ ) {
				$founduser = '1';
				if ( ! $opt{'d'} ) { 
					open(my $WAT, ">", "/root/.hgtogglehash/$targetftp");
						print $WAT $confpass;
					close($WAT);
				}
				last;
			}
		}
	close($DAT);
	if ( $founduser != '1' ) { unlink("/root/.hgtogglehash/$targetftp"); die "[!] Cannot find specified FTP user.\n" }
	my ( $string, undef ) = passgen();
	system("/usr/local/cpanel/bin/proftpd_passwd $cpaneluser -p $ftpuser:$string");
	if ( ! $opt{'d'} ) {
		my $restorecommand = "$0 unsetftp $targetftp '3>/dev/null 2>/dev/null 1>/dev/null'";
		system("echo $restorecommand | at now +15 minute 3>/dev/null 2>/dev/null 1>/dev/null");
		print "\n[*] Temporary Password: \n";
	}
	print "\tUsername: $targetftp\n";
	print "\tPassword: $string\n";
	if ( ! $opt{'d'} ) {
		print "\n\tnote: this password will expire in 15 minutes.\n";
	}
}
	
sub unsetftp {
	my ( $targetuser ) = shift;
	$targetuser =~ /^([a-zA-Z0-9\-\@\.\_]+)$/;
	my $targetftp = $1;
	if ( ! -s "/root/.hgtogglehash/$targetftp" ) {
		die "[!] ERROR: No hash file exists for $targetftp.\n";
	}
	removedupe($action, $targetftp);
	my ( $ftpuser, $domain ) = split(/\@/, $targetftp);
	chomp(my $cpaneluser = `/scripts/whoowns $domain`);
	open(my $DAT, "<", "/root/.hgtogglehash/$targetftp");
		my $orighash = <$DAT>;
	close($DAT);
	open($DAT, "<", "/etc/proftpd/$cpaneluser") or die "Cannot open proftpd file for user.\n";
		my @origconfig = <$DAT>;
	close($DAT);
	open(my $WAT, ">", "/etc/proftpd/$cpaneluser");
		foreach my $line (@origconfig) {
			$line =~ s/^$ftpuser:.*?:/$ftpuser:$orighash:/g;
			print $WAT $line;
		}
	close($WAT);
	unlink("/root/.hgtogglehash/$targetftp");
	print "[*] Original password restored.\n";
}

sub setftpall {
	my ( $targetuser ) = shift;
	if ( -d "/usr/local/cpanel" ) {
		eval { 	use lib '/usr/local/cpanel/';
			require Cpanel::PublicAPI;
			require Cpanel::AddonDomain;
		}
	} else {
		die "[!] This function only available on cPanel servers.\n";
	}
	$targetuser =~ /^([a-zA-Z0-9]+)$/;
	my $primarydomain;
	open(my $DAT, "<", "/etc/trueuserdomains");
		while(<$DAT>) {
			if ( /^([0-9a-zA-Z\-\.]+):\s+$targetuser$/ ) {
				$primarydomain = $1;
			}
		}
	close($DAT);
	if ( ! -f "/root/.accesshash" ) { die "[!] Access hash does not exist. Feature unavailable on this server.\n" }
	my $accesshash;
	open($DAT, "<", "/root/.accesshash");
		while(<$DAT>) {
			chomp;
			$accesshash .= $_;
		}
	close($DAT);
	my $cp = Cpanel::PublicAPI->new('user' => 'root', 'accesshash' => $accesshash);
	$ENV{'REMOTE_USER'} = 'root';
	my $list = $cp->cpanel_api2_request('whostmgr', { 'module' => 'Ftp', 'func' => 'listftp', 'user' => "$targetuser" }, 
		{
			'include_acct_types' => 'sub',
		}
	);
	$list = $list->{cpanelresult}->{data};
	my @ftpusers;
	foreach my $i ( 0 .. $#{$list} ) {
		push(@ftpusers, $list->[$i]->{user});
	}
	print "\n";
	foreach my $i ( 0 .. $#ftpusers) {
		my ( $string, undef ) = passgen();
		my $set = $cp->cpanel_api2_request('whostmgr', { 'module' => 'Ftp', 'func' => 'passwd', 'user' => "$targetuser"},
			{
				'user' => "$ftpusers[$i]",
				'pass' => "$string",
			}
		);
		$set = $set->{cpanelresult}->{data}->[0]->{result};
		if ( $set != 0 ) {
			print "\tUser: $ftpusers[$i]\@$primarydomain\n";
			print "\tPass: $string\n\n";
		}
	}
}

sub setvb {
	my ( $targetuser ) = shift;
	if ( ! $targetuser ) {
		($targetuser) = confcheck($action);
	}
	my $targetdb = checktarget($targetuser);
	my ( $dbprefix, $foundprefix ) = findprefix($action, $targetdb);
	if (!$foundprefix) { 
		die "[!] ERROR: Db prefix could not be determined.\n";
	}
	chomp(my $usergroup = `$mysqlcommand --silent -o $targetdb -e "select usergroupid from ${dbprefix}usergroup where usertitle='Administrator';"`);
	chomp(my $adminuser = `$mysqlcommand --silent -o $targetdb -e "select username from ${dbprefix}user where usergroupid='$usergroup' limit 1;"`);
	chomp(my $adminpass = `$mysqlcommand --silent -o $targetdb -e "select password from ${dbprefix}user where usergroupid='$usergroup' and username='$adminuser';"`);
	chomp(my $adminsalt = `$mysqlcommand --silent -o $targetdb -e "select salt from ${dbprefix}user where usergroupid='$usergroup' and username='$adminuser';"`);
	if ( ! $opt{'d'} ) {
		if ( ! -f "/root/.hgtogglehash/$targetdb" ) {
			open(my $WAT, ">", "/root/.hgtogglehash/$targetdb");
				print $WAT "$adminuser:$adminpass:$adminsalt";
			close($WAT);
			my $mode = 0400; chmod($mode, "/root/.hgtogglehash/$targetdb");
		}
	}
	my ( $string, $salt ) = passgen();
	my $md5 = Digest::MD5->new;
	$md5->add($string);
	my $stageone = $md5->clone->hexdigest;
	$md5 = Digest::MD5->new;
	$md5->add($stageone, $salt);
	my $stagetwo = $md5->clone->hexdigest;
	system("$mysqlcommand -o $targetdb -e \"UPDATE ${dbprefix}user SET password='$stagetwo' where usergroupid='$usergroup' and username='$adminuser'\"");
	system("$mysqlcommand -o $targetdb -e \"UPDATE ${dbprefix}user SET salt='$salt' where usergroupid='$usergroup' and username='$adminuser'\"");
	if ( ! $opt{'d'} ) {
		my $restorecommand = "$0 unsetvb $targetdb '3>/dev/null 2>/dev/null 1>/dev/null'";
		system("echo $restorecommand | at now +15 minute 3>/dev/null 2>/dev/null 1>/dev/null");
		print "\n[*] Temporary Password: \n";
	}
	print "\tUsername: $adminuser\n";
	print "\tPassword: $string\n";
	if ( ! $opt{'d'} ) {
		print "\n\tnote: This password will expire in 15 minutes.\n";
	}
}

sub unsetvb {
	my ( $targetuser ) = shift;
	if ( ! $targetuser ) {
		($targetuser) = confcheck($action);
	}
	my $targetdb = checktarget($targetuser);
	removedupe($action, $targetdb);
	my ( $dbprefix, $foundprefix ) = findprefix($action, $targetdb);
	if (!$foundprefix) {
		die "[!] ERROR: Db prefix could not be determined.\n";
	}
	open(my $DAT, "<", "/root/.hgtogglehash/$targetdb") or die "[!] ERROR: Restore hash not found.\n";
		my $data = <$DAT>;
		my ( $adminuser, $adminpass, $adminsalt ) = split(/:/, $data);
	close($DAT);

	$adminsalt =~ s/'/\\'/g;
	$adminsalt =~ s/\"/\\\"/g;
	$adminsalt =~ s/\$/\\\$/g;
	$adminsalt =~ s|/|\/|g;
	$adminpass =~ s/'/\\'/g;
	$adminpass =~ s/\"/\\\"/g;
	$adminpass =~ s/\$/\\\$/g;
	$adminpass =~ s|/|\/|g;
	system("$mysqlcommand -o $targetdb -e \"UPDATE ${dbprefix}user SET password='$adminpass' WHERE username='$adminuser'\"");
	system("$mysqlcommand -o $targetdb -e \"UPDATE ${dbprefix}user SET salt='$adminsalt' WHERE username='$adminuser'\"");
	unlink("/root/.hgtogglehash/$targetdb");
	print "[*] Original password restored.\n";
}

sub setmailman {
	my ( $targetuser ) = shift;
	$targetuser =~ s/@/_/g;
	$targetuser =~ /^([a-zA-Z0-9\_\.\-]+)$/;
	my $targetlist = checktarget($targetuser);
	if ( ! -d "/usr/local/cpanel/3rdparty/mailman" ) { die "Mailman not found, this toggle only works for cPanel boxes.\n" }
	if ( ! -d "/usr/local/cpanel/3rdparty/mailman/lists/$targetlist" ) { die "List not found!\n" }
	chomp(my $oldpass = `strings /usr/local/cpanel/3rdparty/mailman/lists/$targetlist/config.pck |grep "^passwordq"`);
	if ( ! $opt{'d'} ) {
		open(my $WAT, ">", "/root/.hgtogglehash/$targetlist") or die "FATAL ERROR: Cannot create /root/.hgtogglehash/$targetlist.";
			print $WAT $oldpass;
		close($WAT);
		my $mode = 0400; chmod($mode, "/root/.hgtogglehash/$targetlist");
	}
	my ( $string, $salt ) = passgen();
	system("/usr/local/cpanel/3rdparty/mailman/bin/change_pw --listname=$targetlist -p $string 3>/dev/null 2>/dev/null 1>/dev/null");
	if ( ! $opt{'d'} ) {
		my $restorecommand = "$0 unsetmailman $targetlist '3>/dev/null 2>/dev/null 1>/dev/null'";
		system("echo $restorecommand | at now + 15 minutes 3>/dev/null 2>/dev/null 1>/dev/null");
		print "\n[*] Temporary Password:\n";
	}
	chomp(my $ip = `hostname -i`);
	if ( $ip =~ /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/ ) {
		print "\n\tList: http://$ip/mailman/admin/$targetlist\n";
	}
	print "\tPass: $string\n\n";
	if ( ! $opt{'d'} ) {
		print " note: This pw will expire in 15 minutes.\n\n";
	}
}

sub unsetmailman {
	my ( $targetuser ) = shift;
	$targetuser =~ s/@/_/g;
	$targetuser =~ /^([a-zA-Z0-9\_\.\-]+)$/;
	my $targetlist = checktarget($targetuser);
	removedupe($action, $targetlist);
	open(my $DAT, "<", "/root/.hgtogglehash/$targetlist");
		my $restorepass = <$DAT>;
	close($DAT);
	open($DAT, "<", "/usr/local/cpanel/3rdparty/mailman/lists/$targetlist/config.pck");
		my @origconfig = <$DAT>;
	close($DAT);
	open(my $WAT, ">", "/usr/local/cpanel/3rdparty/mailman/lists/$targetlist/config.pck");
		foreach my $line (@origconfig) {
			$line =~ s/passwordq[\*\)]U.*[\*\+]U/$restorepass/g;
			print $WAT $line;
		}
	close($WAT);
	unlink("/root/.hgtogglehash/$targetlist");
	print "[*] Original password restore.\n";
}

sub setwhmcs {
	my ( $targetuser ) = shift;
	if ( ! $targetuser ) {
		($targetuser) = confcheck($action);
	}
	my $targetdb = checktarget($targetuser);
	my ( $dbprefix, $foundprefix ) = findprefix($action, $targetdb);
	if (!$foundprefix) { 
		die "[!] ERROR: Db prefix could not be determined.\n";
	}
	chomp(my $adminuser = `$mysqlcommand -o $targetdb --silent -e "SELECT username FROM ${dbprefix}admins WHERE roleid='1' limit 1;"`);
	chomp(my $adminpass = `$mysqlcommand -o $targetdb --silent -e "SELECT password FROM ${dbprefix}admins WHERE roleid='1' limit 1;"`);
	if ( ! $opt{'d'} ) {
		if ( ! -f "/root/.hgtogglehash/$targetdb" ) {
			open(my $WAT, ">", "/root/.hgtogglehash/$targetdb") or die "FATAL ERROR: Could not open /root/.hgtogglehash/$targetdb for writing.";
				print $WAT $adminpass;
			close($WAT);
			my $mode = 0400; chmod $mode, "/root/.hgtogglehash/$targetdb";
		}
	}
	my ( $string, $salt ) = passgen();
	my $reset = `$mysqlcommand -o $targetdb -e "UPDATE ${dbprefix}admins SET password=MD5(\'$string\') WHERE username=\'$adminuser\'"`;
	if ( ! $opt{'d'} ) {
		my $restorecommand = "$0 unsetwhmcs $targetdb '3>/dev/null 2>/dev/null 1>/dev/null'";
		system("echo $restorecommand | at now +15 minute 3>/dev/null 2>/dev/null 1>/dev/null");
		print "\n[*] Temporary Password: \n";
	}
	print "\tUsername: $adminuser\n";
	print "\tPassword: $string\n";
	if ( ! $opt{'d'} ) {
		print "\n\tnote: this password will expire in 15 minutes.\n";
	}
}

sub unsetwhmcs {
	my ( $targetuser ) = shift;
	if ( ! $targetuser ) {
		($targetuser) = confcheck($action);
	}
	my $targetdb = checktarget($targetuser);
	removedupe($action, $targetdb);
	my ( $dbprefix, $foundprefix ) = findprefix($action, $targetdb);
	if (!$foundprefix) {
		die "[!] ERROR: Dbprefix could not be determined.\n";
	}
	chomp(my $adminuser = `$mysqlcommand $targetdb -e "SELECT username FROM ${dbprefix}admins WHERE roleid='1' limit 1;"`);
	open(my $DAT, "<", "/root/.hgtogglehash/$targetdb") or die "FATAL ERROR: Cannot find restore file!\n";
		my $orighash = <$DAT>;
	close($DAT);
	$orighash =~ s/\$/\\\$/g;
	$orighash =~ s/\"/\\\"/g;
	my $cmd = `$mysqlcommand $targetdb -e "UPDATE ${dbprefix}admins SET password='$orighash' WHERE roleid='1';"`;
	unlink("/root/.hgtogglehash/$targetdb");
	print "[*] Original password restored.\n";
}

sub setphpbb {
	my ( $targetuser ) = shift;
	if ( ! $targetuser ) {
		($targetuser) = confcheck($action);
	}
	$targetuser =~ /^([a-zA-Z0-9\_\-]+)$/;
	my $targetdb = $1;

	my ( $dbprefix, $foundprefix ) = findprefix($action, $targetdb);
	if (!$foundprefix) { 
		die "[!] ERROR: Db prefix could not be determined.\n";
	}
	chomp(my $usergroup = `$mysqlcommand --silent -o $targetdb -e "select group_id from ${dbprefix}groups where group_name='ADMINISTRATORS' limit 1;"`);
	chomp(my $adminuser = `$mysqlcommand --silent -o $targetdb -e "select username from ${dbprefix}users where group_id='$usergroup' limit 1;"`);
	chomp(my $adminpass = `$mysqlcommand --silent -o $targetdb -e "select user_password from ${dbprefix}users where group_id='$usergroup' and username='$adminuser';"`);
	if ( ! $opt{'d'} ) {
		if ( ! -f "/root/.hgtogglehash/$targetdb" ) {
			open(my $WAT, ">", "/root/.hgtogglehash/$targetdb");
				print $WAT "$adminuser:$adminpass";
			close($WAT);
			my $mode = 0400; chmod($mode, "/root/.hgtogglehash/$targetdb");
		}
	}
	my ( $string, $salt ) = passgen();
	system("$mysqlcommand -o $targetdb -e \"UPDATE ${dbprefix}users SET user_password = MD5('$string') where group_id='$usergroup' and username='$adminuser'\"");
	if ( ! $opt{'d'} ) {
		my $restorecommand = "$0 unsetvb $targetdb '3>/dev/null 2>/dev/null 1>/dev/null'";
		system("echo $restorecommand | at now +15 minute 3>/dev/null 2>/dev/null 1>/dev/null");
		print "\n[*] Temporary Password: \n";
	}
	print "\tUsername: $adminuser\n";
	print "\tPassword: $string\n";
	if ( ! $opt{'d'} ) {
		print "\n\tnote: This password will expire in 15 minutes.\n";
	}
}

sub unsetphpbb {
	my ( $targetuser ) = shift;
	if ( ! $targetuser ) {
		($targetuser) = confcheck($action);
	}
	my $targetdb = checktarget($targetuser);
	removedupe($action, $targetdb);
	my ( $dbprefix, $foundprefix ) = findprefix($action, $targetdb);
	if (!$foundprefix) {
		die "[!] ERROR: Db prefix could not be determined.\n";
	}
	open(my $DAT, "<", "/root/.hgtogglehash/$targetdb") or die "[!] ERROR: Restore hash not found.\n";
		my $data = <$DAT>;
		my ( $adminuser, $adminpass ) = split(/:/, $data);
	close($DAT);

	$adminpass =~ s/'/\\'/g;
	$adminpass =~ s/\$/\\\$/g;
	$adminpass =~ s/\"/\\\"/g;
	$adminpass =~ s|/|\/|g;
	system("$mysqlcommand -o $targetdb -e \"UPDATE ${dbprefix}users SET user_password='$adminpass' WHERE username='$adminuser'\"");
	unlink("/root/.hgtogglehash/$targetdb");
	print "[*] Original password restored.\n";
}

sub setsmf {
	my ( $targetuser ) = shift;
	if ( ! $targetuser ) {
		($targetuser) = confcheck($action);
	}
	$targetuser =~ /^([a-zA-Z0-9\_\-]+)$/;
	my $targetdb = $1;

	my ( $dbprefix, $foundprefix ) = findprefix($action, $targetdb);
	if (!$foundprefix) { 
		die "[!] ERROR: Db prefix could not be determined.\n";
	}
	chomp(my $usergroup = `$mysqlcommand --silent -o $targetdb -e "select id_group from ${dbprefix}membergroups where group_name='Administrator' limit 1;"`);
	chomp(my $adminuser = `$mysqlcommand --silent -o $targetdb -e "select member_name from ${dbprefix}members where id_group='$usergroup' limit 1;"`);
	chomp(my $adminpass = `$mysqlcommand --silent -o $targetdb -e "select passwd from ${dbprefix}members where id_group='$usergroup' and member_name='$adminuser';"`);
	chomp(my $adminsalt = `$mysqlcommand --silent -o $targetdb -e "select password_salt from ${dbprefix}members where id_group='$usergroup' and member_name='$adminuser';"`);
	if ( ! $opt{'d'} ) {
		if ( ! -f "/root/.hgtogglehash/$targetdb" ) {
			open(my $WAT, ">", "/root/.hgtogglehash/$targetdb");
				print $WAT "$adminuser:$adminpass:$adminsalt";
			close($WAT);
			my $mode = 0400; chmod($mode, "/root/.hgtogglehash/$targetdb");
		}
	}
	my ( $string, $salt ) = passgen();
	my $lcadminuser = lc($adminuser);
	my $newstring = $adminuser . $string;
	system("$mysqlcommand -o $targetdb -e \"UPDATE ${dbprefix}members SET passwd = SHA1('$newstring') where id_group='$usergroup' and member_name='$adminuser'\"");
	system("$mysqlcommand -o $targetdb -e \"UPDATE ${dbprefix}members SET password_salt = '$salt' where id_group='$usergroup' and member_name='$adminuser'\"");
	if ( ! $opt{'d'} ) {
		my $restorecommand = "$0 unsetsmf $targetdb '3>/dev/null 2>/dev/null 1>/dev/null'";
		system("echo $restorecommand | at now +15 minute 3>/dev/null 2>/dev/null 1>/dev/null");
		print "\n[*] Temporary Password: \n";
	}
	print "\tUsername: $adminuser\n";
	print "\tPassword: $string\n";
	if ( ! $opt{'d'} ) {
		print "\n\tnote: This password will expire in 15 minutes.\n";
	}
}

sub unsetsmf {
	my ( $targetuser ) = shift;
	if ( ! $targetuser ) {
		($targetuser) = confcheck($action);
	}
	my $targetdb = checktarget($targetuser);
	removedupe($action, $targetdb);
	my ( $dbprefix, $foundprefix ) = findprefix($action, $targetdb);
	if (!$foundprefix) {
		die "[!] ERROR: Db prefix could not be determined.\n";
	}
	open(my $DAT, "<", "/root/.hgtogglehash/$targetdb") or die "[!] ERROR: Restore hash not found.\n";
		my $data = <$DAT>;
		my ( $adminuser, $adminpass, $adminsalt ) = split(/:/, $data);
	close($DAT);

	$adminpass =~ s/'/\\'/g;
	$adminpass =~ s/\$/\\\$/g;
	$adminpass =~ s/\"/\\\"/g;
	$adminpass =~ s|/|\/|g;
	system("$mysqlcommand -o $targetdb -e \"UPDATE ${dbprefix}members SET passwd='$adminpass' WHERE member_name='$adminuser'\"");
	system("$mysqlcommand -o $targetdb -e \"UPDATE ${dbprefix}members SET password_salt='$adminsalt' WHERE member_name='$adminuser'\"");
	unlink("/root/.hgtogglehash/$targetdb");
	print "[*] Original password restored.\n";
}
