#!/bin/bash
set -e
echo ""
echo "========================================"
echo "  QA Tool — Installing on GoDaddy VPS"
echo "========================================"
echo ""

if [ -f /etc/os-release ]; then
  . /etc/os-release
  OS=$ID
  OS_LIKE=${ID_LIKE:-""}
else
  echo "Cannot detect OS. Exiting."; exit 1
fi

echo "Detected OS: $PRETTY_NAME"
echo ""

is_debian() { [[ "$OS" == "ubuntu" || "$OS" == "debian" || "$OS_LIKE" == *"debian"* ]]; }
is_rhel()   { [[ "$OS" == "centos" || "$OS" == "rhel" || "$OS" == "almalinux" || "$OS" == "rocky" || "$OS_LIKE" == *"rhel"* || "$OS_LIKE" == *"fedora"* ]]; }

# 1. Node.js 18
if ! command -v node &> /dev/null; then
  echo "[1/6] Installing Node.js 18..."
  if is_debian; then
    curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
    sudo apt-get install -y nodejs
  elif is_rhel; then
    curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo -E bash -
    sudo yum install -y nodejs 2>/dev/null || sudo dnf install -y nodejs
  else
    echo "Installing via NVM (fallback)..."
    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
    export NVM_DIR="$HOME/.nvm"
    source "$NVM_DIR/nvm.sh"
    nvm install 18 && nvm use 18 && nvm alias default 18
  fi
else
  echo "[1/6] Node.js already installed: $(node -v)"
fi

# 2. Chrome dependencies
echo "[2/6] Installing browser dependencies..."
if is_debian; then
  sudo apt-get update -qq
  sudo apt-get install -y libnss3 libatk1.0-0 libatk-bridge2.0-0 libcups2 libdrm2 \
    libxkbcommon0 libxcomposite1 libxdamage1 libxfixes3 libxrandr2 \
    libgbm1 libasound2 libpango-1.0-0 libcairo2 wget --no-install-recommends 2>/dev/null || true
elif is_rhel; then
  sudo yum install -y epel-release 2>/dev/null || sudo dnf install -y epel-release 2>/dev/null || true
  PKG_MGR="yum"
  command -v dnf &>/dev/null && PKG_MGR="dnf"
  sudo $PKG_MGR install -y nss atk at-spi2-atk libdrm libxkbcommon \
    libXcomposite libXdamage libXfixes libXrandr mesa-libgbm alsa-lib \
    pango cairo wget liberation-fonts 2>/dev/null || true
fi

# 3. PM2
if ! command -v pm2 &> /dev/null; then
  echo "[3/6] Installing PM2..."
  sudo npm install -g pm2
else
  echo "[3/6] PM2 already installed"
fi

# 4. NPM packages
echo "[4/6] Installing npm packages..."
npm install --production

# 5. Playwright Chromium
echo "[5/6] Installing Playwright Chromium..."
npx playwright install chromium
npx playwright install-deps chromium 2>/dev/null || true

# 6. Setup
echo "[6/6] Setting up directories..."
mkdir -p screenshots data logs
[ ! -f .env ] && cp .env.example .env && echo "  .env created — edit it next"

echo ""
echo "========================================"
echo "  Done! Next steps:"
echo "========================================"
echo "  1.  nano .env                          (set your APP_URL)"
echo "  2.  pm2 start ecosystem.config.js"
echo "  3.  pm2 save && pm2 startup"
echo "  4.  Open: http://$(curl -s ifconfig.me 2>/dev/null || echo 'YOUR_IP'):3000"
echo ""
