#!/bin/sh
# vim: set et ai cin sw=2 ts=2 tw=0:
# Start/stop/restart postgres daemon.

. /etc/postgresd.conf

# Start postgres:
pg_start() {
  if [ ! -e "$PGLOG" ]; then
    touch "$PGLOG"
    chown $PGUSER:$PGGROUP "$PGLOG"
  else
    cat /dev/null > "$PGLOG"
  fi
  su - $PGUSER -c "pg_ctl -D $PGDB status" >/dev/null 2>&1
  if [ $? -ne 0 ]; then
    su - $PGUSER -c "pg_ctl -D $PGDB -l \"$PGLOG\" start"
  fi
}

# Stop postgres:
pg_stop() {
  su - $PGUSER -c "pg_ctl -D $PGDB status" >/dev/null 2>&1
  if [ $? -eq 0 ]; then
    su - $PGUSER -c "pg_ctl -D $PGDB -m fast stop"
    # Wait at least 30s for it to exit, as we don't know how big the DB is...
    for second in 0 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 20 1 2 3 4 5 6 7 8 9 30; do
      if [ ! -r "$PGPID" ]; then
        break;
      fi
      sleep 1
    done
    if [ "$second" = "30" ]; then
      echo "WARNING:  Gave up waiting for postgres to exit => kill it!"
      su - $PGUSER -c "pg_ctl -D $PGDB -m immediate stop"
    fi
  fi
}

# Restart postgres:
pg_restart() {
  su - $PGUSER -c "pg_ctl -D $PGDB status" >/dev/null 2>&1
  if [ $? -eq 0 ]; then
    su - $PGUSER -c "pg_ctl -D $PGDB -m fast restart"
  fi
}

# Reload postgres:
pg_reload() {
  su - $PGUSER -c "pg_ctl -D $PGDB status" >/dev/null 2>&1
  if [ $? -eq 0 ]; then
    su - $PGUSER -c "pg_ctl -D $PGDB reload"
  fi
}

# Status of postgres:
pg_status() {
  su - $PGUSER -c "pg_ctl -D $PGDB status" >/dev/null 2>&1
  if [ $? -eq 0 ] ; then
    echo "PostgreSQL is running."
  else
    echo "PostgreSQL is stopped."
  fi
}

if [ ! -e $PGDB ]; then
  echo "
Before you can run PostgreSQL, you must have a database. To install an initial
database, do this as root:

  sh /usr/doc/postgresql-*/install-script.sh"
  exit 1
fi
case "$1" in
  'start')
    pg_start
    ;;
  'stop')
    pg_stop
    ;;
  'restart')
    pg_restart
    ;;
  'reload')
    pg_reload
    ;;
  'status')
    pg_status
    ;;
  *)
    echo "usage $0 start|stop|restart|reload|status"
esac