#!/bin/sh
#
# Manipulates whitelist of hosts allowed to connect to the database.
#
# Usage: sxpsql-whitelist [ip1, ip2, ...]
#
# If ran without arguments, prints current whitelist, one IP address per line.
#
# If ran with arguments, the arguments are added to the whitelist.
# The arguments must be valid ID addresses.
#

# Pass "" to prevent implicit passing of $*
. /opt/scalix-postgres/bin/common-helpers.sh ""

PG_HBA_CONF=$INSTDIR/data/pg_hba.conf

if [ ! -f $PG_HBA_CONF ] ; then
    echo "File $PG_HBA_CONF doesn't exist." >&2
    exit 1
fi

TAG_START="# List of Scalix Platform hosts begins here"
TAG_END="# List of Scalix Platform hosts ends here"

get_whitelist()
{
    cat $PG_HBA_CONF | \
        sed -n -e \
        's@^host[ \t]\+all[ \t]\+scalix[ \t]\+\([.0-9]\+\)/32[ \t]\+md5@\1@p'
}

set_whitelist()
{
    outf="$PG_HBA_CONF.new"

    # Remove previously inserted Scalix blog demarcated by tag lines
    cat $PG_HBA_CONF | sed -e "/^$TAG_START/,/^$TAG_END/d" >$outf

    ( 
    # add whitelist IPs to the top of the file list:
    echo "$TAG_START"
    for i in $* ; do
        echo "host    all      scalix      $i/32   md5"
    done
    echo "$TAG_END"
    cat $outf
    ) >$PG_HBA_CONF

    rm -f $outf

    # restart postgres if it's running:
    /etc/init.d/scalix-postgres status $INSTNAME >/dev/null && \
            /etc/init.d/scalix-postgres restart $INSTNAME
}

if [ $# = 0 ] ; then
    get_whitelist
else
    set_whitelist $*
fi
