#! /bin/sh
# chkconfig: 2345 51 49
# description: PostgreSQL RDBMS
### BEGIN INIT INFO
# Provides: postgresql
# Required-Start: $local_fs
# Required-Stop: $local_fs
# Should-Start: $network
# Default-Start: 3 4 5
# Default-Stop: 0 1 2 6
# Short-Description: PostgreSQL RDBMS
# Description: PostgreSQL RDBMS
# X-Timesys-Start-Number: 49
# X-Timesys-Stop-Number: 51
### END INIT INFO

## EDIT FROM HERE

# Installation prefix
prefix=/usr

# Data directory
PGDATA="/var/pgsql/data"

# PostgreSQL system user (must NOT be root)
PGUSER=postgres

# Log file
PGLOG="$PGDATA/serverlog"

## STOP EDITING HERE

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# PostgreSQL server binary (PG >= 10)
DAEMON="$prefix/bin/postgres"

# Control utility
PGCTL="$prefix/bin/pg_ctl"

# Initdb
PGINITDB="$prefix/bin/initdb"

set -e

# Only start if postgres binary exists
test -x "$DAEMON" || {
	echo "$DAEMON not found"
	[ "$1" = "stop" ] && exit 0 || exit 5
}

pg_setup_system()
{
  if ! grep -q "^postgres:" /etc/passwd 2>/dev/null; then
    echo "$0: Creating system user 'postgres'"
    yes '' | adduser postgres >/dev/null 2>&1 || yes '' | useradd postgres >/dev/null 2>&1
  fi

  if [ ! -f "$PGDATA/PG_VERSION" ]; then
    echo "Initializing database in $PGDATA"
    mkdir -p "$PGDATA"
    chown postgres:postgres "$PGDATA"
    su - "$PGUSER" -c "$PGINITDB -D '$PGDATA'"
  fi
}

case "$1" in
  start)
    pg_setup_system
    echo -n "Starting PostgreSQL: "
    su - "$PGUSER" -c "$PGCTL start -D '$PGDATA' -s -l '$PGLOG'"
    echo "ok"
    ;;

  stop)
    echo -n "Stopping PostgreSQL: "
    su - "$PGUSER" -c "$PGCTL stop -D '$PGDATA' -s -m fast"
    echo "ok"
    ;;

  restart)
    echo -n "Restarting PostgreSQL: "
    su - "$PGUSER" -c "$PGCTL restart -D '$PGDATA' -s -m fast"
    echo "ok"
    ;;

  reload)
    echo -n "Reloading PostgreSQL: "
    su - "$PGUSER" -c "$PGCTL reload -D '$PGDATA' -s"
    echo "ok"
    ;;

  status)
    su - "$PGUSER" -c "$PGCTL status -D '$PGDATA'"
    ;;

  init)
    pg_setup_system
    ;;

  *)
    echo "Usage: $0 {start|stop|restart|reload|status|init}" >&2
    exit 1
    ;;
esac

exit 0

