#!/usr/bin/env perl

# Use mandatory external modules
use strict;
use Cwd;
use File::Basename;
use Data::Dumper;
use POSIX;
use Config;
use Time::HiRes;
use DBI;

# Determine installation dir name
our $SELF_DIR = dirname(dirname(Cwd::abs_path(__FILE__)));

# Include parts of the system
require $SELF_DIR . '/lib/config.pm';

# Read config file and status
our $config = ReadConfig("mmm_agent.conf");

print MySqlAllowWrite();

exit(0);

#-----------------------------------------------------------------
sub MySqlAllowWrite($) {
    my $host = shift;
    
    my $this = $config->{this};
    
    # get self connection info
    my $host = $config->{host}->{$this}->{ip};
    my $port = $config->{host}->{$this}->{port};
    my $user = $config->{host}->{$this}->{user};
    my $pass = $config->{host}->{$this}->{password};
    
    # connect to server
    my $dsn = "DBI:mysql:host=$host;port=$port";
    my $dbh = DBI->connect($dsn, $user, $pass, { PrintError => 0 });
    return "ERROR: Can't connect to MySQL (host = $host:$port, user = $user)!" unless ($dbh);
    
    # set read_only to OFF
    (my $read_only) = $dbh->selectrow_array(q{select @@read_only});
    return "ERROR: SQL Query Error: " . $dbh->errstr unless (defined $read_only);
    return "OK" unless ($read_only);

    my $sth = $dbh->prepare("set global read_only=0");
    my $res = $sth->execute;
    return "ERROR: SQL Query Error: " . $dbh->errstr unless($res);
    $sth->finish;
    
    $dbh->disconnect();
    $dbh = undef;
    
    return "OK";
}
