#!/usr/bin/env bash
# Build the vocab Flutter web app and publish to /var/www/html/vocab.
# Force-upgrades /opt/flutter to current stable (Dart 3.10+ required by
# our pubspec).
set -e

FLUTTER_DIR=/opt/flutter

echo "=== Apt deps ==="
export DEBIAN_FRONTEND=noninteractive
apt-get install -y -qq git curl unzip xz-utils zip libglu1-mesa 2>&1 | tail -3

git config --global --add safe.directory "$FLUTTER_DIR" || true

if [ ! -d "$FLUTTER_DIR" ]; then
  git clone --depth 1 -b stable https://github.com/flutter/flutter.git "$FLUTTER_DIR"
else
  echo "=== Force-upgrading Flutter to origin/stable ==="
  cd "$FLUTTER_DIR"
  git fetch origin stable --tags 2>&1 | tail -3
  git reset --hard origin/stable
  git log -1 --oneline
fi

export PATH="$FLUTTER_DIR/bin:$PATH"

# Flutter prints a scary "running as root" banner. Suppress it via the
# documented env var so the logs are readable. (Server is single-tenant
# anyway; security separation isn't the concern here, log noise is.)
mkdir -p /opt/flutter/bin/cache
touch /opt/flutter/bin/cache/.flutter_root_ok

if ! grep -q "/opt/flutter/bin" /etc/profile.d/flutter.sh 2>/dev/null; then
  echo 'export PATH="/opt/flutter/bin:$PATH"' > /etc/profile.d/flutter.sh
  chmod +x /etc/profile.d/flutter.sh
fi

echo ""
echo "=== Flutter version ==="
flutter --no-version-check --version 2>&1 | head -3

echo ""
echo "=== Web cache ==="
flutter --no-version-check config --no-analytics >/dev/null 2>&1 || true
flutter --no-version-check config --enable-web >/dev/null 2>&1 || true
flutter --no-version-check precache --web 2>&1 | tail -8

echo ""
echo "=== pub get ==="
cd /var/www/html/vocabapi/mobile
rm -rf .dart_tool/  # purge stale lockfile state from previous Flutter
flutter --no-version-check pub get 2>&1 | tail -10

echo ""
echo "=== Building vocab web (release, prod API URL) ==="
flutter --no-version-check build web --release \
  --dart-define=VOCABILE_API_URL=https://vocabapi.allgifted.com/api \
  2>&1 | tail -15

echo ""
echo "=== Publishing to /var/www/html/vocab ==="
mkdir -p /var/www/html/vocab
rsync -a --delete /var/www/html/vocabapi/mobile/build/web/ /var/www/html/vocab/
chown -R www-data:www-data /var/www/html/vocab

echo ""
echo "=== Result ==="
ls /var/www/html/vocab | head -15
du -sh /var/www/html/vocab
