#!/bin/sh

#
# Init Common Variables
#
init_var()
{
    OS=`uname -s`
    if [ "x$OS" = "xFreeBSD" ] || [ "x$OS" = "xDarwin" ] ; then
	PS_CMD="ps -ax"
    else
	PS_CMD="ps -ef"
    fi
    if [ "x$OS" = "xFreeBSD" ] ; then
        LSWS_CTLCMD="/usr/local/etc/rc.d/lsws.sh"
	AP_CTLCMD="/usr/local/etc/rc.d/httpd"
    else
        LSWS_CTLCMD="/sbin/service lsws"
	AP_CTLCMD="/sbin/service httpd"
    fi


    LSWS_PIDFILE=/tmp/lshttpd/lshttpd.pid
    AP_PIDFILE=/usr/local/apache/logs/httpd.pid
    SERIAL_FILE=${LSWS_HOME}/conf/serial.no
    LICENSE_KEY_FILE=${LSWS_HOME}/conf/license.key
    TRIAL_KEY_FILE=${LSWS_HOME}/conf/trial.key
    CONF=${LSWS_HOME}/conf/httpd_config.xml
    LSWSBIN=${LSWS_HOME}/bin/lshttpd

    LSADDON_DIR=/usr/local/cpanel/whostmgr/docroot/cgi/lsws
    LSWS_HOME_DEF=${LSADDON_DIR}/LSWS_HOME.config

    CPFILEPROTECT=/var/cpanel/fileprotect
}

err_exit()
{
  if [ "${1}" -ne "0" ] ; then
    echo "**ERROR** ${2}" 
    exit ${1}
  fi
}

msg_exit()
{
    echo "${2}"
    exit ${1}
}

cat_file()
{
    if [ -e "$1" ] ; then
	cat "$1"
	exit 0
    else
        echo ""
        exit 1
    fi

}

detect_lsws_pid()
{
    LSPID=0

    if [ -f $LSWS_PIDFILE ] ; then
	FPID=`cat $LSWS_PIDFILE`
	if [ "x$FPID" != "x" ] ; then
            PL=`$PS_CMD | grep -w 'lshttpd\|litespeed' | grep -v grep | grep -w $FPID`
            if [ "x$PL" != "x" ] ; then
		LSPID=$FPID
            fi
	fi
    fi
}

detect_ap_pid()
{
    APPID=0

    if [ -f $AP_PIDFILE ] ; then
        FPID=`cat $AP_PIDFILE`
        if [ "x$FPID" != "x" ] ; then
            PL=`$PS_CMD | grep -w $FPID | grep httpd | grep -v grep | grep -v lscgid`
            if [ "x$PL" != "x" ] ; then
                APPID=$FPID
            fi
        fi
    fi
}

#
# start LiteSpeed
#
start_lsws()
{
    `$LSWS_CTLCMD start`

    RETRY=30
    LSPID=0

    while [ $RETRY -gt 0 ] && [ $LSPID -eq 0 ]
    do
	detect_lsws_pid
        ((RETRY--))

        sleep 1
    done
}

stop_lsws()
{
    `$LSWS_CTLCMD stop`

    RETRY=30
    LSPID=1

    while [ $RETRY -gt 0 ] && [ $LSPID -ne 0 ]
    do
	detect_lsws_pid
        ((RETRY--))

        sleep 1
    done

    if [ $LSPID -eq 0 ] ; then
        killall -9 lshttpd
        killall -9 litespeed
	echo "LiteSpeed Stopped."
    else
	echo "LiteSpeed is still running. Fail to stop within 30 secs."
	echo "Will use killall command to stop"
	
	killall -9 lshttpd
	killall -9 litespeed
	sleep 1
	
	detect_lsws_pid

	if [ $LSPID -eq 0 ] ; then
	    echo "LiteSpeed Stopped."
	else
	    echo "LiteSpeed is still running. Fail to stop using kill command."
	fi
    fi

}

stop_apache()
{
    `$AP_CTLCMD stop`

    RETRY=30
    APPID=1

    while [ $RETRY -gt 0 ] && [ $APPID -ne 0 ]
    do
	detect_ap_pid
        ((RETRY--))

        sleep 1
    done

   if [ $APPID -eq 0 ] ; then
	echo "Apache Stopped."
   else
	echo "Apache is still running. Fail to stop within 30 secs."
	echo "Will use killall command to stop"
	
	killall -9 httpd
	sleep 1
	
	detect_ap_pid

	if [ $APPID -eq 0 ] ; then
	    echo "Apache Stopped."
	else
	    echo "Apache is still running. Fail to stop using kill command."
	fi
    fi
}

change_port_offset()
{
    PORT_OFFSET=$1

    if [ ! -f "$CONF" ] ; then
	err_exit 1 "$0: invalid conf file directory!"
    fi

    cp -f $CONF $CONF.orig

    sed -e "s/<apachePortOffset>.*<\/apachePortOffset>/<apachePortOffset>$PORT_OFFSET<\/apachePortOffset>/" "$CONF".orig > "$CONF"

    err_exit $? "$0: sed command error, please try to modify apache port offset manually from config file $CONF"
    
    /bin/rm -f "$CONF".orig
}

SwitchToLiteSpeed()
{
    change_port_offset 0
    
    stop_apache
    
    sleep 8 

    if [ -e "$CPFILEPROTECT" ] ; then
        echo "fileprotect removed, not needed by LiteSpeed"
        /bin/rm -f "$CPFILEPROTECT"
    fi

    start_lsws

    if [ $LSPID -gt 0 ] ; then
	msg_exit 0 "LiteSpeed started successfully."
    fi

    echo "LiteSpeed is not up within 30 secs, try again by removing /tmp/lshttpd/."

    killall -9 lshttpd
    killall -9 litespeed
    /bin/rm -rf /tmp/lshttpd

    start_lsws

    if [ $LSPID -gt 0 ] ; then
        msg_exit 0 "LiteSpeed started successfully."
    else
        err_exit 1 "LiteSpeed is not up within 60 secs, please check the error log and try again."
    fi

}

SwitchToApache()
{
    detect_lsws_pid
    if [ $LSPID -gt 0 ] ; then
	echo "LiteSpeed is running, stop it first."
	stop_lsws

	if [ $LSPID -gt 0 ] ; then
	    err_exit 1 "Abort."
	fi
    fi

    #
    # restore Apache Files
    #
    if [ -f "/usr/local/apache/bin/httpd_ls_bak" ] ; then
	mv -f /usr/local/apache/bin/httpd_ls_bak /usr/local/apache/bin/httpd
    fi

    if [ -f "/scripts/restartsrv_httpd_ls_bak" ] ; then
	mv -f /scripts/restartsrv_httpd_ls_bak /scripts/restartsrv_httpd
    fi

    NEED_PROTECT=`/usr/local/cpanel/3rdparty/bin/perl -MCpanel::Config::Httpd::Perms -e'print Cpanel::Config::Httpd::Perms::webserver_runs_as_user();'`
    
    if [ $NEED_PROTECT -eq 1 ] ; then
        echo "Added fileprotect for Apache"
        touch "$CPFILEPROTECT"
    fi

    # wait 1 sec before start apache
    sleep 1
    
    #
    # start Apache
    #
    # does not change the memory limits, does not work well.
    # `$AP_CTLCMD start`
    #
    # call a cPanel script
    /scripts/restartsrv_httpd

    RETRY=30
    APPID=0

    while [ $RETRY -gt 0 ] && [ $APPID -eq 0 ]
    do
	detect_ap_pid
        ((RETRY--))

        sleep 1
    done
     
    if [ $APPID -ne 0 ] ; then
	echo "Apache started successfully."
    else
	err_exit 1 "Apache is not up within 30 secs. Please check the log file."
    fi

}

CheckLicense()
{
   if [ -f "$SERIAL_FILE" ] ; then
        if [ ! -e "$LICENSE_KEY_FILE" ] ; then
            $LSWSBIN -r 2>&1
        fi
        if [ ! -e "$LICENSE_KEY_FILE" ] ; then
            err_exit 1 "Failed to find a license key file, abort!"
        else
            $LSWSBIN -V 2>&1
        fi

   elif [ -f "$TRIAL_KEY_FILE" ] ; then
       $LSWSBIN -V 2>&1
   else
       err_exit 1 "Failed to find serial.no $SERIAL_FILE or trial key $TRIAL_KEY_FILE file, abort!"
   fi

}

restore_exit()
{
    if [ "$SERIAL" = "TRIAL" ] ; then
	if [ -f "${TRIAL_KEY_FILE}" ] ; then
	    /bin/rm -f ${TRIAL_KEY_FILE}
	    echo "   removed retrieved trial.key"
	fi
    else
	if [ -f "${SERIAL_FILE}" ] ; then
	    /bin/rm -f "${SERIAL_FILE}"
	    echo "   removed uploaded serial.no"
	fi
	if [ -f "${LICENSE_KEY_FILE}" ] ; then
	    /bin/rm -f "${LICENSE_KEY_FILE}"
	    echo "   removed the new license.key"
	fi
	
    fi

    if [ "x" != "x$BACKUP_SERIAL_NO" ] ; then
	mv ${BACKUP_SERIAL_NO} ${SERIAL_FILE}
        echo "   restored the original serial.no from ${BACKUP_SERIAL_NO}"
    fi

    if [ "x" != "x${BACKUP_LICENSE_KEY}" ] ; then
	mv ${BACKUP_LICENSE_KEY} ${LICENSE_KEY_FILE}
        echo "   restored the original license.key from ${BACKUP_LICENSE_KEY}"
    fi

    if [ "x" != "x${BACKUP_TRIAL_KEY}" ] ; then
	mv ${BACKUP_TRIAL_KEY} ${TRIAL_KEY_FILE}
        echo "   restored the original trial.key from ${BACKUP_TRIAL_KEY}"
    fi

    err_exit ${1} ${2}
}

SwitchLicense()
{
    SERIAL=$1

    echo "Back up current license files under ${LSWS_HOME}/conf/ ..."

    if [ -f "${SERIAL_FILE}" ] ; then
	BACKUP_SERIAL_NO=${SERIAL_FILE}.backup.$$ 
	mv ${SERIAL_FILE} ${BACKUP_SERIAL_NO}
	err_exit $? "fail to backup current serial.no"
	echo "... saved current serial.no to ${BACKUP_SERIAL_NO}"
    fi

    if [ -f "${LICENSE_KEY_FILE}" ] ; then
	BACKUP_LICENSE_KEY=${LICENSE_KEY_FILE}.backup.$$
	mv ${LICENSE_KEY_FILE} ${BACKUP_LICENSE_KEY}
	err_exit $? "fail to backup current license.key"
	echo "... saved current license.key to ${BACKUP_LICENSE_KEY}"
    fi

    
    if [ "$SERIAL" = "TRIAL" ] ; then
	echo "Trying to switch to a trial license ..."
	wget -q --output-document=${TRIAL_KEY_FILE} http://license.litespeedtech.com/reseller/trial.key
	if [ $? -ne 0 ] ; then
	    echo "Failed to retrieve a trial license"
	    restore_exit 1 "Aborted!"
	fi
	
    else

	if [ -f "${TRIAL_KEY_FILE}" ] ; then
	    BACKUP_TRIAL_KEY=${TRIAL_KEY_FILE}.backup.$$
	    mv ${TRIAL_KEY_FILE} ${BACKUP_TRIAL_KEY}
	    err_exit $? "fail to back up current trial.key"
	    echo "... saved current trial.key to ${BACKUP_TRIAL_KEY}"
	fi

	echo "Trying to switch to a new production license ..."

	echo "$SERIAL" > ${SERIAL_FILE}
	if [ $? -eq 0 ] ; then
	    echo "... Saved serial number \"$SERIAL\" to ${SERIAL_FILE}"
	else
	    echo "Failed to save serial number to ${SERIAL_FILE}!"
	    restore_exit 1 "Aborted!"
	fi

        # need to retrieve new license file
	echo "... Serial number is available."
	echo "... Contacting licensing server for license key ..."

	REGISTER_OUTPUT=`$LSWSBIN -r 2>&1`

	if [ $? -eq 0 ] ; then
	    echo "... License key received: $REGISTER_OUTPUT"
	else
	    echo "... failed to retrieve license key, please double check your serial number: $REGISTER_OUTPUT."
	    restore_exit 1 "Aborted!"
	fi

    fi

    TEST_RESULT=`$LSWSBIN -t 2>&1`

    if [ $? -ne 0 ] ; then
	echo "Failed to switch to the new license."
	echo "... $TEST_RESULT"
	restore_exit 1 "Aborted!"
    else
	echo "Successfully switched to the new license."
	echo "... $TEST_RESULT"
	echo ""
	echo "*** Your old licenses have been backed up in the same directory."
	echo ""

	detect_lsws_pid

	if [ $LSPID gt 0 ] ; then
	    echo "Restarting LiteSpeed to apply the new license."
	    ${LSWS_HOME}/bin/lswsctrl restart
	fi

    fi

}

TransferLicense()
{
    echo "License status before migration:"
    $LSWSBIN -m 2>&1
    if [ $? -ne 0 ] ; then
	err_exit 1 "Failed to migrate current license."
    fi

    echo "Successfully migrated current license."
    echo "License status after migration:"
    CheckLicense

    detect_lsws_pid

    if [ $LSPID gt 0 ] ; then
	echo "Restarting LiteSpeed to apply the new license."
	${LSWS_HOME}/bin/lswsctrl restart
    fi

}

VersionUp()
{
    $LSWS_HOME/admin/misc/lsup.sh -f -v $1 2>&1
}

VersionSwitch()
{
    $LSWS_HOME/admin/misc/mgr_ver.sh $1 2>&1
}

VersionDel()
{
    $LSWS_HOME/admin/misc/mgr_ver.sh -d $1 2>&1
}


add_lsws_line()
{
    HOOK_SCRIPT=/scripts/${1}
    EXTRA_PARAM=${2}
    CMD_LINE="sh ${LSADDON_DIR}/bin/whm_eahook.sh ${1} ${EXTRA_PARAM}     # for integration of build matching php for LiteSpeed webserver" 

    if [ -f $HOOK_SCRIPT ] ; then
	sed -i '/cgi\/lsws/d' $HOOK_SCRIPT
	if [ $? -ne 0 ] ; then
	    echo "sed command error: $? when adding lsws line in $HOOK_SCRIPT"
	    exit 1
	fi

	echo $CMD_LINE >> $HOOK_SCRIPT

	if [ $? -ne 0 ] ; then
	    echo "cannot append to file $HOOK_SCRIPT : $?"
	    exit 1
	fi

    else
	echo '#!/bin/sh' > $HOOK_SCRIPT
	if [ $? -ne 0 ] ; then
	    echo "cannot create file $HOOK_SCRIPT : $?"
	    exit 1
	fi

	echo $CMD_LINE >> $HOOK_SCRIPT

	if [ $? -ne 0 ] ; then
	    echo "cannot append to file $HOOK_SCRIPT : $?"
	    exit 1
	fi
    fi

    chmod +x $HOOK_SCRIPT
    if [ $? -ne 0 ] ; then
	echo "cannot chmod for file $HOOK_SCRIPT : $?"
	exit 1
    fi

}

EasyApacheHookEnable()
{
    add_lsws_line before_httpd_restart_tests '$4'
    add_lsws_line after_httpd_restart_tests '$4'
    add_lsws_line before_apache_make
}

remove_lsws_line()
{
    HOOK_SCRIPT=/scripts/${1}

    if [ -f $HOOK_SCRIPT ] ; then
	sed -i '/cgi\/lsws/d' $HOOK_SCRIPT

	if [ $? -ne 0 ] ; then
	    echo "sed command error: $? when removing lsws line in $HOOK_SCRIPT"
	    exit 1
	fi

	REMAIN=`cat $HOOK_SCRIPT`
	if [ "x$REMAIN" = 'x#!/bin/sh' ] ; then
	    /bin/rm -f $HOOK_SCRIPT
	fi
    fi
}

EasyApacheHookDisable() 
{
    remove_lsws_line before_httpd_restart_tests
    remove_lsws_line after_httpd_restart_tests
    remove_lsws_line before_apache_make
}

EasyApacheHookRefresh() 
{
    # check if hook is enabled, if yes, update with latest script, if lsws not there, remove hook
    
    TEST_SCRIPT=/scripts/before_httpd_restart_tests

    if [ -f $TEST_SCRIPT ] ; then
	RESULT=`grep "^sh /usr/local/cpanel/whostmgr/docroot/cgi/lsws/" $TEST_SCRIPT`
	if [ "x$RESULT" != "x" ] ; then
	    echo "EasyApache Hooks is enabled"

	    EasyApacheHookDisable

	    if [ -f "$LSWS_HOME_DEF" ] ; then
		echo "LSWS is installed, refresh hook scripts"
		EasyApacheHookEnable 
	    else
		echo "LSWS is not installed, removed existing hooks"
	    fi
	fi
    fi
}

UninstallLiteSpeed()
{
    KEEP_CONF=$1
    KEEP_LOG=$2

    if [ "x$KEEP_CONF" != "xY" ] && [ "x$KEEP_CONF" != "xN" ] ; then
	err_exit 1 "[ERROR] Invalid parameter KEEP_CONF!"
    fi

    if [ "x$KEEP_LOG" != "xY" ] && [ "x$KEEP_LOG" != "xN" ] ; then
	err_exit 1 "[ERROR] Invalid parameter KEEP_LOG!"
    fi

    SwitchToApache

    CUR_DIR=`pwd`
    LSINSTALL_DIR=${LSWS_HOME}/admin/misc

    if [ ! -d "$LSINSTALL_DIR" ]; then
	err_exit 1 "[ERROR] Cannot find dir $LSINSTALL_DIR"
    fi

    INST_USER=`id`
    INST_USER=`expr "$INST_USER" : 'uid=.*(\(.*\)) gid=.*'`
    if [ "x$INST_USER" != "xroot" ]; then
	DIR_OWN=`ls -ld ${LSWS_HOME} | awk '{print $3}'`
	if [ "x$DIR_OWN" != "x$INST_USER" ]; then
	    err_exit 1 "[ERROR] You do not have the permission to uninstall LiteSpeed web server!"
	fi
    fi

    if [ "x$INST_USER" = "xroot" ]; then
	echo ""
	echo "Uninstalling rc scripts ..."
	$LSINSTALL_DIR/rc-uninst.sh
	echo ""
    fi

    DELETE_ALL=1

    if [ $KEEP_CONF != "Y" ] ; then
	/bin/rm -rf ${LSWS_HOME}/conf
	echo "removed ${LSWS_HOME}/conf"
    else
	DELETE_ALL=0
	echo "keep ${LSWS_HOME}/conf untouched"
    fi

    if [ $KEEP_LOG != "Y" ] ; then
	/bin/rm -rf ${LSWS_HOME}/logs
	echo "removed ${LSWS_HOME}/logs"
    else
	DELETE_ALL=0
	echo "keep ${LSWS_HOME}/logs untouched"
    fi

    
    /bin/rm -rf ${LSWS_HOME}/add-ons
    echo "removed ${LSWS_HOME}/add-ons"
    /bin/rm -rf ${LSWS_HOME}/admin
    echo "removed ${LSWS_HOME}/admin"
    /bin/rm -rf ${LSWS_HOME}/autoupdate
    echo "removed ${LSWS_HOME}/autoupdate"
    /bin/rm -rf ${LSWS_HOME}/bin
    echo "removed ${LSWS_HOME}/bin"
    /bin/rm -rf ${LSWS_HOME}/DEFAULT
    echo "removed ${LSWS_HOME}/DEFAULT"
    /bin/rm -rf ${LSWS_HOME}/docs
    echo "removed ${LSWS_HOME}/docs"
    /bin/rm -rf ${LSWS_HOME}/fcgi-bin
    echo "removed ${LSWS_HOME}/fcgi-bin"
    /bin/rm -rf ${LSWS_HOME}/lib
    echo "removed ${LSWS_HOME}/lib"
    /bin/rm -rf ${LSWS_HOME}/php
    echo "removed ${LSWS_HOME}/php"
    /bin/rm -rf ${LSWS_HOME}/phpbuild
    echo "removed ${LSWS_HOME}/phpbuild"
    /bin/rm -rf ${LSWS_HOME}/share
    echo "removed ${LSWS_HOME}/share"
    /bin/rm -rf ${LSWS_HOME}/LICENSE*
    echo "removed ${LSWS_HOME}/LICENSE*"
    /bin/rm -f ${LSWS_HOME}/VERSION
    echo "removed ${LSWS_HOME}/VERSION"
    
    if [ $DELETE_ALL -ne 0 ]; then
        FILES=`ls ${LSWS_HOME} | wc -l`
        if [ $FILES -eq 0 ]; then
            /bin/rm -rf ${LSWS_HOME}
	    echo "${LSWS_HOME} is empty, deleted."
	else
	    echo "${LSWS_HOME} is not empty, kept there"
        fi
    else
	echo "${LSWS_HOME} is not empty, kept there"
    fi


    /bin/rm -f $LSWS_HOME_DEF
    
    # remove EAHook if there, has to be run after LSWS_HOME_DEF removed
    EasyApacheHookRefresh

    echo "LiteSpeed Web Server has been successfully uninstalled."

    cd $CUR_DIR

}
