#!/bin/sh
# SiteManager install.sh
# Same flow as the original panel installer (docs/analysis/original-installer.md):
# checks, prompts, repository setup, telemetry events, license fetch, package
# installation, recommended setup, Let's Encrypt, banner. All endpoints are ours.

exec 9>"/var/lock/sitemgr.install.lock"
if ! flock -n 9; then
	echo "Another instance of install.sh is already running"
	exit 1
fi

LOG_PIPE=/tmp/log.pipe.$$
mkfifo ${LOG_PIPE}
LOG_FILE="install_$(date +%Y_%m_%d-%H_%M_%S).log"
AFTER_INSTALL_LOG_PATH=/usr/local/sitemgr/var

# Our endpoints. Every host derives from SM_DOMAIN; override it (or a single variable) for tests.
SM_DOMAIN=${SM_DOMAIN:-vallorean.ru}
DEFAULTMIRROR=${DEFAULTMIRROR:-download.${SM_DOMAIN}}
FAILSAFEMIRROR=${FAILSAFEMIRROR:-mirrors.download.${SM_DOMAIN}}
INTMIRROR=${INTMIRROR:-intrepo.download.${SM_DOMAIN}}
SCHEMA=https
DB_CONF=/usr/local/sitemgr/etc/sitemgr.conf.d/db.conf
APT_LOCK_WAIT="-o DPkg::Lock::Timeout=1800"
REPO_KEY_NAME=sitemanager

# Package names (SiteManager branding, same structure as the original)
CORE_PKG=sitemanager-core
CORE_PKG_PREFIX=sitemanager-core-pkg-
LITE_PKG=sitemanager-lite
LITE_COMMON_PKG=sitemanager-lite-common
BUSINESS_PKG=sitemanager-business
PKG_PREFIX=sitemanager-pkg-
PRODUCT="SiteManager"

: > "${LOG_FILE}"
tee < ${LOG_PIPE} ${LOG_FILE} &

exec > ${LOG_PIPE}
exec 2> ${LOG_PIPE}

RUN_ID=$(date +%s%N)

LogClean() {
	rm -f ${LOG_PIPE}
}

EU=false

Usage()
{
	cat << EOU >&2

Usage:
	$0 --help 	Print this help

	$0 [options] [mgrname]
	--osfamily <FAMILY>     REDHAT, DEBIAN . Force if can not be detected.
	--osversion <VERSION>   Version for OS. Example: bookworm for debian, resolute for ubuntu. Force if can not be detected.
	--release <type>        Installs managers non-interactively with desired release <type>.
	--noinstall             Not install packages. Just add repository. Also disable mirror detecting.
	--install-business      Install the business edition (available only for REDHAT OS family).
	--ignore-hostname       Ignore incorrect hostname.
	--silent                Do not ask hostname and activation key. Exit on these errors immediatly. Also enabling --ignore-hostname
	--le-domain             Domain for LetsEncrypt certificate. If not set, server IP address will be used.
	--no-letsencrypt        Disable automatic certificate generation
	--disable-fail2ban      Disable fail2ban setup
	--sitemgr5               Force 5 version of sitemgr
	--openlitespeed         Install OpenLiteSpeed web server (takes effect only when mgrname=${LITE_PKG})
	--litespeed <SERIAL>    Install LiteSpeed web server. SERIAL - serial number of your LiteSpeed license. Type TRIAL to get trial license.
	--dbtype <type>         mysql, sqlite . Type of database to be used by the panel. Default: sqlite (when using the --silent option).
	--mysql-server <type>	mysql, mariadb . MySQL server engine. Only on Ubuntu and RedHat based 8-10.
	--allow-eol-os          Allow to install on EOL OS.
	--activation-key <key>  Activation key for your ${PRODUCT} license
	--dns-only              Install in DNS-only configuration (for use as secondary DNS in a cluster).

EOU
}

GetServerIp() {
	local IPADDR
	IPADDR=$(echo "${SSH_CONNECTION}" | awk '{print $3}')
	if [ -z "${IPADDR}" ]; then
		IPADDR=$(ip addr show | awk '$1 ~ /inet/ && $2 !~ /127.0.0|::1|fe80:/ {print $2}' | cut -d/ -f1 | head -1)
	fi
	echo "${IPADDR}"
}

GetMgrUrl() {
	# $1 - manager
	[ -n "${1}" ] || { echo "Empty arg 1"; return 1; }
	local ADDR SHOWADDR
	ADDR="$(GetServerIp)"
	case "${ADDR}" in
		*:*) SHOWADDR="[${ADDR}]" ;;
		*) SHOWADDR=${ADDR} ;;
	esac
	echo "https://${SHOWADDR}:1500/${1}"
}

PkgInstalled() {
	case ${SMOSTYPE} in
		DEBIAN) dpkg -s "${1}" >/dev/null 2>&1 ;;
		*) return 1 ;;
	esac
}

PkgAvailable() {
	case ${SMOSTYPE} in
		DEBIAN) apt-cache -q show "${1}" 2>/dev/null | grep -q "${1}" ;;
		*) return 1 ;;
	esac
}

MgrInstalled() {
	[ -n "${1}" ] || { echo "Empty arg 1"; return 1; }
	[ -n "${2}" ] || { echo "Empty arg 2"; return 1; }
	Info "================================================="
	Info "Your newly installed ${PRODUCT} panel is available at:"
	if [ -n "${LE_DOMAIN}" ] && ! echo "${LE_DOMAIN}" | grep -qE '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' ; then
		Info "https://${LE_DOMAIN}:1500/${1}"
		Info "Login: root"
		Info "Password: <root password>"
		Info ""
		echo "If this doesn't work you can use IP instead of domain"
		echo "Like: \"$(GetMgrUrl "${1}")\""
	else
		Info "$(GetMgrUrl "${1}")"
		Info "Login: root"
		Info "Password: <root password>"
	fi
	Info "================================================="
}

ValidForLetsEncrypt() {
	# $1 - ip or domain
	[ -n "${1}" ] || return 1
	[ -n "${LE_DOMAIN}" ] && return 0
	grep -q -- "--certificate-profile" /usr/local/sitemgr/etc/scripts/acmesh/acme.sh 2>/dev/null || return 1
	case "${1}" in
		*:*|10.*|172.1[6-9].*|172.2[0-9].*|172.3[0-1].*|192.168.*|127.*|169.254.*) return 1 ;;
		*) return 0 ;;
	esac
}

SendLetsEncryptMetric() {
	# $1 - status
	local LE_TYPE=domain
	[ -z "${LE_DOMAIN}" ] && LE_TYPE=ip
	SendMetric "letsencrypt" "status=${1}&type=${LE_TYPE}"
}

LetsEncrypt() {
	if [ -n "${no_letsencrypt}" ]; then
		SendLetsEncryptMetric "disabled"
		return
	fi
	local MGRDOMAIN="${LE_DOMAIN:-$(GetServerIp)}"
	if ValidForLetsEncrypt "${MGRDOMAIN}"; then
		Infon "Trying to get and install Let\`s Encrypt certificate for ${MGRDOMAIN}... "
		if /usr/local/sitemgr/sbin/mgrctl -m sitemgr ihttpd.certs.edit domain="${MGRDOMAIN}" type=letsencrypt sok=ok >/dev/null 2>&1; then
			Info "OK"
			SendLetsEncryptMetric "ok"
		else
			Error "Failed. For more information see /usr/local/sitemgr/var/sitemgr_acme_sh.log"
			SendLetsEncryptMetric "failed"
		fi
	else
		SendLetsEncryptMetric "unavailable"
	fi
}

debian_OSVERSIONS="bookworm trixie"
debian_EOL_OSVERSIONS=""
debian_PYTHON2=""

ubuntu_OSVERSIONS="jammy noble resolute"
ubuntu_EOL_OSVERSIONS=""
ubuntu_PYTHON2=""

selectos_OSVERSIONS="hele"

export DEBIAN_FRONTEND=noninteractive
export NOTIFY_SERVER=${NOTIFY_SERVER:-https://stat.${SM_DOMAIN}:8443/notify/v1}

CheckRoot() {
	if [ "$(id -u)" != "0" ]; then
		Error "You must be root user to continue"
		exit 1
	fi
	local RID
	if ! RID=$(id -u root 2>/dev/null); then
		Error "User root no found. You should create it to continue"
		exit 1
	fi
	if [ "${RID}" -ne 0 ]; then
		Error "User root UID not equals 0. User root must have UID 0"
		exit 1
	fi
}

Infon() {
	# shellcheck disable=SC2059
	printf "\033[1;32m$*\033[0m"
}

Info() {
	Infon "$*\n"
}

Warningn() {
	# shellcheck disable=SC2059
	printf "\033[1;35m$*\033[0m"
}

Warning() {
	Warningn "$*\n"
}

Error() {
	# shellcheck disable=SC2059
	printf "\033[1;31m$*\033[0m\n"
}

DetectManager() {
	if [ "${MIGRATION}" != "sitemgr" ] && [ "${noinstall}" != "true" ] && [ -d /usr/local/ispmgr ]; then
		Error "Old managers is installed: $(ls /usr/local/ispmgr/bin/ 2>/dev/null | tr '\n' ' ')"
		exit 1
	fi
}

CheckAppArmor() {
	[ "${SMOSTYPE}" = "DEBIAN" ] || return 0
	[ "$(lsb_release -s -i)" = "Ubuntu" ] || return 0
	if systemctl status apparmor >/dev/null 2>&1 ; then
		Error "AppArmor is enabled on your server. Can not install with AppArmor. Trying to disable it"
		DisableAppArmor
		Info "AppArmor is disabled."
	fi
}

DisableAppArmor() {
	systemctl stop apparmor
	systemctl disable apparmor
	if [ "${OSVER}" = "resolute" ]; then
		which aa-teardown >/dev/null 2>&1 && aa-teardown
	fi
	echo "blacklist apparmor" > /etc/modprobe.d/blacklist-apparmor.conf
	if which update-initramfs >/dev/null 2>&1; then
		update-initramfs -u
	else
		Error "update-initramfs not installed..."
	fi
}

CheckSELinux() {
	[ "$(uname -s)" = "Linux" ] || return 0
	selinuxenabled >/dev/null 2>&1 || return 0
	if [ -n "${release}" ] || [ -n "${silent}" ]; then
		Error "SELinux is enabled, aborting installation."
		exit 1
	fi
	Error "SELinux is enabled on your server. It is strongly recommended to disable SELinux before you proceed."
	[ "$(id -u)" = "0" ] || return 0
	printf "Would you like to disable SELinux right now (yes/no)?"
	while true; do
		read -r answer
		if [ -z "${answer}" ] || [ "${answer}" = "yes" ]; then
			setenforce 0 >/dev/null 2>&1
			cp -n /etc/selinux/config /etc/selinux/config.orig >/dev/null 2>&1
			echo SELINUX=disabled > /etc/selinux/config
			Error "Reboot is requred to complete the configuration of SELinux."
			printf "Reboot now (yes/no)?"
			while true; do
				read -r answer
				if [ "${answer}" = "yes" ]; then
					Info "Rebooting now. Please start installation script again once the server reboots."
					shutdown -r now
					exit 0
				elif [ "${answer}" = "no" ]; then
					Error "It is strongly recommended to reboot server before you proceed the installation"
					break
				fi
				printf "Please type 'yes' or 'no':"
			done
			break
		elif [ "${answer}" = "no" ]; then
			break
		fi
		printf "Please type 'yes' or 'no':"
	done
}

DetectFetch() {
	if [ -x /usr/bin/fetch ]; then
		fetch="/usr/bin/fetch -o "
	elif [ -x /usr/bin/wget ]; then
		fetch="/usr/bin/wget -T 30 -t 10 --waitretry=5 -q -O "
	elif [ -x /usr/bin/curl ]; then
		fetch="/usr/bin/curl --connect-timeout 30 --retry 10 --retry-delay 5 -o "
	else
		Error "ERROR: no fetch program found."
		exit 1
	fi
}

OSDetect() {
	[ -n "${SMOSTYPE}" ] && return 0
	SMOSTYPE=unknown
	case "$(uname -s)" in
		Linux)
			if [ -f /etc/redhat-release ] || [ -f /etc/centos-release ]; then
				export SMOSTYPE=REDHAT
			elif [ -f /etc/debian_version ]; then
				export SMOSTYPE=DEBIAN
			fi
			;;
		FreeBSD)
			export SMOSTYPE=FREEBSD
			;;
	esac
	if [ "${SMOSTYPE}" = "unknown" ]; then
		Error "Unknown os type. Try to use \"--osfamily\" option"
		exit 1
	fi
}

BadHostname() {
	# True when $1 is a usable hostname (the name is kept from the original's API)
	[ -n "${1}" ] || return 1
	local HOSTNAME=${1} LENGTH TOPLEVEL
	LENGTH=$(echo "${HOSTNAME}" | wc -m)
	if [ "${LENGTH}" -lt 2 ] || [ "${LENGTH}" -gt 50 ]; then
		return 1
	fi
	echo "${HOSTNAME}" | grep -q '\.' || return 1
	echo "${HOSTNAME}" | grep -q '_' && return 1
	TOPLEVEL=$(echo "${HOSTNAME}" | awk -F. '{print $NF}')
	[ -n "${TOPLEVEL}" ] || return 1
	[ -z "$(echo "${TOPLEVEL}" | sed -r 's/[a-zA-Z0-9\-]//g')" ]
}

GetFirstIp() {
	if [ -n "$(which ip 2>/dev/null)" ]; then
		ip route get 1 | awk '{print $NF; exit}'
	fi
}

SetHostname() {
	# $1 - new hostname, $2 - old hostname
	[ -n "${1}" ] || return 1
	local HOSTNAME CUTHOSTNAME
	HOSTNAME=$(echo "${1}" | sed 's|\.+$||')
	case "${SMOSTYPE}" in
		DEBIAN)
			CUTHOSTNAME=${HOSTNAME%.*}
			hostname "${CUTHOSTNAME}" || return 1
			echo "${CUTHOSTNAME}" > /etc/hostname || return 1
			if [ -n "${2}" ]; then
				sed -i -r "s|${2}|${HOSTNAME}|g" /etc/hosts || return 1
			fi
			if ! hostname -f >/dev/null 2>&1; then
				sed -i -r "s|^([0-9\.]+\s+)${HOSTNAME}\s*$|\1${HOSTNAME} ${CUTHOSTNAME}|g" /etc/hosts
			fi
			if ! hostname -f >/dev/null 2>&1; then
				echo "$(GetFirstIp) ${HOSTNAME} ${CUTHOSTNAME}" >> /etc/hosts
			fi
			if ! hostname -f >/dev/null 2>&1; then
				Error "Can not set hostname"
				return 1
			fi
			;;
		*)
			return 1
			;;
	esac
}

CheckHostname() {
	local CURHOSTNAME HOSTNAME
	CURHOSTNAME=$(hostname -f || :)
	HOSTNAME=${CURHOSTNAME}
	if [ "${silent}" != "true" ]; then
		while ! BadHostname "${HOSTNAME}"; do
			Error "You have incorrect hostname: ${HOSTNAME}"
			printf "Enter new hostname(or Ctrl+C to exit): "
			read -r HOSTNAME
			echo
		done
		Info "Your hostname: ${HOSTNAME}"
		if [ "${CURHOSTNAME}" != "${HOSTNAME}" ]; then
			if ! SetHostname "${HOSTNAME}" "${CURHOSTNAME}"; then
				echo
				Error "Can not change hostname. Please change it manually"
				exit 1
			fi
		fi
	elif ! BadHostname "${HOSTNAME}"; then
		Error "You have incorrect hostname: ${HOSTNAME}"
		Error "Please change it manually"
		exit 1
	fi
}

OSVersion() {
	[ -n "${OSVER}" ] && return 0
	OSVER=unknown

	case ${SMOSTYPE} in
		DEBIAN)
			/usr/bin/apt-get ${APT_LOCK_WAIT} -qy update
			/usr/bin/apt-get ${APT_LOCK_WAIT} -qy --allow-unauthenticated -u install ca-certificates
			if ! which which >/dev/null 2>&1; then
				/usr/bin/apt-get ${APT_LOCK_WAIT} -qy --allow-unauthenticated install which
			fi
			if [ -z "$(which lsb_release 2>/dev/null)" ]; then
				/usr/bin/apt-get ${APT_LOCK_WAIT} -qy --allow-unauthenticated install lsb-release
			fi
			if [ -x /usr/bin/lsb_release ]; then
				OSVER=$(lsb_release -s -c)
			fi
			local toinstall=""
			if echo "${debian_PYTHON2} ${ubuntu_PYTHON2}" | grep -q -w "${OSVER}"; then
				[ -n "$(which python 2>/dev/null)" ] || toinstall="${toinstall} python"
			else
				[ -n "$(which python3 2>/dev/null)" ] || toinstall="${toinstall} python3"
			fi
			[ -n "$(which hexdump 2>/dev/null)" ] || toinstall="${toinstall} bsdmainutils"
			[ -n "$(which logger 2>/dev/null)" ] || toinstall="${toinstall} bsdutils"
			[ -n "$(which free 2>/dev/null)" ] || toinstall="${toinstall} procps"
			[ -n "$(which ip 2>/dev/null)" ] || toinstall="${toinstall} iproute2"
			[ -n "$(which gpg 2>/dev/null)" ] || toinstall="${toinstall} gnupg"
			[ -n "$(which wget curl 2>/dev/null)" ] || toinstall="${toinstall} wget"
			if [ -n "${toinstall}" ]; then
				# shellcheck disable=SC2086
				/usr/bin/apt-get ${APT_LOCK_WAIT} -qy --allow-unauthenticated install ${toinstall}
			fi
			if ! echo "${debian_OSVERSIONS} ${ubuntu_OSVERSIONS} ${selectos_OSVERSIONS}" | grep -q -w "${OSVER}"; then
				unsupported_osver="true"
			fi
			if echo "${debian_EOL_OSVERSIONS} ${ubuntu_EOL_OSVERSIONS}" | grep -q -w "${OSVER}"; then
				eol_osver="true"
			fi
			if [ "$(lsb_release -s -i)" = "Ubuntu" ]; then
				export reponame=ubuntu
			elif [ "$(lsb_release -s -i)" = "SELECTOS" ]; then
				export reponame=selectos
			else
				export reponame=debian
			fi
			OS_NAME="$(lsb_release -s -i | tr '[:upper:]' '[:lower:]')"
			;;
		*)
			unsupported_osver="true"
			;;
	esac
	if [ "${OSVER}" = "unknown" ] && [ "${unsupported_osver}" != "true" ]; then
		Error "Unknown os version. Try to use \"--osversion\" option"
		exit 1
	fi
	if [ "${unsupported_osver}" = "true" ]; then
		Error "Unsupported os version (${OSVER})"
		exit 1
	fi
	if [ "${eol_osver}" = "true" ] && [ "${ALLOW_EOL}" != "true" ]; then
		Error "Your operating system is at End of Support (EOL). Correct operation of ${PRODUCT} on this OS is not guaranteed."
		echo "Continue installation? (y/N)"
		echo
		printf "Your choice is: "
		read -r answer
		echo
		if [ "${answer}" = "y" ]; then
			ALLOW_EOL=true
		else
			exit 0
		fi
	fi
}

CheckMirror() {
	# $1 - mirror. A valid mirror lists install.sh in its index
	${fetch} - "http://${1}/" | grep -q install.sh
}

Ver6to5() {
	# Panel release 6.X runs on core 5.(X+295)
	echo "5.$(( $(echo "${1}" | cut -d . -f2) + 295 ))"
}

GetFastestMirror() {
	if CheckMirror "${DEFAULTMIRROR}"; then
		export BASEMIRROR=${DEFAULTMIRROR}
	else
		export BASEMIRROR=${FAILSAFEMIRROR}
	fi

	if [ -n "${ARGMIRROR}" ]; then
		export BASEMIRROR=${ARGMIRROR}
		export MIRROR=${ARGMIRROR}
		return 0
	fi

	# Development branches live on the internal repository
	if ! echo "${release}" | grep -qE "^(stable|beta|beta5|beta6|stable5|stable6|intbeta|intstable|5\.[0-9]+|6\.[0-9]+)$"; then
		export MIRROR=${INTMIRROR}
		export SCHEMA=http
		return 0
	fi

	if echo "${release}" | grep -qE "^6\.[0-9]"; then
		FORCE_SM6=yes
		release=$(Ver6to5 "${release}")
	fi

	if CheckMirror "${DEFAULTMIRROR}"; then
		export MIRROR=${DEFAULTMIRROR}
	else
		export MIRROR=${FAILSAFEMIRROR}
	fi
	Info "Using ${MIRROR}"
}

CleanMachineID() {
	if [ -f /etc/machine-id ] && [ -n "$(which systemd-machine-id-setup 2>/dev/null)" ] && [ -z "${core_installed}" ]; then
		rm -f /var/lib/dbus/machine-id
		rm -f /etc/machine-id
		systemd-machine-id-setup
	fi
}

GetMachineID() {
	CleanMachineID >/dev/null 2>&1 || :
	if [ ! -f /etc/machine-id ]; then
		if [ -n "$(which systemd-machine-id-setup 2>/dev/null)" ]; then
			systemd-machine-id-setup >/dev/null 2>&1
		else
			hexdump -n 16 -e '/2 "%x"' /dev/urandom > /etc/machine-id
		fi
	fi
	awk '{print $1}' /etc/machine-id
}

GetMacHash() {
	md5sum < "/sys/class/net/$(ip route show default | awk '/default/ {print $5}')/address" | awk '{print $1}'
}

SendMetric() {
	# $1 - event, $2 - extra form data
	local HOSTID MACHASH URL DATA
	HOSTID=$(GetMachineID)
	MACHASH=$(GetMacHash)
	URL="${NOTIFY_SERVER}/${1}"
	DATA="hostid=${HOSTID}&machash=${MACHASH}&runid=${RUN_ID}&${2}"
	if [ -x /usr/bin/wget ]; then
		timeout -s INT 60 wget --quiet --tries=3 --read-timeout=20 --connect-timeout=10 --no-check-certificate --post-data="${DATA}" -O - "${URL}" 2>/dev/null || :
	elif [ -x /usr/bin/curl ]; then
		timeout -s INT 60 curl --silent --max-time 30 --connect-timeout 10 --insecure -d "${DATA}" -o /dev/null "${URL}" || :
	else
		Warning "WARNING: wget or curl not found."
	fi
	return 0
}

StartInstall() {
	SendMetric "startinstall" "os=${SMOSTYPE}-${OSVER}&mirror=${MIRROR}&repo=${release}&mgr=${pkgname}&dbtype=${DBTYPE}&webserver=${webserver}"
}

LicInstall() {
	local licid licexpire corever DATA
	licid=$(/usr/local/sitemgr/sbin/licctl info "/usr/local/sitemgr/etc/${mgr}.lic" 2>/dev/null | awk '$1 == "ID:" {print $2}' || :)
	licexpire=$(/usr/local/sitemgr/sbin/licctl info "/usr/local/sitemgr/etc/${mgr}.lic" 2>/dev/null | awk '$1 == "Expire:" {print $2}' || :)
	corever=$(/usr/local/sitemgr/bin/core core -v 2>/dev/null)
	DATA="mgr=${pkgname}&corever=${corever}"
	if [ "${licid}" != "0" ]; then
		DATA="${DATA}&licid=${licid}&licexpire=${licexpire}"
	fi
	SendMetric "licinstall" "${DATA}"
}

CancelInstall() {
	local REASON=""
	[ -n "${1}" ] && REASON="&reason=${1}"
	SendMetric "cancelinstall" "mgr=${pkgname}${REASON}"
	LogClean
}

FinishInstall() {
	local BILL_SETTINGS=/usr/local/sitemgr/etc/billing.settings mgrver
	if [ ! -e ${BILL_SETTINGS} ]; then
		if [ "${EU}" = true ]; then
			printf 'Api https://api-eu.%s/billmgr\nLicense license.%s\nSite https://eu.%s/billmgr\n' "${SM_DOMAIN}" "${SM_DOMAIN}" "${SM_DOMAIN}" > ${BILL_SETTINGS}
		else
			printf 'Api https://api.%s/billmgr\nLicense license.%s\nSite https://my.%s/billmgr\n' "${SM_DOMAIN}" "${SM_DOMAIN}" "${SM_DOMAIN}" > ${BILL_SETTINGS}
		fi
	fi
	mgrver=$(/usr/local/sitemgr/bin/core "${mgr}" -v 2>/dev/null)
	SendMetric "finishinstall" "mgr=${pkgname}&mgrver=${mgrver}&url=$(GetMgrUrl "${mgr}")"
	LogClean
	if [ -s "${LOG_FILE}" ]; then
		mv "${LOG_FILE}" "${AFTER_INSTALL_LOG_PATH}/${LOG_FILE}"
	fi
}

# shellcheck disable=SC2120 # optional message argument, as in the original
ErrorInstall() {
	local err_text
	if [ -n "${1}" ]; then
		err_text="${1}"
	else
		CheckPkg "${CORE_PKG}"
		if [ -f /usr/local/sitemgr/var/licctl.log ]; then
			tail -n50 /usr/local/sitemgr/var/licctl.log >> "${LOG_FILE}" 2>&1
		fi
		err_text="$(sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g" "${LOG_FILE}" | hexdump -v -e '/1 "%02x"' | sed 's/\(..\)/%\1/g')"
	fi
	SendMetric "errorinstall" "mgr=${pkgname}&text=${err_text}"
	LogClean
	exit 1
}

DetectInstalled() {
	if PkgInstalled "${CORE_PKG}" || [ -f /usr/local/sitemgr/etc/core.conf ]; then
		export core_installed=yes
	fi
}

GetAvailVersion() {
	# $1 - release; newest core version in that release's suite
	[ -n "${1}" ] || return 1
	/usr/bin/apt-get ${APT_LOCK_WAIT} -y update >/dev/null 2>&1
	/usr/bin/apt-cache madison "${CORE_PKG}" 2>/dev/null | awk -v rel="${1}" -v dist="$(lsb_release -c -s)" '$6 == rel"-"dist"/main" {print $3}' | sort -V | tail -1
}

GetAvailPkgVersion() {
	# $1 - package; candidate version or nothing
	[ -n "${1}" ] || return 1
	LC_ALL=C /usr/bin/apt-cache policy "${1}" 2>/dev/null | awk '/Candidate:/ && $2 != "(none)" {print $2}'
}

GetInstalledVersion() {
	dpkg -s "${CORE_PKG}" 2>/dev/null | awk '/^Version/ {print $2}'
}

VersionToRelease() {
	echo "${1}" | awk -F- '{print $1}' | cut -d. -f1,2
}

GetCurrentRepo() {
	local list=/etc/apt/sources.list.d/sitemanager.list
	[ -f ${list} ] || return 0
	release=$(awk '$1 == "deb" && $2 ~ /http|ftp/ {print $3}' ${list} | awk -F- '{print $1}')
	if [ -z "${release}" ]; then
		rm -f ${list}
	else
		added_repo=yes
		MIRROR="$(awk -F/ 'END{print $3}' ${list})"
		export MIRROR
	fi
}

CheckMEM() {
	[ -n "${silent}" ] && return 0
	local lowmemlimit=512 lowmem
	lowmem=$(free -m | awk -v lml=${lowmemlimit} 'NR==2 && $2 <= lml {print $2}')
	if [ -n "${lowmem}" ]; then
		Error "You have to low memory: ${lowmem}"
		Error "You need to have at least ${lowmemlimit} Mb"
		CancelInstall lowmem
		exit 1
	fi
}

CheckRecommended() {
	if [ -n "$(free -m | awk 'NR==2 && $2 <= 1024 {print $2}')" ]; then
		INSTALL_MINI=yes
	else
		INSTALL_MINI=no
	fi
}

CheckPkg() {
	{
		echo ""
		echo "Checking package ${1}"
		dpkg -l | grep "${1}"
	} >> "${LOG_FILE}" 2>&1
}

GetMysqlDisplayName() {
	# Name of the database server the "mysql" choice installs, shown in Step 4
	local pkg=${mysqlserver:-mariadb-server} ver
	ver=$(GetAvailPkgVersion "${pkg}" | sed -r 's/^[0-9]+://; s/^([0-9]+\.[0-9]+).*/\1/')
	case "${pkg}" in
		mariadb*) DB_DISPLAY_NAME="MariaDB ${ver}" ;;
		*) DB_DISPLAY_NAME="MySQL ${ver}" ;;
	esac
	DB_DISPLAY_NAME=$(echo "${DB_DISPLAY_NAME}" | sed 's/ *$//')
	DB_INSTALL_PKG=""
}

trap ErrorInstall TERM
set -e

# Parsing arguments
while true
do
	case "${1}" in
		-h | --help)
			Usage
			LogClean
			exit 0
			;;
		--mirror)
			ARGMIRROR="${2:-.}"
			shift 2
			if [ -z "${ARGMIRROR}" ]; then
				Error "Empty mirror"
				exit 1
			fi
			;;
		--release)
			release=$(echo "${2:-.}" | awk -F. '{if(NF>1){print $1 "." $2}else{print $0}}')
			shift 2
			;;
		--osfamily)
			SMOSTYPE="${2:-.}"
			if ! echo "${SMOSTYPE}" | grep -qE "^(REDHAT|DEBIAN)$"; then
				Error "Incorrect OS"
				exit 1
			fi
			shift 2
			;;
		--osversion)
			OSVER="${2:-.}"
			shift 2
			;;
		--noinstall)
			noinstall="true"
			shift 1
			;;
		--install-business)
			pkgname="${BUSINESS_PKG}"
			shift 1
			;;
		--silent)
			silent="true"
			ignore_hostname="true"
			ALLOW_EOL="true"
			[ -z "${DBTYPE}" ] && DBTYPE="sqlite"
			[ -z "${INSTALL_MINI}" ] && INSTALL_MINI=no
			shift 1
			;;
		--ignore-hostname)
			ignore_hostname="true"
			shift 1
			;;
		--disable-fail2ban)
			disable_fail2ban="true"
			shift 1
			;;
		--no-letsencrypt)
			no_letsencrypt="true"
			shift 1
			;;
		--le-domain)
			LE_DOMAIN="${2:-.}"
			shift 2
			;;
		--sitemgr6)
			# shellcheck disable=SC2034 # accepted for compatibility; version 6 is the default
			FORCE_SM6="true"
			shift 1
			;;
		--sitemgr5)
			FORCE_SM5="true"
			shift 1
			;;
		--dns-only)
			INSTALL_DNS_ONLY="yes"
			shift 1
			;;
		--openlitespeed)
			webserver=openlitespeed
			shift 1
			;;
		--litespeed)
			webserver=litespeed
			LITESPEED_SERIAL="${2:-.}"
			if [ "${LITESPEED_SERIAL}" != "TRIAL" ] && ! expr "${LITESPEED_SERIAL}" : "^.\{4\}\(-.\{4\}\)\{3\}$" > /dev/null; then
				echo "Bad LiteSpeed serial number ${LITESPEED_SERIAL}! Expect xxxx-xxxx-xxxx-xxxx format"
				exit 1
			fi
			mkdir -p "/usr/local/sitemgr/tmp"
			echo "${LITESPEED_SERIAL}" > "/usr/local/sitemgr/tmp/lsws-serial.no"
			shift 2
			;;
		--dbtype)
			DBTYPE="${2:-.}"
			if ! echo "${DBTYPE}" | grep -qE "^(mysql|sqlite)$"; then
				Error "Incorrect database type"
				exit 1
			fi
			shift 2
			;;
		--mysql-server)
			mysqlserver="${2:-.}-server"
			if ! echo "${mysqlserver}" | grep -qE "^(mysql-server|mariadb-server)$"; then
				Error "Incorrect mysql server"
				exit 1
			fi
			shift 2
			;;
		--allow-eol-os)
			ALLOW_EOL="true"
			shift 1
			;;
		--activation-key)
			ACTIVATION_KEY="${2:-.}"
			shift 2
			;;
		*)
			[ -z "${1}" ] && break
			inpkgname=${1}
			shift 1
			;;
	esac
done

if [ -f /.dockerinit ]; then
	export ignore_hostname="true"
fi

case "${release}" in
	beta) release=beta6 ;;
	stable) release=stable6 ;;
	4*)
		Error "Unsupported version"
		exit 1
		;;
esac

#don't change order
OSDetect
OSVersion

SendMetric "runinstall" "os=${SMOSTYPE}-${OSVER}"

if [ -n "${mysqlserver}" ]; then
	if [ "$(lsb_release -s -i)" = "Debian" ] || [ "${SMOSTYPE}-${OSVER}" = "DEBIAN-resolute" ] || [ "${SMOSTYPE}-${OSVER}" = "DEBIAN-hele" ]; then
		Error "The '--mysql-server' option not supported on this OS"
		exit 1
	fi
fi

Infon "Installing on ${SMOSTYPE} ${OSVER}"
echo ""

Info "System memory:"
free -m
echo ""

Info "Disk space:"
df -h -P -l -x tmpfs -x devtmpfs
echo ""

DetectManager
CheckRoot
CheckSELinux
CheckAppArmor
CheckMEM
CheckRecommended

if [ "${ignore_hostname}" != "true" ]; then
	CheckHostname
else
	export IGNORE_HOSTNAME=yes
fi

DetectFetch
DetectInstalled

if [ -z "${release}" ]; then
	GetCurrentRepo
fi
if [ -n "${release}" ] && [ -n "${added_repo}" ]; then
	Info "Detected added repository: ${release}"
	Info "updating cache"
	/usr/bin/apt-get ${APT_LOCK_WAIT} -y update
fi

while [ -z "${release}" ]
do
	echo "Step 1. Select update branch:"
	echo "b) beta — has the latest functionality"
	echo "s) stable — time-tested version"
	echo
	printf "Type b or s: "
	read -r n
	echo
	case ${n} in
		r|s|2|stable) release="stable6" ;;
		b|1|beta) release="beta6" ;;
		m|master) release="master" ;;
		si) release="stable-int" ;;
		bi) release="beta-int" ;;
		ib) release="intbeta" ;;
		is) release="intstable" ;;
		i)
			printf "Enter full repository name: "
			read -r rn
			release="${rn}"
			;;
		*) : ;;
	esac
	SendMetric "choicerepo" "repo=${release}"
done

InstallGpgKey() {
	local KEY=/etc/apt/trusted.gpg.d/${REPO_KEY_NAME}.gpg
	if [ ! -s ${KEY} ]; then
		${fetch} ${KEY} "${SCHEMA}://${MIRROR}/repo/${REPO_KEY_NAME}.gpg" || :
	fi
}

CheckRepo() {
	# $1 - suite; true when apt knows it
	apt-cache policy | awk -v rname="${1}/main" '$NF == "Packages" && $(NF-2) == rname' | grep -q "${1}"
}

InstallBaseRepo() {
	[ -z "${BASEMIRROR}" ] && GetFastestMirror
	InstallGpgKey || return 1
	Infon "Checking base repo... "
	if ! CheckRepo "base-${OSVER}"; then
		Warning "Not found"
		Info "Adding repository base.."
		rm -f /etc/apt/sources.list.d/sitemanager-base.list
		mkdir -p /etc/apt/sources.list.d
		echo "deb http://${BASEMIRROR}/repo/${reponame} base-${OSVER} main" > /etc/apt/sources.list.d/sitemanager-base.list
	else
		Info "Found"
	fi
	if echo "${MIRROR}" | grep -q intrepo && [ ! -f /etc/apt/sources.list.d/intrepo-base.list ]; then
		echo "deb http://${MIRROR}/repo/${reponame} base-${OSVER} main" > /etc/apt/sources.list.d/intrepo-base.list
	fi
}

DebianRepo() {
	# $1 - suite prefix (release), $2 - list name
	local rel=${1} rname=${2}
	rm -f /etc/apt/sources.list.d/${rname}.list
	if echo "${rel}" | grep -qE "^(6-)?(stable|beta|intbeta|intstable)[56]?$"; then
		echo "deb ${SCHEMA}://${MIRROR}/repo/${reponame} ${rel}-${OSVER} main" > /etc/apt/sources.list.d/${rname}.list
	else
		echo "deb http://${MIRROR}/repo/${reponame} ${rel}-${OSVER} main" > /etc/apt/sources.list.d/${rname}.list
	fi
}

InstallRepo() {
	GetFastestMirror
	InstallBaseRepo || return 1
	InstallGpgKey || return 1

	if [ -z "${FORCE_SM5}" ]; then
		Info "Adding repository ${PRODUCT} 6.."
		DebianRepo "6-${release}" "exosoft"
	else
		Info "Adding repository ${PRODUCT} 5.."
		DebianRepo "${release}" "sitemanager"
	fi
	case ${release} in
		5.*)
			if [ -z "${FORCE_SM5}" ] && [ "${release#5.}" -lt 361 ]; then
				Info "Adding repository core.."
				DebianRepo "${release}" "sitemanager"
			fi
			;;
	esac
	/usr/bin/apt-get ${APT_LOCK_WAIT} -y update >/dev/null

	mkdir -p /usr/local/sitemgr/etc
	chmod 750 /usr/local/sitemgr/etc
	case "${release}" in
		beta6) echo "beta" > /usr/local/sitemgr/etc/repo.version ;;
		stable6) echo "stable" > /usr/local/sitemgr/etc/repo.version ;;
		*) echo "${release}" > /usr/local/sitemgr/etc/repo.version ;;
	esac
}

BinaryExists() {
	command -v "${1}" >/dev/null 2>&1 || [ -e "/usr/sbin/${1}" ] || [ -e "/sbin/${1}" ]
}

PkgInstall() {
	/usr/bin/apt-get ${APT_LOCK_WAIT} -y update
	# shellcheck disable=SC2068
	/usr/bin/apt-get ${APT_LOCK_WAIT} -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" -qy install $@
}

PkgRemove() {
	# shellcheck disable=SC2068
	/usr/bin/apt-get ${APT_LOCK_WAIT} -y -q remove $@
}

CoreInstall() {
	PkgInstall "${CORE_PKG}"
}

Fail2Ban() {
	if PkgAvailable "${CORE_PKG_PREFIX}fail2ban"; then
		PkgInstall "${CORE_PKG_PREFIX}fail2ban" || :
	elif [ -x /usr/local/sitemgr/sbin/fail2ban.sh ]; then
		Info "Instaling fail2ban"
		PkgInstall fail2ban || :
		/usr/local/sitemgr/sbin/fail2ban.sh && Info "fail2ban configured" || :
	fi
}

if [ "${noinstall}" = "true" ]; then
	InstallRepo
	LogClean
	exit 0
fi

# Choosing the manager and edition
if [ -n "${inpkgname}" ]; then
	inpkgname=$(echo "${inpkgname}" | awk '{print tolower($0)}')
	while [ -z "${mgr}" ] && [ -n "${inpkgname}" ]
	do
		case ${inpkgname} in
			"${CORE_PKG}"|sitemanager-core)
				mgr=core
				pkgname=${CORE_PKG}
				;;
			"${LITE_COMMON_PKG}"|sitemanager-lite-common)
				mgr=sitemgr
				pkgname=${LITE_COMMON_PKG}
				;;
			"${LITE_PKG}"|sitemanager-lite)
				mgr=sitemgr
				pkgname=${LITE_PKG}
				;;
			sitemanager-pro|sitemanager-pro|"${BUSINESS_PKG}"|sitemanager-business)
				mgr=sitemgr
				pkgname=${BUSINESS_PKG}
				;;
			sitemanager|sitemanager)
				mgr=sitemgr
				;;
			*)
				if echo "${inpkgname}" | grep -q -- '-'; then
					inpkgname=$(echo "${inpkgname}" | cut -d- -f1)
				else
					Error "Incorrect package name"
					exit 1
				fi
				;;
		esac
	done
	[ -z "${DBTYPE}" ] && DBTYPE="sqlite"
else
	mgr=sitemgr
fi

licname="${mgr%[0-9]}"

case "${mgr}" in
	sitemgr)
		if [ "${pkgname}" = "${BUSINESS_PKG}" ] && [ "${SMOSTYPE}" = "DEBIAN" ]; then
			Error "${PRODUCT} Business is not supported on Debian-based systems."
			exit 1
		fi
		if [ "${INSTALL_DNS_ONLY}" = "yes" ]; then
			pkgname=${LITE_COMMON_PKG}
		fi
		while [ -z "${pkgname}" ]
		do
			echo "Step 2. Select edition:"
			echo "1) ${PRODUCT} lite, pro, host with recommended software"
			echo "2) ${PRODUCT} lite, pro, host with minimal software"
			echo "3) ${PRODUCT} lite, pro, host with DNS only (for DNS cluster)"
			echo
			printf "Type 1, 2 or 3: "
			read -r n
			echo
			echo "Chosen: ${n}"
			echo
			case "${n}" in
				1)
					pkgname=${LITE_PKG}
					if [ "${INSTALL_MINI}" = "yes" ]; then
						if [ "${webserver}" = "openlitespeed" ]; then
							Error "Can't use openlitespeed as a web server because too little RAM"
							CancelInstall lowmem
							exit 1
						fi
						webserver=nginx
					fi
					while [ -z "${webserver}" ]
					do
						echo "Step 3. Select web server:"
						echo "1) Nginx + Apache"
						if [ "${OS_NAME}" = "cloudlinux" ]; then
							echo "2) OpenLiteSpeed (not supported on this OS)"
						elif [ "${OS_NAME}" = "selectos" ]; then
							echo "2) OpenLiteSpeed (not supported on SelectOS)"
						else
							echo "2) OpenLiteSpeed"
						fi
						echo "3) LiteSpeed"
						echo
						printf "Type 1, 2 or 3: "
						read -r w
						echo
						echo "Chosen: ${w}"
						echo
						case "${w}" in
							1) webserver=nginx ;;
							2)
								if [ "${OS_NAME}" != "cloudlinux" ] && [ "${OS_NAME}" != "selectos" ]; then
									webserver=openlitespeed
								else
									echo "Invalid choice. Try again."
									echo
								fi
								;;
							3) webserver=litespeed ;;
							*) ;;
						esac
					done
					;;
				2) pkgname=${LITE_COMMON_PKG} ;;
				3)
					pkgname=${LITE_COMMON_PKG}
					INSTALL_DNS_ONLY="yes"
					;;
				*)
					echo "Invalid choice. Try again."
					echo
					;;
			esac
		done
		SendMetric "choicepkg" "mgr=${pkgname}"
		;;
	core)
		pkgname=${CORE_PKG}
		;;
esac

if [ "${pkgname}" = "${LITE_PKG}" ] && [ "${webserver}" = "openlitespeed" ]; then
	if [ "${OS_NAME}" = "cloudlinux" ]; then
		Error "Can't use openlitespeed as a web server in CloudLinux"
		exit 1
	fi
	if [ "${OS_NAME}" = "selectos" ]; then
		Error "Can't use openlitespeed as a web server on SelectOS"
		exit 1
	fi
fi

[ "${pkgname}" != "${LITE_PKG}" ] && webserver=""

if [ "${pkgname}" = "${LITE_PKG}" ]; then
	if [ "${INSTALL_MINI}" = "yes" ] && [ "${webserver}" = "openlitespeed" ]; then
		Error "Can't use openlitespeed as a web server because too little RAM"
		CancelInstall lowmem
		exit 1
	fi
	[ -z "${webserver}" ] && webserver=nginx
	pkgname=${LITE_COMMON_PKG}
fi

# for licctl
case "${pkgname}" in
	"${BUSINESS_PKG}") SITEMGR_TYPE=business ;;
	"${LITE_COMMON_PKG}"|"${LITE_PKG}") SITEMGR_TYPE=lite ;;
	*) SITEMGR_TYPE="" ;;
esac
export SITEMGR_TYPE

if PkgInstalled "${pkgname}"; then
	Error "You have already installed package ${pkgname}"
	Error "Do not use install.sh script for upgrading!"
	Error "Use \"/usr/local/sitemgr/sbin/pkgupgrade.sh ${CORE_PKG}\" command instead"
	exit 1
fi
if PkgInstalled "${BUSINESS_PKG}"; then
	Error "${BUSINESS_PKG} already installed"
	exit 1
fi
if PkgInstalled "${LITE_COMMON_PKG}"; then
	Error "${LITE_PKG} already installed"
	exit 1
fi

if [ "${pkgname}" = "${LITE_COMMON_PKG}" ]; then
	if [ "${INSTALL_MINI}" = "yes" ]; then
		if [ "${DBTYPE}" = "mysql" ]; then
			Error "Can't use MySQL to run the panel because too little RAM is available"
			CancelInstall lowmem
			exit 1
		fi
		DBTYPE=sqlite
	fi
	if [ "${INSTALL_DNS_ONLY}" = "yes" ] && [ -z "${DBTYPE}" ]; then
		DBTYPE=sqlite
	fi
	if [ -z "${DBTYPE}" ]; then
		GetMysqlDisplayName
	fi
	while [ -z "${DBTYPE}" ]
	do
		echo "Step 4. Select database server for panel data:"
		echo "1) SQLite (regular load, up to 5-10 sites, 5-10 users)"
		echo "2) ${DB_DISPLAY_NAME} (recommended for projects with numerous sites and users)"
		echo
		printf "Type 1 or 2: "
		read -r d
		echo
		echo "Chosen: ${d}"
		echo
		case "${d}" in
			1) DBTYPE=sqlite ;;
			2) DBTYPE=mysql ;;
			*) ;;
		esac
		SendMetric "choicedb" "dbtype=${DBTYPE}"
	done
fi

StartInstall
trap CancelInstall INT

if [ "${added_repo}" != "yes" ]; then
	if [ "${release}" = "beta6" ] || [ "${release}" = "stable6" ]; then
		if [ "${mgr}" = "sitemgr" ] && [ -n "${FORCE_SM5}" ]; then
			# Strict max version
			release=5.333
		fi
	fi
	# Several attempts: the CDN may need time to settle on new addresses
	IR_FAIL=0
	trc=0
	while [ ${trc} -le 3 ]; do
		trc=$((trc + 1))
		IR_FAIL=0
		InstallRepo || IR_FAIL=1
		if [ ${IR_FAIL} -ne 0 ]; then
			Error "Some errors with repository"
			sleep 20
		else
			break
		fi
	done
	if [ ${IR_FAIL} -ne 0 ]; then
		Error "Problems with repository. Please try again in an hour"
		ErrorInstall
	fi
else
	InstallBaseRepo || ErrorInstall
fi

MgrNotExist() {
	local cur_os
	cur_os="$(lsb_release -s -i | awk '{print tolower($0)}')-${OSVER}"
	Error "${pkgname} was not found in repos for ${cur_os} ( $(uname -m) )"
	CancelInstall norepo
	trap - INT TERM EXIT
	exit 1
}

PkgAvailable "${pkgname}" || MgrNotExist

if [ "${mgr}" != "core" ]; then
	CoreInstall || ErrorInstall

	# Xmlgen...
	/usr/local/sitemgr/sbin/mgrctl exit >/dev/null

	# new license
	touch /usr/local/sitemgr/var/new_license

	# License: the activation key given (or one the server's address has: a trial taken for it in the account).
	# Without one the installation goes on and the panel asks for the key (SiteManager: no trial is issued by itself).
	licfetch_count=0
	export HTTP_PROXY=""
	export http_proxy=""
	while true
	do
		licerror=0
		licfetch_count=$((licfetch_count + 1))
		/usr/local/sitemgr/sbin/licctl fetch "${licname}" "${ACTIVATION_KEY}" >/dev/null 2>&1 || licerror=$?
		if [ ${licerror} -eq 0 ]; then
			LicInstall
			break
		elif [ "${licfetch_count}" -lt 3 ]; then
			sleep 2
			continue
		fi
		if [ -n "${ACTIVATION_KEY}" ]; then
			Warning "Invalid activation key"
		else
			Warning "There is no license for this server yet"
		fi
		Warning "Get a free 14-day trial for this server's IP address or buy a license at https://${SM_DOMAIN}/account"
		ACTIVATION_KEY=""
		if [ "${silent}" != "true" ]; then
			printf "Please enter activation key or press Enter to continue without a license: "
			read -r ACTIVATION_KEY
		fi
		export ACTIVATION_KEY
		if [ -z "${ACTIVATION_KEY}" ]; then
			NO_LICENSE=true
			Info "Installation continues. The panel will ask for the activation key"
			break
		fi
		licfetch_count=0
	done

	grep -q "manager sitemgr" /usr/local/sitemgr/etc/mgrlist.conf || echo "manager sitemgr" >> /usr/local/sitemgr/etc/mgrlist.conf

	# Fetching license for repo change
	/usr/local/sitemgr/sbin/licctl fetch "${mgr}" >/dev/null 2>&1 || :

	if [ -z "${core_installed}" ]; then
		Info "Checking core downgrade"
		crelease=${release}
		GetCurrentRepo
		chk_inst_ver=$(VersionToRelease "$(GetInstalledVersion)")
		chk_avail_ver=$(VersionToRelease "$(GetAvailVersion "${release}")")
		Info "Installed version from repo ${crelease}: ${chk_inst_ver}"
		Info "Remote version in repo ${release}: ${chk_avail_ver}"
		if [ "${crelease}" != "${release}" ] && [ "${chk_inst_ver}" != "${chk_avail_ver}" ]; then
			Info "Downgrading core"
			PkgRemove "${CORE_PKG}"
			PkgInstall "${CORE_PKG}"
		else
			Info "Not need to downgrade core"
		fi
	else
		Info "Core installed before this run. Downgrade checking skipped"
	fi
fi

if [ -n "${mysqlserver}" ]; then
	PkgInstall "${mysqlserver}"
fi

if [ "${DBTYPE}" = "mysql" ]; then
	# shellcheck disable=SC2086
	PkgInstall "${CORE_PKG_PREFIX}mysql" ${DB_INSTALL_PKG}
else
	mkdir -p /usr/local/sitemgr/etc/sitemgr.conf.d
	touch ${DB_CONF}
fi

# The lite edition depends on a virtual firewall package from FW_META_MIN_VERSION on;
# the provider is chosen the same way the panel does: iptables when that binary exists
FW_META_MIN_VERSION="6.151.0"
case "${pkgname}" in
	"${LITE_COMMON_PKG}")
		fw_avail_ver=$(GetAvailPkgVersion "${LITE_COMMON_PKG}")
		if [ -n "${fw_avail_ver}" ] && dpkg --compare-versions "${fw_avail_ver}" ge "${FW_META_MIN_VERSION}"; then
			Info "Selecting firewall backend"
			if ! BinaryExists iptables && BinaryExists nft; then
				Info "iptables not found, using nftables (${PKG_PREFIX}fw-nftables)"
				PkgInstall "${PKG_PREFIX}fw-nftables" || ErrorInstall
			else
				Info "using iptables (${PKG_PREFIX}fw-iptables)"
				PkgInstall "${PKG_PREFIX}fw-iptables" || ErrorInstall
			fi
		fi
		;;
esac

PkgInstall "${pkgname}" || ErrorInstall

if { [ "${DBTYPE}" = "mysql" ] || [ -n "${mysqlserver}" ] || [ -n "${webserver}" ]; } && [ "${pkgname}" != "${BUSINESS_PKG}" ]; then
	PkgInstall "${PKG_PREFIX}mysql"
fi

# Until full systemd-networkd support
mkdir -p /etc/network/if-up.d

# new license
touch /usr/local/sitemgr/var/new_license

if [ -z "${disable_fail2ban}" ]; then
	Fail2Ban
fi

if [ -n "${webserver}" ]; then
	if [ -x /usr/local/sitemgr/sbin/install_recommended_setup.sh ]; then
		Info "Installing common recommended setup packages"
		/usr/local/sitemgr/sbin/install_recommended_setup.sh --webserver "${webserver}" --dbtype "${DBTYPE}" --mini "${INSTALL_MINI}"
	elif [ "${webserver}" = "nginx" ]; then
		PkgInstall "${LITE_PKG}"
	fi
fi

if [ "${INSTALL_DNS_ONLY}" = "yes" ]; then
	grep -qF "Option DnsOnly" /usr/local/sitemgr/etc/sitemgr.conf || echo "Option DnsOnly" >> /usr/local/sitemgr/etc/sitemgr.conf
	Info "Installing PowerDNS for DNS-only configuration"
	PkgInstall "${PKG_PREFIX}pdns" || ErrorInstall
fi

if [ "${pkgname}" = "${LITE_COMMON_PKG}" ]; then
	/usr/local/sitemgr/sbin/mgrctl -m sitemgr feature.update sok=ok >/dev/null || :
	/usr/local/sitemgr/sbin/mgrctl -m sitemgr -R >/dev/null || :
fi

LetsEncrypt || :

if [ -f ${DB_CONF} ] && [ ! -s ${DB_CONF} ]; then
	rm -f ${DB_CONF}
fi

FinishInstall &
MgrInstalled "${mgr}" "${pkgname}"
if [ "${NO_LICENSE}" = "true" ]; then
	Warning "The panel needs a license to work. Get a free trial for this server's IP address or buy a license at https://${SM_DOMAIN}/account, then enter the activation key in the panel"
fi

trap - INT TERM EXIT
