#!/bin/bash
# Esporta branding MTM da vte_dev: file tema + SQL vte_vteprop theme.* + organizationdetails
#
# Uso: sudo -u www-data bash /var/www/html/server-ops/mtm-migration/mtm-export-branding.sh
#
# SPDX-FileCopyrightText: 2026 Pantarei

set -euo pipefail

VTE_ROOT="${VTE_ROOT:-/var/www/html/vte_dev}"
DB_NAME="${DB_NAME:-vte_dev_new}"
DB_USER="${DB_USER:-gabry}"
OUT_BASE="${OUT_BASE:-/var/www/html/_backups/mtm-config-26}"
BRAND_DIR="${OUT_BASE}/branding"
SQL_DIR="${OUT_BASE}/sql"

mkdir -p "${BRAND_DIR}/themes/logos/custom"
mkdir -p "${BRAND_DIR}/themes/wallpapers"
mkdir -p "${BRAND_DIR}/storage/logo"
mkdir -p "${SQL_DIR}"

# Logo custom login
if [[ -f "${VTE_ROOT}/themes/logos/custom/login.png" ]]; then
	cp -a "${VTE_ROOT}/themes/logos/custom/." "${BRAND_DIR}/themes/logos/custom/"
fi

# Wallpaper MTM (da vte_vteprop)
WALLPAPER=$(mysql -N -u "${DB_USER}" -p'PantAdmin@9' "${DB_NAME}" -e \
	"SELECT value FROM vte_vteprop WHERE property='theme.login_background_images' LIMIT 1" 2>/dev/null || true)
if [[ -n "${WALLPAPER}" ]]; then
	# JSON array es. ["9b102b40-....png"]
	for f in $(echo "${WALLPAPER}" | grep -oE '[a-zA-Z0-9_.-]+\.(png|jpg|jpeg|gif)' || true); do
		if [[ -f "${VTE_ROOT}/themes/wallpapers/${f}" ]]; then
			cp -a "${VTE_ROOT}/themes/wallpapers/${f}" "${BRAND_DIR}/themes/wallpapers/"
		fi
	done
fi

# Logo società (PDF/email)
if [[ -d "${VTE_ROOT}/storage/logo" ]]; then
	cp -a "${VTE_ROOT}/storage/logo/." "${BRAND_DIR}/storage/logo/" 2>/dev/null || true
fi

# SQL theme.* (merge su target)
mysql -u "${DB_USER}" -p'PantAdmin@9' "${DB_NAME}" -N -e \
	"SELECT property, value FROM vte_vteprop WHERE property LIKE 'theme.%'" 2>/dev/null \
	| while IFS=$'\t' read -r prop val; do
		val_esc=$(printf '%s' "$val" | sed "s/'/''/g")
		echo "REPLACE INTO vte_vteprop (property, value) VALUES ('${prop}', '${val_esc}');"
	done > "${SQL_DIR}/mtm-vteprop-theme.sql"

echo "-- organizationdetails (aggiorna riga id=1 se esiste)" >> "${SQL_DIR}/mtm-vteprop-theme.sql"
mysqldump -u "${DB_USER}" -p'PantAdmin@9' "${DB_NAME}" \
	--no-create-info --complete-insert \
	vte_organizationdetails 2>/dev/null >> "${SQL_DIR}/mtm-organizationdetails.sql" || true

tar -czf "${OUT_BASE}/mtm-branding.tar.gz" -C "${OUT_BASE}" branding sql/mtm-vteprop-theme.sql sql/mtm-organizationdetails.sql 2>/dev/null \
	|| tar -czf "${OUT_BASE}/mtm-branding.tar.gz" -C "${OUT_BASE}" branding sql/mtm-vteprop-theme.sql

echo "Branding in ${BRAND_DIR}"
echo "Archivio: ${OUT_BASE}/mtm-branding.tar.gz"
echo "SQL theme: ${SQL_DIR}/mtm-vteprop-theme.sql"
