package MySQLServer;

use strict;
use warnings;

use SimpleDbConnect;

my $_db;
my $_mysqlRootPassword;

sub getDatabases {
  my ($dbPrefix) = shift;

  my $db = _getDb();
  my @userDatabases = $db->queryList("SHOW DATABASES LIKE '$dbPrefix%'");

  return @userDatabases;
}

sub getDatabaseUsers {
  my ($dbName, $excludeUsers) = @_;
  
  my $db = _getDb();

  $dbName =~ s/_/\\_/g;
  my (@users);

  my $sql = "SELECT DISTINCT User FROM db WHERE Db = '$dbName'";
  if (defined $excludeUsers && @{$excludeUsers}) {
    $sql .= " AND User NOT IN (" . join(", ", map {"'$_'"} @{$excludeUsers}) . ")";
  }

  @users = $db->queryList($sql);
  if (scalar(@users) == 0) { # bug 94641
    @users = $db->queryList("SELECT DISTINCT User FROM db WHERE Db LIKE '$dbName'");
  }
  return @users;
}

sub getDatabaseUserData {
  my ($userName) = @_;

  my $db = _getDb();
  my $sql = "SELECT password,host FROM user WHERE user='$userName'";
  my @rows = $db->queryTable($sql);

  my $password = undef;
  my @accessHosts = ();
  foreach my $row (@rows) {
    push @accessHosts, $row->{'host'};
    $password ||= $row->{'password'}; # first password wins, assuming they're all the same
  }
  return ($password, \@accessHosts);
}

# TODO it should depend on users we are going to migrate, not on all users existing in the database
sub getUserDatabaseNames {
  my ($userName) = @_;
  my $db = _getDb();
  my $sql = "SELECT count(1) from db where user = '$userName';";
  return $db->queryOneValue($sql);
}

sub _getDb() {
  unless (defined($_db)) {
    $_db = SimpleDbConnect->new('mysql', _getDbAdminCredentials(), 'mysql', undef);
  }

  return $_db;
}

# @return list (<username> <password>)
sub _getDbAdminCredentials {
  $_mysqlRootPassword ||= _getMysqlPassword(); 
  return ('root', $_mysqlRootPassword);
}

# This function uses internal PPCPL library for reading MySQL root password
sub _getMysqlPassword {
  my $python = AgentConfig::pythonBin();
  my $script =<< "EOS"
import sys
sys.path.append('/usr/lib/opcenter/mysql')
from mysqlbe import read_mysqlpass

sys.stdout.write(read_mysqlpass())
EOS
;
	unless (open(PY, "$python -c \"$script\" |")) {
		return '';
	}
	binmode PY;

	my $passwd = <PY>;
	close(PY);
	chomp $passwd;

	return $passwd;
}

1;
