#!/bin/bash
#
# (c) Copyright 2011-2012 Cloudera, Inc.
#
# Init script for the Cloudera SCM Server's Embedded Database (postgresql).
#
# chkconfig: 2345 79 11
# description: Cloudera SCM Server Embedded DB.

### BEGIN INIT INFO
# Provides: cloudera-scm-server-db
# Required-Start: $local_fs $network $syslog
# Should-Start:
# Required-Stop:
# Default-Start: 3 4 5
# Default-Stop: 0 1 2 6
# Short-Description: Cloudera SCM Server's Embedded DB
# Description: Cloudera SCM Server's Embedded DB
### END INIT INFO

DATA_DIR=/var/lib/cloudera-scm-server-db/data

# Source function library.
# This not only pulls in functions that we don't use,
# but it also sanitizes the environment a bit
# by setting standard umask, PATH, etc.
if [ -f /etc/rc.d/init.d/functions ]; then
  . /etc/rc.d/init.d/functions
elif [ -f /lib/lsb/init-functions ]; then
  . /lib/lsb/init-functions
  . /etc/rc.status
  rc_reset
fi

# For SELinux we need to use 'runuser' not 'su'
USER=cloudera-scm
if [ -x /sbin/runuser ]; then
    SU="runuser -s /bin/bash $USER"
else
    SU="su -s /bin/bash $USER"
fi

RETVAL=0
SERVER_LOGFILE="/var/log/cloudera-scm-server/db.log"

case "$1" in
  initdb)
    INITIALIZE_SCRIPT="/usr/share/cmf/bin/initialize_embedded_db.sh"
    $SU -c "$INITIALIZE_SCRIPT $DATA_DIR $SERVER_LOGFILE"
    RETVAL=$?
    ;;
  start)
    STATUS=$($SU -c "pg_ctl status -D $DATA_DIR")
    if [[ $? -ne 0 ]]; then
        $SU -c "pg_ctl start -w -D $DATA_DIR -l $SERVER_LOGFILE"
    else
        # Already started
        echo $STATUS
    fi
    RETVAL=$?
    ;;
  stop)
    STATUS=$($SU -c "pg_ctl status -D $DATA_DIR")
    if [[ $? -eq 0 ]]; then
        $SU -c "pg_ctl stop -w -D $DATA_DIR"
    else
        # Already stopped
        echo $STATUS
    fi
    RETVAL=$?
    ;;
  status)
    $SU -c "pg_ctl status -D $DATA_DIR"
    RETVAL=$?
    ;;
  restart)
    $SU -c "pg_ctl restart -D $DATA_DIR"
    RETVAL=$?
    ;;
  *)
    echo "Usage: $prog {initdb|start|stop|restart|status}"
    RETVAL=3
esac

exit $RETVAL
