#!/bin/bash
# setup-mva154.sh — установка UI-тестового окружения на mva154
# Запускать через: ssh_exec.sh --host mva154 --cmd "bash /home/slin/ui-tests/scripts/setup-mva154.sh" --timeout 300

set -e

echo "==> Проверяем Node.js..."
node --version || { echo "Node.js не найден, устанавливаем..."; curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -S bash -; sudo apt-get install -y nodejs; }

echo "==> Проверяем Chromium..."
which chromium-browser || which chromium || {
  echo "Chromium не найден, устанавливаем..."
  sudo apt-get update -qq
  sudo apt-get install -y chromium-browser
}

CHROME_BIN=$(which chromium-browser 2>/dev/null || which chromium 2>/dev/null)
echo "==> Chromium: $CHROME_BIN"
$CHROME_BIN --version

echo "==> Создаём директории..."
mkdir -p /home/slin/ui-tests/{scripts,tests,screenshots,reports}

echo "==> Устанавливаем puppeteer-core..."
cd /home/slin/ui-tests
cat > package.json << 'EOF'
{
  "name": "ui-tests",
  "version": "1.0.0",
  "dependencies": {
    "puppeteer-core": "^22.0.0"
  }
}
EOF
npm install --quiet

echo "==> Проверочный тест..."
node -e "
const puppeteer = require('puppeteer-core');
const CHROME = process.env.CHROME_BIN || '$(which chromium-browser 2>/dev/null || which chromium 2>/dev/null)';
(async () => {
  const browser = await puppeteer.launch({
    executablePath: CHROME,
    headless: 'new',
    args: ['--no-sandbox','--disable-setuid-sandbox','--disable-dev-shm-usage']
  });
  const page = await browser.newPage();
  await page.goto('about:blank');
  console.log('Browser OK:', await browser.version());
  await browser.close();
})().catch(e => { console.error('FAIL:', e.message); process.exit(1); });
"

echo ""
echo "✅ Окружение готово!"
echo "   Node: $(node --version)"
echo "   Chrome: $($CHROME_BIN --version)"
echo "   Dir: /home/slin/ui-tests/"
