#!/bin/bash
#
# metadata_begin
# recipe: Bitrix Env 9
# tags: centos9,centos9-stream
# revision: 4
# description_ru: Рецепт установки BitrixVM 9
# description_en: Recipe for installing the BitrixVM 9
# metadata_end
#

RNAME="Bitrix-Env-9"

set -x

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

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

# Переменные
BITRIX_SCRIPT="https://repo.bitrix.info/dnf/bitrix-env-9.sh"
BITRIX_SETUP_PHP="https://www.1c-bitrix.ru/download/scripts/bitrixsetup.php"
BITRIX_RESTORE_PHP="https://www.1c-bitrix.ru/download/scripts/restore.php"

# Информация об ОС
. /etc/os-release
[ "${ID}" = "centos" -a ${VERSION} -eq 9 ] || { echo "The script can only work on CentOS 9 Stream" && exit 1 ; }

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

# Финальный текст
final_text() {
cat > /root/${RNAME}-script-final.txt <<- EOF
=========================
Работа скрипта ${RNAME} успешно завершена.
Журнал выполнения вы можете посмотреть в файле /root/${RNAME}.log
Панель ${RNAME} доступна по адресам:
http://${ipv4Addr}/
Установка конфигураций Bitrix доступна по адресу:
http://${ipv4Addr}/bitrixsetup.php
=========================

=========================
The ${RNAME} script completed successfully.
You can see the execution log in /root/${RNAME}.log.
The ${RNAME} panel is available at:
http://${ipv4Addr}/
Installation of Bitrix configurations is available at:
http://${ipv4Addr}/bitrixsetup.php
=========================
EOF
}

# Отключение обновления определённых пакетов
disable_update_packages() {
case $1 in
	"start" )
		dnf versionlock add qemu-guest-agent
		;;
	"stop" )
		dnf versionlock del qemu-guest-agent
		return 0
	;;
	* )
		echo "I do not know this option"
		return 1
	;;
esac
}

# Установка основных программ и подготовка базовых репозиториев
install_soft() {
dnf clean all 
dnf install -y dnf-utils yum-utils 'dnf-command(versionlock)' || { echo "Can not preinstall soft" && exit 1 ; }
dnf -y install tuned
systemctl enable --now tuned 2>/dev/null || return 0
}

# Определение и настройка фаервола
config_firewall() {
if [ -f /usr/sbin/ufw ] && $(ufw status | grep -i "Status" | grep -qi " active\|enable"); then
	ufw allow http
	ufw allow https
fi
if [ -f /usr/sbin/firewalld -a $(systemctl is-active firewalld.service 2>/dev/null) = "active" ]; then
	firewalldZone="$(firewall-cmd --get-default-zone)"
	firewall-cmd --permanent --zone=${firewalldZone} --remove-service=dhcpv6-client 2>&1 >/dev/null || return 0
	firewall-cmd --permanent --zone=${firewalldZone} --add-service=http
	firewall-cmd --permanent --zone=${firewalldZone} --add-service=https
	firewall-cmd --reload
fi
}

# Установка Bitrix Env 9
install_bitrix_env_9() {
wget -O /root/bitrix-env-9.sh ${BITRIX_SCRIPT} || { echo "Can not download install script" && exit 1 ; }
chmod +x /root/bitrix-env-9.sh
/root/bitrix-env-9.sh || /root/bitrix-env-9.sh || { echo "Can not install bitrix-env-9.sh script" && exit 1 ; }
wget -O /home/bitrix/www/bitrixsetup.php ${BITRIX_SETUP_PHP} && { chown bitrix:bitrix /home/bitrix/www/bitrixsetup.php ; } \
|| { echo "Can not download bitrixsetup.php" ; }
#wget -O /home/bitrix/www/restore.php ${BITRIX_RESTORE_PHP} && { chown bitrix:bitrix /home/bitrix/www/restore.php ; } \
#|| { echo "Can not download restore.php" ; }
}

install_soft
disable_update_packages start || { echo "Can not block update soft" && exit 1 ; }
config_firewall
install_bitrix_env_9
disable_update_packages stop

# Проверка
q=0
i=20
while [ $q -le $i ]; do
	curl -v --silent http://127.0.0.1 2>&1 | grep -q "Bitrix" && { final_text && exit 0 ; }
	q=$(($q + 1))
	sleep 2
done

exit 1
