# Copyright 1999-2016. Parallels IP Holdings GmbH. All Rights Reserved.
package Storage::PostgresqlDbBundle;

use strict;
use Storage::DbBundle;
use Db::Connection;
use AgentConfig;
use vars qw|@ISA|;

@ISA = qw|Storage::DbBundle|;

sub run {
	my ($self) = @_;
	my %params = %{$self->{params}};
	my $dbname = $params{'name'};
	my $user = $params{'user'};

	$params{'name'} = 'template1';

	my $connection;
    if (!(-e AgentConfig::psqlBin()) || !(-e AgentConfig::pgdumpBin())) {
        return;
    }
	# dbi has bug with array fields such as grolist. bug # 114630
	for (my $i = 0; $i < 2; $i++) {
		$params{'nodbi'} = $i ? undef : 1;
		$connection = Db::Connection::getConnection(%params);
		$i++ if $connection->execute_rownum_quiet("SELECT 1");
		$connection->finish();
	}

	my $group_exist = $connection->execute_rownum_quiet("SELECT grolist FROM pg_group WHERE groname = '?'", $dbname);
	my $user_exist = 0;

	if ($group_exist) {
		my $row = $connection->fetchrow();
		my $grolist = $row->[0];
		$grolist =~ s/[{}]//g; # 100,101

		if ($grolist ne "") {
			$connection->finish();
			my @ids = split(',', $grolist);
			my $sql = "SELECT usesysid FROM pg_user WHERE usename = '?' AND usesysid IN (" . join(',', ("?")x@ids) . ")";
			$user_exist = $connection->execute_rownum_quiet($sql, $user, @ids);
		}
	}

	$connection->finish();

	if (!$user_exist) { # user does not exist in group
		if (!$group_exist) {
			$self->{'params'}->{'group_created'} = $connection->execute_rownum("CREATE GROUP \"$dbname\" WITH USER \"$user\"");
		}
		else {
			$connection->execute_rownum("ALTER GROUP \"$dbname\" ADD USER \"$user\"");
		}

		$connection->finish();
		$self->{'params'}->{'connection'} = $connection;
	}
	else {
		$connection->disconnect();
	}

	if (defined $params{'plesk_7'}) {
		my $cmd = AgentConfig::pg_manageBin().' add_db_usr '.$self->{'params'}->{'name'}.' '.$params{'user'};
		$cmd = `$cmd`;
	}

	return $self->SUPER::run();
}

sub cleanup {
	my ($self) = @_;
	my %params = %{$self->{params}};

	my $exit_code = $self->SUPER::cleanup();

	if (defined $params{'connection'}) {
		my $connection = $params{'connection'};

		if (defined $params{'group_created'}) {
			$connection->execute_rownum('DROP GROUP "'.$params{'name'}.'"');
		}
		else {
			$connection->execute_rownum('ALTER GROUP "'.$params{'name'}.'" DROP USER "'.$params{'user'}.'"');
		}

		$connection->finish();
		$connection->disconnect();
	}

	if (defined $params{'plesk_7'}) {
		my $cmd = AgentConfig::pg_manageBin().' rm_db_usr '.$params{'name'}.' '.$params{'user'};
		$cmd = `$cmd`;
	}

	return $exit_code;
}


1;