#!/usr/bin/perl
# Copyright 1999-2016. Parallels IP Holdings GmbH. All Rights Reserved.

# Execute SQL query on Plesk database
# The query is specified by STDIN
# Result is returned to STDOUT in JSON format

use strict;

# Prefer internal modules over external
use lib '.';

use Db::Connection;
use AgentConfig;
use DAL;
use JSON;

# =========================== Functions =======================================

# Exit from the script with error, print error as JSON
sub exitWithError {
	my ($message) = @_;

	my $json = JSON->new->allow_nonref;
	print $json->pretty->encode({
		status => 'error',
		message => $message
	});
	exit 1;
}

# Exit from the script with success, print result row set as JSON
sub exitWithRowSet {
	my ($rowset) = @_;

	my $json = JSON->new->allow_nonref;
	print $json->pretty->encode({
		status => 'ok',
		rowset => $rowset
	});
	exit 0;
}

# Read whole contents of STDIN
sub readWholeStdin {
	my $stdinContents = do {
		local $/;
		<STDIN>
	};
	return $stdinContents;
}

# Create database connection to Plesk database
sub createDatabaseConnection {
	my $dbh = Db::Connection::getConnection(
		'type'      => 'mysql',
		'user'      => 'admin',
		'password'  => AgentConfig::get('password'),
		'name'      => 'psa',
		'host'      => 'localhost',
		'utf8names' => 1,
		'connRetries' => AgentConfig::getMaxDbConnectionsRetries()
	);

	if (!$dbh) {
		exitWithError("Can not connect to the Plesk database. Please, check database server is running.")
	}

	return $dbh;
}

# =========================== Entry point =====================================
my $dbh = createDatabaseConnection();
DAL::init($dbh);
my $stdin = readWholeStdin();
my $inputData = decode_json($stdin);
my $result = DAL::__getArrayOfHashes($inputData->{'query'}, @{$inputData->{'query_args'}});
exitWithRowSet($result);
