#!/bin/sh
#
#
#    Scalix Public License
#
#
#    The contents of this file are subject to the Scalix Public License
#    Version 1.1 ("License"); you may not use this file except in
#    compliance with the License. You may obtain a copy of the License at
#
# 
#    http://www.scalix.com/community/licensing 
#
# 
#    Software distributed under the License is distributed on an "AS IS"
#    basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
#    the License for the specific language governing rights and limitations
#    under the License.
#
# 
#    The Original Code is Scalix Server. 
#    The Initial Developer of the Original Code is Scalix Corporation. 
#    Copyright (C) 2006 Scalix Corporation. 
#    All Rights Reserved.
#    Additional Copyrights may apply - see the notice in each file
#
#
#
#
#
#
# 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]\+scalix[ \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    scalix      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
