#!/bin/sh
#
# metadata_begin
# recipe: ISPmanager Lite
# tags: alma8,alma9,debian11,ubuntu2004,ubuntu2204,ubuntu2404,rocky8,lic_ISPmanager_6_Lite
# revision: 3
# description_ru: Рецепт установки ISPmanager Lite
# description_en: ISPmanager Lite installing recipe
# metadata_end
# copyright Pradedov G.V. trashwind@yandex.ru
#

RNAME="ISPmanager_6_Lite"

set -x

#umask 0022

LOG_PIPE=/tmp/log.pipe.$$
mkfifo ${LOG_PIPE}
LOG_FILE=/root/${RNAME}.log
touch ${LOG_FILE}
chmod 600 ${LOG_FILE}
tee < ${LOG_PIPE} ${LOG_FILE} &
exec > ${LOG_PIPE}
exec 2> ${LOG_PIPE}

killjobs() {
    test -n "$(jobs -p)" && kill $(jobs -p) || :
}
trap killjobs INT TERM EXIT

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

echo
echo "== Recipe ${RNAME} started at $(date) =="
echo

# Переменные
HOME=/root
export HOME

# Определение IP-адресов и сетевой карты
ipv4Addr=$(ip route get 1 | grep -Po '(?<=src )[^ ]+')

# Информация об ОС
. /etc/os-release
osLike="${ID_LIKE}"
[ "${ID}" = "debian" ] && osLike="debian"
echo ${ID_LIKE} | grep -q "rhel\|fedora" && osLike="rhel"
[ "${ID}" = "fedora" ] && osLike="rhel"
unaID=$(echo ${VERSION_ID} | sed -r 's/\..+//')

# Определение пакетного менеджера
DNF="/usr/bin/yum"
[ -f /usr/bin/dnf ] && DNF="/usr/bin/dnf"
[ -f /usr/bin/apt ] && { export DEBIAN_FRONTEND=noninteractive ; DNF="apt_Installer" ; }
[ -n "${DNF}" ] || exit 1

# Финальный текст
final_text() {
cat > /root/${RNAME}-final.txt <<- EOF
=========================
Работа скрипта ${RNAME} успешно завершена.
Перейдите по адресу "https://${ipv4Addr}:1500/ispmgr" для входа в панель
Имя пользователя: root
Пароль: <root password>
=========================

=========================
The ${RNAME} script completed successfully.
Go to the "https://${ipv4Addr}:1500/ispmgr" to login
Login: root
Password: <root password>
=========================
EOF
}

# Определяем инсталятор apt и его опции. Обходим фоновые задачи установки и одновления ОС
apt_Installer() {
while ps uxaww | grep -v grep | grep -Eq 'apt|dpkg' ; do echo "waiting..." ; sleep 5 ; done && \
/usr/bin/apt -o Dpkg::Options::="--force-confold" -o Dpkg::Options::="--force-confdef" -q --allow-downgrades --allow-remove-essential --allow-change-held-packages $@
}

# Установка основных программ и подготовка базовых репозиториев
install_soft() {
if [ "${osLike}" = "debian" ]; then
	[ $(systemctl is-active unattended-upgrades.service 2>/dev/null) = "active" ] && { systemctl stop unattended-upgrades.service && unattServ="1" ; }
	${DNF} update
fi
[ "${osLike}" = "rhel" ] && { ${DNF} -y update libmodulemd 2>/dev/null ; ${DNF} -y install glibc-all-langpacks initscripts 2>/dev/null ; }
${DNF} -y install curl
}

# Определение и настройка фаервола
config_firewall() {
([ -f /usr/sbin/ufw ] && $(ufw status | grep -i "Status" | grep -qi " active\|enable")) && ufw allow 1500/tcp
if [ -f /usr/sbin/firewalld -a $(systemctl is-active firewalld.service 2>/dev/null) = "active" ]; then
	firewalldZone="$(firewall-cmd --get-default-zone)"
	[ ! -f /usr/lib/firewalld/services/ispmanager.xml ] && \
	cat << 'EOF' > /etc/firewalld/services/ispmanager.xml
<?xml version="1.0" encoding="utf-8"?>
<service>
  <short>ispmanager</short>
  <description>ISPmanager rule</description>
  <port protocol="tcp" port="1500"/>
</service>
EOF
	firewall-cmd --reload
	firewall-cmd --permanent --zone=${firewalldZone} --remove-service=dhcpv6-client 2>&1 >/dev/null || return 0
	firewall-cmd --permanent --zone=${firewalldZone} --add-service=ispmanager
	firewall-cmd --reload
fi
}

# Установка ISPmanager
install_ispmanager() {
curl -o /root/install.sh -s --connect-timeout 30 --retry 10 --retry-delay 5 -k -L "https://download.ispmanager.com/install.sh"
while ps uxaww | grep -v grep | grep -Eq 'apt|dpkg|dnf|yum' ; do echo "waiting..." ; sleep 5 ; done && \
/bin/bash /root/install.sh --silent --ignore-hostname --release stable ispmanager-lite
}

install_soft
config_firewall
install_ispmanager && final_text
rm -rf /root/install.sh

# Включаем обратно сервис самообновления Ubuntu
[ -n "${unattServ}" ] && systemctl start unattended-upgrades.service

# Проверка
q=0
i=20
while [ $q -le $i ]; do
	/usr/local/mgr5/sbin/mgrctl -m ispmgr db.server.edit elid=MySQL sok=ok && final_text && exit 0
	q=$(($q + 1))
	sleep 1
done

exit 1
