#!/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
use strict;
use Cwd;
use Getopt::Std;
use File::Copy;
use File::LckPwdF;
use Digest::MD5 qw(md5 md5_hex);
my %opt;
my $opt_string = 'dilu';
getopts("$opt_string", \%opt );

chomp(my $action = $ARGV[0]);
chomp(my $targetuser = $ARGV[1]);

my @cpuserlist;
chomp(my $hostname = `hostname`);
open(DAT, "<", "/etc/trueuserowners");
	while (<DAT>) {
		$_ =~ /^([a-z0-9\-\.]{1,14}):/;
		push(@cpuserlist, $1);
	}
close(DAT);
if ( $hostname !~ /(hostgator\.com|websitewelcome\.com)/ ) {
        push(@cpuserlist, "root");
}

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

# plesk / my.cnf check
my $rootpass;
if ( -f "/etc/psa/.psa.shadow" ) {
	chomp($rootpass = `cat /etc/psa/.psa.shadow`);
	if ( ! -f "/root/.my.cnf" ) {
		open(my $WAT, ">", "/root/.my.cnf") or die "FATAL ERROR: Failed to create /root/.my.cnf\n";
			print $WAT qq([client]\n);
			print $WAT qq(user="admin"\n);
			print $WAT qq(pass="$rootpass"\n);
		close($WAT);
	}
}


if ( $action !~ /^(setuser|unsetuser|setftp|unsetftp|setftpall|setmail|unsetmail|setwp|unsetwp|setjoom|unsetjoom|setjoomla|unsetjoomla|setdrupal|unsetdrupal|setmagento|unsetmagento|setzencart|unsetzencart|setvb|unsetvb|setmailman|unsetmailman|setwhmcs|unsetwhmcs)$/ ) {
	print "Usage: $0 <action> <username|email|ftpaccount|database|maillist>\n";
	print qq(
Options:
	-i	- will display the URL using the IP address rather than the hostname.
	-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.

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

);
	exit;
}

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

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

sub passgen {
        my @chars = ('A'..'Z','a'..'z','0'..'9');
        my $num = scalar(@chars);
        my ( $i, $x, $string, $salt );
        for ( $i = 10; $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 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;
}

if ($action =~ /^setuser$/) {
	if ( ! $targetuser ) {
		if ( Cwd->cwd() =~ /^\/home\/([0-9a-zA-Z\.]{1,14})/ ) {
			$targetuser = $1;
		} else {
			die "[!] No user specified and not in home directory!\n";
		}
	}
	$targetuser =~ /^([a-zA-Z0-9\.]{1,14})$/;
	$targetuser =~ tr/A-Z/a-z/;
	if ((!grep(/^$targetuser$/,@cpuserlist)) && ($hostname =~ /(websitewelcome|hostgator).com/)) {
		print "[!] ERROR: $targetuser is not a valid cPanel user on this server\n";
		exit;
	}
	if ( -s "/root/.hgtogglehash/$targetuser" ) { 
		print "[!] ERROR: User already toggled! Exiting!\n";
		exit;
	}
	my $shadowuser;
	my $shadowhash;
	my $founduser;
	(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) {
		print "[!] ERROR: No user found with that username.\n";
		exit;
	}
	if (($shadowhash !~ /^.{34}$/)&&($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";
				system("passwd -u $targetuser 3>/dev/null 2>/dev/null 1>/dev/null");
			}
		} else {
			print "[!] FATAL ERROR: Invalid Length (!34) [$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";
			exit;
		}
	}
	my $mysqlhash;
	if ($shadowuser ne 'root') { $mysqlhash = `/usr/bin/mysql --defaults-file=/root/.my.cnf mysql -e "select password from user where User=\'$shadowuser\' and host='localhost'" |grep -v password`; }
	chomp($mysqlhash);
	if ( ! -d "/root/.hgtogglehash" ) { system("mkdir -p /root/.hgtogglehash && chmod 700 /root/.hgtogglehash"); }
	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 = crypt($string,"\$1\$" . $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$/) {
			chomp($thisline);
			$thisline =~ s/^[a-z0-9\-]{1,14}:.{34}/$targetuser:$newpass/g;
			$thisline .= "\n";
		}
	}
	open(WRITE, ">", "/etc/shadow") || die "[!] FATAL ERROR: Can't open shadow file for writing.";
		print WRITE @origshadow;
	close(WRITE);
	(unlock_passwd()) || (die "Can't unlock password file:\n$! stopped");
	if ($mysqlhash) {
		print "[*] Updating mysql hash \n";
		system("mysql mysql -e \"update user set password=password(\'$string\') where user=\'$targetuser\' limit 2; flush privileges\""); 
	}
	system("/scripts/ftpupdate 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";
		if ( $targetuser eq "root" ) {
			if ( $opt{'i'} ) {
				chomp(my $ip = `hostname -i`);
				print " http://$ip:2086/login?user=$targetuser&pass=$string \n\n";
			} else {
				print " https://$hostname:2087/login?user=$targetuser&pass=$string \n\n";
			}
		} else {
			open(my $DAT, "<", "/var/cpanel/resellers");
				while(<$DAT>) {
					if ( /^$targetuser:/ ) {
						print " https://$hostname:2087/login?user=$targetuser&pass=$string \n";
						last;
					}
				}
			close($DAT);
			if ( $opt{'i'} ) { 
				chomp(my $ip = `hostname -i`); 
				print " http://$ip:2082/login?user=$targetuser&pass=$string \n\n";
			} else {
				print " https://$hostname:2083/login?user=$targetuser&pass=$string \n\n";
			}
		}
	} else {
		print "\n[*] Cpanel password for $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");
		}
	}
}


if ($action =~ /^unsetuser$/) {
	if ( ! $targetuser ) {
		if ( Cwd->cwd() =~ /^\/home\/([0-9a-zA-Z\.]{1,14})/ ) {
			$targetuser = $1;
		} else {
			die "[!] No user specified and not in home directory!\n";
		}
	}
	$targetuser =~ /^([a-zA-Z0-9\_\.]{1,14})$/;
	$targetuser =~ tr/A-Z/a-z/;
	if ( ! -s "/root/.hgtogglehash/$targetuser" ) { 
		print "[!] ERROR: No hash file exists for $targetuser.\n";
		exit;
	}
	removedupe($action, $targetuser);
	(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}$/) { 
		print "[!] ERROR: This is not a proper hash. [$orighash[0]]\n";
		exit;
	}
	my $origuserhash = $orighash[0];
	my $myhash = $orighash[1];
	chomp($origuserhash,$myhash);
	#print "[*] Original hash located. user: [$targetuser] hash: [$orighash]\n";
	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,14}:.{34}/$targetuser:$origuserhash/g;
			$thisline .= "\n";
		}
	}
	open(WRITE, ">/etc/shadow") || die "[!] FATAL ERROR: Can't open shadow file for writing.";
		print WRITE @origshadow;
	close(WRITE);
	(unlock_passwd()) || (die "Can't unlock password file:\n$! stopped");
	#print "[*] Shadow file written.\n";
	#print "[*] Testing shadow file integrity...";
	my @output = `passwd -S $targetuser`;
	#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 (grep(m/warning/i,@output)) { 
		print "\n\n[!] **** SUPER FATAL ERROR: THERE IS A PROBLEM WITH THE SHADOW FILE CONTACT LVL III IMMEDIATELY!\n\n";
		print "	 IF LOGGED IN VIA SSH - DO NOT LOG OUT! ****\n\n";
	} else {
		#print "OK!\n";
		if (($myhash) && ($targetuser ne 'root')) { system("mysql mysql -e \"update user set password=\'$myhash\' where user=\'$targetuser\' limit 2; flush privileges\""); }
		system("/scripts/ftpupdate 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");
	}
}

if ($action =~ /^setmail$/) { 
	$targetuser =~ tr/A-Z/a-z/;
	if ( -s "/root/.hgtogglehash/$targetuser" ) { 
		print "[!] ERROR: User already toggled! Exiting!\n";
		exit;
	}
	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]{2,4}$/ ) ||
		( $shadowdomain =~ /^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+\.[a-zA-Z]{2,4}$/ ) ||
		( $shadowdomain =~ /^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+\.[a-zA-Z]{2,4}$/ ) ||
		( $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-]+\.travel$/ ) ||
		( $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,9})$/) {
					$user = $1;
					$founddomain = 1;
					last;
				}
			}
		close(DAT);
		if (!$founddomain) { 
			print "[!] ERROR: Can't locate domain.\n";
			exit;
		}
		if ( ! -s "/home/$user/etc/$shadowdomain/shadow" ) {
			print "[!] ERROR: No e-mail shadow file exists for $shadowdomain at /home/$user/etc/$shadowdomain/shadow !\n";
			exit;
		}
		open(DAT, "<", "/home/$user/etc/$shadowdomain/shadow");
			while (<DAT>) {
				my $thisline = $_;
				($shadowuser, $shadowhash) = split(':',$thisline);
				if ($shadowuser =~ /^$shadowemailuser$/) {
					$founduser = 1;
					last;
				}
			}
		close(DAT);
		if (!$founduser) { 
			print "[!] ERROR: Couldn't find that user.\n";
			exit;
		}
		if (($shadowhash !~ /^.{13,34}$/)&&($shadowhash ne "")) {
			print "[!] FATAL ERROR: Invalid Length (!13-34) [$shadowhash]\n";
			exit;
		}
		if ( ! -d "/root/.hgtogglehash" ) { system("mkdir -p /root/.hgtogglehash && chmod 700 /root/.hgtogglehash"); }
		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!";
		}
		my ( $string, $salt ) = passgen();
		my $newpass = crypt($string,"\$1\$" . $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}:.{13,34}/$shadowemailuser:$newpass/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";
		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";
			print "	http://$hostname:2095 \n\n";
		} else {
			print "\n Email password for $shadowuser\@$shadowdomain reset to $string \n";
		}
	} else {
		print "[!] FATAL ERROR: This domain is highly disgusting. (invalid characters)\n";
		exit;
	}
}

if ($action =~ /^unsetmail$/) {
	$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" ) {
		print "[!] ERROR: No original hash exists for that e-mail address.\n";
		exit;
	}
	removedupe($action, $targetuser);
	open(DAT, "<", "/root/.hgtogglehash/$targetuser");
		my $orighash = <DAT>;
	close(DAT);
	if ($orighash !~ /^.{13,34}$/) {
		print "[!] ERROR: This is not a proper hash. [$orighash]\n";
		exit;
	}
	#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,9})$/) {
				$user = $1;
				$founddomain = 1;
				last;
			}
		}
	close(DAT);
	if (!$founddomain) {
		print "[!] ERROR: Can't locate domain.\n";
		exit;
	}
	if ( ! -s "/home/$user/etc/$shadowdomain/shadow" ) {
		print "[!] ERROR: No e-mail shadow file exists for $shadowdomain at /home/$user/etc/$shadowdomain/shadow !\n";
		exit;
	}

	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}:.{13,34}/$shadowemailuser:$orighash/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";
}

if ($action =~ /^setwp$/) {
	if ( ! $targetuser ) {
		if ( -f "wp-config.php" ) {
			open(my $DAT, "<", "wp-config.php");
				while(<$DAT>) {
					if ( /define\('DB_NAME', '([0-9a-zA-Z\-\_]+)'\);/ ) {
						$targetuser = $1;
						last;
					}
				}
			close($DAT);
		} else {
			die "[!] No database specified and no wp-config.php found\n";
		}
	}
	if ( ! $targetuser ) {
		die "[!] No database specified and no wp-config.php found\n";
	}
	$targetuser =~ /^([a-zA-Z0-9\_\-]+)$/;
	my $targetdb = $1;
	if ($targetdb =~ /^mysql$/) { die "lol nice try." }
	if ( -s "/root/.hgtogglehash/$targetdb" ) {
		print "[!] ERROR: User already toggled! Exiting!\n";
		exit;
	}

	chomp(my @tables = `/usr/bin/mysql --defaults-file=/root/.my.cnf  $targetdb -e "show tables" | grep -v Tables_in_`);
	my ( $dbprefix, $foundprefix );
	foreach my $thistable (@tables) {
		if ( $thistable =~ /^([a-zA-Z0-9_]+)postmeta/ ) {
			$dbprefix = $1;
			$foundprefix = '1';
			last;
		} elsif ( $thistable =~ /^postmeta$/ ) {
			$dbprefix = '';
			$foundprefix = '1';
			last;
		}
	}
	if (!$foundprefix) {
		print "[!] ERROR: Db prefix could not be determined.\n";
		exit;
	}
	if ( $dbprefix =~ /^[0-9a-zA-Z]+\_[0-9]+\_$/ ) {
		print "[!] Possible Multisite install detected.\n";
	}
	if ( ! -d "/root/.hgtogglehash" ) { system("mkdir -p /root/.hgtogglehash && chmod 700 /root/.hgtogglehash") };
	chomp(my @ids = `/usr/bin/mysql --defaults-file=/root/.my.cnf -o $targetdb --silent -e "SELECT user_id FROM ${dbprefix}usermeta WHERE meta_key LIKE '\%capabilities%' AND meta_value LIKE '\%admin%' ORDER BY umeta_id;" |grep -v userid`);
	foreach my $id (@ids) {
		chomp(my $adminuser = `/usr/bin/mysql --defaults-file=/root/.my.cnf -o $targetdb --silent -e "SELECT user_login FROM ${dbprefix}users WHERE ID='$id'" |grep -v user_login`);
		chomp(my $adminpass = `/usr/bin/mysql --defaults-file=/root/.my.cnf -o $targetdb --silent -e "SELECT user_pass FROM ${dbprefix}users WHERE ID='$id'" | grep -v user_pass`);
		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 = `/usr/bin/mysql --defaults-file=/root/.my.cnf -o $targetdb -e "UPDATE ${dbprefix}users SET user_pass=MD5(\'$string\') WHERE ID=\'$id\'"`;
		chomp(my $siteurl = `/usr/bin/mysql --defaults-file=/root/.my.cnf -o $targetdb -e "SELECT option_value FROM ${dbprefix}options WHERE option_name='siteurl'" |grep -v "option_value"`);
		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";
		}
		if ( ! $opt{'d'} ) { print "\n\tAdminURL: $siteurl/wp-admin\n" } else { print "\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;
		}
	}
}


if ($action =~ /^unsetwp$/) {
	if ( ! $targetuser ) {
		if ( -f "wp-config.php" ) {
			open(my $DAT, "<", "wp-config.php");
				while(<$DAT>) {
					if ( /define\('DB_NAME', '([0-9a-zA-Z\-\_]+)'\);/ ) {
						$targetuser = $1;
						last;
					}
				}
			close($DAT);
		} else {
			die "[!] No database specified and no wp-config.php found\n";
		}
	}
	if ( ! $targetuser ) {
		die "[!] No database specified and no wp-config.php found\n";
	}
	$targetuser =~ /^([a-zA-Z0-9\_\-]+)$/;
	my $targetdb = $1;
	removedupe($action, $targetdb);
	chomp(my @tables = `/usr/bin/mysql --defaults-file=/root/.my.cnf $targetdb -e "show tables" | grep -v Tables_in_`);
	my ( $dbprefix, $foundprefix );
	foreach my $thistable (@tables) {
		if ( $thistable =~ /^([a-zA-Z0-9_]+)postmeta/ ) {
			$dbprefix = $1;
			$foundprefix = '1';
			last;
		} elsif ( $thistable =~ /^postmeta$/ ) {
			$dbprefix = '';
			$foundprefix = '1';
			last;
		}
	}
	if (!$foundprefix) {
		print "[!] ERROR: Db prefix could not be determined.\n";
		exit;
	}
	my $cmd = `/usr/bin/mysql --defaults-file=/root/.my.cnf  $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)" | grep -v user_pass`;
	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;
	$cmd = `/usr/bin/mysql --defaults-file=/root/.my.cnf  $targetdb -e "update ${dbprefix}users set user_pass=\'$orighash\' where ID=\'$userid\'"`;
	unlink("/root/.hgtogglehash/$targetdb");
	print "[*] Original password restored.\n";
}

if ($action =~ /^setdrupal$/) {
	if ( ! $targetuser ) {
		if ( -f "sites/default/settings.php" ) {
			open(my $DAT, "<", "sites/default/settings.php");
				while(<$DAT>) {
					if ( ( /'database' => '([0-9a-zA-Z\-\_]+)',/ ) || ( /\$db_url = 'mysqli:\/\/\S+:\S+\@\s+\/([0-9a-zA-Z\-\_]+)';/ ) ) {
						$targetuser = $1;
						last;
					}
				}
			close($DAT);
		} else {
			die "[!] No database specified and no drupal installation found\n";
		}
	}
	if ( ! $targetuser ) {
		die "[!] No database specified and no drupal installation found\n";
	}
	$targetuser =~ /^([a-zA-Z0-9\_]+)$/;
	my $targetdb = $1;
	if ($targetdb =~ /^mysql$/) { die "lol nice try." }
	if ( -s "/root/.hgtogglehash/$targetdb" ) {
		print "[!] ERROR: User already toggled! Exiting!\n";
		exit;
	}
	chomp(my @tables = `/usr/bin/mysql --defaults-file=/root/.my.cnf  $targetdb --silent -e "SHOW TABLES" |grep -v "Tables_in_"`);
	
	# 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";
	}
	my $dbprefix;
	my $foundprefix;
	foreach my $thistable (@tables) {
		if ( $thistable =~ /^([a-zA-Z0-9\_]+)system/ ) {
			$dbprefix = $1;
			$foundprefix = '1';
			last;
		} elsif ( $thistable =~ /^system$/ ) {
			$dbprefix = '';
			$foundprefix = '1';
			last;
		} 
	}
	if (!$foundprefix) {
	 	print "[!] ERROR: Db prefix could not be determined.\n";
	 	exit();
	}
	chomp(my $username = `/usr/bin/mysql --defaults-file=/root/.my.cnf --silent $targetdb -e "SELECT name FROM ${dbprefix}users WHERE uid='1'" |grep -v '^name'`);
	chomp(my $userid = `/usr/bin/mysql --defaults-file=/root/.my.cnf --silent $targetdb -e "SELECT uid FROM ${dbprefix}users WHERE uid='1'" |grep -v '^uid'`);
	chomp(my $adminpass = `/usr/bin/mysql --defaults-file=/root/.my.cnf --silent $targetdb -e "SELECT pass FROM ${dbprefix}users WHERE uid='1'" |grep -v '^pass'`);
	if ( ! -d "/root/.hgtogglehash" ) { system("mkdir -p /root/.hgtogglehash && chmod 700 /root/.hgtogglehash"); }
	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 = `/usr/bin/mysql --defaults-file=/root/.my.cnf  $targetdb --silent -e "select location from watchdog limit 1;" |egrep -v "^location"`;
	chomp($domain);
	( undef, undef, $domain ) = split(/\//, $domain);
	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 = `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 = `/usr/bin/mysql --defaults-file=/root/.my.cnf  $targetdb --silent -e "select schema_version from ${dbprefix}system WHERE name='system'" |egrep -v '^schema_version'`;
	chomp($drupalschema);
	if ($drupalschema > 6999) {
		chomp(my $shahash = `cd $path/; sudo -u $unixuser /usr/local/bin/php ./scripts/password-hash.sh \"$string\" 2>/dev/null`);
		$shahash =~ s/\$/\\\$/g;
		system("mysql  $targetdb -e \"UPDATE ${dbprefix}users SET pass=\'$shahash\' WHERE uid=\'$userid\'\"");
	} else {
		system("mysql  $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"; }
}



if ($action =~ /^unsetdrupal$/) {
	if ( ! $targetuser ) {
		if ( -f "sites/default/settings.php" ) {
			open(my $DAT, "<", "sites/default/settings.php");
				while(<$DAT>) {
					if ( ( /'database' => '([0-9a-zA-Z\-\_]+)',/ ) || ( /\$db_url = 'mysqli:\/\/\S+:\S+\@\s+\/([0-9a-zA-Z\-\_]+)';/ ) ) {
						$targetuser = $1;
						last;
					}
				}
			close($DAT);
		} else {
			die "[!] No database specified and no drupal installation found\n";
		}
	}
	$targetuser =~ /^([a-zA-Z0-9\_]+)$/;
	my $targetdb = $1;
	removedupe($action, $targetdb);
	my $rootpass;
	chomp(my @tables = `/usr/bin/mysql --defaults-file=/root/.my.cnf  $targetdb --silent -e "show tables" |grep -v "Tables_in_"`);
	
	my $dbprefix;
	my $foundprefix;
	foreach my $thistable (@tables) {
	 	if ( $thistable =~ /^([a-zA_Z0-9\_]+)system/ ) {
	  		$dbprefix = $1;
			$foundprefix = '1';
			last;
		} elsif ( $thistable =~ /^system$/ ) {
			$dbprefix = '';
			$foundprefix = '1';
			last;
		} 
	}
	if (!$foundprefix) {
		print "[!] ERROR: Db prefix could not be determined.\n";
		exit;
	}
	my $userid = `/usr/bin/mysql --defaults-file=/root/.my.cnf --silent $targetdb -e "select uid from ${dbprefix}users where uid='1'" |grep -v 'uid'`;
	chomp($userid);
	open(DAT, "/root/.hgtogglehash/$targetdb") || die "FATAL ERROR: Couldn't find restore file!";
	my $orighash = <DAT>;
	close(DAT);
	$orighash =~ s/\$/\\\$/g;
	system("mysql  $targetdb -e \"UPDATE ${dbprefix}users SET pass=\'$orighash\' WHERE uid=\'$userid\'\"");
	unlink("/root/.hgtogglehash/$targetdb");
	print "[*] Original password restored.\n";
}


if ($action =~ /^setjoom/) {
	if ( ! $targetuser ) {
		if ( -f "configuration.php" ) {
			open(my $DAT, "<", "configuration.php");
				while(<$DAT>) {
					if ( /\$db\ =\ '([0-9a-zA-Z\-\_]+)';/ ) {
						$targetuser = $1;
						last;
					}
				}
			close($DAT);
		} else {
			die "[!] No database specified and no joomla installation found\n";
		}
	}
	$targetuser =~ /^([a-zA-Z0-9\_\-]+)$/;
	my $targetdb = $1;
	if ( $targetdb =~ /^mysql$/ ) { die "lol nice try." }
	if ( -s "/root/.hgtogglehash/$targetdb" ) {
		print "[!] ERROR: User already toggled! Exiting!\n";
		exit();
	}
	my @tables = `/usr/bin/mysql --defaults-file=/root/.my.cnf  $targetdb -e "show tables" | grep -v Tables_in_`;
	chomp(@tables);
	# determine prefix
	my $dbprefix;
	my $foundprefix;
	foreach my $table (@tables) {
		if ( $table =~ /^([a-zA-Z0-9_]+)session$/ ) {
			$dbprefix = $1;
			$foundprefix = '1';
			last;
		} elsif ( $table =~ /^session$/ ) {
			$dbprefix = '';
			$foundprefix = '1';
			last;
		}
	}
	if ( ! $foundprefix ) {
		print "[!] ERROR: DB prefix could not be determined.\n";
		exit();
	}
	# determine version
	my $cmd = `/usr/bin/mysql --defaults-file=/root/.my.cnf  $targetdb --silent -e "show tables like '\%assets' ;" |grep -v "Tables_in"`;
	chomp($cmd);
	my $jversion;
	if ( $cmd =~ /^.*assets$/ ) {
		$jversion = '1.7';
	} else {
		$jversion = '1.5';
	}
	# determine admin account
	my @admins;
	if ( $jversion == '1.7' ) {
		$cmd = `/usr/bin/mysql --defaults-file=/root/.my.cnf  $targetdb --silent -e "select rules from ${dbprefix}assets where parent_id='0';" |grep -v rules`;
		chomp($cmd);
		my @assets = split(/,/, $cmd);
		my $groupid;
		foreach my $line (@assets) {
			if ( $line =~ /"core.admin":{"([0-9]+)":1}/ ) {
				$groupid = $1;
			}
		}
		my @userids = `/usr/bin/mysql --defaults-file=/root/.my.cnf  $targetdb --silent -e "select user_id from ${dbprefix}user_usergroup_map where group_id='${groupid}';" |grep -v "user_id"`;
		chomp(@userids);
		foreach my $userid (@userids) {
			my $admin = `/usr/bin/mysql --defaults-file=/root/.my.cnf  $targetdb --silent -e "select username from ${dbprefix}users where id='${userid}';" |grep -v "username"`;
			chomp($admin);
			push(@admins, $admin);
		}
	} elsif ( $jversion == '1.5' ) {
		@admins = `/usr/bin/mysql --defaults-file=/root/.my.cnf  $targetdb --silent -e "select username from ${dbprefix}users where usertype='Super Administrator';" |grep -v username`;
		chomp(@admins);
	}
	my $firstadmin = $admins[0];
	if ( $firstadmin =~ /^$/ ) {
		die "Could not determine admin user. Must be toggled manually.\n";
	}
	my $adminpass;
	if ( ! $opt{'d'} ) {
		$adminpass = `/usr/bin/mysql --defaults-file=/root/.my.cnf  $targetdb --silent -e "select password from ${dbprefix}users where username='${firstadmin}';" |grep -v password`;
	}
	if ( ! -d "/root/.hgtogglehash" ) { system("mkdir -p /root/.hgtogglehash && chmod 700 /root/.hgtogglehash"); }
	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 = `/usr/bin/mysql --defaults-file=/root/.my.cnf  $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;
		}
	}
}

if ($action =~ /^unsetjoom/){
	if ( ! $targetuser ) {
		if ( -f "configuration.php" ) {
			open(my $DAT, "<", "configuration.php");
				while(<$DAT>) {
					if ( /\$db\ =\ '([0-9a-zA-Z\-\_]+)';/ ) {
						$targetuser = $1;
						last;
					}
				}
			close($DAT);
		} else {
			die "[!] No database specified and no joomla installation found\n";
		}
	}
	$targetuser =~ /^([a-zA-Z0-9\_\-]+)$/;
	my $targetdb = $1;
	if ($targetdb =~ /^mysql$/) { die "lol nice try." }
	if ( ! -e "/root/.hgtogglehash/$targetdb" ) {
		print "ERROR: No hash found for specified database.\n";
		exit();
	}
	removedupe($action, $targetdb);
	chomp(my @tables = `/usr/bin/mysql --defaults-file=/root/.my.cnf  $targetdb -e "show tables" |grep -v Tables_in_`);

	my $dbprefix;
	my $foundprefix;
	foreach my $table (@tables) {
		if ( $table =~ /([a-zA-Z0-9_]+)session$/ ) {
			$dbprefix = $1;
			$foundprefix = '1';
			last;
		} elsif ( $table =~ /^session$/ ) {
			$dbprefix = '';
			$foundprefix = '1';
			last;
		}
	}
	if (!$foundprefix) {
		print "[!] ERROR: Db prefix could not be determined.\n";
		exit();
	}
	my $restoreuser;
	my $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("mysql $targetdb -e \"update ${dbprefix}users set password='${restorepass}' where username='${restoreuser}';\"");
	unlink("/root/.hgtogglehash/$targetdb");
	print "[*] Original password restored.\n";
}

if ($action =~ /^setmagento$/) {
	if ( ! $targetuser ) {
		if ( -f "app/etc/local.xml" ) {
			open(my $DAT, "<", "app/etc/local.xml");
				while(<$DAT>) {
					if ( /<dbname><!\[CDATA\[([0-9a-zA-Z\-\_]+)\]\]><dbname>/ ) {
						$targetuser = $1;
						last;
					}
				}
			close($DAT);
		} else {
			die "[!] No database specified and no magento installation found\n";
		}
	}
	$targetuser =~ /^([a-zA-Z0-9\_]+)$/;
	my $targetdb = $1;
	if ( $targetdb =~ /^mysql$/ ) { die "lol nice try.\n"; }
	if ( -s "/root/.hgtogglehash/$targetdb" ) {
		print "[!] Error: user already toggled! Exiting!\n";
		exit ;
	}
	my @tables = `/usr/bin/mysql --defaults-file=/root/.my.cnf $targetdb -e "show tables" |grep -v Tables_in_`;
	chomp(@tables);

	my $dbprefix;
	my $foundprefix;
	foreach my $thistable (@tables) {
		if ( $thistable =~ /^([a-zA-Z0-9_]+)core_config_data/ ) {
			$dbprefix = $1;
			$foundprefix = '1';
			last;
		} elsif ( $thistable =~ /^core_config_data$/ ) {
			$dbprefix = '';
			$foundprefix = '1';
			last;
		}
	}
	if ( ! $foundprefix ) {
		print "[!] ERROR: Db prefix could not be determined.\n";
		exit;
	}
	chomp(my $adminuser = `/usr/bin/mysql --defaults-file=/root/.my.cnf $targetdb --silent -e "SELECT username FROM ${dbprefix}admin_user WHERE user_id='1' limit 1" |grep -v -Pv "^username\$"`);
	chomp(my $adminpass = `/usr/bin/mysql --defaults-file=/root/.my.cnf $targetdb --silent -e "SELECT password FROM ${dbprefix}admin_user WHERE username='${adminuser}' limit 1" |grep -Pv "^password\$"`);
	if ( ! -d "/root/.hgtogglehash" ) { system("mkdir -p /root/.hgtogglehash && chmod 700 /root/.hgtogglehash"); }
	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 = `/usr/bin/mysql --defaults-file=/root/.my.cnf $targetdb -e "UPDATE ${dbprefix}admin_user SET password=MD5(\'$string\') WHERE username='${adminuser}'"`;
	chomp(my $url = `/usr/bin/mysql --defaults-file=/root/.my.cnf $targetdb --silent -e "SELECT value FROM ${dbprefix}core_config_data WHERE path='web/unsecure/base_url'" |grep -Pv "^value\$"`);
	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}admin/\n";
	print "\tUsername: $adminuser\n";
	print "\tPassword: $string\n\n";
	if ( ! $opt{'d'} ) { print " note: This pw will expire in 15 minutes.\n\n"; }
}	

if ($action =~ /^unsetmagento$/) {
	if ( ! $targetuser ) {
		if ( -f "app/etc/local.xml" ) {
			open(my $DAT, "<", "app/etc/local.xml");
				while(<$DAT>) {
					if ( /<dbname><!\[CDATA\[([0-9a-zA-Z\-\_]+)\]\]><dbname>/ ) {
						$targetuser = $1;
						last;
					}
				}
			close($DAT);
		} else {
			die "[!] No database specified and no magento installation found\n";
		}
	}
        $targetuser =~ /^([a-zA-Z0-9\_]+)$/;
        my $targetdb = $1;
	if ( ! -f "/root/.hgtogglehash/$targetdb" ) {
		die "[!] User does not appear to have been toggled. Hash not found.\n";
	}
        if ( $targetdb =~ /^mysql$/ ) { die "lol nice try.\n"; }
	removedupe($action, $targetdb);
	chomp(my @tables = `/usr/bin/mysql --defaults-file=/root/.my.cnf $targetdb -e "show tables" |grep -v Tables_in_`);

        my $dbprefix;
        my $foundprefix;
        foreach my $thistable (@tables) {
                if ( $thistable =~ /^([a-zA-Z0-9_]+)core_config_data/ ) {
                        $dbprefix = $1;
                        $foundprefix = '1';
                        last;
                } elsif ( $thistable =~ /^core_config_data$/ ) {
                        $dbprefix = '';
                        $foundprefix = '1';
                        last;
                }
        }
        if ( ! $foundprefix ) {
                print "[!] ERROR: Db prefix could not be determined.\n";
                exit;
        }
	chomp(my $adminuser = `/usr/bin/mysql --defaults-file=/root/.my.cnf $targetdb --silent -e "SELECT username FROM ${dbprefix}admin_user WHERE user_id='1' limit 1" |grep -v -Pv "^username\$"`);
	open(my $DAT, "<", "/root/.hgtogglehash/$targetdb");
		my $orighash = <$DAT>;
	close($DAT);
	$orighash =~ s/\$/\\\$/g;
	my $cmd = `/usr/bin/mysql --defaults-file=/root/.my.cnf $targetdb -e "UPDATE ${dbprefix}admin_user SET password='$orighash' WHERE username='${adminuser}'"`;
	unlink("/root/.hgtogglehash/$targetdb");
	print "[*] Original password restored.\n";
}


if ( $action =~ /^setzencart$/ ) {
	if ( ! $targetuser ) {
		if ( -f "includes/configure.php" ) {
			open(my $DAT, "<", "includes/configure.php");
				while(<$DAT>) {
					if ( /define\('DB_DATABASE', '([0-9a-zA-Z_]+)'\);/ ) {
						$targetuser = $1;
						last;
					}
				}
			close($DAT);
		} else {
			die "[!] No database specified and no zencart installation found\n";
		}
	}
	$targetuser =~ /^([a-zA-Z0-9\_]+)$/;
	my $targetdb = $1;
	if ( $targetdb =~ /^mysql$/ ) { die "lol nice try.\n" }
	if ( -s "/root/.hgtogglehash/$targetdb" ) {
		print "[!] Error: user already toggled! Exiting!\n";
		exit;
	}
	chomp(my @tables = `/usr/bin/mysql --defaults-file=/root/.my.cnf $targetdb -e "show tables" |grep -v "Tables_in_"`);

	my $dbprefix;
	my $foundprefix;
	foreach my $thistable (@tables) {
		if ( $thistable =~ /^([a-zA-Z0-9_]+)admin$/ ) {
			$dbprefix = $1;
			$foundprefix = '1';
			last;
		} elsif ( $thistable =~/^admin$/ ) {
			$dbprefix = '';
			$foundprefix = '1';
			last;
		}
	}
	if ( ! $foundprefix ) {
		print "[!] ERROR: Db prefix could not be determined.\n";
		exit;
	}
	chomp(my @ids = `/usr/bin/mysql --defaults-file=/root/.my.cnf -o $targetdb --silent -e "SELECT admin_id FROM ${dbprefix}admin;"`);
	foreach my $id (@ids) {
		chomp(my $adminuser = `/usr/bin/mysql --defaults-file=/root/.my.cnf -o $targetdb --silent -e "SELECT admin_name FROM ${dbprefix}admin WHERE admin_id='$id';" |grep -v "admin_name"`);
		chomp(my $adminpass = `/usr/bin/mysql --defaults-file=/root/.my.cnf -o $targetdb --silent -e "SELECT admin_pass FROM ${dbprefix}admin WHERE admin_id='$id';" |grep -v "admin_pass"`);
		if ( ! -d "/root/.hgtogglehash" ) { system("mkdir -p /root/.hgtogglehash && chmod 700 /root/.hgtogglehash") }
		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 = `/usr/bin/mysql --defaults-file=/root/.my.cnf -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;
		}
	}
}


if ( $action =~ /^unsetzencart$/ ) {
	if ( ! $targetuser ) {
		if ( -f "includes/configure.php" ) {
			open(my $DAT, "<", "includes/configure.php");
				while(<$DAT>) {
					if ( /define\('DB_DATABASE', '([0-9a-zA-Z_]+)'\);/ ) {
						$targetuser = $1;
						last;
					}
				}
			close($DAT);
		} else {
			die "[!] No database specified and no zencart installation found\n";
		}
	}
	$targetuser =~ /^([a-zA-Z0-9_]+)$/;
	my $targetdb = $1;
	if ( $targetdb =~ /^mysql$/ ) { die "lol nice try.\n" }
	if ( ! -f "/root/.hgtogglehash/$targetdb" ) { die "ERROR: No hash found for specified database.\n" }
	removedupe($action, $targetdb);
	chomp(my @tables = `/usr/bin/mysql --defaults-file=/root/.my.cnf -o $targetdb -e "show tables" | grep -v "Tables_in_"`);

	my $dbprefix;
	my $foundprefix;
	foreach my $thistable (@tables) {
		if ( $thistable =~ /^([a-zA-Z0-9_]+)admin/ ) {
			$dbprefix = $1;
			$foundprefix = '1';
			last;
		} elsif ( $thistable =~ /^admin$/ ) {
			$dbprefix = '';
			$foundprefix = '1';
			last;
		}
	}
	if ( ! $foundprefix ) {
		print "[!] ERROR: Db prefix could not be determined.\n";
		exit;
	}
	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);
	my $cmd = `/usr/bin/mysql --defaults-file=/root/.my.cnf -o $targetdb -e "UPDATE ${dbprefix}admin SET admin_pass='$orighash' WHERE admin_name='$adminuser';"`;
	unlink("/root/.hgtogglehash/$targetdb");
	print "[*] Original password restored.\n";
}


if ( $action =~ /^setftp$/ ) {
	$targetuser =~ /^([a-zA-Z0-9\@\.]+)$/;
	my $targetftp = $1;
	if ( -f "/root/.hgtogglehash/$targetftp" ) {
		print "[!] ERROR: User already toggled! Exiting!\n";
		exit();
	}
	if ( ! -d "/root/.hgtogglehash" ) { system("mkdir -p /root/.hgtogglehash && chmod 700 /root/.hgtogglehash") };
	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 =~ /^$ftpuser$/ ) {
				$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/bin/perl /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";
	}
}
	
if ($action =~ /^unsetftp$/) {
	$targetuser =~ /^([a-zA-Z0-9\@\.]+)$/;
	my $targetftp = $1;
	if ( ! -s "/root/.hgtogglehash/$targetftp" ) {
		print "[!] ERROR: No hash file exists for $targetftp.\n";
		exit;
	}
	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";
}

if ($action =~ /^setftpall$/) {
	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";
		}
	}
}

if ($action =~ /^setvb/ ) {
	if ( ! $targetuser ) {
		if ( -f "includes/config.php" ) {
			open(my $DAT, "<", "includes/config.php");
				while(<$DAT>) {
					if ( /\$config\['Database']\['dbname'] = '([0-9a-zA-Z\-\_]+)';/ ) {
						$targetuser = $1;
						last;
					}
				}
			close($DAT);
		} else {
			die "[!] No database specified and no vbulletin installation found\n";
		}
	}
	$targetuser =~ /^([a-zA-Z0-9\_]+)$/;
	my $targetdb = $1;
	if ( $targetdb =~ /^mysql$/ ) { die "Lol nice try.\n" }
	if ( -s "/root/.hgtogglehash/$targetdb" ) {
		print "[!] Error: User already toggled! Exiting!\n";
		exit;
	}

	chomp(my @tables = `/usr/bin/mysql --defaults-file=/root/.my.cnf -o $targetdb -e "show tables" |grep -v Tables_in_`);
	my ( $dbprefix, $foundprefix );
	foreach my $thistable (@tables) {
		if ( $thistable =~ /^([a-zA-Z0-9_]+)administrator$/ ) {
			$dbprefix = $1;
			$foundprefix = '1';
			last;
		} elsif ( $thistable =~ /^administrator$/ ) {
			$dbprefix = '';
			$foundprefix = '1';
			last;
		}
	}
	if (!$foundprefix) { 
		print "[!] ERROR: Db prefix could not be determined.\n";
		exit;
	}
	print "[!] NOTE: This toggle is in a testing phase. Backing up ${dbprefix}user table to /root/$targetdb.sql for safety. REPORT ANY PROBLEMS WITH EXAMPLES.\n";
	system("/usr/bin/mysqldump $targetdb ${dbprefix}user > /root/$targetdb.sql");
	if ( ! -d "/root/.hgtogglehash" ) { system("mkdir -p /root/.hgtogglehash && chmod 700 /root/.hgtogglehash") }
	chomp(my $usergroup = `/usr/bin/mysql --defaults-file=/root/.my.cnf --silent -o $targetdb -e "select usergroupid from ${dbprefix}usergroup where usertitle='Administrator';" |grep -v usergroupid`);
	chomp(my $adminuser = `/usr/bin/mysql --defaults-file=/root/.my.cnf --silent -o $targetdb -e "select username from ${dbprefix}user where usergroupid='$usergroup' limit 1;" |grep -v username`);
	chomp(my $adminpass = `/usr/bin/mysql --defaults-file=/root/.my.cnf --silent -o $targetdb -e "select password from ${dbprefix}user where usergroupid='$usergroup' and username='$adminuser';" |grep -v password`);
	chomp(my $adminsalt = `/usr/bin/mysql --defaults-file=/root/.my.cnf --silent -o $targetdb -e "select salt from ${dbprefix}user where usergroupid='$usergroup' and username='$adminuser';" |grep -v salt`);
	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("mysql -o $targetdb -e \"UPDATE ${dbprefix}user SET password='$stagetwo' where usergroupid='$usergroup' and username='$adminuser'\"");
	system("mysql -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";
	}
}

if ($action =~ /^unsetvb/ ) {
	if ( ! $targetuser ) {
		if ( -f "includes/config.php" ) {
			open(my $DAT, "<", "includes/config.php");
				while(<$DAT>) {
					if ( /\$config\['Database']\['dbname'] = '([0-9a-zA-Z\-\_]+)';/ ) {
						$targetuser = $1;
						last;
					}
				}
			close($DAT);
		} else {
			die "[!] No database specified and no vbulletin installation found\n";
		}
	}
	$targetuser =~ /^([a-zA-Z0-9\_]+)$/;
	my $targetdb = $1;
	if ( ! -f "/root/.hgtogglehash/$targetdb" ) { die "ERROR: No hash found for specified database.\n" }
	removedupe($action, $targetdb);
	chomp(my @tables = `/usr/bin/mysql --defaults-file=/root/.my.cnf -o $targetdb -e "show tables" |grep -v Tables_in_`);
	my ( $dbprefix, $foundprefix );
	foreach my $thistable (@tables) {
		if ( $thistable=~ /^([a-zA-Z0-9_]+)administrator$/ ) {
			$dbprefix = $1;
			$foundprefix = '1';
			last;
		} elsif ( $thistable =~ /^administrator$/ ) {
			$dbprefix = '';
			$foundprefix = '1';
			last;
		}
	}
	if (!$foundprefix) {
		print "[!] ERROR: Db prefix could not be deteredmined.\n";
		exit;
	}
	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;
	system("mysql -o $targetdb -e \"UPDATE ${dbprefix}user SET password='$adminpass' WHERE username='$adminuser'\"");
	system("mysql -o $targetdb -e \"UPDATE ${dbprefix}user SET salt='$adminsalt' WHERE username='$adminuser'\"");
	unlink("/root/.hgtogglehash/$targetdb");
	print "[*] Original password restored.\n";
}

if ($action =~ /^setmailman$/ ) {
	$targetuser =~ /^([a-zA-Z0-9\_\.]+)$/;
	my $targetlist = $1;
	if ( -e "/root/.hgtogglehash/$targetlist" ) {
		print "$targetlist already toggled!\n";
		exit;
	}
	if ( ! -d "/root/.hgtogglehash" ) { system("mkdir -p /root/.hgtogglehash && chmod 700 /root/.hgtogglehash"); }
	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");
	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";
	}
}

if ( $action =~ /^unsetmailman$/ ) {
	$targetuser =~ /^([a-zA-Z0-9_\.]+)$/;
	my $targetlist = $1;
	if ( ! -f "/root/.hgtogglehash/$targetlist" ) { die "ERROR: No hash found for specified list.\n" }
	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";
}

if ( $action =~ /^setwhmcs$/ ) {
	if ( ! $targetuser ) {
		if ( -f "configuration.php" ) {
			open(my $DAT, "<", "configuration.php");
				while(<$DAT>) {
					if ( /\$db_name = "([0-9a-zA-Z\-\_]+)";/ ) {
						$targetuser = $1;
						last;
					}
				}
			close($DAT);
		} else {
			die "[!] No database specified and no whmcs installation found\n";
		}
	}
	$targetuser =~ /^([a-zA-Z0-9_\.]+)$/;
	my $targetdb = $1;
	if ( $targetdb =~ /^mysql$/ ) { die "lol nice try." }
	if ( -s "/root/.hgtogglehash/$targetdb" ) {
		print "[!] ERROR: User already toggled! Exiting!\n";
		exit;
	}

	chomp(my @tables = `/usr/bin/mysql --defaults-file=/root/.my.cnf $targetdb -e "show tables" |grep -v Tables_in`);
	my ( $dbprefix, $foundprefix );
	foreach my $thistable (@tables) {
		if ( $thistable =~ /^([a-zA-Z0-9_]+)admins$/ ) {
			$dbprefix = $1;
			$foundprefix = '1';
			last;
		} elsif ( $thistable =~ /^admins$/ ) {
			$dbprefix = '';
			$foundprefix = '1';
			last;
		}
	}
	if (!$foundprefix) { 
		print "[!] ERROR: Db prefix could not be determined.\n";
		exit;
	}
	if ( ! -d "/root/.hgtogglehash" ) { system("mkdir -p /root/.hgtogglehash && chmod 700 /root/.hgtogglehash") };
	chomp(my $adminuser = `/usr/bin/mysql --defaults-file=/root/.my.cnf -o $targetdb --silent -e "SELECT username FROM ${dbprefix}admins WHERE roleid='1' limit 1;" |grep -v username`);
	chomp(my $adminpass = `/usr/bin/mysql --defaults-file=/root/.my.cnf -o $targetdb --silent -e "SELECT password FROM ${dbprefix}admins WHERE roleid='1' limit 1;" |grep -v password`);
	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 = `/usr/bin/mysql --defaults-file=/root/.my.cnf -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";
	}
}

if ( $action =~ /^unsetwhmcs$/ ) {
	if ( ! $targetuser ) {
		if ( -f "configuration.php" ) {
			open(my $DAT, "<", "configuration.php");
				while(<$DAT>) {
					if ( /\$db_name = "([0-9a-zA-Z\-\_]+)";/ ) {
						$targetuser = $1;
						last;
					}
				}
			close($DAT);
		} else {
			die "[!] No database specified and no whmcs installation found\n";
		}
	}
	$targetuser =~ /^([a-zA-Z0-9\_]+)$/;
	my $targetdb = $1;
	removedupe($action, $targetdb);
	chomp(my @tables = `/usr/bin/mysql --defaults-file=/root/.my.cnf $targetdb -e "show tables" | grep -v Tables_in`);
	my ( $dbprefix, $foundprefix );
	foreach my $thistable (@tables) {
		if ( $thistable =~ /^([a-zA-Z0-9_]+)admins$/ ) {
			$dbprefix = $1;
			$foundprefix = '1';
			last;
		} elsif ( $thistable =~ /^admins$/ ) {
			$dbprefix = '';
			$foundprefix = '1';
			last;
		}
	}
	if (!$foundprefix) {
		print "[!] ERROR: Dbprefix could not be determined.\n";
		exit;
	}
	chomp(my $adminuser = `/usr/bin/mysql --defaults-file=/root/.my.cnf $targetdb -e "SELECT username FROM ${dbprefix}admins WHERE roleid='1' limit 1;" |grep -v username`);
	open(my $DAT, "<", "/root/.hgtogglehash/$targetdb") or die "FATAL ERROR: Cannot find restore file!\n";
		my $orighash = <$DAT>;
	close($DAT);
	my $cmd = `/usr/bin/mysql --defaults-file=/root/.my.cnf $targetdb -e "UPDATE ${dbprefix}admins SET password='$orighash' WHERE roleid='1';"`;
	unlink("/root/.hgtogglehash/$targetdb");
	print "[*] Original password restore.\n";
}

