#! /bin/sh
#
# sqlrelay   This starts and stops SQL relay.
#
# chkconfig: 345 85 15
# description: Persistent database connection system.

prefix=${DESTDIR}/usr/pkg
sysconfdir=${DESTDIR}/usr/pkg/etc/sqlrelay
localstatedir=${DESTDIR}/var
tmpdir=${localstatedir}/sqlrelay/tmp
cachedir=${localstatedir}/sqlrelay/cache
debugdir=${localstatedir}/sqlrelay/debug

if ( test ! -r "${sysconfdir}/sqlrelay.conf" ); then
        exit 1
fi

RETVAL=0

# Add appropriate bin/lib paths
if ( test "${prefix}" != "/usr" ); then
        PATH=$PATH:${prefix}/bin
        LD_LIBRARY_PATH=$LD_LIBRARY_PATH:${prefix}/lib
        export PATH LD_LIBRARY_PATH
fi

cleanup(){
    for i in `ls ${tmpdir}/pids/* 2>/dev/null`
    do
        if ( test -r "$i" )
        then
            PID=`cat $i`
            if ( test -z "`ps -p $PID | egrep -E 'sqlr-cachemana|sqlr-connectio|sqlr-listener|sqlr-scaler'`" )
            then
                echo "$PID is not sqlr! removing pidfile ..."
                rm $i
            fi
        fi
    done
}

start(){
    echo -n $"Starting SQL Relay: "
    if ( test -r "${DESTDIR}/usr/pkg/etc/sqlrelay/sqlrelay" ); then
        launched=0
        for connid in `grep -v ^# ${DESTDIR}/usr/pkg/etc/sqlrelay/sqlrelay`; do
            echo
            echo -n $"Launching instance with id '${connid}':"
            sqlr-start -id ${connid} 0<&- 1>&- 2>&-
            RETVAL=$?
            if ( test "$RETVAL" -eq "0" ); then
                echo "success"
            else
                echo "failure"
            fi
            launched=1
        done
        if ( test "$launched" -ne "1" ); then
            echo "passed"
        fi
        echo
    else
        echo "failure"
    fi
    cleanup
    return $RETVAL
}

stop(){
    echo -n $"Stopping SQL Relay: "
    if ( test -r "${DESTDIR}/usr/pkg/etc/sqlrelay/sqlrelay" ); then
        launched=0
        for connid in `grep -v ^# ${DESTDIR}/usr/pkg/etc/sqlrelay/sqlrelay`; do
            echo
            echo -n $"Launching instance with id '${connid}':"
            sqlr-stop ${connid} 0<&- 1>&- 2>&-
            RETVAL=$?
            if ( test "$RETVAL" -eq "0" ); then
                echo "success"
            else
                echo "failure"
            fi
            launched=1
        done
        if ( test "$launched" -ne "1" ); then
            echo "passed"
        fi
        echo
    else
        echo "failure"
    fi
    cleanup
    return $RETVAL
}

restart(){
    stop
    start
}


# See how we were called.
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        restart
        ;;
    *)
        echo "Usage: sqlrelay {start|stop|restart}"
        RETVAL=1
esac

exit $RETVAL
