#!/bin/sh
### BEGIN INIT INFO
# Provides:          pgweb
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start daemon at boot time
# Description:       Enable service provided by daemon.
### END INIT INFO

# Installation instructions (originally written for Debian)
#
# Save this script into /etc/init.d/pgweb file, make it executable,
# and install it into the boot sequence:
#
#    chmod 755 /etc/init.d/pgweb
#    update-rc.d pgweb defaults
# 
# This script assumes that pgweb binary is located at /home/pgweb/, and that
# there's a bookmark 'server' in /home/pgweb/.pgweb/bookmarks/.
#

NAME="pgweb"
PIDFILE="/var/run/$NAME.pid"

USER="pgweb"  # Linux system user
SU="su $USER -s /bin/bash"

TIMEOUT=5  # Time in seconds to wait postgresql to show up

case "$1" in
  start)
    if [ -f $PIDFILE ]; then
        echo "Already running... cat $PIDFILE"
        exit 0
    fi
    
    # Wait postgresql to show up
    while ! test -f /var/run/postgresql/*main.pid
    do
        sleep 1
        TIMEOUT=`expr $TIMEOUT - 1`
        if test $TIMEOUT -eq 0; then
            exit 1
        fi
    done
    
    # Ready to start pgweb
    PID=`$SU -c '/home/pgweb/pgweb -s -b server >/dev/null & echo $!'`  # Note! Logs are lost.
    if [ -z $PID ]; then
        exit 1
    else
        echo $PID > $PIDFILE
    fi
    ;;
  stop)
    PID=`cat $PIDFILE`
    kill $PID && rm $PIDFILE
    ;;
  *)
    echo "Usage: /etc/init.d/$NAME {start|stop}"
    exit 1
    ;;
esac

exit 0