#!/bin/sh
## +----------------------------------------------------------------------+
## | NEXCESS.NET InterWorx                                                |
## +----------------------------------------------------------------------+
## | Copyright (c) 2000-2010 NEXCESS.NET L.L.C., All Rights Reserved.     |
## +----------------------------------------------------------------------+
## | Redistribution and use in source form, with or without modification  |
## | is NOT permitted without consent from the copyright holder.          |
## |                                                                      |
## | THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND |
## | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,    |
## | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A          |
## | PARTICULAR PURPOSE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,    |
## | EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,  |
## | PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR   |
## | PROFITS; OF BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY  |
## | OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT         |
## | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE    |
## | USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH     |
## | DAMAGE.                                                              |
## +----------------------------------------------------------------------+
## | Authors: Chris Wells <clwells@nexcess.net>                           |
## |          Paul Oehler <poehler@nexcess.net>                           |
## +----------------------------------------------------------------------+
##
## $Id$

#
# Startup script for the InterWorx Server Management Suite
#
# chkconfig: 345 56 24
# description: InterWorx
# processname: iworx

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

IWORXHOME='/home/interworx'
IWORXUSER=iworx
IWORXGROUP=iworx
RETVAL=1

iworx_log() {
  message=$1
  ${IWORXHOME}/bin/log.pex --request_id init --message "${message}" --level DEBUG > /dev/null 2>&1 || :
}
#
# Start the InterWorx Webserver
#
# @returns integer (return value )
#
iworx_start_apache() {
        iworx_log "${FUNCNAME} called"
        which systemctl &>/dev/null
        retval=$?
        if [ $retval -eq 0 ]; then
        systemctl start iworxphp72-php-fpm.service
        else
        service iworxphp72-php-fpm start
        fi
        # if OPENSSL_NO_DEFAULT_ZLIB is undefined or empty, turn it on.
        if [ "$OPENSSL_NO_DEFAULT_ZLIB" == "" ]; then
          export OPENSSL_NO_DEFAULT_ZLIB="1"
        fi

        $IWORXHOME/bin/iworx-web -f $IWORXHOME/etc/httpd/httpd.conf -DSSL
        ret=$?
        if [ $ret -eq 0 ]; then
            action "Starting InterWorx-web: " /bin/true
        else
            action "Starting InterWorx-web: " /bin/false
        fi
        touch $IWORXHOME/var/lock/subsys/httpd

        return $ret
}

iworx_stop_apache() {
        iworx_log "${FUNCNAME} called"
        which systemctl &>/dev/null
        retval=$?
        if [ $retval -eq 0 ]; then
        systemctl stop iworxphp72-php-fpm.service
        else
        service iworxphp72-php-fpm stop
        fi
        ret=$?
        if [ -f $IWORXHOME/var/run/httpd.pid ] ; then
            httpd_pid=`cat $IWORXHOME/var/run/httpd.pid`
            kill $httpd_pid 2>/dev/null
        fi
        if [ $ret -eq 0 ]; then
            action "Stopping InterWorx-web: " /bin/true
        else
            action "Stopping InterWorx-web: " /bin/false
        fi
        [ $ret -eq 0 ] && rm -f $IWORXHOME/var/lock/subsys/httpd
        return $ret
}

iworx_restart_apache_graceful() {
        iworx_log "${FUNCNAME} called"
        /usr/bin/killall -USR1 iworx-web 2> /dev/null
        which systemctl &>/dev/null
        retval=$?
        if [ $retval -eq 0 ]; then
        systemctl restart iworxphp72-php-fpm.service
        else
        service iworxphp72-php-fpm restart
        fi
        ret=$?
        if [ $ret -eq 0 ]; then
            action "Gracefully restarting iworx-web: " /bin/true
        else
            action "Gracefully restarting iworx-web: " /bin/false;
            echo "Starting iworx-web manually ";
            iworx_start_apache;
        fi
}

# Starts ip6tables if managed by iworx.
iworx_start_ip6tables() {
    iworx_log "${FUNCNAME} called"
    $IWORXHOME/bin/ip6tables-control.pex --iptables-to-ip6tables
    return $?
}

iworx_start_mysql() {
  iworx_log "${FUNCNAME} called"
  cat $IWORXHOME/iworx.ini | grep dsn | grep iworx-db.sock > /dev/null
  local __ret=$?

  if [ $__ret -eq 0 ]; then
    iworx_start_mysql_new
    __ret=$?
  else
    iworx_start_mysql_old
    __ret=$?
  fi

  return $__ret
}

# Sync license.
iworx_sync_license() {
    iworx_log "${FUNCNAME} called"
    $IWORXHOME/cron/license.pex --sync
    return $?
}

#
# Start the InterWorx Database
#
# @returns integer (Return value)
#
iworx_start_mysql_new() {
  iworx_log "${FUNCNAME} called"
  $IWORXHOME/mysql/usr/bin/mysqld_safe --defaults-file=$IWORXHOME/mysql/my.cnf > /dev/null 2>&1 &
  ret=$?
  if [ $ret -eq 0 ]; then
      action "Starting InterWorx-db: " /bin/true
  else
      action "Starting InterWorx-db: " /bin/false
  fi

  [ $ret -eq 0 ] && touch $IWORXHOME/var/lock/subsys/iworx-db-2
  return $ret
}

#
# Start the InterWorx Database
#
# @returns integer (Return value)
#
iworx_start_mysql_old() {
    iworx_log "${FUNCNAME} called"
    if [ ! -d $IWORXHOME/var/lib/mysql ] ; then
            if [ -f $IWORXHOME/bin/mysql/mysql_install_db ]; then
                    action "Initializing InterWorx database" $IWORXHOME/bin/mysql/mysql_install_db --defaults-file=$IWORXHOME/etc/my.cnf --force > /dev/null 2>&1
            else
                    action "Initializing InterWorx database" mysql_install_db --defaults-file=$IWORXHOME/etc/my.cnf --force > /dev/null 2>&1
            fi

        ret=$?
        chown -R $IWORXUSER.$IWORXGROUP $IWORXHOME/var/lib/mysql

        if [ $ret -ne 0 ] ; then
            return $ret
        fi
    fi

        if [ -f $IWORXHOME/bin/mysql/mysqld_safe ]; then
            $IWORXHOME/bin/mysql/mysqld_safe --defaults-file=$IWORXHOME/etc/my.cnf > /dev/null 2>&1 &
        else
            safe_mysqld --defaults-file=$IWORXHOME/etc/my.cnf > /dev/null 2>&1 &
        fi

    ret=$?
    if [ $ret -eq 0 ]; then
        action "Starting Old InterWorx-db: " /bin/true
    else
        action "Starting Old InterWorx-db: " /bin/false
    fi

    [ $ret -eq 0 ] && touch $IWORXHOME/var/lock/subsys/mysqld
    return $ret
}

iworx_get_db_pid() {
    iworx_log "${FUNCNAME} called"
    local __output=$1
    local __mysqld_pid=0

    if [ -f $IWORXHOME/mysql/iworx-db.pid ] ; then
        __mysqld_pid=`cat $IWORXHOME/mysql/iworx-db.pid`
    fi

    eval $__output="$__mysqld_pid"
}

iworx_stop_mysql() {
  iworx_log "${FUNCNAME} called"
  iworx_get_db_pid pid

  if [ $pid -eq 0 ] ; then
    ret=0
  else

    iworx_db_status

    if [ $? -eq 0 ]; then # 0
      kill $pid 2> /dev/null

      for (( i=0; i<10; i++ ))
      do
        sleep 1

        iworx_db_status
        if [ $? -ne 0 ]; then
          break;
        fi
      done

      iworx_db_status

      if [ $? -eq 0 ]; then # 1
        action "Stopping InterWorx-db with 'kill $pid'" /bin/false
        kill -9 $mysqld_pid 2> /dev/null

        for (( i=0; i<10; i++ ))
        do
          sleep 1

          iworx_db_status
          if [ $? -ne 0 ]; then
            break;
          fi
        done

        iworx_db_status

        if [ $? -eq 0 ]; then # 2
          action "Stopping InterWorx-db with 'kill -9 $pid'" /bin/false
          grabpid=`ps auxf | grep iworx-db-2 | grep -v grep | awk '{print $2}'`
          kill $grabpid 2> /dev/null
          sleep 5

          iworx_db_status

          if [ $? -eq 0 ]; then # 3
            action "Stopping InterWorx-db with 'kill $grabpid'" /bin/false
            kill -9 $grabpid 2> /dev/null
            sleep 5

            iworx_db_status

            if [ $? -eq 0 ]; then # 4
              action "Stopping InterWorx-db with 'kill -9 $grabpid'" /bin/false
              killall iworx-db-2 2> /dev/null

              sleep 5
              iworx_db_status

              if [ $? -eq 0 ]; then # 5
                action "Stopping InterWorx-db with 'killall iworx-db-2'" /bin/false
                killall -9 iworx-db-2 2> /dev/null

                sleep 5
                iworx_db_status

                if [ $? -eq 0 ]; then # 6
                  action "Stopping InterWorx-db with 'killall -9 iworx-db-2'" /bin/false
                  # Bloody thing why won't you DIE!
                  ret=1
                else
                  ret=0
                fi # end 6
              else
                ret=0
              fi # end 5
            else
              ret=0
            fi # end 4
          else
            ret=0
          fi # end 3
        else
          ret=0
        fi # end 2
      else
        ret=0
      fi # end 1
    else
      ret=0
    fi # end 0
  fi

  if [ $ret -eq 0 ]; then
      action "Stopping InterWorx-db: " /bin/true
  else
      action "Stopping InterWorx-db: " /bin/false
  fi
  [ $ret -eq 0 ] && rm -f $IWORXHOME/var/lock/subsys/iworx-db-2
  [ $ret -eq 0 ] && rm -f $IWORXHOME/mysql/iworx-db.sock
  return $ret
}

iworx_stop_mysql_old() {
  iworx_log "${FUNCNAME} called"
  if [ -f $IWORXHOME/var/run/mysqld.pid ] ; then
    mysqld_pid=`cat $IWORXHOME/var/run/mysqld.pid`
    kill $mysqld_pid 2> /dev/null
  fi

  sleep 3
  iworx_db_status_old
  if [ "$?" -eq "0" ]; then #0
    kill -9 $mysqld_pid 2> /dev/null

    sleep 3
    iworx_db_status_old
    if [ "$?" -eq "0" ]; then #1
       grabpid=`ps auxf | grep iworx-db | grep -v grep | awk '{print $2}'`
       kill $grabpid 2> /dev/null

       sleep 2
       iworx_db_status_old
       if [ "$?" -eq "0" ]; then #2
          kill -9 $grabpid 2> /dev/null

          sleep 2
          iworx_db_status_old
           if [ "$?" -eq "0" ]; then #3
             killall iworx-db 2> /dev/null

             sleep 2
             iworx_db_status_old
              if [ "$?" -eq "0" ]; then #4
                killall -9 iworx-db 2> /dev/null

                sleep 2
                iworx_db_status_old

                if [ "$?" -eq "0" ]; then #5
                   ret=1
                else
                  ret=0
                fi

             else #4
                ret=0
             fi

          else #3
             ret=0
          fi

       else #2
          ret=0
       fi

    else #1
       ret=0
    fi

  else  #0
      ret=0
  fi

  if [ $ret -eq 0 ]; then
      action "Stopping Old InterWorx-db: " /bin/true
  else
      action "Stopping Old InterWorx-db: " /bin/false
  fi
  [ $ret -eq 0 ] && rm -f $IWORXHOME/var/lock/subsys/mysqld
  [ $ret -eq 0 ] && rm -f $IWORXHOME/var/run/mysql.sock
  return $ret
}

iworx_db_status() {
    iworx_log "${FUNCNAME} called"
    iworx_get_db_pid pid

    if [ $pid -ne 0 ]; then
        # Check if it's really running, or just full of shit
        ps auxf | grep iworx-db-[2] > /dev/null
        db_running=${PIPESTATUS[1]}
        if [ $db_running -eq 0 ]; then
                return 0 # Running
        else
                return 1 # Dead, but pid exists
        fi
    else
        return 3 # Not running
    fi
}

iworx_db_status_old() {
    iworx_log "${FUNCNAME} called"
    pidof iworx-db > /dev/null
    db_running=$?

    if [ $db_running -eq 0 ]; then
        #For realz?
        ps auxf | grep iworx-d[b] > /dev/null
        db_running=${PIPESTATUS[1]}
        if [ $db_running -eq 0 ]; then
                return 0
        else
                return 3
        fi
    else
        return 3
    fi
}

iworx_web_status() {
    iworx_log "${FUNCNAME} called"
    pidof iworx-web > /dev/null
    web_running=$?

    if [ $web_running -eq 0 ]; then
        return 0
    else
        return 3
    fi
}

iworx_fpm_status() {
    iworx_log "${FUNCNAME} called"
    service iworxphp72-php-fpm status &> /dev/null
    fpm_running=$?

    return $fpm_running
}


iworx_status() {
    iworx_log "${FUNCNAME} called"
    iworx_web_status
    web_running=$?

    iworx_fpm_status
    fpm_running=$?

    iworx_db_status
    db_running=$?

    if [ $web_running -eq 0 ] && [ $db_running -eq 0 ] && [ $fpm_running -eq 0 ]; then
        return 0
    else
        return 3
    fi
}

iworx_bind_ips() {
    iworx_log "${FUNCNAME} called"
    $IWORXHOME/exec_timeout.sh $IWORXHOME/cron/license.pex > /dev/null 2>&1
    if [ -f $IWORXHOME/bin/ip.pex ]; then
        $IWORXHOME/bin/ip.pex --bind-aliases > /dev/null 2>&1

        ret=$?
        if [ $ret -ne 0 ]; then
          sleep 5
          $IWORXHOME/bin/ip.pex --bind-aliases 2> /dev/null
          ret=$?
        fi

        if [ $ret -eq 0 ]; then
            action "Binding IP Aliases: " /bin/true
        else
            action "Binding IP Aliases: " /bin/false
        fi
    fi
}

iworx_start_all() {
    iworx_log "${FUNCNAME} called"
    iworx_status
    is_running=$?

    if [ $is_running -eq 0 ]; then
        echo "InterWorx is already running..."
        RETVAL=0
    else
        iworx_db_status
        db_running=$?

        if [ $db_running -ne 0 ]; then
            iworx_start_mysql
            db_running=$?
        fi

        iworx_web_status
        web_running=$?
        if [ $web_running -ne 0 ]; then
            iworx_start_apache
            web_running=$?

        fi

        iworx_bind_ips
        if [[ $web_running -eq 0 ]] && [[ $db_running -eq 0 ]]; then
            RETVAL=0
        else
            RETVAL=1
        fi

        iworx_start_ip6tables
        iworx_sync_license
    fi
}

iworx_stop_all() {
    iworx_log "${FUNCNAME} called"
    iworx_stop_apache
    apache_ret=$?
    iworx_stop_mysql
    mysql_ret=$?

    iworx_db_status_old

    if [ $? -eq 0 ]; then
      iworx_stop_mysql_old
    fi

    if [ $apache_ret -eq 0 ] && [ $mysql_ret -eq 0 ]; then
        RETVAL=0
    else
        RETVAL=1
    fi
}

### The start, stop, restart, force-reload, and status actions shall be supported by all init scripts

date >> ~iworx/var/log/iworx-init.log
echo "iworx init: ${1}\n" >> ~iworx/var/log/iworx-init.log
ps auxf >> ~iworx/var/log/iworx-init.log

case "$1" in
    startweb)
        iworx_start_apache
        ;;
    stopweb)
        iworx_stop_apache
        ;;
    startdb)
        iworx_start_mysql
        ;;
    stopdb)
        iworx_stop_mysql
        ;;
    startdbnew)
        iworx_start_mysql_new
        ;;
    startdbold)
        iworx_start_mysql_old
        ;;
    stopdbold)
        iworx_stop_mysql_old
        ;;
    restartweb)
        iworx_stop_apache
        iworx_stop_apache
        sleep 3
        iworx_start_apache
        ;;
    restartdb)
        iworx_stop_mysql
        sleep 3
        iworx_start_mysql
        ;;
    start)
        iworx_start_all
        ;;
    bind_ips)
        iworx_bind_ips
        ;;
    stop)
	      iworx_stop_all
        ;;
    restart)
        iworx_stop_all
        sleep 3
        iworx_stop_all > /dev/null 2>&1
        sleep 1
        iworx_start_all
        ;;
    graceful)
        iworx_restart_apache_graceful
        ;;
    force-reload)
        iworx_stop_all
        sleep 3
        iworx_stop_all > /dev/null 2>&1
        sleep 1
        iworx_start_all
        ;;
    db-status)
        iworx_db_status
        RETVAL=$?
        if [ $RETVAL -eq 0 ]; then
            echo "InterWorx DB is running..."
        elif [ $RETVAL -eq 3 ]; then
            echo "InterWorx DB is not running..."
        elif [ $RETVAL -eq 1 ]; then
            echo "InterWorx DB is not running but pid file exists..."
        else
            echo "Reserved for future error codes"
        fi

        ;;
    status)
        RETVAL=0
        iworx_web_status
        web_running=$?

        iworx_fpm_status
        fpm_running=$?

        iworx_db_status
        db_running=$?

        if [ $web_running -eq 0 ]; then
          action "iworx-web is running..." /bin/true
        else
          action "iworx-web is not running..." /bin/false
          RETVAL=3
        fi

        if [ $fpm_running -eq 0 ]; then
          action "iworxphp72-php-fpm is running..." /bin/true
        else
          action "iworxphp72-php-fpm is not running..." /bin/false
          RETVAL=3
        fi

        if [ $db_running -eq 0 ]; then
          action "iworx-db is running..." /bin/true
        else
          action "iworx-db is not running..." /bin/false
          RETVAL=3
        fi
        ;;
    *)
        echo $"Usage: {start|stop|restart|status|force-reload}"
        RETVAL=0
esac

exit $RETVAL
