#!/bin/bash
#
# Distruzione automatica istanza vteguzzini alla data di fine trial.
# Legge la data da: /var/www/html/vteguzzini/trial_settings.php ($trial_expiry_date, formato Y-m-d).
# Esegue solo se: oggi == data scadenza E ora locale >= 23:59.
#
# CRON (root, consigliato controllo ogni minuto alle 23):
#   * 23 * * * /bin/bash /var/www/html/vteguzzini_destroy_trial.sh >>/var/log/vteguzzini-trial-destroy.log 2>&1
# oppure solo il giorno 15/5 (attenzione: se cambi data in trial_settings.php aggiorna il cron):
#   59 23 15 5 * /bin/bash /var/www/html/vteguzzini_destroy_trial.sh >>/var/log/vteguzzini-trial-destroy.log 2>&1
#
# MySQL: lo script prova in ordine:
#   1) mysql -u root (socket, tipico su Ubuntu)
#   2) --defaults-extra-file=/root/.vteguzzini-destroy.cnf  (vedi sotto)
#
# File opzionale /root/.vteguzzini-destroy.cnf (chmod 600):
#   [client]
#   user=gabry
#   password=LA_TUA_PASSWORD

set -uo pipefail

TRIAL_DIR=/var/www/html/vteguzzini
SETTINGS="${TRIAL_DIR}/trial_settings.php"
LOG_TAG="vteguzzini-trial-destroy"
APACHE_CONF_HTTP=/etc/apache2/sites-available/vtesmau.conf
APACHE_CONF_SSL=/etc/apache2/sites-available/vtesmau-le-ssl.conf

log() {
	logger -t "$LOG_TAG" "$*" || true
	echo "$(date -Is) $*"
}

if [ ! -f "$SETTINGS" ]; then
	log "Nessun trial_settings.php: istanza già rimossa o non presente. Uscita."
	exit 0
fi

EXP=$(php -r "require '${SETTINGS}'; echo isset(\$trial_expiry_date) ? trim((string)\$trial_expiry_date) : '';")
if [ -z "$EXP" ]; then
	log "trial_expiry_date vuota: nessuna distruzione programmata."
	exit 0
fi

TODAY=$(date +%Y-%m-%d)
if [ "$TODAY" != "$EXP" ]; then
	exit 0
fi

# Solo dalla finestra 23:59 (minuto 59, ora 23) in poi
HM=$(date +%H%M)
if [ "$HM" -lt 2359 ]; then
	exit 0
fi

LOCK=/tmp/vteguzzini-trial-destroy.lock
if ! mkdir "$LOCK" 2>/dev/null; then
	log "Lock presente, skip."
	exit 0
fi
trap 'rmdir "$LOCK" 2>/dev/null || true' EXIT

log "INIZIO distruzione istanza vteguzzini (data=$EXP)."

mysql_exec() {
	if mysql -u root -e "SELECT 1" &>/dev/null; then
		mysql -u root -e "$1"
	elif [ -f /root/.vteguzzini-destroy.cnf ]; then
		mysql --defaults-extra-file=/root/.vteguzzini-destroy.cnf -e "$1"
	else
		log "ERRORE: impossibile connettersi a MySQL (root o /root/.vteguzzini-destroy.cnf)."
		exit 1
	fi
}

mysql_exec "DROP DATABASE IF EXISTS vteguzzini;"
mysql_exec "DROP USER IF EXISTS 'vteguzzini'@'localhost';" 2>/dev/null || mysql_exec "DROP USER 'vteguzzini'@'localhost';" 2>/dev/null || true
mysql_exec "FLUSH PRIVILEGES;" || true

strip_guzzini_vhosts() {
	python3 <<'PY'
import re, sys
paths = ["/etc/apache2/sites-available/vtesmau.conf", "/etc/apache2/sites-available/vtesmau-le-ssl.conf"]
for path in paths:
    try:
        with open(path, "r", encoding="utf-8", errors="replace") as f:
            c = f.read()
    except FileNotFoundError:
        continue
    orig = c
    # HTTP: blocco Guzzini (con commento opzionale)
    c = re.sub(
        r"\n# Istanza VTE Guzzini \(HTTP[^\n]*\n<VirtualHost \*:80>.*?</VirtualHost>\s*",
        "\n",
        c,
        flags=re.DOTALL,
    )
    # HTTP fallback
    c = re.sub(
        r"<VirtualHost \*:80>\s*(?:(?!</VirtualHost>).)*?ServerName\s+vteguzzini\.mypantarei\.net.*?</VirtualHost>\s*",
        "",
        c,
        count=1,
        flags=re.DOTALL | re.IGNORECASE,
    )
    # HTTPS
    c = re.sub(
        r"<VirtualHost \*:443>\s*(?:(?!</VirtualHost>).)*?ServerName\s+vteguzzini\.mypantarei\.net.*?</VirtualHost>\s*",
        "",
        c,
        count=1,
        flags=re.DOTALL | re.IGNORECASE,
    )
    if c != orig:
        with open(path, "w", encoding="utf-8") as f:
            f.write(c)
        print("updated", path)
PY
}

if [ -w "$APACHE_CONF_HTTP" ] || [ -w "$APACHE_CONF_SSL" ]; then
	strip_guzzini_vhosts || true
elif [ "$(id -u)" -eq 0 ]; then
	strip_guzzini_vhosts || true
else
	log "ATTENZIONE: senza root non posso modificare Apache. Rimuovere a mano i VirtualHost vteguzzini da vtesmau.conf / vtesmau-le-ssl.conf."
fi

if [ -d "$TRIAL_DIR" ]; then
	rm -rf "$TRIAL_DIR"
	log "Rimossa directory $TRIAL_DIR"
fi

# Certificati (sistema o cartella utente certbot usata in passato)
if command -v certbot &>/dev/null; then
	certbot delete --cert-name vteguzzini.mypantarei.net --non-interactive 2>/dev/null || true
fi
for d in /home/*/.certbot/config/live/vteguzzini.mypantarei.net; do
	[ -d "$d" ] || continue
	base=$(dirname "$(dirname "$d")")
	rm -rf "$base/live/vteguzzini.mypantarei.net" "$base/archive/vteguzzini.mypantarei.net" 2>/dev/null || true
	rm -f "$base/renewal/vteguzzini.mypantarei.net.conf" 2>/dev/null || true
	log "Rimossi file certbot locali per vteguzzini sotto $base"
done

if systemctl is-active --quiet apache2 2>/dev/null; then
	if apache2ctl configtest 2>/dev/null; then
		systemctl reload apache2 && log "Apache ricaricato."
	else
		log "ATTENZIONE: apache2ctl configtest fallito (altri siti?). Ricarico comunque."
		systemctl reload apache2 2>/dev/null || true
	fi
fi

log "FINE distruzione vteguzzini."
exit 0
