#!/bin/bash
#
# Startup script for Tomcat Servlet Engine.
#
# chkconfig: 345 86 14
# description: Tomcat Servlet Engine
# processname: pageseeder
# CATALINA_PID=$PS_TOMCAT_HOME/bin/pageseeder.pid
# It is set in tomcat/bin/catalina.sh

# PS folders
export PS_HOME=/opt/pageseeder
export PS_TOMCAT_HOME=$PS_HOME/tomcat

# User under which pageseeder will run
TOMCAT_USER=pageseeder

# current user
CURRENT_USER=$(whoami)

# find java home using which command and going back up two folders
export JRE_HOME=$(dirname $(dirname $(readlink -f $(which java))))
export CATALINA_PID=$PS_TOMCAT_HOME/bin/pageseeder.pid

RETVAL=0

# migrate function
migrate() {
    # Check if tomcat is running
    SHUTDOWN_PORT=`netstat -vatn|grep LISTEN|grep 8005|wc -l`
    if [ $SHUTDOWN_PORT -ne 0 ]; then
        echo "Pageseeder Server must be stopped to be migrated, use 'service pageseeder stop'."
    else
        $PS_HOME/migrate.sh
    fi
}

# config function
config() {
    # Check if tomcat is running
    SHUTDOWN_PORT=`netstat -vatn|grep LISTEN|grep 8005|wc -l`
    if [ $SHUTDOWN_PORT -ne 0 ]; then
        echo "Pageseeder Server must be stopped to be configured, use 'service pageseeder stop'."
    else
      UPDATE=false
      # check for drivers folder
      if [ -d $PS_HOME/webapp/WEB-INF/drivers ]; then
        UPDATE=true
      fi

      if [ "$CURRENT_USER" = "$TOMCAT_USER" ]; then
        $PS_HOME/configure.sh
      else
        # check for drivers folder
        if [ ! -d $PS_HOME/webapp/WEB-INF/drivers ]; then
          echo "Have you downloaded the MySQL Connector/J JDBC driver (y/n) [y]?"
          read -e DRIVER_DOWNLOAD
          if [ -z $DRIVER_DOWNLOAD ]; then DRIVER_DOWNLOAD="y"; fi
          if [ $DRIVER_DOWNLOAD != "y" ]; then
            echo "Please find the latest CONNECTOR/J version on the MySQL website and then download, for example:"
            echo ""
            echo "wget http://dev.mysql.com/get/Downloads/Connector-J/mysql-connector-java-5.1.36.tar.gz"
            echo "tar xzvf mysql-connector-java-5.1.36.tar.gz"
            exit 0
          fi
          # wait until a valid jar file is selected
          DRIVER=invalid
          while [ ! -f $DRIVER ]; do
            echo "Please locate the MySQL JDBC driver jar file";
            read -e DRIVER
            # empty value
            if [ -z $DRIVER ]; then DRIVER="invalid"; fi
          done;
        fi

        su $TOMCAT_USER -c '$PS_HOME/configure.sh'

        # read existing mailport
        EXISTINGMAILPORT=`sed -n "s/^mailPort=\([0-9]*\)/\1/p" $PS_HOME/webapp/WEB-INF/config/global.properties | sed "s/\r//"`
        if [ -z $EXISTINGMAILPORT ]; then
          DEFAULTMAILPORT=2525;
        else
          DEFAULTMAILPORT=$EXISTINGMAILPORT;
        fi

        # ask for mail port
        USEMAILPORT="n"
        while [ $USEMAILPORT != "y" ]; do
          echo "Please enter the port used by the SMTP mail server [$DEFAULTMAILPORT]"
          read -e MAILPORT
          if [ -z $MAILPORT ]; then MAILPORT=$DEFAULTMAILPORT; fi
          # make sure it's a number
          if [[ "$MAILPORT" =~ ^[0-9]+$ ]]; then
            # check range
            if [ "$MAILPORT" -lt 1024 ]; then
              echo "This port can not be below 1024 (2525 is recommended)."
            else
              USEMAILPORT="y"
            fi
          fi
        done;

        # set mail port
        if [ -z $EXISTINGMAILPORT ]; then
          sed "s/productKey=.*/mailPort=$MAILPORT\n&/" $PS_HOME/webapp/WEB-INF/config/global.properties > $PS_HOME/temp4.p
        else
          sed "s/^mailPort=.*/mailPort=$MAILPORT/" $PS_HOME/webapp/WEB-INF/config/global.properties > $PS_HOME/temp4.p
        fi
        mv -f $PS_HOME/temp4.p $PS_HOME/webapp/WEB-INF/config/global.properties
        chown -R pageseeder $PS_HOME/webapp/WEB-INF/config/global.properties

        # setup mail redirect
        sed "s/2525/$MAILPORT/" $PS_HOME/webapp/WEB-INF/sysconfig/ps_smtp_forward > /etc/xinetd.d/ps_smtp_forward

        if [[ $(pidof systemd) ]]; then
          systemctl enable xinetd
          systemctl restart xinetd
        elif [[ $(pidof init) ]]; then
          chkconfig --add xinetd
          service xinetd restart
        else
          chkconfig --add xinetd
          service xinetd restart
          echo "Unable to determine the service manager installed on this server. Please manually check that the xinetd service is enabled, and restart the service if it is currently running."
        fi

        # always start pageseeder
        chkconfig --add pageseeder

        # if no drivers folder
        if [ ! -d $PS_HOME/webapp/WEB-INF/drivers ]; then
          # copy driver to drivers and lib
          mkdir $PS_HOME/webapp/WEB-INF/drivers
          cp -pf $DRIVER $PS_HOME/webapp/WEB-INF/drivers/
          chown $TOMCAT_USER $PS_HOME/webapp/WEB-INF/drivers/*
        fi

        # copy drivers to lib
        cp -f $PS_HOME/webapp/WEB-INF/drivers/*.jar $PS_HOME/webapp/WEB-INF/lib/
        chown $TOMCAT_USER $PS_HOME/webapp/WEB-INF/lib/*

      fi

      if [ $UPDATE != true ]; then
        echo "To complete setup of the PageSeeder Server, please start the pageseeder service then go to $SCHEME://[host]:$PORT/ps/ui/setup.html"
      else
        echo "To complete the update of the PageSeeder Server, please start the pageseeder service."
      fi

    fi
}

# start, debug, stop, and status functions
start() {
    # check if tomcat config has been updated
    NEWTOMCAT=`grep ThreadLocalLeakPreventionListener $PS_TOMCAT_HOME/conf/server.xml`
    WEBSOCKETS=`grep pageseeder-misc- $PS_TOMCAT_HOME/conf/server.xml`
    DBURL=`grep DBURL= $PS_HOME/webapp/WEB-INF/config/database.properties`
    if [ ! -f $PS_HOME/webapp/WEB-INF/drivers/*.jar ]; then
      echo "PageSeeder has not been configured, use 'service pageseeder config' or 'service pageseeder migrate' if PageSeeder v4.6 or before is already installed"
    elif [ -z "$NEWTOMCAT" ]; then
      echo "PageSeeder must be re-configured due to Tomcat upgrade, use 'service pageseeder config'"
    elif [ -z "$WEBSOCKETS" ]; then
      echo "PageSeeder must be re-configured to support WebSockets, use 'service pageseeder config'"
    else
      # Start Tomcat in normal mode
      SHUTDOWN_PORT=`netstat -vatn|grep LISTEN|grep 8005|wc -l`
      if [ $SHUTDOWN_PORT -ne 0 ]; then
          echo "PageSeeder Server already started"
      else
          echo "Starting Pageseeder Server..."
          if [ -f $PS_HOME/webapp/WEB-INF/sysconfig/update.txt ]; then
            if [ -n "$DBURL" ]; then
              echo "**********************************"
              echo "Database update may take some time - to view progress see pageseeder/webapp/WEB-INF/state/logs/general/general.log"
              echo "**********************************"
            fi
          fi
          rm -rf $PS_TOMCAT_HOME/temp/*
          chmod 755 $PS_TOMCAT_HOME/bin/*.sh
          chown -R $TOMCAT_USER:$TOMCAT_USER $PS_TOMCAT_HOME/*
          if [ "$CURRENT_USER" = "$TOMCAT_USER" ]; then
            $PS_TOMCAT_HOME/bin/startup.sh
          else
            su $TOMCAT_USER -c '$PS_TOMCAT_HOME/bin/startup.sh'
          fi
          SHUTDOWN_PORT=`netstat -vatn|grep LISTEN|grep 8005|wc -l`
          while [ $SHUTDOWN_PORT -eq 0 ]; do
              sleep 1
              SHUTDOWN_PORT=`netstat -vatn|grep LISTEN|grep 8005|wc -l`
          done
          RETVAL=$?
          echo "Pageseeder Server started in normal mode"
          if [ "$CURRENT_USER" = "root" ]; then
            [ $RETVAL=0 ] && touch /var/lock/subsys/pageseeder
          fi
      fi
    fi
}

debug() {
    # Start Tomcat in debug mode
    SHUTDOWN_PORT=`netstat -vatn|grep LISTEN|grep 8005|wc -l`
    if [ $SHUTDOWN_PORT -ne 0 ]; then
        echo "Pageseeder Server already started"
    else
        echo "Starting Pageseeder Server in debug mode..."
        rm -rf $PS_TOMCAT_HOME/temp/*
        chown -R $TOMCAT_USER:$TOMCAT_USER $PS_TOMCAT_HOME/*
        if [ "$CURRENT_USER" = "$TOMCAT_USER" ]; then
          $PS_TOMCAT_HOME/bin/catalina.sh jpda start
        else
          su $TOMCAT_USER -c '$PS_TOMCAT_HOME/bin/catalina.sh jpda start'
        fi
        SHUTDOWN_PORT=`netstat -vatn|grep LISTEN|grep 8005|wc -l`
        while [ $SHUTDOWN_PORT -eq 0 ]; do
            sleep 1
            SHUTDOWN_PORT=`netstat -vatn|grep LISTEN|grep 8005|wc -l`
        done
        RETVAL=$?
        echo "Pageseeder Server started in debug mode"
        if [ "$CURRENT_USER" = "root" ]; then
          [ $RETVAL=0 ] && touch /var/lock/subsys/pageseeder
        fi
    fi
}

stop() {
    SHUTDOWN_PORT=`netstat -vatn|grep LISTEN|grep 8005|wc -l`
    if [ $SHUTDOWN_PORT -eq 0 ]; then
        echo "Pageseeder Server already stopped"
    else
        echo "Stopping Pageseeder Server..."
        if [ "$CURRENT_USER" = "$TOMCAT_USER" ]; then
          $PS_TOMCAT_HOME/bin/shutdown.sh
        else
          su $TOMCAT_USER -c '$PS_TOMCAT_HOME/bin/shutdown.sh'
        fi
        SHUTDOWN_PORT=`netstat -vatn|grep LISTEN|grep 8005|wc -l`
        while [ $SHUTDOWN_PORT -ne 0 ]; do
            sleep 1
            SHUTDOWN_PORT=`netstat -vatn|grep LISTEN|grep 8005|wc -l`
        done

        count=0;
        if [ -f $PS_TOMCAT_HOME/bin/pageseeder.pid ]; then

            read kpid < $PS_TOMCAT_HOME/bin/pageseeder.pid
            let kwait=20

            until [ `ps --pid $kpid | grep -c $kpid` = '0' ] || [ $count -gt $kwait ]
            do
                echo -n -e "\nwaiting for processes to exit";
                sleep 1
                let count=$count+1;
            done

            if [ $count -gt $kwait ]; then
                echo -n -e "\nkilling processes which didn't stop after $kwait seconds"
                kill -9 $kpid
            fi

            if [ $count -gt 0 ]; then
                echo -n -e "\n"
            fi
        fi


        RETVAL=$?
        echo "Pageseeder Server stopped"
        if [ "$CURRENT_USER" = "root" ]; then
          [ $RETVAL=0 ] && rm -f /var/lock/subsys/pageseeder
        fi
        [ $RETVAL=0 ] && rm -f $PS_TOMCAT_HOME/bin/pageseeder.pid
    fi
}

status() {
    SHUTDOWN_PORT=`netstat -vatn|grep LISTEN|grep 8005|wc -l`
    if [ $SHUTDOWN_PORT -eq 0 ]; then
        echo "Pageseeder Server stopped"
    else
        MODE="normal"
        JPDA_PORT=`netstat -vatn|grep LISTEN|grep 8000|wc -l`
        if [ $JPDA_PORT -ne 0 ]; then
            MODE="debug"
        fi
        echo "Pageseeder Server running in $MODE mode"
    fi
}

case "$1" in
  config)
        config
        ;;
  migrate)
        migrate
        config
        ;;
  start)
        start
        ;;
  debug)
        debug
        ;;
  stop)
        stop
        ;;
  restart)
        stop
        start
        ;;
  redebug)
        stop
        debug
        ;;
  status)
        status
        ;;
  *)
        echo "Usage: $0 {config|migrate|start|debug|stop|restart|redebug|status}"
        exit 1
esac

exit $RETVAL
