#!/bin/sh

# LiNe Control Script
#
# This script is used to setup a LiNe or Linux appliance for running
# the web source content.  For more information about the usage of this
# script type:
#   lc or launcher -h
#
# Note:  This is not run during the build process, but is copied to the output
#        directory so that it is available on a LiNe platform.
#

ERROR_RETVAL=1
SUCCESS_RETVAL=0

CONFIG_PATH=/mnt/fastpath
EXEC_PATH=/mnt/application
DOWNLOAD_PATH=/mnt/download
WEB_PATH=/mnt/www/htdocs
OPEN_WEB_PATH=/mnt/www/open
RESTCONF_WEB_PATH=/mnt/www/restconf
SWITCH_EXEC_NAME=switchdrvr
SWITCH_EXEC_NAME_COMPRESSED=switchdrvr.bz2
PROCMGR_EXEC_NAME=procmgr
SYNCDB_EXEC_NAME=syncdb
DATAPLANE_EXEC_NAME=dataplane
# Get Luaweb content from the output (not src) location
LUAWEB_SRC_PATH=../objects/luaweb/content/htdocs
LUARESTCONF_SRC_PATH=../objects/restconf/content
FCGI_EXEC_NAME=lua_magnet
FCGI_EXEC_OPEN_NAME=open_magnet
FCGI_EXEC_RESTCONF_NAME=restconf_magnet
LIGHTY_MAGNET_CONF_TXT=lua_magnet_cfg.txt
LIGHTY_MAGNET_OPEN_CONF_TXT=open_magnet_cfg.txt
LIGHTY_MAGNET_RESTCONF_CONF_TXT=restconf_magnet_cfg.txt
LIGHTY_EXEC_NAME=lighttpd
LIGHTY_CONF_NAME=lighttpd.conf
LIGHTY_CSRF_CONF_NAME=lighttpd_csrf.conf
LIGHTY_AUTH_CONF_NAME=lighttpd_fpauth.conf
LIGHTY_PROD_CONF_NAME=lighttpd_prod.conf
LIGHTY_CTRL_NAME=lighttpd_ctrl.sh
LIGHTY_USR_CTRL_NAME=lighttpd_usr.sh
LIGHTY_TMP_PATH=/tmp
LIGHTY_LOG_PATH=$LIGHTY_TMP_PATH/logs
LIGHTY_ACCESS_LOG=$LIGHTY_LOG_PATH/access.log
LIGHTY_ERROR_LOG=$LIGHTY_LOG_PATH/error.log
# /* QB: G#9 2018/07/31 */
ISSU_STAT_FILE=/mnt/fastpath/issu_stat
# /* QE: G#9 */
# Make lighttpd sources relative from output directory
LIGHTY_SOURCE_PATH=../../../vendor/webserver/lighttpd/etc
export FP_SERVICE_PORT_NAME=eth0
SERVICE_PORT_WAIT_TIME=60

# Coredump params
COREDUMP_SCRIPT=../../../bsp/cpu/common/linux/rootfs/core_dump.sh
COREDUMP_DEBUG_PARMS=coredump_debug_config
COREDUMP_REGULAR_PARMS=coredump_regular_config

PLAT_SUPPORTS_COREDUMP=Y
PLAT_SUPPORTS_USB=N
PLAT_COREDUMP_EXT="bin"
PLAT_COREDUMP_COUNT_MAX=2
PLAT_SUPPORT_X86=Y

# Special user and group for running Lighttpd
LIGHTY_USER=root
LIGHTY_GROUP=root
LIGHTY_USER_GROUP="$LIGHTY_USER:$LIGHTY_GROUP"

WEBOPENSRC_NAME=open_magnet
WEBRESTCONFSRC_NAME=restconf_magnet
WEBSRC_NAME=lua_magnet
WEBSRC_CONTENT=websrc.tar.gz
OPENSRC_CONTENT=open_websrc.tar.gz
RESTCONFSRC_CONTENT=restconf_websrc.tar.gz
WEBSRC_PATH=/mnt/www
WEBROOT=/webroot
NLSROOT=/tmp/nls
SYNCDB_TMP_PATH=/tmp/syncdb

VPD_FILE=fastpath.vpd
LINEAPPS=lineapps.tar.gz
LKBDE=linux-kernel-bde.ko
LKBDE_DEV=/dev/linux-kernel-bde
LUBDE=linux-user-bde.ko
LUBDE_DEV=/dev/linux-user-bde
LFPTI=fpti.ko
LFPTI_DEV=/dev/fpti
PST_FILE=/tmp/cli_terminal
SIM_BOOT_COMPLETE_FILE=/tmp/switchdrvr_ready
SERVICE_NAME=qnos

PWDSAVE=`/bin/pwd`
SCRIPT_NAME=`basename $0`
# Usage text

usage=$(cat <<EOF
LiNe control script.  Use this script to control switchdrvr for a LiNe or
Linux Appliance device.  This script also facilitates use of Luaweb and
switchdrvr on a hardware device which is mounting a build directory on
remote file server.  This script will determine if the Luaweb content is
present and set it up correctly as needed.  The parameters listed below that
are related to the Luaweb content are not relevant for a non-web build.

Usage:

./${SCRIPT_NAME} [option]

Chose from one of the following options:

cleanup [restart]
            : Clean up LiNe and switchdrvr after use on a shared system (VM).
              Stops all switchdrvr related processes and removes any files used
              by luaweb.  Use this before un-reserving a LiNe box.  Can add
              "restart" option which will clean up a previous build of switchdrvr
              on LiNe and immediately start a new one.

help        : List the options (what you are reading now)
(or --help)

hwsync [/path/to/staging/directory]
            : Synchronizes the Luaweb source files from this built output
              to a specified staging directory.  This staging directory can
              be directly accessed by a hardware switch.  Likely a symbolic
              link will need to be created from the mount point and sub-
              directory to the /mnt/www/htdocs directory on the device.


lstop       : Stops just the lighttpd process. The lighttpd will immediately
              be restarted by the Process Manager.

lsync       : Synchronizes the lighttpd configuration files and restarts
              lighttpd so that it will re-read the configuration files.  Note
              that the source files used to update the lighttpd configuration
              files reside in the /vendor/webserver/lighttpd/etc directory,
              not the /ipl directory in which this script resides.  lighttpd
              will also be restarted to ensure the changes are read.  This
              parameter is only useful if lighttpd is already running.  Use
              "restart" or "start" to start lighttpd for the first time.

refresh     : Resets and resyncs everything, then restarts.  This option is a
              shortcut for running the following:
                  sane, setup, sync, lsync, start

restart [procmgr options]
            : (Default option) Resets and restarts everthing. This option is a
              shortcut for running the following options in order:
                  sane, setup, and start
              This option it will overwrite any previously updated files (from
              this "sync" or "lsync" commands) with whatever was last built.
              If you wish to test a new build that includes your latest
              changes, first run the build, then run this command.  You can also
              pass additional options used by procmgr (preceeded by a dash "-").
              See the note at the end of this listing about these options.

resync :      Synchronizes the Luaweb source files from the build output
              (which is mounted on the LiNe box) to the web directory of
              the LiNe box and causes the lighttpd process to be restarted
              so that any Lua environment or static file location changes are
              detected (same as "sync lstop".)  This parameter is only useful if
              lighttpd is already running.  Use "restart" or "start" to start
              lighttpd for the first time.

sane        : A simple shortcut to call "stty sane"
(or fixtty)

setup       : Sets up LiNe environment to run switchdrvr and web server.  Run
              this after a rebuild.  Note that the "reset" option will force
              this option.  See its comments for more info.  Any old contents
              will be overwritten.

start [procmgr options]
            : Starts all processes necessary for LiNe (lighttpd and switchdrvr)
              if they are note already started.  Lighttpd will not be restarted
              if it is already running.  Note that once switchdrvr is started
              it will own the terminal session.  To stop it in the current
              terminal you must press Ctrl-C.  You will likely need to type "${SCRIPT_NAME}
              sane" (or stty sane) to restore.  You can also pass additional
              options used by procmgr (preceeded by a dash "-"). See the note
              at the end of this listing about these options.

stop        : Stops all processes necessary for LiNe (lighttpd, switchdrv,
              etc.)

sync [lstop]: Synchronizes the Luaweb source files from the build output
              (which is mounted on the LiNe box) to the web directory of
              the LiNe box.  If the "lstop" option is used lighttpd will
              also be restarted to ensure that any Lua environment or static
              file location changes are detected.

[procmgr options]

procmgr is responsible for launching all of the necessary executables that are
part of switchdrvr . If an option provides for the ability to pass-through
options to procmgr you may use one of the following procmgr options.  Note that
the complete list of procmgr options is found by viewing the progmgr.c source
file.  These options are preceeded by a dash ("-").  procmgr options are:

  -console  : Displays valgrind information in the console

  -diag     : Run only diagnostic processes

  -gdb [IP address:Port Number]
            : Starts switchdrvr with gdbserver instructing gdbserver to expect
              a remote connection from the specified IP address at the
              specified port.

  -v        : Verbose console output mode

  -valgrind : Valgrind mode.  See the procmgr.c source code to view the default
              valgrind options.  The valgrind output log is "/tmp/valgrind.log".
              You can pass other options to valgrind by placing a file in the
              "/root" directory named ".valgrindrc".

Examples:

Setting up a LiNe box, then starting switchdrvr:
  > ${SCRIPT_NAME} setup
  > ${SCRIPT_NAME} start
    - or -
  > ${SCRIPT_NAME} restart

Synchronizing some minor changes in Luaweb files to the LiNe box:
  > ${SCRIPT_NAME} sync

Resetting a LiNe box to use your last build plus any Luaweb or Lighttpd
configuration changes since the last build:
  > ${SCRIPT_NAME} refresh
EOF
)

PRINT()
{
  if [ "${FP_SERVICE}" != "1" ]; then
     echo $@
  else
     # QB: B#253798 2018/10/18 #
     if [ "$*" != "" ]; then
     # QE: E#253798 #
        logger -t ${SERVICE_NAME} $@
     fi
  fi
}

option="$1"
retval=$SUCCESS_RETVAL

# Include environment variables
if [ -e /etc/${SERVICE_NAME}.conf ]; then
. /etc/${SERVICE_NAME}.conf
fi

# Setup lighttpd configuration file with custom defined user and group
if [ "$CUSTOM_LIGHTY_GROUP" != "" ] && [ "$CUSTOM_LIGHTY_GROUP" != "root"  ] ; then
    sed -i '/server.groupname/d' ${EXEC_PATH}/${LIGHTY_PROD_CONF_NAME}
    echo "server.groupname = \"$CUSTOM_LIGHTY_USER\"" >> ${EXEC_PATH}/${LIGHTY_PROD_CONF_NAME}
fi

if [ "$CUSTOM_LIGHTY_USER" != "" ] && [ "$CUSTOM_LIGHTY_USER" != "root"  ] ; then
    sed -i '/server.username/d' ${EXEC_PATH}/${LIGHTY_PROD_CONF_NAME}
    echo "server.username = \"$CUSTOM_LIGHTY_USER\"" >> ${EXEC_PATH}/${LIGHTY_PROD_CONF_NAME}
fi

# Determine if build includes Luaweb
is_luaweb_build=0
if [ "${SCRIPT_NAME}" = "lc" ]; then
  web_contents=$(tar -tf ${LINEAPPS} | grep ${WEBSRC_NAME})
  if [ "${web_contents}" = "${WEBSRC_NAME}" ]; then
    is_luaweb_build=1
  fi
else
  if [ -e ${EXEC_PATH}/${WEBSRC_NAME} ]; then
    is_luaweb_build=1
  fi
fi

# Determine if Luaopen (a web variant of Luaopen) is in the build
is_luaopen_build=0
if [ "${SCRIPT_NAME}" = "lc" ]; then
  web_contents=$(tar -tf ${LINEAPPS} | grep ${WEBOPENSRC_NAME})
  if [ "${web_contents}" = "${WEBOPENSRC_NAME}" ]; then
    is_luaopen_build=1
  fi
else
  if [ -e ${EXEC_PATH}/${WEBOPENSRC_NAME} ]; then
    is_luaopen_build=1
  fi
fi

#Determine if RESTCONF is in the build
is_restconf_build=0
if [ "${SCRIPT_NAME}" = "lc" ]; then
  web_contents=$(tar -tf ${LINEAPPS} | grep ${WEBRESTCONFSRC_NAME})
  if [ "${web_contents}" = "${WEBRESTCONFSRC_NAME}" ]; then
    is_restconf_build=1
  fi
else
  if [ -e ${EXEC_PATH}/${WEBRESTCONFSRC_NAME} ]; then
    is_restconf_build=1
  fi
fi

# Determine if build includes any of Luaweb, Luaopen, Instrumentation and Restconf
is_lua_any_build=0
if [ $is_luaweb_build -eq 1 ] || [ $is_luaopen_build -eq 1 ] || [ $is_instru_build -eq 1 ] || [ $is_restconf_build -eq 1 ]; then
  is_lua_any_build=1
fi

# Determine if build includes switch SDK
is_esw_build=0
if [ "${SCRIPT_NAME}" = "lc" ]; then
  lkbde_contents=$(tar -tf ${LINEAPPS} | grep ${LKBDE})
  if [ "${lkbde_contents}" = "${LKBDE}" ]; then
    is_esw_build=1
  fi
else
  if [ -e ${EXEC_PATH}/${LKBDE} ]; then
    is_esw_build=1
  fi
fi

if [ "${FP_SERVICE}" != "1" ]; then
  #/* QB: B#1550 2018/01/04 */
  if [ -e /bin/systemctl ]; then
    if systemctl -q is-active ${SERVICE_NAME} ; then
      PRINT "${SERVICE_NAME} service is running. Stop service to run ${SERVICE_NAME} in interractive mode."
      exit 0
    fi
  else
    if [ -e /etc/init/${SERVICE_NAME}.conf ]; then
       if [ "$(status ${SERVICE_NAME} | grep -i running)" != "" ]; then
          PRINT "${SERVICE_NAME} service is running. Stop service to run ${SERVICE_NAME} in interractive mode."
          exit 0
       fi
    fi
  fi
  #/* QE: B#1550 */
fi

#------------------------------------------------------------------------------
# Prints the usage help
#------------------------------------------------------------------------------
usage_printed=0
print_usage()
{
   if [ $usage_printed -eq 0 ]; then
      PRINT "$usage"
      PRINT
      usage_printed=1
   fi
}

#------------------------------------------------------------------------------
# Reads coredump environment configuration
#------------------------------------------------------------------------------
read_coredump_parms()
{
    COREDUMP_DHCP_PROTOCOL="DISABLED"
    COREDUMP_HOST_IP=
    COREDUMP_HOST_NETMASK=
    COREDUMP_GATEWAY_IP=

    COREDUMP_MODE="DISABLED"
    COREDUMP_PROTOCOL=none
    COREDUMP_SERVER_IP=
    COREDUMP_FILEPATH=
    COREDUMP_PREFIX=core
    COREDUMP_HOSTNAME=n
    COREDUMP_TIMESTAMP=n
    COREDUMP_FTP_USERNAME=
    COREDUMP_FTP_PASSWORD=
    COREDUMP_REGISTERDUMP=n
    COREDUMP_COMPRESS=n
    COREDUMP_ACTIVE_UNIT=
    COREDUMP_ACTIVE_PORT=

    if [ -s ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS} ] \
    && md5sum -c ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}.md5sum >/dev/null 2>&1
    then
        . ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}
    fi
}

#------------------------------------------------------------------------------
# Saves coredump environment configuration
#------------------------------------------------------------------------------
save_coredump_parms()
{
    echo "COREDUMP_DHCP_PROTOCOL=$COREDUMP_DHCP_PROTOCOL" > ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}
    echo "COREDUMP_HOST_IP=$COREDUMP_HOST_IP" >> ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}
    echo "COREDUMP_HOST_NETMASK=$COREDUMP_HOST_NETMASK" >> ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}
    echo "COREDUMP_GATEWAY_IP=$COREDUMP_GATEWAY_IP" >> ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}

    echo "COREDUMP_MODE=$COREDUMP_MODE" >> ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}
    echo "COREDUMP_PROTOCOL=$COREDUMP_PROTOCOL" >> ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}
    echo "COREDUMP_SERVER_IP=$COREDUMP_SERVER_IP" >> ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}
    echo "COREDUMP_FILEPATH=$COREDUMP_FILEPATH" >> ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}
    echo "COREDUMP_PREFIX=$COREDUMP_PREFIX" >> ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}
    echo "COREDUMP_HOSTNAME=$COREDUMP_HOSTNAME" >> ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}
    echo "COREDUMP_TIMESTAMP=$COREDUMP_TIMESTAMP" >> ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}
    echo "COREDUMP_FTP_USERNAME=$COREDUMP_FTP_USERNAME" >> ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}
    echo "COREDUMP_FTP_PASSWORD=$COREDUMP_FTP_PASSWORD" >> ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}
    echo "COREDUMP_REGISTERDUMP=$COREDUMP_REGISTERDUMP" >> ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}
    echo "COREDUMP_COMPRESS=$COREDUMP_COMPRESS" >> ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}
    echo "COREDUMP_ACTIVE_UNIT=$COREDUMP_ACTIVE_UNIT" >> ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}
    echo "COREDUMP_ACTIVE_PORT=$COREDUMP_ACTIVE_PORT" >> ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}

    echo "if [ \"\$HW_CONFIG_APPLY\" = \"Y\" ]; then" >> ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}
    echo "PLAT_SUPPORTS_COREDUMP=$PLAT_SUPPORTS_COREDUMP" >> ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}
    echo "PLAT_SUPPORTS_USB=$PLAT_SUPPORTS_USB" >> ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}
    echo "PLAT_COMPRESSION=$PLAT_COMPRESSION" >> ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}
    echo "PLAT_COMPRESSION_FILE=$PLAT_COMPRESSION_FILE" >> ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}
    echo "PLAT_COMPRESSION_EXT=$PLAT_COMPRESSION_EXT" >> ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}
    echo "PLAT_COREDUMP_EXT=$PLAT_COREDUMP_EXT" >> ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}
    echo "FP_SERVICE_PORT_NAME=$FP_SERVICE_PORT_NAME" >> ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}
    echo "PLAT_COREDUMP_COUNT_MAX=$PLAT_COREDUMP_COUNT_MAX" >> ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}
    echo "PLAT_SUPPORT_X86=$PLAT_SUPPORT_X86" >> ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}
    echo "PLAT_COREDUMP_VIA_NETWORK=$PLAT_COREDUMP_VIA_NETWORK" >> ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}
    echo "PLAT_COREDUMP_ACTIVE_UNIT=$PLAT_COREDUMP_ACTIVE_UNIT" >> ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}
    echo "PLAT_COREDUMP_ACTIVE_PORT=$PLAT_COREDUMP_ACTIVE_PORT" >> ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}
    echo "fi" >> ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}

    md5sum ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS} > ${CONFIG_PATH}/${COREDUMP_DEBUG_PARMS}.md5sum
}

#------------------------------------------------------------------------------
# Setups coredump environment
#------------------------------------------------------------------------------
setup_coredump()
{
  ulimit -c unlimited
  ln -sf /mnt/application/coredump_config.sh /usr/bin/coredump

  echo 1 > /proc/sys/fs/suid_dumpable
  echo 0 > /proc/sys/kernel/core_uses_pid
  echo "|${EXEC_PATH}/core_dump.sh %p %t" > /proc/sys/kernel/core_pattern

  BZIP2_PATH=`which bzip2`
  if [ $? -eq 0 ]; then
    PLAT_COMPRESSION=1
    PLAT_COMPRESSION_EXT="bz2"
    export PLAT_COMPRESSION_FILE="$BZIP2_PATH"
  else
    PLAT_COMPRESSION=0
    PLAT_COMPRESSION_EXT="bin"
    export PLAT_COMPRESSION_FILE=""
  fi

  read_coredump_parms
  save_coredump_parms
}

#------------------------------------------------------------------------------
# Checks for presence of .gdbinit file.  If not present will create a default
#------------------------------------------------------------------------------
check_gdbinit()
{
  if [ ! -e "${EXEC_PATH}/.gdbinit" ]; then
    PRINT "set listsize 20" >> ${EXEC_PATH}/.gdbinit
    PRINT "handle SIG32 pass nostop noprint" >> ${EXEC_PATH}/.gdbinit
    PRINT "handle SIGBUS pass nostop noprint" >> ${EXEC_PATH}/.gdbinit
  fi

  chown root:root ${EXEC_PATH}/.gdbinit
}

#------------------------------------------------------------------------------
# Remove any leftover shared memory areas (by key)
#
# Note: The lua_magnet shared memory keys start at 13680 ==> 0x000035xx
#       so this covers a range of approximately 256 separate areas.
#------------------------------------------------------------------------------
cleanup_shared_mem()
{
  for key in `ipcs -m | grep "0x00003[5-6]" | cut -f1 -d" "`; do ipcrm -M $key; done
}

#------------------------------------------------------------------------------
# Remove any routes, namespaces created
#
#------------------------------------------------------------------------------
cleanup_routes()
{
  # Delete all remnant qnos routes from kernel stack
  for rt_entry in `ip route show all | grep ${SERVICE_NAME} | awk '{print $1 "|" $2}'`
  do
     rt_entry=`echo $rt_entry | sed -e 's/|/ /g'`
     ip route del $rt_entry
  done

  for rt_entry in `ip -6 route show | grep ${SERVICE_NAME} | awk '{print $1 "|" $2}'`
  do
     rt_entry=`echo $rt_entry | sed -e 's/|/ /g'`
     ip -6 route del $rt_entry
  done

  # Delete stale network interfaces from kernel stack
  for intf in `ip link show | grep _drv | awk '{print $2}'`
  do
     intf=`echo $intf | sed -e 's/://g'`
     ip link del $intf
  done

  for intf in `ip link show | grep _stk | awk '{print $2}'`
  do
     intf=`echo $intf | sed -e 's/://g'`
     ip link del $intf
  done

  # Delete all namespaces
  for vrf_id in `ip netns list | grep vrf-id- | awk '{print $1}'`
  do
     ip netns delete $vrf_id
  done
}

#------------------------------------------------------------------------------
# Gets user and group values for Luaweb and lighttpd from setup files.
#------------------------------------------------------------------------------
get_usrgrp()
{
  # (read optional values from /mnt/application/lighttpd_prod.conf file created by build process)
  if [ "$CUSTOM_LIGHTY_USER" != "" ]; then
     LIGHTY_USER=$CUSTOM_LIGHTY_USER
  else
     LIGHTY_USER=`grep "username" ${EXEC_PATH}/${LIGHTY_PROD_CONF_NAME} | cut -d'"' -f2`
  fi
 
  if [ "$CUSTOM_LIGHTY_GROUP" != "" ]; then
     LIGHTY_GROUP=$CUSTOM_LIGHTY_GROUP
  else
      LIGHTY_GROUP=`grep "groupname" ${EXEC_PATH}/${LIGHTY_PROD_CONF_NAME} | cut -d'"' -f2`
  fi

  if [ "${LIGHTY_USER}" = "" ]; then
    LIGHTY_USER=root
  fi

  if [ "${LIGHTY_GROUP}" = "" ]; then
    LIGHTY_GROUP=${LIGHTY_USER}
  fi

  if [ "${LIGHTY_GROUP}" = "root" ]; then
    sed -i '/server.groupname/d' ${EXEC_PATH}/${LIGHTY_PROD_CONF_NAME}
  fi

  if [ "${LIGHTY_USER}" = "root" ]; then
    sed -i '/server.username/d'  ${EXEC_PATH}/${LIGHTY_PROD_CONF_NAME}
  fi

  LIGHTY_USER_GROUP=${LIGHTY_USER}:${LIGHTY_GROUP}
  export LIGHTY_USER_GROUP LIGHTY_USER LIGHTY_GROUP
}
#-------------------------------------------------------------------------------
# Loads kernel modules if present
#-------------------------------------------------------------------------------
load_modules()
{

    PRINT "Install Kernel Modules PATH is ${EXEC_PATH}"
    L7_MODULE_LIST=$(grep "L7_MODULE_LIST" ${EXEC_PATH}/${VPD_FILE} | cut -d= -f2-)
    INSMOD_PARAMS=""
    for WORD in ${L7_MODULE_LIST} ; do
        if [ -f ${EXEC_PATH}/${WORD} ] ; then
            if [ -n "${INSMOD_PARAMS}" ] ; then
                `insmod ${EXEC_PATH}/${INSMOD_PARAMS}`
            fi

            INSMOD_PARAMS=${WORD}
        else
            INSMOD_PARAMS="${INSMOD_PARAMS} ${WORD}"
        fi
    done

    if [ -n "${INSMOD_PARAMS}" ] ; then
                    `insmod ${EXEC_PATH}/${INSMOD_PARAMS}`
    fi

    if [ $is_esw_build -eq 1 ]; then
      if [ "$(lsmod | grep linux_user_bde)" = "" ]; then
         PRINT "Error. Critical modules not loaded"
         exit  ${ERROR_RETVAL}
      fi
    fi
}
#-------------------------------------------------------------------------------
# Removes kernel modules if present
#-------------------------------------------------------------------------------
remove_modules()
{

    PRINT "Remove Kernel Modules.."
    L7_MODULE_LIST=$(grep "L7_MODULE_LIST" ${EXEC_PATH}/${VPD_FILE} | cut -d= -f2-)
    export L7_MODULE_LIST
    LIST=$(awk 'BEGIN { blen = split( ENVIRON["L7_MODULE_LIST"], array, " "); for (i=blen;i>=1;i--) { print array[i]; } }')

    for WORD in ${LIST} ; do
        if [ -f ${EXEC_PATH}/${WORD} ] ; then
                MODULE_NAME=${WORD%.*}
                MODULE_NAME=$(echo $MODULE_NAME | tr -s "-" "_")
                MODULE_PRESENT=$(grep  $MODULE_NAME /proc/modules )
                if [ -n "$MODULE_PRESENT" ]; then
                   `rmmod -f ${EXEC_PATH}/${WORD}`
                fi
        fi
    done

}

#-------------------------------------------------------------------------------
# Checks and wait for serviceport presence if not found
#-------------------------------------------------------------------------------
check_serviceport()
{
  # Do not check for serviceport presence in LINE environment
  if [ "${SCRIPT_NAME}" = "lc" ]; then
     return;
  fi

  PRINT "Detecting serviceport $FP_SERVICE_PORT_NAME"
  if [ ! -e /sys/class/net/$FP_SERVICE_PORT_NAME/address ]; then
    COUNTER=0
    PRINT "Waiting $SERVICE_PORT_WAIT_TIME seconds for serviceport $FP_SERVICE_PORT_NAME to be detected"
    # Wait for service port to be available
    while [ ! -e /sys/class/net/$FP_SERVICE_PORT_NAME/address ]
    do
      sleep 1
      COUNTER=`expr $COUNTER + 1`
      if [ $COUNTER -ge ${SERVICE_PORT_WAIT_TIME} ]; then
         PRINT "Proceeding without serviceport $FP_SERVICE_PORT_NAME, modify /etc/$SERVICE_NAME.conf to select different interface"
         break;
      fi
    done
  fi
}

#------------------------------------------------------------------------------
# Starts the switchdrvr and lighttpd processes if not already started.
#
# Parameters:
#   Any arguments passed to this function are passed on to procmgr
#------------------------------------------------------------------------------
start()
{
  load_modules
  check_serviceport

  PRINT "Starting processes..."
  ${EXEC_PATH}/${PROCMGR_EXEC_NAME} "$@"
  reset_tty
}

#------------------------------------------------------------------------------
# Stops the switchdrvr and lighttpd processes if not already stopped.
#------------------------------------------------------------------------------
stop()
{
  PRINT "Stopping switchdrvr..."
  killall -9 -q ${SWITCH_EXEC_NAME}

  # If switchdrvr was run with valgrind enabled, the process running would actually be valgrind and not switchdrvr.
  if [ "`pidof valgrind`" ]; then
    PRINT "Stopping valgrind..."
    pidof valgrind | xargs kill -9
  fi

  # Killing switchdrvr should signal procmgr to kill other processes and
  # quit itself, too.  Wait for procmgr to cleanup
  sleep 5

  PRINT "Stopping procmgr..."
  killall -9 -q ${PROCMGR_EXEC_NAME}

  PRINT "Stopping any remnant syncdb"
  killall -9 -q ${SYNCDB_EXEC_NAME}

  PRINT "Stopping any renmant dataplace"
  killall -9 -q ${DATAPLANE_EXEC_NAME}

  if [ $is_lua_any_build -eq 1 ]; then
    stop_lighttpd
  fi

  cleanup_routes

  remove_modules

}

sighandle()
{
  PRINT "Received terminate signal"
  # /* QB: G#9 2018/07/31 */
  # If /mnt/fastpath/issu_stat file is present then append switch stop event
  if [ -f $ISSU_STAT_FILE ] ; then
    grep "ISSU_STATE_SWITCH_STOP" $ISSU_STAT_FILE
    if [ "$?:" != "0:" ] ; then
      #If event ISSU_STATE_SWITCH_STOP is not present append it */
      echo "`date +%s`:3:ISSU_STATE_SWITCH_STOP:" >> $ISSU_STAT_FILE
    fi
  fi

  sync
  # /* QE: G#9 */
# Send signal to shutdown all ports
  pidof switchdrvr | xargs kill -s SIGRTMIN+7
  # QB: B#253798 2018/10/18 #
  COUNTER=0
  while pidof switchdrvr >/dev/null 2>&1
  do
    sleep 1
    COUNTER=`expr $COUNTER + 1`
    if [ $COUNTER -ge 10 ]; then
       PRINT "Proceeding without waiting for switchdrvr to cleanly exit"
       break;
    fi
  done
  # QE: E#253798 #
  cleanup
  exit 0
}

trap 'sighandle'  TERM
#------------------------------------------------------------------------------
# Resets the tty session that may have been corrupted by switchdrvr
#------------------------------------------------------------------------------
reset_tty()
{
  stty sane
  PRINT "Restored tty"
}

#------------------------------------------------------------------------------
# Refreshes the Luaweb environment.  Will include any current Luaweb or
# lighttpd configuration code changes
#
# Parameters:
#   Any arguments passed to this function are passed on to the start function
#------------------------------------------------------------------------------
refresh()
{
  if [ $is_lua_any_build -eq 1 ]; then
    PRINT "Refreshing the Luaweb environment..."
    reset_tty
    setup
    luaweb_sync
    lighty_sync
    start "$@"
  else
    PRINT "This build does not include the Luaweb environment."
  fi
}

#------------------------------------------------------------------------------
# Provides a quick "kick it" function to restart switchdrvr and ensure all
# files are up-to-date.  Uses the latest built Luaweb and does not
# restart lighttpd if it is already running.
#
# Parameters:
#   Any arguments passed to this function are passed on to the start function
#------------------------------------------------------------------------------
restart()
{
  PRINT "Restarting (and re-setting up) LiNe processes..."
  # /* QB: G#9 2018/07/31 */
  # If /mnt/fastpath/issu_stat file is present then append switch start event
  if [ -f $ISSU_STAT_FILE ] ; then
    grep "ISSU_STATE_SWITCH_START" $ISSU_STAT_FILE
    if [ "$?:" != "0:" ] ; then
      #If event ISSU_STATE_SWITCH_START is not present append it */
      echo "`date +%s`:4:ISSU_STATE_SWITCH_START:" >> $ISSU_STAT_FILE
    fi
  fi
  # /* QE: G#9 */
  reset_tty
  setup
  start "$@"
}

#------------------------------------------------------------------------------
# Synchronizes the current view's Luaweb source files into the running LiNe
# files.
#
# Parameters:
#   $1 If "lstop" will kill lighttpd after syncing resulting in a restart of
#      lighttp by the process manager.
#------------------------------------------------------------------------------
luaweb_sync()
{
  need_stop_lighttpd=0
  if [ $is_luaweb_build -eq 1 ]; then
    # Remember to exclude any symbolic links in the source as these don't sync correctly
    # over a SAMBA share.  If the symbolic links change with each build then another solution
    # is needed besides rsync.
    PRINT "Synchronizing Luaweb code with ${SERVICE_NAME} (be sure to run 'bmake luaweb' first!)..."
    rsync -r --delete-before --force --exclude=web_msg_strings.js --exclude=/lang ${LUAWEB_SRC_PATH}/ ${WEB_PATH}/

    get_usrgrp
    chown -R ${LIGHTY_USER_GROUP} ${WEB_PATH}/

    if [ "$1" = "lstop" ]; then
      need_stop_lighttpd=1
    fi
  else
    PRINT "This build does not include the Luaweb environment."
  fi

  if [ $is_luaopen_build -eq 1 ]; then
    # Remember to exclude any symbolic links in the source as these don't sync correctly
    # over a SAMBA share.  If the symbolic links change with each build then another solution
    # is needed besides rsync.
    PRINT "Synchronizing Luaopen code with ${SERVICE_NAME} (be sure to run 'bmake luaopen' first!)..."
    rsync -r --delete-before --force --exclude=/lang ${LUAOPEN_SRC_PATH}/ ${OPEN_WEB_PATH}/

    get_usrgrp
    chown -R ${LIGHTY_USER_GROUP} ${OPEN_WEB_PATH}/

    if [ "$1" = "lstop" ]; then
      need_stop_lighttpd=1
    fi
  else
    PRINT "This build does not include the Luaopen environment."
  fi

  if [ $is_instru_build -eq 1 ]; then
    # Remember to exclude any symbolic links in the source as these don't sync correctly
    # over a SAMBA share.  If the symbolic links change with each build then another solution
    # is needed besides rsync.
    PRINT "Synchronizing INSTRU code with ${SERVICE_NAME} (be sure to run 'bmake instru' first!)..."
    rsync -r --delete-before --force --exclude=/lang ${LUAINSTRU_SRC_PATH}/ ${INSTRU_WEB_PATH}/

    get_usrgrp
    chown -R ${LIGHTY_USER_GROUP} ${INSTRU_WEB_PATH}/

    if [ "$1" = "lstop" ]; then
      need_stop_lighttpd=1
    fi
  else
    PRINT "This build does not include the INSTRU environment."
  fi

  if [ $is_restconf_build -eq 1 ]; then
    # Remember to exclude any symbolic links in the source as these don't sync correctly
    # over a SAMBA share.  If the symbolic links change with each build then another solution
    # is needed besides rsync.
    PRINT "Synchronizing RESTCONF code with ${SERVICE_NAME} (be sure to run 'bmake restconf' first!)..."
    rsync -r --delete-before --force --exclude=/lang ${LUARESTCONF_SRC_PATH}/ ${RESTCONF_WEB_PATH}/

    get_usrgrp
    chown -R ${LIGHTY_USER_GROUP} ${RESTCONF_WEB_PATH}/

    if [ "$1" = "lstop" ]; then
      need_stop_lighttpd=1
    fi
  else
    PRINT "This build does not include the RESTCONF environment."
  fi

  if [ $need_stop_lighttpd -eq 1 ]; then
    stop_lighttpd
  fi
}

#------------------------------------------------------------------------------
# Synchronizes the current view's lighttpd configuration files and restarts
# lighttpd.
#------------------------------------------------------------------------------
lighty_sync()
{
  if [ $is_lua_any_build -eq 1 ]; then
    # Stop lighty before copying over the files.  Note that there is a chance
    # proc manager will restart it before we get a chance to copy it, but an
    # error message will appear if this is the case.
    stop_lighttpd

    PRINT "Updating lighttpd configuration files from source in ${LIGHTY_SOURCE_PATH} ..."

    # Copy configuration files from their source paths (not the current output path)
    get_usrgrp

    cp ${LIGHTY_SOURCE_PATH}/${LIGHTY_CONF_NAME} ${EXEC_PATH}/${LIGHTY_CONF_NAME}
    chown ${LIGHTY_USER_GROUP} ${EXEC_PATH}/${LIGHTY_CONF_NAME}

    cp ${LIGHTY_SOURCE_PATH}/${LIGHTY_CSRF_CONF_NAME} ${EXEC_PATH}/${LIGHTY_CSRF_CONF_NAME}
    chown ${LIGHTY_USER_GROUP} ${EXEC_PATH}/${LIGHTY_CSRF_CONF_NAME}

    cp ${LIGHTY_SOURCE_PATH}/${LIGHTY_AUTH_CONF_NAME} ${EXEC_PATH}/${LIGHTY_AUTH_CONF_NAME}
    chown ${LIGHTY_USER_GROUP} ${EXEC_PATH}/${LIGHTY_AUTH_CONF_NAME}

    cp ../target/${LIGHTY_PROD_CONF_NAME} ${EXEC_PATH}/${LIGHTY_PROD_CONF_NAME}
    chown ${LIGHTY_USER_GROUP} ${EXEC_PATH}/${LIGHTY_PROD_CONF_NAME}

    # Copy the most recently built lighttpd
    cp ./${LIGHTY_EXEC_NAME} ${EXEC_PATH}/${LIGHTY_EXEC_NAME}
    chown ${LIGHTY_USER_GROUP} ${EXEC_PATH}/${LIGHTY_EXEC_NAME}
  else
    PRINT "This build does not include the Luaweb environment."
  fi
}

#------------------------------------------------------------------------------
# Synchronizes the current view's luaweb output to a specified staging
# directory.
#
# Parameters:
#   $1 -  The path to the folder to where to sync the web output files
#------------------------------------------------------------------------------
hardware_sync()
{
  # Remember to exclude any symbolic links in the source as these don't sync correctly
  # over a SAMBA share.  If the symbolic links change with each build then another solution
  # is needed besides rsync.
  PRINT "Synchronizing Luaweb code with hardware staging directory (be sure to run 'bmake luaweb' first!)..."
  rsync -r --delete-before --force --exclude=web_msg_strings.js --exclude=/lang ${LUAWEB_SRC_PATH}/ "$1/"

  PRINT "Synchronizing Luaopen code with hardware staging directory (be sure to run 'bmake luaopen' first!)..."
  rsync -r --delete-before --force --exclude=/lang ${LUAOPEN_SRC_PATH}/ "$1/"

}

#------------------------------------------------------------------------------
# Stops the lighttpd process and any fastcgi processes
#
# Returns the exit code of killing the processes
#------------------------------------------------------------------------------
stop_lighttpd()
{
  killLighttpd=0
  all_CGI=""

  if [ $is_luaweb_build -eq 1 ]; then
    killLighttpd=1
    all_CGI=${FCGI_EXEC_NAME}
  fi

  if [ $is_luaopen_build -eq 1 ]; then
    killLighttpd=1
    all_CGI="${all_CGI} ${FCGI_EXEC_OPEN_NAME}"
  fi

  if [ $is_instru_build -eq 1 ]; then
    killLighttpd=1
    all_CGI="${all_CGI} ${FCGI_EXEC_INSTRU_NAME}"
  fi

  if [ $is_restconf_build -eq 1 ]; then
    killLighttpd=1
    all_CGI="${all_CGI} ${FCGI_EXEC_RESTCONF_NAME}"
  fi

  if [ $killLighttpd -eq 1 ]; then
    echo "Stopping lighttpd and fastcgi processes..."
    echo "killall -9 ${LIGHTY_EXEC_NAME} ${all_CGI}"

    echo "Process manager will restart lighttpd as needed..."
  fi
}

#------------------------------------------------------------------------------
# Stops all Luaweb related processes and cleans up LiNe box
#
# Parameters:
#   $1 -  If "restart" will call the restart function
#------------------------------------------------------------------------------
cleanup()
{
  stop

  # Preserve current location
  local current_dir=${PWDSAVE}

  # Unlink any links defined for Lighttpd
  if [ -h "${WEBROOT}" ]; then unlink ${WEBROOT}; fi
  cd ${EXEC_PATH}
  for i in `ls *.so` ;
  do
    if [ -h "/lib/$i" ] ;
    then
      unlink /lib/$i
    fi
  done

  cleanup_shared_mem
  if [ $is_lua_any_build -eq 1 ]; then
    get_usrgrp
  fi

  # Cleanup Luaweb related files even if this build not a web build.  This
  # action will ensure any leftovers from previous LiNe runs are removed.

  # Clean up leftover Unix socket files from lighttpd (fpc*)
  # and switchdrvr (fps*) sides
  rm -f ${LIGHTY_TMP_PATH}/fpc*
  rm -f ${LIGHTY_TMP_PATH}/fps*
  rm -f ${LIGHTY_TMP_PATH}/lighty-fcgi.*
  rm -f ${LIGHTY_TMP_PATH}/open-lighty-fcgi.*
  rm -f ${LIGHTY_TMP_PATH}/lighty-instru-fcgi.*
  rm -f ${LIGHTY_TMP_PATH}/lighty-restconf-fcgi.*
  rm -rf ${SYNCDB_TMP_PATH}
 
  # Remove pseudo terminal info file
  rm -f ${PST_FILE}

  # Remove file which specifies Application is ready for configuration
  rm -f ${SIM_BOOT_COMPLETE_FILE}

  # Remove data directories
  rm -rf ${LIGHTY_TMP_PATH}/lighttpd
  rm -rf ${WEBSRC_PATH}
  rm -rf ${NLSROOT}
  rm -rf ${EXEC_PATH}/valgrind

  # Remove Lighttpd-related files from config directory
  rm -f ${CONFIG_PATH}/${LIGHTY_MAGNET_CONF_TXT}

  # Remove Lighttpd-related OPEN files from config directory
  rm -f ${CONFIG_PATH}/${LIGHTY_MAGNET_OPEN_CONF_TXT}

  # Remove Lighttpd-related INSTRU files from config directory
  rm -f ${CONFIG_PATH}/${LIGHTY_MAGNET_INSTRU_CONF_TXT}

  # Remove Lighttpd-related RESTCONF files from config directory
  rm -f ${CONFIG_PATH}/${LIGHTY_MAGNET_RESTCONF_CONF_TXT}

  if [ "${SCRIPT_NAME}" = "lc" ]; then
    # Remove all remaining executables and files
    rm -f ${EXEC_PATH}/*
  fi

  # Remove special lighttpd user (also removes its group)
  if [ "${LIGHTY_USER}" != "root" ] && [ "${CUSTOM_LIGHTY_USER}" = "" ]; then
    for i in `grep ${LIGHTY_USER} /etc/passwd | cut -f1 -d":"`; do userdel $i; done
  fi

  # Restore directory location
  cd ${PWDSAVE}

  PRINT
  PRINT "Finished cleanup."

  # Added this as a convenience allowing "./${SCRIPT_NAME} cleanup restart"
  if [ "$1" = "restart" ]; then
    restart
  fi
}

#------------------------------------------------------------------------------
# Setup prepares the RAM disk files to run the lighttpd and switchdrvr
# processes and starts them (if they are not already running.)
#------------------------------------------------------------------------------
setup()
{
  PRINT "Setting up environment..."

  # Create folders
  if [ ! -d ${CONFIG_PATH} ]; then      
     mkdir -p ${CONFIG_PATH}
  fi
 
  if [ ! -d ${EXEC_PATH} ]; then 
      mkdir -p ${EXEC_PATH}
  fi

  if [ ! -d ${DOWNLOAD_PATH} ]; then
      mkdir -p ${DOWNLOAD_PATH}
  fi

  if [ ! -e /dev/tap ]; then
     ln -s /dev/net/tun /dev/tap
  fi

  # Stop everyting so all files can be updated
  stop

  if [ $is_lua_any_build -eq 1 ]; then
    cleanup_shared_mem
  fi

  # Clean up leftover Unix socket files from lighttpd (fpc*) and switchdrvr
  # (fps*) sides.  This is necessary to fix issue with socket files that
  # sometimes get in a funny state.
  rm -f ${LIGHTY_TMP_PATH}/fpc*
  rm -f ${LIGHTY_TMP_PATH}/fps*
  rm -f ${LIGHTY_TMP_PATH}/lighty-fcgi.*
  rm -f ${LIGHTY_TMP_PATH}/open-lighty-fcgi.*
  rm -f ${LIGHTY_TMP_PATH}/lighty-instru-fcgi.*
  rm -f ${LIGHTY_TMP_PATH}/lighty-restconf-fcgi.*

  # Copy files to LiNe environment
  if [ "${SCRIPT_NAME}" = "lc" ]; then
    rm -f ${EXEC_PATH}/${LINEAPPS}
    cp -pf ${LINEAPPS} ${EXEC_PATH}
    # Setup coredump environment
    cp ${COREDUMP_SCRIPT} ${EXEC_PATH}
  fi

  setup_coredump

  # Preserve current location
  local current_dir=${PWDSAVE}

  # Unpack tar file
  cd ${EXEC_PATH}
  if [ "${SCRIPT_NAME}" = "lc" ]; then
    PRINT "Extracting extra files into ${EXEC_PATH}..."
    tar -mxzf ${LINEAPPS}

    # Copy switchdrvr to the LiNE environment.  If compressed, first uncompress it
    # and move resulting uncompressed file
    if [ -e "${current_dir}/${SWITCH_EXEC_NAME_COMPRESSED}" ]; then
      PRINT "Uncompressing switchdrvr into ${EXEC_PATH}..."
      cp -f ${current_dir}/${SWITCH_EXEC_NAME_COMPRESSED} ${EXEC_PATH}
      bzip2 -d ${EXEC_PATH}/${SWITCH_EXEC_NAME_COMPRESSED}
    else
      if [ -e "${current_dir}/${SWITCH_EXEC_NAME}" ]; then
         PRINT "Copying switchdrvr into ${EXEC_PATH}..."
         cp -f ${current_dir}/${SWITCH_EXEC_NAME} ${EXEC_PATH}
      fi
    fi
  fi

  if [ $is_esw_build -eq 1 ]; then
    if [ ! -c ${LKBDE_DEV} ]; then
       PRINT "Creating node ${LKBDE_DEV}"
       mknod ${LKBDE_DEV} c 127 0
    fi

    if [ ! -c ${LUBDE_DEV} ]; then
       PRINT "Creating node ${LUBDE_DEV}"
       mknod ${LUBDE_DEV} c 126 0
    fi

    if [ ! -c ${LFPTI_DEV} ]; then
       PRINT "Creating node ${LFPTI_DEV}"
       mknod ${LFPTI_DEV} c 10 201
    fi
  fi

  if [ $is_lua_any_build -eq 1 ]; then
    # Give execute permission to Lighttpd control script
    chmod +x ${EXEC_PATH}/${LIGHTY_CTRL_NAME}

    # Give execute permission to Lighttpd user control script
    chmod +x ${EXEC_PATH}/${LIGHTY_USR_CTRL_NAME}

    # Clean up leftover Unix socket files from lighttpd (fpc*)
    # and switchdrvr (fps*) sides
    rm -f /tmp/fpc*
    rm -f /tmp/fps*

    # Create a special user and group to run lighttpd
    get_usrgrp

    if [ "${LIGHTY_USER}" != "root" ] && [ "${CUSTOM_LIGHTY_USER}" = ""  ]; then
      PRINT "Creating 'lighttpd' user..."
      for i in `grep ${LIGHTY_USER} /etc/passwd | cut -f1 -d":"`; do userdel $i; done
      if [ "${LIGHTY_GROUP}" != "root" ]; then
        if [ "${CUSTOM_LIGHTY_GROUP}" = "" ]; then
           groupadd -r ${LIGHTY_GROUP}
        fi
        useradd -M -g ${LIGHTY_GROUP} -r ${LIGHTY_USER} -s /bin/bash
      fi
    fi

    PRINT "Will run lighttpd as the user:group of ${LIGHTY_USER_GROUP}..."
  fi

  # Restore directory location
  cd ${PWDSAVE}

  PRINT
  PRINT "Finished setup, use '${SCRIPT_NAME} start' to begin ${SERVICE_NAME} processes..."
}

#------------------------------------------------------------------------------
# Main routine
#------------------------------------------------------------------------------
PRINT

# Parse the options
case "$1" in
  cleanup)
    cleanup "$2"
    ;;
  lsync)
    check_gdbinit
    lighty_sync
    ;;
  help)
    print_usage
    ;;
  --help)
    print_usage
    ;;
  hwsync)
    hardware_sync "$2"
    ;;
  refresh)
    shift
    refresh "$@"
    ;;
  restart)
    check_gdbinit
    shift
    restart "$@"
    ;;
  resync)
    luaweb_sync "lstop"
    ;;
  sane)
    reset_tty
    ;;
  fixtty)
    reset_tty
    ;;
  setup)
    check_gdbinit
    setup
    ;;
  start)
    check_gdbinit
    shift
    start "$@"
    ;;
  stop)
    stop
    ;;
  # QB: B#253798 2018/10/18 #
  user_stop)
    sighandle
    ;;
  # QE: E#253798 #
  lstop)
    stop_lighttpd
    ;;
  sync)
    luaweb_sync "$2"
    ;;
  *)
    if [ -z "$option" ]; then
      restart
    else
      PRINT "Invalid option: $option"
      PRINT
      print_usage
      reval=$ERROR_RETVAL
    fi
esac

PRINT
exit $retval
