#!/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$

### BEGIN INIT INFO
# Provides:          iworx interworx
# Required-Start:    $local_fs $network $named $remote_fs
# Required-Stop:     $local_fs $network $named $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: InterWorx – Web Hosting Control Panel
# Description:       InterWorx is a comprehensive and scalable hosting
#                    control panel for server admins and customers. It
#                    offers features such as NodeWorx for server
#                    management, SiteWorx for domain and website
#                    hosting, API, CLI, and plugins support, and more.
### END INIT INFO

#
# 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() {
        local ret retval

        iworx_log "${FUNCNAME} called"
        conditional_stop_iworxphp72
        systemctl start iworxphp82-php-fpm.service
        # 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() {
        local ret retval
        iworx_log "${FUNCNAME} called"
        systemctl stop iworxphp82-php-fpm.service
        stop_php=$?
        kill_httpd=0
        if [ -f $IWORXHOME/var/run/httpd.pid ] ; then
            httpd_pid=`cat $IWORXHOME/var/run/httpd.pid`
            kill $httpd_pid 2>/dev/null
            kill_httpd=$?
        fi
        if [ $stop_php -eq 0 ] && [ $kill_httpd -eq 0 ]; then
            action "Stopping InterWorx-web: " /bin/true
            ret=0
        else
            action "Stopping InterWorx-web: " /bin/false
            ret=1
        fi
        [ $ret -eq 0 ] && rm -f $IWORXHOME/var/lock/subsys/httpd
        return $ret
}

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

# Stop iworxphp72 if we're updating from IW7
conditional_stop_iworxphp72() {
    iworx_log "${FUNCNAME} called"
    IWORX_UPGRADE_FILE="$IWORXHOME/etc/env/shutdown-iworxphp72"
    if [ -f $IWORX_UPGRADE_FILE ]; then
        # everything should be systemd for IW8 upgrades
        systemctl stop iworxphp72-php-fpm.service
        rm -f $IWORX_UPGRADE_FILE
    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() {
  local ret
  iworx_log "${FUNCNAME} called"
  iworx_is_iworx_db_55
  is55=$?
  if [ $is55 -eq 0 ]; then
      $IWORXHOME/mysql/usr/bin/mysqld_safe --defaults-file=$IWORXHOME/mysql/my.cnf --mysqld=iworx-db-2 --ledir=$IWORXHOME/mysql/usr/sbin > /dev/null 2>&1 &
  else
      systemctl start iworx-db-mariadb
  fi
  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() {
    local ret
    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() {
  local ret
  iworx_log "${FUNCNAME} called"
  iworx_get_db_pid pid
  iworx_is_iworx_db_55
  is55=$?

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

      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
    else # is not iworx-db-55
      systemctl stop iworx-db-mariadb
      ret=$?
    fi
  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() {
  local ret
  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
        iworx_is_iworx_db_55
        is55=$?
        if [ $is55 -eq 0 ]; then
            package='iworx-db-[2]'
        else
            package='interworx/mysql/sbin/mariadb[d]'
        fi

        # Check if it's really running, or just full of shit
        ps auxf | grep $package > /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_is_iworx_db_55() {
    iworx_log "${FUNCNAME} called"
    rpm -qi iworx-db-55 > /dev/null 2>&1
    is_55=$?
    if [ $is_55 -eq 0 ]; then
        return 0
    else
        return 1
    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 iworxphp82-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() {
    local ret
    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
    return $ret;
}

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

    if [ $is_running -eq 0 ]; then
        echo "InterWorx is already running..."
        ret=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
            ret=0
        else
            ret=1
        fi

        iworx_start_ip6tables
        iworx_sync_license
    fi
    return $ret
}

iworx_stop_all() {
    local ret
    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
        ret=0
    else
        ret=1
    fi
    return $ret
}

### 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
        RETVAL=$?
        ;;
    stopweb)
        iworx_stop_apache
        RETVAL=$?
        ;;
    startdb)
        iworx_start_mysql
        RETVAL=$?
        ;;
    stopdb)
        iworx_stop_mysql
        RETVAL=$?
        ;;
    startdbnew)
        iworx_start_mysql_new
        RETVAL=$?
        ;;
    startdbold)
        iworx_start_mysql_old
        RETVAL=$?
        ;;
    stopdbold)
        iworx_stop_mysql_old
        RETVAL=$?
        ;;
    restartweb)
        iworx_stop_apache
        iworx_stop_apache
        RETVAL=$?
        if [ $RETVAL -eq 0 ]; then
          sleep 3
          iworx_start_apache
          RETVAL=$?
        fi
        ;;
    restartdb)
        iworx_stop_mysql
        RETVAL=$?
        if [ $RETVAL -eq 0 ]; then
          sleep 3
          iworx_start_mysql
          RETVAL=$?
        fi
        ;;
    start)
        iworx_start_all
        RETVAL=$?
        ;;
    bind_ips)
        iworx_bind_ips
        RETVAL=$?
        ;;
    stop)
	      iworx_stop_all
        ;;
    restart)
        iworx_stop_all
        sleep 3
        iworx_stop_all > /dev/null 2>&1
        RETVAL=$?
        if [ $RETVAL -eq 0 ]; then
          sleep 1
          iworx_start_all
          RETVAL=$?
        fi
        ;;
    graceful)
        iworx_restart_apache_graceful
        RETVAL=$?
        ;;
    force-reload)
        iworx_stop_all
        sleep 3
        iworx_stop_all > /dev/null 2>&1
        RETVAL=$?
        if [ $RETVAL -eq 0 ]; then
          sleep 1
          iworx_start_all
          RETVAL= $?
        fi
        ;;
    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 "iworxphp82-php-fpm is running..." /bin/true
        else
          action "iworxphp82-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
