#!/bin/bash

# ---
# RSB installer bootstrap script
#
# Version: 1.18
#
# Usage: "${0} VPS_IP_ADDRESS RSB_INSTALLERS_SITE installer_application.sh"
#
# (c) 2016-2023, RapidSeedbox, alexey@rapidseedbox.com
#

export PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin

SCRIPT_VER="$( grep -m 1 -e '^# Version:' "${0}" | awk '{print $NF}' )"

NODE="$( hostname -s )"
LOGFILE="/var/log/whmcs_installer_bootstrap.log"

function INFO()
{
    local msg="${1}"
    local tstamp="$( date )"
    echo -e "[${tstamp}] [INFO] ${L_PFX}: ${msg}" >> "${LOGFILE}"
}

function WARN()
{
    local msg="${1}"
    local tstamp="$( date )"
    echo -e "[${tstamp}] [WARN] ${L_PFX}: ${msg}" >> "${LOGFILE}"
}

function ERROR()
{
    local msg="${1}"
    local tstamp="$( date )"
    echo -e "[${tstamp}] [ERROR] ${L_PFX}: ${msg}" >> "${LOGFILE}"
}

function DEBUG()
{
    local msg="${1}"
    local tstamp="$( date )"
    echo -e "[${tstamp}] [DEBUG] ${L_PFX}: ${msg}" >> ${LOGFILE}
}


# -- Main secton

export SOLUSVM_WEB_DIR="/var/www/html/whmcs_installers"

[ ! -d "${SOLUSVM_WEB_DIR}" ] \
    && mkdir -p "${SOLUSVM_WEB_DIR}" > /dev/null 2>&1

L_PFX="$( basename "${0}" )"

INFO "Started with arguments: [${*}]"

if [ -z "${1}" ] ; then ERROR "Arg #1 is missing !" ; echo "33" ; exit 33 ; fi 
if [ -z "${2}" ] ; then ERROR "Arg #2 is missing !" ; echo "34" ; exit 34 ; fi 
if [ -z "${3}" ] ; then ERROR "Arg #3 is missing !" ; echo "35" ; exit 35 ; fi 

VPS_IP="${1}"
CTID="$( vzlist | awk -v i="${VPS_IP}" '$4 == i  {print $1}' )"
#RSB_SITE="${2}"
RSB_SITE="https://installers.rapidseedbox.com/scripts/whmcs_client_installers"
case "${NODE}" in
  testnode*)
      RSB_SITE="https://installers.rapidseedbox.com/scripts/whmcs_client_installers_test"
      ;;
esac

APP_SCRIPT="${3}"


# Generate WHMCS JSON (errors reporting only!):
__json () {
    local rc="${1}"
    local msg="${2}"
    cat <<-EOF > "${SOLUSVM_WEB_DIR}/${VPS_IP}.json"
	{
	   "status":"bootstrap",
	   "message":"${msg}",
	   "rc":"${rc}",
	   "application":[]
	}
	EOF
}


if [ -z "${CTID}" ] ; then
    __json "51" "Error retrieving CTID for IP: [${VPS_IP}] !"
    ERROR "Error retrieving CTID for IP: [${VPS_IP}] !"
    echo "51"
    >&2 echo "51"
    exit 51
fi

export VPS_ROOT_DIR="/vz/root/${CTID}"
export VPS_DB_DIR="${VPS_ROOT_DIR}/var/db/whmcs_client_installers"

( while true ; do
    diff -q \
        "${VPS_DB_DIR}/app-whmcs.json" \
        "${SOLUSVM_WEB_DIR}/${VPS_IP}.json" > /dev/null 2>&1
    if [ $? -ne 0 ] ; then
        [ -e "${VPS_DB_DIR}/app-whmcs.json" ] \
            && cp -f "${VPS_DB_DIR}/app-whmcs.json" \
                     "${SOLUSVM_WEB_DIR}/${VPS_IP}.json"
    fi
    sleep 5
  done ) > /dev/null 2>&1 &
WATCH_PID=$!
INFO "Watchdog PID: ${WATCH_PID}"


[ -e "${VPS_ROOT_DIR}/tmp/${APP_SCRIPT}" ] \
    && rm -vf "${VPS_ROOT_DIR}/tmp/${APP_SCRIPT}" >> ${LOGFILE} 2>&1

wget --no-cache -4 -t 5 -T 5 --no-check-certificate \
     -O "${VPS_ROOT_DIR}/tmp/${APP_SCRIPT}" \
        "${RSB_SITE}/${APP_SCRIPT}" >> ${LOGFILE} 2>&1
_rc=$?
if [ ${_rc} -eq 0 ] ; then
    CMD=$( cat <<-EOF
		export OCI_BOOTSTRAP_SCRIPT_VER="${SCRIPT_VER}" ;
		export SUPPORT="${RSB_SITE}/support" ;
		cd /tmp ;
		flock -w 1 /var/lock/whmcs_client_installers.lock date > /dev/null 2>&1 || exit 1 ;
		export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin ;
		rm -f /tmp/functions*.sh ;
		echo "\${0} \${*}|\$\$|\$( date -u +'%s' )" > "/var/lock/whmcs_client_installers.status" ;
		flock -w 1 /var/lock/whmcs_client_installers.lock /bin/bash ./${APP_SCRIPT}
		EOF
         )
    vzctl exec2 "${CTID}" "${CMD}"
    _rc=$?
    if [ ${_rc} -eq 1 ] ; then
        __json "114" "Another installation procedure is in progress."
        _rc=114
        echo "114"
        >&2 echo "114"
    elif [ ${_rc} -eq 115 ] ; then
        __json "115" "Seedbox not ready. Uptime still less than 10 minutes."
    else
        [ -e "${VPS_DB_DIR}/app-whmcs.json" ] \
            && cp -f "${VPS_DB_DIR}/app-whmcs.json" \
                     "${SOLUSVM_WEB_DIR}/${VPS_IP}.json"
        if [ -e "${VPS_ROOT_DIR}/var/run/reboot-required" ]
        then
            curl -X POST -F "action=maintenanceCompleted" -F "dedicated_ip=${VPS_IP}" \
                   "https://members.rapidseedbox.com/modules/addons/whmcs_client_installers/ajax/db.php"
            if [ ${_rc} -eq 0 ] ; then
                INFO "Rebooting ${CTID}..."
                rm -vf "${VPS_ROOT_DIR}/var/run/reboot-required" >> ${LOGFILE} 2>&1
                vzctl exec2 "${CTID}" "rm -vf \"/tmp/${APP_SCRIPT}\" ; shutdown -r now"
            fi
        fi
    fi
else
    __json "50" "Error fetching real installer script from node to VPS"
    _rc=50
    echo "50"
    >&2 echo "50"
fi

if [ -e "${VPS_ROOT_DIR}/tmp/${APP_SCRIPT}" ] ; then
    rm -vf "${VPS_ROOT_DIR}/tmp/${APP_SCRIPT}" >> ${LOGFILE} 2>&1
fi

INFO "Killing watchdog: [${WATCH_PID}] ..."
kill -9 "${WATCH_PID}" > /dev/null 2>&1

INFO "Finished with exit code: [${_rc}]"
INFO "----------------------------------"
exit ${_rc}
