#!/usr/bin/env bash
# build_linux.sh - build daw_engine (PyInstaller ONEDIR) + Tauri v2 (deb + AppImage)
# Chay tren Linux:  bash build_linux.sh
# Yeu cau: python3, pip, node/npm, rust/cargo, webkit2gtk-4.1, libappindicator,
#          librsvg (xem README / DISTRIBUTION_PLAN.md)
set -euo pipefail
cd "$(dirname "$0")"

echo "== [1/6] Python dependencies =="
# PyInstaller tren Linux can objdump (binutils). May build that phai co:
#   sudo apt-get install -y binutils
python3 -m pip install --upgrade pip >/dev/null
python3 -m pip install -r requirements.txt pyinstaller

echo "== [2/6] Frontend bundle (app.jsx -> app.precompiled.js) =="
npm install --no-audit --no-fund
if [ ! -d "node_modules/@babel/standalone" ]; then
  echo "Thieu @babel/standalone - dang cai them..."
  npm install @babel/standalone --no-audit --no-fund
fi
node build.mjs

echo "== [3/6] Build daw_engine (PyInstaller ONEDIR) =="
python3 -m PyInstaller engine.spec --clean --noconfirm

echo "== [3.5/6] Verify bundle contents (app/static, app/templates phai co) =="
python3 tools/verify_bundle.py || { echo "ERROR: Bundle thieu asset - dung build!"; exit 1; }

echo "== [4/6] Copy onedir engine -> src-tauri/resources/daw_engine =="
if [ ! -f "dist/daw_engine/daw_engine" ]; then
  echo "ERROR: dist/daw_engine/daw_engine khong ton tai (onedir build loi?)"
  exit 1
fi
rm -rf src-tauri/resources/daw_engine
mkdir -p src-tauri/resources/daw_engine
cp -a dist/daw_engine/. src-tauri/resources/daw_engine/
echo "Copied onedir engine -> src-tauri/resources/daw_engine"

echo "== [5/6] Kiem tra resources truoc khi tauri build =="
if [ ! -f "src-tauri/resources/daw_engine/daw_engine" ] || [ ! -d "src-tauri/resources/daw_engine/_internal" ]; then
  echo "ERROR: thieu src-tauri/resources/daw_engine/{daw_engine,_internal}"
  exit 1
fi

echo "== [6/6] Tauri build (deb + AppImage) =="
npm install -D @tauri-apps/cli --no-audit --no-fund
npx tauri build

echo ""
echo "== DONE =="
echo "  deb     : src-tauri/target/release/bundle/deb/sonicforge-daw_1.0.0_amd64.deb"
echo "  AppImage: src-tauri/target/release/bundle/appimage/SonicForgeDAW_1.0.0_amd64.AppImage"
