#!/bin/bash
# Installa istanza demo vtemessiniegori (tutto-in-uno, richiede root).
# Se la build è già in /home/pantarei/vtemessiniegori-build (e MySQL fatto), usare solo:
#   sudo bash /var/www/html/server-ops/mypantarei/install-vtemessiniegori-sudo-step.sh
#
# Fase 1: solo HTTP, niente certbot (DNS non ancora registrato).
#
#   sudo bash /var/www/html/server-ops/mypantarei/install-vtemessiniegori.sh
#
# Dopo DNS + certbot (fase 2):
#   sudo certbot certonly --webroot -w /var/www/html/vtemessiniegori -d vte-messiniegori.mypantarei.net
#   sudo a2ensite vtemessiniegori-le-ssl.conf && sudo systemctl reload apache2
#   Aggiornare $site_URL in config.inc.php a https://

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/vtemessiniegori
SRC=/var/www/html/vtesmau
SRC_DB=vte_dev_new
DB_NAME=vtemessiniegori
DB_USER=vtemessiniegori
HOST=vte-messiniegori.mypantarei.net
SITE_URL="http://${HOST}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
APACHE_SRC=/var/www/html/vte2472/scripts
CRON_D=/etc/cron.d/vtemessiniegori
PHP74=/usr/bin/php7.4
WRAPPER74="${SCRIPT_DIR}/vte-RunCron-php74.sh"
DESTROY="${SCRIPT_DIR}/vtemessiniegori_destroy_trial.sh"
TRIAL_EXPIRY='2026-06-26'
APP_KEY='3f8828d70c43ad94daf87442c4aafa7a'
CSRF_SECRET='602a1f58da2e694f6b42238fa4c8a971ee835d37ae26f4d4'

if [[ -d "$VTE_ROOT" ]] && [[ ! -f "$VTE_ROOT/.install-vtemessiniegori-done" ]]; then
	echo "ATTENZIONE: $VTE_ROOT esiste già. Rimuovere manualmente o toccare .install-vtemessiniegori-done per forzare." >&2
	exit 1
fi

echo "=== 1) Rsync da vtesmau ==="
rsync -a \
	--exclude='/cache/' \
	--exclude='/storage/' \
	--exclude='/logs/' \
	--exclude='/Smarty/templates_c/' \
	--exclude='/user_privileges/' \
	"${SRC}/" "${VTE_ROOT}/"

mkdir -p "${VTE_ROOT}/cache/upload" "${VTE_ROOT}/cache/images" \
	"${VTE_ROOT}/storage" "${VTE_ROOT}/logs/cron" \
	"${VTE_ROOT}/Smarty/templates_c" "${VTE_ROOT}/user_privileges"
# /storage/ esclude solo la root dati, non modules/*/storage/
rsync -a "${SRC}/modules/Documents/storage/" "${VTE_ROOT}/modules/Documents/storage/"
rsync -a "${SRC}/modules/VteSync/VteSyncLib/storage/" "${VTE_ROOT}/modules/VteSync/VteSyncLib/storage/" 2>/dev/null || true
rsync -a "${SRC}/portal/v2/storage/" "${VTE_ROOT}/portal/v2/storage/" 2>/dev/null || true
# SDK AuthControllerNoVTCH (import DB vte_dev_new registra custom_debug/ — serve file 25.x)
mkdir -p "${VTE_ROOT}/custom_debug"
if [[ -f "${SCRIPT_DIR}/templates/AuthControllerNoVTCH-25.php" ]]; then
	cp -a "${SCRIPT_DIR}/templates/AuthControllerNoVTCH-25.php" "${VTE_ROOT}/custom_debug/AuthControllerNoVTCH.php"
fi

echo "=== 2) 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 {} \;

echo "=== 3) MySQL database e utente dedicato ==="
DB_PASS="$(openssl rand -base64 24 | tr -dc 'A-Za-z0-9@#%_+-' | head -c 24)"
mysql -e "CREATE DATABASE IF NOT EXISTS \`${DB_NAME}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
mysql -e "CREATE USER IF NOT EXISTS '${DB_USER}'@'localhost' IDENTIFIED BY '${DB_PASS}';" 2>/dev/null || \
	mysql -e "CREATE USER '${DB_USER}'@'localhost' IDENTIFIED BY '${DB_PASS}';"
mysql -e "GRANT ALL PRIVILEGES ON \`${DB_NAME}\`.* TO '${DB_USER}'@'localhost';"
mysql -e "FLUSH PRIVILEGES;"

echo ">>> Import da ${SRC_DB} (può richiedere alcuni minuti)..."
mysqldump --single-transaction --routines --triggers "${SRC_DB}" | mysql "${DB_NAME}"

echo "=== 4) config.inc.php e trial ==="
CONFIG="${VTE_ROOT}/config.inc.php"
php -r "
\$f = file_get_contents('${CONFIG}');
\$f = preg_replace(\"/\\\$dbconfig\\['db_username'\\] = '[^']*';/\", \"\\\$dbconfig['db_username'] = '${DB_USER}';\", \$f);
\$f = preg_replace(\"/\\\$dbconfig\\['db_password'\\] = '[^']*';/\", \"\\\$dbconfig['db_password'] = '${DB_PASS}';\", \$f);
\$f = preg_replace(\"/\\\$dbconfig\\['db_name'\\] = '[^']*';/\", \"\\\$dbconfig['db_name'] = '${DB_NAME}';\", \$f);
\$f = preg_replace(\"#\\\$site_URL = '[^']*';#\", \"\\\$site_URL = '${SITE_URL}';\", \$f);
\$f = preg_replace(\"#\\\$root_directory = '[^']*';#\", \"\\\$root_directory = '${VTE_ROOT}/';\", \$f);
\$f = preg_replace(\"#\\\$PORTAL_URL = '[^']*';#\", \"\\\$PORTAL_URL = '${SITE_URL}/portal';\", \$f);
\$f = preg_replace(\"#\\\$gdpr_URL = '[^']*';#\", \"\\\$gdpr_URL = '${SITE_URL}/gdpr';\", \$f);
\$f = preg_replace(\"/\\\$HELPDESK_SUPPORT_EMAIL_ID = '[^']*';/\", \"\\\$HELPDESK_SUPPORT_EMAIL_ID = 'vtemessiniegori@mypantarei.net';\", \$f);
\$f = preg_replace(\"/\\\$REMINDER_EMAIL_ID ='[^']*';/\", \"\\\$REMINDER_EMAIL_ID ='vtemessiniegori@mypantarei.net';\", \$f);
\$f = preg_replace(\"/\\\$application_unique_key = '[^']*';/\", \"\\\$application_unique_key = '${APP_KEY}';\", \$f);
\$f = preg_replace(\"/\\\$csrf_secret = '[^']*';/\", \"\\\$csrf_secret = '${CSRF_SECRET}';\", \$f);
\$f = preg_replace(
	'/\\/\\/ Blocco accesso post-scadenza.*?TrialCountdown::enforceAccessLock\\(\\);\\s*\\n/s',
	\"// Demo vtemessiniegori: teardown automatico (no enforceAccessLock)\\n\",
	\$f
);
file_put_contents('${CONFIG}', \$f);
"

cat >"${VTE_ROOT}/trial_settings.php" <<EOF
<?php
/**
 * Demo Massini e Gori — 30 giorni (fine inclusiva).
 * Teardown: ${DESTROY}
 * Cron root: 59 23 * * * bash ${DESTROY} >>/var/log/vtemessiniegori-trial-destroy.log 2>&1
 */
\$trial_expiry_date = '${TRIAL_EXPIRY}';
EOF
chown www-data:www-data "${VTE_ROOT}/trial_settings.php"
chmod 664 "${VTE_ROOT}/trial_settings.php"

echo "=== 5) Morphsuit bypass ==="
touch "${VTE_ROOT}/disable_morphsuit.flag"
chown www-data:www-data "${VTE_ROOT}/disable_morphsuit.flag"

echo "=== 6) Apache HTTP (no SSL / no certbot) ==="
cp -a "${APACHE_SRC}/apache_vtemessiniegori.conf" /etc/apache2/sites-available/vtemessiniegori.conf
cp -a "${APACHE_SRC}/apache_vtemessiniegori-le-ssl.conf" /etc/apache2/sites-available/vtemessiniegori-le-ssl.conf
a2ensite vtemessiniegori.conf
# NON a2ensite vtemessiniegori-le-ssl.conf finché non esiste il certificato
apache2ctl configtest
systemctl reload apache2

echo "=== 7) Cron VTE dedicato (www-data) ==="
cat >"$CRON_D" <<EOF
# VTENEXT vtemessiniegori — install-vtemessiniegori.sh
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

* * * * * www-data USE_PHP=${PHP74} ${VTE_ROOT}/cron/RunCron.sh >> ${VTE_ROOT}/logs/cron.log 2>&1
EOF
chmod 644 "$CRON_D"
mkdir -p "${VTE_ROOT}/logs/cron"
touch "${VTE_ROOT}/logs/cron.log"
chown -R www-data:www-data "${VTE_ROOT}/logs"

chmod +x "$DESTROY"

echo "=== 8) Credenziali MySQL (salvare in vault) ==="
CREDS_FILE=/root/.vtemessiniegori-db.cnf
cat >"$CREDS_FILE" <<EOF
[client]
user=${DB_USER}
password=${DB_PASS}
database=${DB_NAME}
EOF
chmod 600 "$CREDS_FILE"

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

echo ""
echo "Fatto."
echo "  URL (HTTP):     ${SITE_URL}"
echo "  Cartella:       ${VTE_ROOT}"
echo "  DB / user:      ${DB_NAME} / ${DB_USER}"
echo "  Password DB:    ${DB_PASS}"
echo "  Credenziali:    ${CREDS_FILE}"
echo "  Trial scade:    ${TRIAL_EXPIRY}"
echo "  Destroy script: ${DESTROY}"
echo ""
echo "Fase 2 (dopo DNS): certbot + a2ensite vtemessiniegori-le-ssl.conf + https in config.inc.php"
echo "Cron destroy root (opzionale, aggiungere a crontab -e):"
echo "  59 23 * * * /bin/bash ${DESTROY} >>/var/log/vtemessiniegori-trial-destroy.log 2>&1"
