#!/usr/bin/perl
# -----------------------------------------------------------------------------
#  Updates postgresql config file to grant nodes access to master DB.
#  Writes htaccess rules for http proxy script
# -----------------------------------------------------------------------------
#  Author: Alex Titov
#  Edited by: Alexey Tsibulnik
#  QA by:  Christopher C Gettings
#  Copyright: videoNEXT LLC
# -----------------------------------------------------------------------------
use strict;
use warnings;
use Socket;
use Master::Conf;

my $APL=$ENV{APL};
my $nlist=NodeList;
my $nip_list='';

#PLATFORM-SPECIFIC (mac|lin)
my ($xargs,$db_access_conf) = ('','');
if($^O=~/darwin/i) {
    $xargs = 'xargs';
    $db_access_conf = "$APL/db/bin/db_access_conf";
}
else {
    $xargs = 'xargs --no-run-if-empty';
    $db_access_conf = "sudo  $APL/db/bin/db_access_conf";
}

die "Should run on master only!\n" unless -f "$APL/var/conf/master/s_master";
foreach my $node (keys %$nlist) {
    $nip_list.=" $node:$nlist->{$node}->{IP}";
}
print STDERR "Configure  $APL/db/bin/db_access_conf for access from $nip_list\n";
# ------------------ Get s_master IP and add it to $nip_list if absent
my $iaddr=gethostbyname('s_master');
if($iaddr) {
    my $ipaddr=inet_ntoa($iaddr);
    $nip_list.=" s_master:$ipaddr" unless $nip_list=~/:$ipaddr/;
}
system("$db_access_conf $nip_list");
#------------ I do not like these dependency (mgears and db) but cannot find better way
# kill tserver to restart with new node conf
$_=`ps ax|grep tserver|grep -v grep|cut -c 1-6|$xargs kill -1`;
print STDERR "tserver was killed and will be restarted soon:$_\n";

# Configure Avatars to use with openvpn
system("sudo $APL/conf/bin/av_access");
