#!/usr/bin/perl -w
# $Id: db_access_conf 26714 2012-09-05 14:52:33Z teetov $
# 
# Configure DB access to allow nodes access master
# [postgres edition]
# 
# Usage:
#      db_access_conf [n1:IP] [n2:IP] .. [n99:IP] 
#
# Note:
#      - This script has to be run by postgres
#      - IP4 only 
#      - any argument different from n\d+:\d+\.\d+\.\d+\.\d+ is ignored with out error
#      - create pg_hba.conf.tmp then rename to  pg_hba.conf if success (avoid loosing pg_hba.conf)
#      - since in may ba called from different environments we cannot rely on ENV except APL
#      - TBD: populate die into the log and present the log for support files

use strict;
$ENV{APL}='/opt/sarch';
my $ENV_CFG="$ENV{APL}/base/etc/env.conf";
open (ECF,$ENV_CFG)     || die "Cannot read $ENV_CFG for reading";
map {$ENV{$1}=$2 if /^(\w+)=(\S+)/} grep {/^\w+=\S+/} (<ECF>);
close ECF;

my $PGDATA=$ENV{APL_DB_DATA};
my $HBA="$PGDATA/pg_hba.conf";
my $PG_CTL=( -e "$ENV{APL}/imp/bin/pg_ctl")?"$ENV{APL}/imp/bin/pg_ctl  reload -D $PGDATA":"su postgres -c '/usr/bin/pg_ctl  reload -D $PGDATA'";

my %nconf=map {/(\w+):(\d+\.\d+\.\d+\.\d+)/} @ARGV;

open HBA,$HBA    or die "Cannot open $HBA for reading";
my @strs=grep {!/\t#SARCH\sS_NODE\s\w+/} <HBA>;
close HBA;
open HBA,">$HBA.tmp"  or die "Cannot open $HBA for writing";
foreach(@strs) {
   print(HBA $_)  or die "Cannot print into $HBA";
}
foreach(sort keys %nconf) {
   print(HBA "host\tall\tall\t$nconf{$_}\t255.255.255.255\ttrust\t#SARCH S_NODE $_\n")
                  or die "Cannot print into $HBA";
}
close HBA;
system("/usr/bin/diff $HBA.tmp $HBA >/dev/null 2>&1");
if($?) { # different
   rename ("$HBA.tmp", "$HBA") or die "Cannot rename $HBA.tmp to $HBA";
   system("/bin/chown $ENV{APL_DB_USR}:$ENV{APL_DB_USR} $HBA; /bin/chmod 600 $HBA");
   system($PG_CTL);
} else {
   unlink "$HBA.tmp"; # remove since identical 
}
