#!/usr/bin/env perl

use warnings;
use strict;
use v5.10;
use Fcntl qw(:flock SEEK_END);
use Getopt::Long;

my $pghba     = q{/var/lib/pgsql/data/pg_hba.conf};
my $db        = q{};
my $user      = q{};
my $ip        = q{};
my $add       = q{};
my $del       = q{};
my $debug     = q{};

GetOptions ("debug"  => \$debug,
            "db=s"   => \$db,
            "user=s" => \$user,
            "ip=s"   => \$ip,
            "add"    => \$add,
            "del"    => \$del);

# Sanity checks
__PACKAGE__->usage() unless $db   =~ m/^([a-z\d]+)(_[a-zA-Z_\d-]{1,64})$/;
__PACKAGE__->usage() unless $user =~ m/^([a-z\d]+)(_[a-zA-Z_\d-]{1,64})$/;
__PACKAGE__->usage() unless $ip   =~ m|^(?:[0-9]{1,3}\.){3}[0-9]{1,3}(?:\/\d\d)?$|;
__PACKAGE__->usage() unless $add || $del;

$ip = $ip . "/32" unless $ip =~ m|(?:[0-9]{1,3}\.){3}[0-9]{1,3}\/\d\d|;

(bless {}, __PACKAGE__)->run();
exit;

sub usage {
    my $self = shift;

my $usage = <<"END_USAGE";
Usage:
    $0 --user=\$pgsql_user --db=\$pgsql_db --ip=\$ipv4 --add
    $0 --user=\$pgsql_user --db=\$pgsql_db --ip=\$ipv4 --del
Options:
    --add : Add remote connection allow to postgresql
    --del : Remove remote connection from postgresql
END_USAGE

    say $usage;

    exit 33;
}

sub run {
    my $self = shift;

    $self->delete_entry() if $del;
    $self->add_entry()    if $add;

    return 1;
};

sub delete_entry {
    my $self = shift;
    my $require_restart = 0;

    open my $fh, '+<', $pghba or die $!;
    flock($fh, LOCK_EX) or die "Unable to lock $pghba : $!";

    my @contents = <$fh>;
    foreach my $line (@contents) {
        if ($line =~ m/(^host\s+$db\s+$user\s+$ip\s+md5$)/) {
            $line =~ s/$1//;
            $require_restart = 1;
        }
    }

    if ($require_restart) {
        say "Writing new pg_hba.conf";
        seek $fh, 0, 0;      #Rewind the filehandle to the beginning
        truncate $fh, 0;     #Remove the content of the file
        say {$fh} @contents; #Add updated contents in mem to file

        say "Restarting postgres for config changes to take effect";
        my $cmd = q{su - postgres -c 'pg_ctl reload'};
        system($cmd) == 0 or warn "Problem reloading postgress config : $!";
    }
    else {
        say "$user:$db:$ip not found in $pghba";
    }

    close $fh;

    return 1;
}

sub add_entry {
    my $self = shift;

    open my $fh, '+<', $pghba or die $!;
    flock($fh, LOCK_EX) or die "Unable to lock $pghba : $!";

    my @contents = <$fh>;
    foreach my $line (@contents) {
        if ($line =~ m/(^host\s+$db\s+$user\s+$ip\s+md5$)/) {
            say "$user is already allowed to connect to $db from $ip. Have a nice day!";
            return 0;
        }
    }

    say "Updating pg_hba.conf";
    seek $fh, 0,2; # Go to end of file
    say {$fh} "host $db $user $ip md5";

    say "Restarting postgres for config changes to take effect";
    my $cmd = q{su - postgres -c 'pg_ctl reload'};
    system($cmd) == 0 or warn "Problem reloading postgress config : $!";

    close $fh;

    return 1;
}

__END__;

Description:
A simple utility to whitelist remote connections to postgresql

Misc:
- log location for postgres = /var/lib/pgsql/data/
