#!/bin/sh
#
### BEGIN INIT INFO
# Provides:           pe-postgresql
# Required-Start:     $local_fs $remote_fs $network
# Required-Stop:      $local_fs $remote_fs $network
# Default-Start:      3 4 5
# Default-Stop:       0 1 2 6
# Short-Description:  Puppet Enterprise PostgreSQL RDBMS server
# Description         Start the Puppet Enterprise Postgresql Database server
### END INIT INFO
#
# chkconfig: 345 60 20
# description         Start the Puppet Enterprise Postgresql Database server
# processname: postgresql
# config: /etc/syconfig/pe-pgsql
#
# PGVERSION is the full package version, e.g. 9.1.0
# Note: the specfile inserts the correct version during package build
PGVERSION=9.4.5
# PGMAJORVERSION is major version, e.g. 9.1 (this should match PGVERSION)
PGMAJORVERSION=`echo "$PGVERSION" | sed 's/^\([0-9]*\.[0-9]*\).*$/\1/'`

# Find the name of the script
NAME=`basename $0`
if [ ${NAME:0:1} = "S" -o ${NAME:0:1} = "K" ] ; then
  NAME=${NAME:3}
fi

# For SELinux we need to use 'runuser' not 'su'
if [ -x /sbin/runuser ] ; then
  SU=runuser
else
  SU=su
fi

# Define variable for the locale parameter
LOCALEPARAMETER=$2

# Set defaults for configuration variables
PGENGINE=/opt/puppetlabs/server/apps/postgresql/bin
PGDATA=/opt/puppetlabs/server/data/postgresql/${PGMAJORVERSION}/data
PGLOGDIR=/var/log/puppetlabs/postgresql
PGSTARTUPLOG=${PGLOGDIR}/pgstartup.log
PIDDIR=/var/run/puppetlabs/postgresql
PGSTARTTIMEOUT=30

lockfile="/var/lock/subsys/${NAME}"
pidfile=${PIDDIR}/postgresql.pid

# Override defaults from /etc/sysconfig/pgsql if file is present
[ -f /etc/sysconfig/pe-pgsql/${NAME} ] && . /etc/sysconfig/pe-pgsql/${NAME}

# Source lsb functions. This also sources /etc/rc.status
[ -f /lib/lsb/init-functions ] && . /lib/lsb/init-functions

# reset overall exit code status
rc_reset

export PGDATA

[ -f "$PGENGINE/postmaster" ] || exit 5

start(){
  PSQL_START=$"Starting ${NAME} service: "

  # Make sure startup-time log file is valid
  if [ ! -e "$PGSTARTUPLOG" -a ! -h "$PGSTARTUPLOG" ] ; then
    touch "$PGSTARTUPLOG" || exit 1
    chown pe-postgres:pe-postgres "$PGSTARTUPLOG"
    chmod go-rwx "$PGSTARTUPLOG"
    [ -x /sbin/restorecon ] && /sbin/restorecon "$PGSTARTUPLOG"
  fi

  # Check for the PGDATA structure
  if [ -f "$PGDATA/PG_VERSION" ] && [ -d "$PGDATA/base" ] ; then
    # Check version of existing PGDATA
    if [ x`cat "$PGDATA/PG_VERSION"` != x"$PGMAJORVERSION" ] ; then
      SYSDOCDIR=/opt/puppetlabs/server/share/doc
      echo
      log_failure_msg $"An old version of the database format was found."
      log_failure_msg $"You need to upgrade the data format before using PostgreSQL."
      log_failure_msg $"See $SYSDOCDIR/postgresql-$PGVERSION/README.rpm-dist for more information."
      exit 1
    fi
  else
    # No existing PGDATA! Warn the user to initdb it.
    log_failure_msg $"$PGDATA is missing. Use \"service pe-postgresql initdb\" to initialize the cluster first."
    exit 6
  fi

  # Check for the default pid directory, create if not present
  if ! [ -d $PIDDIR ] ; then
    mkdir -p $PIDDIR
  fi
  chown pe-postgres:pe-postgres "$PIDDIR"
  chmod go-rwx "$PIDDIR"

  echo -n "$PSQL_START"
  $SU -l pe-postgres -s /bin/bash -c "$PGENGINE/postmaster -D '$PGDATA' -c log_directory=${PGLOGDIR} ${PGOPTS} &" >> "$PGSTARTUPLOG" 2>&1 < /dev/null

  # Wait up to 30 seconds for pidfile creation.
  # Adapted from rh-postgresql94 init script
  # See rhbz#800534 and rhbz#1188942 for more info.
  # Original waiting implementation by Jozef Mlích.

  decounter=${PGSTARTTIMEOUT:-30}
  while test "$decounter" -ge 0; do
    pid=$(head -n 1 "$PGDATA/postmaster.pid" 2>/dev/null)
    test "x$pid" != x && break
    # pidfile does not exist yet, wait a sec more
    decounter=$(( decounter - 1 ))
    sleep 1
  done

  if [ "x$pid" != x ] ; then
    rc_status -v
    touch "$lockfile"
    echo $pid > "$pidfile"
    log_success_msg $"Started ${NAME} service "
    echo
  else
    log_failure_msg "$PSQL_START"
    echo
    rc_failed 7
  fi
}

stop(){
  PSQL_STOP=$"Stopping ${NAME} service: "
  echo -n "$PSQL_STOP"
  if [ -e "$lockfile" ] ; then
    $SU -l pe-postgres -s /bin/bash -c "$PGENGINE/pg_ctl stop -D '$PGDATA' -s -m fast" > /dev/null 2>&1 < /dev/null
    rc_status -v
    ret=$?
    if [ $ret -eq 0 ] ; then
      log_success_msg "Stopped ${NAME} service"
      rm -f "$pidfile"
      rm -f "$lockfile"
    else
      log_failure_msg "${PSQL_STOP}"
      rc_failed 1
    fi
  else
    # not running; per LSB standards this is "ok"
    log_warning_msg "${NAME} service not running"
  fi
}

status(){
  $SU -l pe-postgres -s /bin/bash -c "$PGENGINE/pg_ctl status -D $PGDATA -s" >/dev/null 2>&1 < /dev/null
  ret=$?
  if [ $ret -ne 0 ] ; then
    if [ -e "$pidfile" ] ; then
      log_warning_msg "${NAME} is not running but $pidfile exists..."
      rc_failed 1
    elif [ -e "$lockfile" ] ; then
      log_warning_msg "${NAME} is not running but $lockfile exists..."
      rc_failed 2
    else
      log_success_msg "${NAME} is not running..."
      rc_failed 3
    fi
  else
    log_success_msg "${NAME} is running..."
  fi
}

restart(){
  stop
  start
}

initdb(){
  # If the locale name is specified just after the initdb parameter, use it:
  if [ -z $LOCALEPARAMETER ] ; then
    LOCALE=`echo $LANG`
  else
    LOCALE=`echo $LOCALEPARAMETER`
  fi
  LOCALESTRING="--locale=$LOCALE"

  if [ -f "$PGDATA/PG_VERSION" ] ; then
    log_failure_msg "Data directory is not empty!"
    exit 1
  else
    echo -n $"Initializing database: "
    if [ ! -d "$PGDATA" -a ! -h "$PGDATA" ] ; then
      mkdir -p "$PGDATA" || exit 1
      chown pe-postgres:pe-postgres "$PGDATA"
      chmod go-rwx "$PGDATA"
    fi
    # Clean up SELinux tagging for PGDATA
    [ -x /sbin/restorecon ] && /sbin/restorecon "$PGDATA"

    # Make sure the startup-time log file is OK, too
    if [ ! -e "$PGSTARTUPLOG" -a ! -h "$PGSTARTUPLOG" ] ; then
      touch "$PGSTARTUPLOG" || exit 1
      chown pe-postgres:pe-postgres "$PGSTARTUPLOG"
      chmod go-rwx "$PGSTARTUPLOG"
      [ -x /sbin/restorecon ] && /sbin/restorecon "$PGSTARTUPLOG"
    fi

    # Initialize the database
    $SU -l pe-postgres -s /bin/bash -c "$PGENGINE/initdb --pgdata='$PGDATA' --auth-local=peer --auth-host=md5 $LOCALESTRING" >> "$PGSTARTUPLOG" 2>&1 < /dev/null
    rc_status -v

    # Create directory for the postmaster log
    if ! [ -d "$PGDATA/pg_log" ] ; then
      mkdir "$PGDATA/pg_log"
      chown pe-postgres:pe-postgres "$PGDATA/pg_log"
      chmod go-rwx "$PGDATA/pg_log"
    fi

    [ -f "$PGDATA/PG_VERSION" ] && log_success_msg "Initialized database"
    [ ! -f "$PGDATA/PG_VERSION" ] && log_failure_msg "Unable to initialize database"
    echo
  fi
}

condrestart(){
  [ -e "$lockfile" ] && restart || :
}

reload(){
  $SU -l pe-postgres -s /bin/bash -c "$PGENGINE/pg_ctl reload -D '$PGDATA' -s" > /dev/null 2>&1 < /dev/null
}

# See how we were called.
case "$1" in
  start)
  start
  ;;
  stop)
  stop
  ;;
  status)
  status
  ;;
  restart)
  restart
  ;;
  initdb)
  initdb
  ;;
  condrestart|try-restart)
  condrestart
  ;;
  reload)
  reload
  ;;
  force-reload)
  restart
  ;;
  *)
  echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|initdb}"
  exit 2
esac

rc_exit
