#!/bin/bash
# Parte root: Apache vhost, hosts, cron.d, credenziali /root
# Prerequisito: bash install-vteaxess.sh già eseguito.
#
#   sudo bash /var/www/html/server-ops/mypantarei/install-vteaxess-root-finish.sh

set -euo pipefail

if [[ "$(id -u)" -ne 0 ]]; then
	echo "Eseguire come root: sudo bash $0" >&2
	exit 1
fi

VTE_ROOT=/var/www/html/vteaxess
HOST=vte-axess.mypantarei.net
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
APACHE_SRC=/var/www/html/vte2472/scripts
ENV_FILE="${SCRIPT_DIR}/vteaxess-install.env"

if [[ ! -f "${VTE_ROOT}/config.inc.php" ]]; then
	echo "Prima esegui: bash ${SCRIPT_DIR}/install-vteaxess.sh" >&2
	exit 1
fi

# shellcheck disable=SC1090
source "$ENV_FILE"

echo "=== Apache ==="
cp -a "${APACHE_SRC}/apache_vteaxess.conf" /etc/apache2/sites-available/vteaxess.conf
cp -a "${APACHE_SRC}/apache_vteaxess-le-ssl.conf" /etc/apache2/sites-available/vteaxess-le-ssl.conf
if ! grep -q "vte-axess.mypantarei.net" /etc/hosts; then
	echo "127.0.0.1 vte-axess.mypantarei.net VTE-Axess.mypantarei.net" >> /etc/hosts
fi
a2ensite vteaxess.conf
# SSL: NON a2ensite finché certbot non ha creato i pem
apache2ctl configtest
systemctl reload apache2

echo "=== Permessi www-data ==="
chown -R www-data:www-data "$VTE_ROOT"
find "$VTE_ROOT" -type d -exec chmod 775 {} \;
find "$VTE_ROOT" -type f -exec chmod 664 {} \;
chmod +x "${VTE_ROOT}/cron/"*.sh "${VTE_ROOT}/vteUpdater.sh" 2>/dev/null || true

echo "=== Cron di sistema ==="
cat >/etc/cron.d/vteaxess <<EOF
# VTENEXT vteaxess — PHP 8.3
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

* * * * * www-data /var/www/html/server-ops/mypantarei/vte-RunCron-php83.sh ${VTE_ROOT} >> ${VTE_ROOT}/logs/cron.log 2>&1
EOF
chmod 644 /etc/cron.d/vteaxess

echo "=== Credenziali root ==="
cat >/root/.vteaxess-db.cnf <<EOF
[client]
user=${DB_USER}
password=${DB_PASS}
database=${DB_NAME}
EOF
chmod 600 /root/.vteaxess-db.cnf

touch "${VTE_ROOT}/.install-vteaxess-apache-done"
chown www-data:www-data "${VTE_ROOT}/.install-vteaxess-apache-done"

echo "Fatto. URL: http://${HOST}"
echo "SSL dopo DNS: vedi ${SCRIPT_DIR}/SSL-VTEAXESS.md"
