#!/usr/bin/env bash
# Rulează pe Listara după fiecare deploy (REMOTE_POST_DEPLOY).
set -euo pipefail

APP="/opt/apps/main-updater"
NGINX_SITE="/etc/nginx/sites-available/main-updater"

cd "${APP}"

# Nginx → Laravel public/
if [[ -f artisan && -d public ]]; then
  sed -i "s|^[[:space:]]*root .*;|    root ${APP}/public;|" "${NGINX_SITE}" 2>/dev/null || true
fi

# Composer (dacă lipsește vendor sau s-a schimbat lock)
if [[ -f composer.json ]]; then
  COMPOSER_ALLOW_SUPERUSER=1 composer install --no-dev --optimize-autoloader --ignore-platform-reqs --no-interaction 2>/dev/null || true
fi

# După rsync de pe local, fișierele vin cu UID 1000 (asterix) — www-data nu poate scrie/citi
# Obligatoriu: vendor + storage + bootstrap/cache
chown -R www-data:www-data \
  storage bootstrap/cache vendor app Modules resources routes config database public 2>/dev/null || \
  chown -R www-data:www-data storage bootstrap/cache vendor

find vendor -type d -exec chmod 755 {} \; 2>/dev/null || true
find vendor -type f -exec chmod 644 {} \; 2>/dev/null || true
chmod -R 775 storage bootstrap/cache 2>/dev/null || true

# Nu rula optimize:clear aici — remote-tasks-linux.sh face deja clear + cache:warm.
# Un clear suplimentar după warm golește layout/homepage și încetinește site-ul post-deploy.

nginx -t && systemctl reload nginx

# Patch performanță (supraviețuiește rsync --delete din deploy local)
if [[ -x /opt/apps/scripts/apply-listara-performance.sh ]]; then
  bash /opt/apps/scripts/apply-listara-performance.sh || true
fi

# Re-publică kit deploy HTTPS (rsync poate șterge public/deploy-kit)
if [[ -x /opt/apps/scripts/publish-deploy-kit.sh ]]; then
  /opt/apps/scripts/publish-deploy-kit.sh >/dev/null 2>&1 || true
fi

echo "[post-deploy] Listara OK — https://listara.online"
