#!/usr/bin/env bash
# Serverda yangilash — bitta buyruq (cPanel foydalanuvchisi nomidan):
#   ~/esxalta.uz/deploy.sh          — oxirgi deploy'dan beri o'zgargan qismlar (odatda bir necha soniya)
#   ~/esxalta.uz/deploy.sh --full   — frontend'ni baribir qayta quradi
#
# Qadamlar: git (faqat fast-forward) → composer install (kerak bo'lsa) → npm ci (kerak bo'lsa) → npm run build
# (frontend o'zgargan bo'lsa) → migrate → tariflar (faqat birinchi deploy'da, mavjudlariga tegmaydi) → kesh →
# queue:restart → telegram:setup (birinchi deploy'da va uning sozlamasi o'zgarganda).
#
# Cron (cPanel → Cron Jobs) — SOATIGA bir marta, daqiqa aniqligi kerak emas:
#   0 * * * * cd ~/esxalta.uz && /opt/cpanel/ea-php85/root/usr/bin/php artisan schedule:run >> /dev/null 2>&1
#
# Frontend serverda quriladi (public/build git'da yo'q). Sayt to'xtamasligi uchun avval alohida papkaga
# (public/build-next) quriladi, keyin public/build ga ko'chiriladi: eski fayllar o'chirilmaydi (sahifasi ochiq turgan
# odamning brauzeri eski bo'laklarni yuklay olsin), manifest.json oxirida bir zumda almashtiriladi. 7 kundan eski
# bo'laklar tozalanadi. Build xato bersa — sayt eski build bilan ishlayveradi, skript to'xtaydi.
#
# `npm install` / `composer update` serverda lock fayllarni qayta yozadi va keyingi `git pull` to'xtaydi — ular tiklanadi
# (serverda faqat `npm ci` va `composer install` ishlatiladi). Boshqa kuzatiladigan faylda o'zgarish bo'lsa (masalan cPanel
# public/.htaccess ga PHP handler yozgan bo'lsa), skript hech narsani buzmay to'xtaydi va o'sha faylni ko'rsatadi.
# .env, storage/ va public/build git'da yo'q — ularga tegilmaydi.
#
# PHP'ni qo'lda tanlash: PHP=/opt/cpanel/ea-php85/root/usr/bin/php ~/esxalta.uz/deploy.sh
set -euo pipefail

# Odatda skript loyiha papkasidan ishlaydi. Birinchi marta (skript hali serverda yo'q) `bash <(git show origin/main:deploy.sh)`
# bilan ishga tushirilsa — joriy papka (loyiha) olinadi.
ROOT="$(cd "$(dirname "$0")" 2>/dev/null && pwd || true)"
[ -f "$ROOT/artisan" ] || ROOT="$PWD"
cd "$ROOT"
[ -f artisan ] || { echo "✗ Loyiha papkasida ishga tushiring (artisan topilmadi)" >&2; exit 1; }

FULL=0
[ "${1:-}" = "--full" ] && FULL=1

# PHP: berilmasa — serverdagi eng yangi cPanel PHP'si (ea-php85 → ea-php84), bo'lmasa PATH'dagi `php`.
# Eski ea-php83 ham o'rnatilgan bo'lishi mumkin — u bilan composer "lock file is not compatible" deydi.
if [ -z "${PHP:-}" ]; then
    PHP=php
    for v in 85 84; do
        if [ -x "/opt/cpanel/ea-php$v/root/usr/bin/php" ]; then PHP="/opt/cpanel/ea-php$v/root/usr/bin/php"; break; fi
    done
fi
# composer.lock (Symfony 8) PHP 8.4.1+ talab qiladi.
if ! "$PHP" -r 'exit(PHP_VERSION_ID >= 80401 ? 0 : 1);'; then
    echo "✗ PHP 8.4+ kerak, $PHP — $("$PHP" -r 'echo PHP_VERSION;'). Masalan: PHP=/opt/cpanel/ea-php85/root/usr/bin/php ./deploy.sh" >&2
    exit 1
fi
COMPOSER=/opt/cpanel/composer/bin/composer
[ -f "$COMPOSER" ] || COMPOSER="$(command -v composer)"

# Ikki deploy bir vaqtda ishlamasin.
mkdir -p storage/app
if command -v flock >/dev/null; then
    exec 9>storage/app/.deploy.lock
    flock -n 9 || { echo "✗ Boshqa deploy hozir ishlayapti" >&2; exit 1; }
fi

echo "→ PHP $("$PHP" -r 'echo PHP_VERSION;') ($PHP)"
echo "→ git"
git fetch --quiet origin main
# Lock fayllar serverda faqat o'qiladi: kimdir `composer update` / `npm install` qilgan bo'lsa ham — repodagisi tiklanadi.
git checkout -- package-lock.json composer.lock
if [ -n "$(git status --porcelain --untracked-files=no)" ]; then
    echo "✗ Serverda o'zgartirilgan fayllar bor — yangilash to'xtatildi:" >&2
    git status --short --untracked-files=no >&2
    echo "  Ko'rish: git diff <fayl>. Keraksiz bo'lsa: git checkout -- <fayl>, keyin skriptni qayta ishga tushiring." >&2
    exit 1
fi
# public/build ilgari git'da edi: shu commit'ga o'tishda git uni o'chiradi — sayt yangi build tayyor bo'lguncha
# eski build bilan ishlashi uchun nusxasi olinib, darhol qaytariladi (endi u git'da emas, keyin tegilmaydi).
BUILD_BACKUP=
if git ls-files --error-unmatch public/build/manifest.json >/dev/null 2>&1; then
    BUILD_BACKUP="storage/app/build-backup"
    rm -rf "$BUILD_BACKUP"
    cp -a public/build "$BUILD_BACKUP"
fi
git merge --ff-only --quiet origin/main
if [ -n "$BUILD_BACKUP" ]; then
    [ -f public/build/manifest.json ] || cp -a "$BUILD_BACKUP" public/build
    rm -rf "$BUILD_BACKUP"
fi
NEW=$(git rev-parse HEAD)

# O'zgarishlar oxirgi muvaffaqiyatli deploy qilingan commit'ga nisbatan hisoblanadi (git HEAD'ga emas):
# kimdir qo'lda `git pull` qilgan bo'lsa ham, qurilmagan frontend/paketlar o'tkazib yuborilmaydi.
MARKER=storage/app/.deployed-commit
OLD=$(cat "$MARKER" 2>/dev/null || true)
FIRST=0
if [ -z "$OLD" ] || ! git cat-file -e "$OLD^{commit}" 2>/dev/null; then
    echo "  oldingi deploy belgisi yo'q — hammasi qaytadan"
    FULL=1
    FIRST=1
    OLD=$NEW
fi

# Shu yo'llardan biri OLD..NEW orasida o'zgarganmi (--full bo'lsa — doim "ha").
changed() { [ "$FULL" = 1 ] || [ -n "$(git diff --name-only "$OLD" "$NEW" -- "$@")" ]; }

if [ "$OLD" = "$NEW" ] && [ "$FULL" = 0 ]; then
    echo "  yangi commit yo'q"
fi

# Paketlar — o'rnatilgan holatga qarab (--full ham ularni behuda qayta o'rnatmaydi): vendor/ yoki node_modules/ yo'q
# bo'lsa yoki lock fayl oxirgi o'rnatishdan yangiroq bo'lsa (git pull lock'ni yangilaganda uning vaqti o'zgaradi).
if [ ! -f vendor/autoload.php ] || [ composer.lock -nt vendor/autoload.php ]; then
    echo "→ composer install"
    "$PHP" "$COMPOSER" install --no-dev --optimize-autoloader --no-interaction --quiet
fi

if [ ! -f node_modules/.package-lock.json ] || [ package-lock.json -nt node_modules/.package-lock.json ]; then
    echo "→ npm ci"
    # Vite devDependencies'da — ular ham kerak (--include=dev). npm ci lockfile'ni o'zgartirmaydi. Server npm'i
    # lockfile'ni "mos emas" desa (npm versiyalari farqi) — npm install va qayta yozilgan lockfile darhol tiklanadi.
    if ! npm ci --include=dev --no-audit --no-fund --loglevel=error; then
        echo "  npm ci o'tmadi — npm install bilan o'rnatiladi"
        npm install --include=dev --no-audit --no-fund --loglevel=error
        git checkout -- package-lock.json
        touch node_modules/.package-lock.json   # keyingi deploy shu lock uchun qayta o'rnatmasin
    fi
fi

if [ ! -f public/build/manifest.json ] || changed resources/js resources/css vite.config.js package.json package-lock.json; then
    echo "→ npm run build"
    rm -rf public/build-next
    BUILD_OUT_DIR=public/build-next npm run build --silent
    [ -f public/build-next/manifest.json ] || { echo "✗ Build manifest'i yo'q — sayt eski build bilan qoldi" >&2; exit 1; }
    mkdir -p public/build
    # Avval bo'laklar (eskilari qoladi), oxirida manifest — bir zumda (mv bir diskda atomar).
    mv -f public/build-next/manifest.json public/build/manifest.json.new
    cp -R public/build-next/. public/build/
    mv -f public/build/manifest.json.new public/build/manifest.json
    rm -rf public/build-next
    find public/build/assets -type f -mtime +7 -delete 2>/dev/null || true
fi

echo "→ baza va kesh"
"$PHP" artisan migrate --force
# Boshlang'ich tariflar (firstOrCreate — admin o'zgartirgan tariflarga tegilmaydi).
if [ "$FIRST" = 1 ]; then
    "$PHP" artisan db:seed --force
fi
[ -e public/storage ] || "$PHP" artisan storage:link --quiet
# optimize:clear EMAS: u ilova keshini ham tozalaydi (kirish havolalari, rate-limit, cron heartbeat'lari yo'qoladi).
# Faqat kodga bog'liq keshlar qayta quriladi: config, route, view, event.
"$PHP" artisan config:clear --quiet
"$PHP" artisan route:clear --quiet
"$PHP" artisan view:clear --quiet
"$PHP" artisan event:clear --quiet
"$PHP" artisan optimize --quiet
# Sozlamalar va tariflar keshi — yangi kod bilan mos bo'lishi uchun faqat shu kalitlar.
"$PHP" artisan cache:forget settings --quiet || true
"$PHP" artisan cache:forget plan:free --quiet || true

echo "→ navbat (worker bo'lsa — yangi kod bilan qayta ko'tariladi; QUEUE_VIA_CRON=true bo'lsa cron o'zi ishlatadi)"
"$PHP" artisan queue:restart --quiet || true

# Webhook, buyruqlar va bot tavsifi — birinchi deploy'da va TelegramSetup.php o'zgarganda. Qo'lda: php artisan telegram:setup
if [ "$FIRST" = 1 ] || [ -n "$(git diff --name-only "$OLD" "$NEW" -- app/Console/Commands/TelegramSetup.php)" ]; then
    echo "→ telegram:setup"
    "$PHP" artisan telegram:setup || echo "  ⚠ telegram:setup o'tmadi — qo'lda tekshiring"
fi

echo "$NEW" > "$MARKER"
echo "✓ $(git log --oneline -1)"
