
do 'mysql-lib.pl';

# useradmin_create_user(&details)
# Create a new mysql user if syncing is enabled
sub useradmin_create_user
{
if ($config{'sync_create'}) {
	local %privs;
	map { $privs{$_}++ } split(/\s+/, $config{'sync_privs'});
	for($i=3; $i<=16; $i++) {
		push(@yesno, $privs{$i} ? "'Y'" : "'N'");
		}
	local $sql = sprintf "insert into user (Host, User, Password, Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, Reload_priv, Shutdown_priv, Process_priv, File_priv, Grant_priv, References_priv, Index_priv, Alter_priv) values ('', '%s', %s, %s)",
		$_[0]->{'user'},
		$_[0]->{'passmode'} == 3 ? "password('$_[0]->{'plainpass'}')" :
		$_[0]->{'passmode'} == 0 ? "'NULL'" : "'*'",
		join(",", @yesno);
	&execute_sql_logged($master_db, $sql);
	&execute_sql_logged($master_db, 'flush privileges');
	}
}

# useradmin_delete_user(&details)
# Delete a mysql user
sub useradmin_delete_user
{
if ($config{'sync_delete'}) {
	&execute_sql_logged($master_db,
		    "delete from user where user = '$_[0]->{'user'}'");
	&execute_sql_logged($master_db,
		    "delete from db where user = '$_[0]->{'user'}'");
	&execute_sql_logged($master_db,
		    "delete from tables_priv where user = '$_[0]->{'user'}'");
	&execute_sql_logged($master_db,
		    "delete from columns_priv where user = '$_[0]->{'user'}'");
	&execute_sql_logged($master_db, 'flush privileges');
	}
}

# useradmin_modify_user(&details)
# Update a mysql user
sub useradmin_modify_user
{
if ($config{'sync_modify'}) {
	local $sql;
	if ($_[0]->{'passmode'} == 4) {
		# Not changing password
		$sql = sprintf "update user set user = '%s' where user = '%s'", $_[0]->{'user'}, $_[0]->{'olduser'};
		}
	elsif ($_[0]->{'passmode'} == 3) {
		# Setting new password
		$sql = sprintf "update user set user = '%s', password = password('%s') where user = '%s'", $_[0]->{'user'}, $_[0]->{'plainpass'}, $_[0]->{'olduser'};
		}
	elsif ($_[0]->{'passmode'} == 0) {
		# No password
		$sql = sprintf "update user set user = '%s', password = NULL where user = '%s'", $_[0]->{'user'}, $_[0]->{'olduser'};
		}
	else {
		# Assume locked
		$sql = sprintf "update user set user = '%s', password = '*' where user = '%s'", $_[0]->{'user'}, $_[0]->{'olduser'};
		}
	&execute_sql_logged($master_db, $sql);
	if ($_[0]->{'user'} ne $_[0]->{'olduser'}) {
		&execute_sql_logged($master_db,
			"update db set user = '$_[0]->{'user'}' ".
			"where user = '$_[0]->{'olduser'}'");
		&execute_sql_logged($master_db,
			"update tables_priv set user = '$_[0]->{'user'}' ".
			"where user = '$_[0]->{'olduser'}'");
		&execute_sql_logged($master_db,
			"update columns_priv set user = '$_[0]->{'user'}' ".
			"where user = '$_[0]->{'olduser'}'");
		}
	&execute_sql_logged($master_db, 'flush privileges');
	}
}

1;

