#!/bin/bash
#
# sfa
# Provides a generic SFA wrapper based on the initial PlanetLab Implementation
#
# hopefully right after plc
# chkconfig: 2345 61 39
#
### BEGIN INIT INFO
# Provides:		sfa
# Required-Start:	postgresql 
# Required-Stop:	postgresql 
# Default-Start:	2 3 4 5
# Default-Stop:		0 1 6
# Short-Description:	An implementation  of the SFA Architecture
### END INIT INFO

####################
# borrowed from postgresql
function debian_get_postgresql_versions () {
    versions=()
    for v in `ls /usr/lib/postgresql/ 2>/dev/null`; do
	if [ -x /usr/lib/postgresql/$v/bin/pg_ctl ] && [ ! -x /etc/init.d/postgresql-$v ]; then
            versions+=($v)
	fi
    done
    if [[ ${#versions[*]} == "0" ]]; then 
	echo "E: Missing postgresql installation. Aborting."
	exit
    fi
    if [[ ${#versions[*]} != "1" ]]; then 
	echo "E: Too many postgresql versions installed. Aborting."
	exit
    fi
    pgver=${versions[0]}
}

####################
if [ -f /etc/redhat-release ] ; then
    # source function library
    . /etc/init.d/functions
    PGDATA=/var/lib/pgsql/data/
    PGWATCH=postmaster
    PGLOCK=/var/lock/subsys/postgresql
    SFALOCK=/var/lock/subsys/sfa-start.pid
elif [ -f /etc/debian_version ] ; then
    . /etc/init.d/functions.sfa
    debian_get_postgresql_versions
    PGDATA=/etc/postgresql/$pgver/main/
    PGWATCH=postgres
    PGLOCK=/var/run/postgresql/$pgver-main.pid
    SFALOCK=/var/run/sfa-start.pid
else
    echo "initscript can only handle redhat/fedora or debian/ubuntu systems"
    exit 1
fi


postgresql_conf=$PGDATA/postgresql.conf
pg_hba_conf=$PGDATA/pg_hba.conf
postgresql_sysconfig=/etc/sysconfig/pgsql

# SFA consolidated (merged) config file
sfa_whole_config=/etc/sfa/sfa_config
# SFA default config (read-only template)
sfa_default_config=/etc/sfa/default_config.xml
# SFA local (site-dependent) file
sfa_local_config=/etc/sfa/configs/site_config
sfa_local_config_xml=/etc/sfa/configs/site_config.xml

# Source sfa shell config if present 
[ -f /etc/sfa/sfa_config.sh ] && . /etc/sfa/sfa_config.sh

# Export so that we do not have to specify -p to psql invocations
export PGPORT=$SFA_DB_PORT

##########
# Total number of errors
ERRORS=0

# Count the exit status of the last command
check ()
{
    ERRORS=$(($ERRORS+$?))
}

# can't trust the return of service postgresql start / nor status
function postgresql_check () {

    # wait until postmaster is up and running - or 10s max
    if status $PGWATCH >& /dev/null && [ -f $PGLOCK ] ; then
	# The only way we can be sure is if we can access it
	for i in $(seq 1 10) ; do
	    # Must do this as the postgres user initially (before we
	    # fix pg_hba.conf to passwordless localhost access).
	    su -c 'psql -U postgres -c "" template1' postgres && return 0
	    sleep 1
	done
    fi

    return 1
}

# use a single date of this script invocation for the dump_*_db functions.
DATE=$(date +"%Y-%m-%d-%H-%M-%S")

# Dumps the database - optional argument to specify filename suffix
function dump_sfa_db() {
    if [ -n "$1" ] ; then suffix="-$1" ; else suffix="" ; fi
    mkdir -p /usr/share/sfa/backups
    dumpfile=/usr/share/sfa/backups/$(date +"${SFA_DB_NAME}.${DATE}${suffix}.sql")
    pg_dump -U $SFA_DB_USER $SFA_DB_NAME > $dumpfile
    echo "Saved sfa database in $dumpfile"
    check
}

# Regenerate configuration files - almost verbatim from plc.init
function reload () {
    force=$1

    # Regenerate the main configuration file from default values
    # overlaid with site-specific and current values.
    files=( $sfa_default_config $sfa_local_config )
    for file in "${files[@]}" ; do
	if [ -n "$force" -o $file -nt $sfa_whole_config ] ; then
	    tmp=$(mktemp /tmp/sfa_config.XXXXXX)
	    sfa-config --python "${files[@]}" >$tmp
	    if [ $? -eq 0 ] ; then
		mv $tmp $sfa_whole_config
		chmod 444 $sfa_whole_config
	    else
		echo "SFA: Warning: Invalid configuration file(s) detected"
		rm -f $tmp
	    fi
	    break
	fi
    done

    # Convert configuration to various formats
    if [ -f $sfa_local_config_xml ] ; then
    sfa-config --python $sfa_local_config_xml > $sfa_local_config 
    rm $sfa_local_config_xml 
    fi
    if [ -n "$force" -o $sfa_local_config -nt $sfa_whole_config ] ; then
	sfa-config --python $sfa_default_config $sfa_local_config > $sfa_whole_config
    fi
    if [ -n "$force" -o $sfa_whole_config -nt /etc/sfa/sfa_config.sh ] ; then
	sfa-config --shell $sfa_default_config $sfa_local_config > /etc/sfa/sfa_config.sh
    fi

    # [re]generate the sfa_component_config
    # this is a server-side thing but produces a file that somehow needs to be pushed
    # on the planetlab nodes; in the case where sfa and myplc run on different boxes 
    # (or there is no myplc at all) this should be turned off
    # as the component manager is not operational yet we skip this for now
    #gen-sfa-cm-config.py        

    # reload the shell version
    [ -f /etc/sfa/sfa_config.sh ] && . /etc/sfa/sfa_config.sh

}

### initialize DB (don't chkconfig postgresql on)
function db_start () {
    
    # only if enabled
    [ "$SFA_DB_ENABLED" == 1 -o "$SFA_DB_ENABLED" == True ] || return

    #if ! rpm -q myplc >& /dev/null; then

        ######## standalone deployment - no colocated myplc

        ######## sysconfig 
        # Set data directory and redirect startup output to /var/log/pgsql
        mkdir -p $(dirname $postgresql_sysconfig)
        # remove previous definitions
        touch $postgresql_sysconfig
        tmp=${postgresql_sysconfig}.new
        ( egrep -v '^(PGDATA=|PGLOG=|PGPORT=)' $postgresql_sysconfig 
            echo "PGDATA=$PGDATA"
            echo "PGLOG=/var/log/pgsql"
            echo "PGPORT=$SFA_DB_PORT"
        ) >> $tmp ; mv -f $tmp $postgresql_sysconfig

        ######## /var/lib/pgsql/data 
        # Fix ownership (rpm installation may have changed it)
        chown -R -H postgres:postgres $(dirname $PGDATA)

        # PostgreSQL must be started at least once to bootstrap
        # /var/lib/pgsql/data
        if [ ! -f $postgresql_conf ] ; then
            service postgresql initdb &> /dev/null || :
            check
        fi

        ######## /var/lib/pgsql/data/postgresql.conf
        registry_ip=""
        foo=$(python -c "import socket; print socket.gethostbyname(\"$SFA_REGISTRY_HOST\")") && registry_ip="$foo"
        # Enable DB server. drop Postgresql<=7.x
        # PostgreSQL >=8.0 defines listen_addresses
        # listen on a specific IP + localhost, more robust when run within a vserver
        sed -i -e '/^listen_addresses/d' $postgresql_conf
        if [ -z "$registry_ip" ] ; then
            echo "listen_addresses = 'localhost'" >> $postgresql_conf
        else
            echo "listen_addresses = '${registry_ip},localhost'" >> $postgresql_conf
        fi
        # tweak timezone to be 'UTC'
        sed -i -e '/^timezone=/d' $postgresql_conf
        echo "timezone='UTC'" >> $postgresql_conf

        ######## /var/lib/pgsql/data/pg_hba.conf
        # Disable access to all DBs from all hosts
        sed -i -e '/^\(host\|local\)/d' $pg_hba_conf

        # Enable passwordless localhost access
        echo "local all all trust" >>$pg_hba_conf
        # grant access
        (
            echo "host $SFA_DB_NAME $SFA_DB_USER 127.0.0.1/32 password"
            [ -n "$registry_ip" ] && echo "host $SFA_DB_NAME $SFA_DB_USER ${registry_ip}/32 password"
        ) >>$pg_hba_conf

        if [ "$SFA_GENERIC_FLAVOUR" == "openstack" ] ; then
            [ -n "$registry_ip" ] && echo "host nova nova ${registry_ip}/32 password" >> $pg_hba_conf
        fi   
        
        # Fix ownership (sed -i changes it)
        chown postgres:postgres $postgresql_conf $pg_hba_conf

        ######## compute a password if needed
        if [ -z "$SFA_DB_PASSWORD" ] ; then
            SFA_DB_PASSWORD=$(uuidgen)
            sfa-config --category=sfa_db --variable=password --value="$SFA_DB_PASSWORD" --save=$sfa_local_config $sfa_local_config >& /dev/null
            reload force
        fi

    #else

        ######## we are colocated with a myplc
        # no need to worry about the pgsql setup (see /etc/plc.d/postgresql)
        # myplc enforces the password for its user
        
        # The code below overwrites the site specific sfa db info with myplc db info. 
        # This is most likely unncecessary and wrong so I'm commenting it out for now.  
    #    PLC_DB_USER=$(plc-config --category=plc_db --variable=user)
    #    PLC_DB_PASSWORD=$(plc-config --category=plc_db --variable=password)
        # store this as the SFA user/password 
    #    sfa-config --category=sfa_db --variable=user --value=$PLC_DB_USER --save=$sfa_local_config $sfa_local_config >& /dev/null
    #    sfa-config --category=sfa_db --variable=password --value=$PLC_DB_PASSWORD --save=$sfa_local_config $sfa_local_config >& /dev/null
    #    reload force
    #fi

    ######## Start up the server
    # not too nice, but.. when co-located with myplc we'll let it start/stop postgresql
    if [ ! -f /etc/myplc-release ] ; then
	echo STARTING...
	service postgresql start >& /dev/null
    fi
    postgresql_check
    check
	
    ######## make sure we have the user and db created
    # user
    if ! psql -U $SFA_DB_USER -c "" template1 >/dev/null 2>&1 ; then
	psql -U postgres -c "CREATE USER $SFA_DB_USER PASSWORD '$SFA_DB_PASSWORD'" template1 >& /dev/null
    else
	psql -U postgres -c "ALTER USER $SFA_DB_USER WITH PASSWORD '$SFA_DB_PASSWORD'" template1 >& /dev/null
    fi
    check
    
    # db
    if ! psql -U $SFA_DB_USER -c "" $SFA_DB_NAME >/dev/null 2>&1 ; then
	createdb -U postgres --template=template0 --encoding=UNICODE --owner=$SFA_DB_USER $SFA_DB_NAME
	check
    fi
    check
    # mention sfaadmin.py instead of just sfaadmin for safety
    sfaadmin.py reg sync_db

    MESSAGE=$"SFA: Checking for PostgreSQL server"
    echo -n "$MESSAGE"
    [ "$ERRORS" == 0 ] && success "$MESSAGE" || failure "$MESSAGE" ; echo
}

# shutdown DB
function db_stop () {

    # only if enabled
    [ "$SFA_DB_ENABLED" == 1 -o "$SFA_DB_ENABLED" == True ] || return

    # not too nice, but.. when co-located with myplc we'll let it start/stop postgresql
    if [ ! -f /etc/myplc-release ] ; then
	service postgresql stop >& /dev/null
	check
	MESSAGE=$"Stopping PostgreSQL server"
	echo -n "$MESSAGE"
	[ "$ERRORS" == 0 ] && success "$MESSAGE" || failure "$MESSAGE" ; echo
    fi
}

function start() {
    
    reload

    db_start
    # migrations are now handled in the code by sfa.storage.dbschema

    # install peer certs
    action $"SFA: installing peer certs" daemon /usr/bin/sfa-start.py -t -d $OPTIONS 

    [ "$SFA_REGISTRY_ENABLED" == 1 -o "$SFA_REGISTRY_ENABLED" == True ] && action $"SFA: Registry" daemon /usr/bin/sfa-start.py -r -d $OPTIONS
    
    [ "$SFA_AGGREGATE_ENABLED" == 1  -o "$SFA_AGGREGATE_ENABLED" == True ] && action $"SFA: Aggregate" daemon /usr/bin/sfa-start.py -a -d $OPTIONS
        
    [ "$SFA_SM_ENABLED" == 1 -o "$SFA_SM_ENABLED" == True ] && action "SFA: SliceMgr" daemon /usr/bin/sfa-start.py -s -d $OPTIONS

    [ "$SFA_FLASHPOLICY_ENABLED" == 1 -o "$SFA_FLASHPOLICY_ENABLED" == True ] && \
        action "Flash Policy Server" daemon /usr/bin/sfa_flashpolicy.py --file="$SFA_FLASHPOLICY_CONFIG_FILE" --port=$SFA_FLASHPOLICY_PORT -d

    touch $SFALOCK

}

function stop() {
    action $"Shutting down SFA" killproc sfa-start.py
# a possible alternative reads; esp. as we remove lock manually below
#    echo $"Shutting down SFA" ; pkill '^sfa-start'

    db_stop

    rm -f $SFALOCK
}


case "$1" in
    start) start ;;
    stop) stop ;;
    reload) reload force ;;
    restart) stop; start ;;
    condrestart)
	if [ -f $SFALOCK ]; then
            stop
            start
	fi
	;;
    status)
	status sfa-start.py
# possible alternative for debian
#	pids=$(pgrep '^sfa-start'); [ -n "$pids" ] && ps $pids

	RETVAL=$?
	;;
    dbdump)
	dump_sfa_db
	;;
    *)
	echo $"Usage: $0 {start|stop|reload|restart|condrestart|status|dbdump}"
	exit 1
	;;
esac

exit $RETVAL
