#!/usr/bin/env bash
# Run on your Mac (unrestricted internet). Produces iran-bundle.tar.gz for the Iran server.
# The server never talks to npmjs / Prisma CDN during docker build.
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"
BUNDLE_DIR="$ROOT/iran-bundle"
ARCHIVE="$ROOT/iran-bundle.tar.gz"

if ! command -v docker >/dev/null 2>&1; then
  echo "ERROR: Docker is required."
  exit 1
fi

if [[ ! -f prisma-binaries/libquery_engine-debian-openssl-3.0.x.so.node ]]; then
  echo "ERROR: prisma-binaries/ missing. Run: bash scripts/fetch-prisma-binaries.sh"
  exit 1
fi

echo "==> Building linux/amd64 app inside Docker (this uses your Mac's internet)..."
rm -rf "$BUNDLE_DIR" "$ARCHIVE"

docker run --rm --platform linux/amd64 \
  -v "$ROOT:/app" -w /app \
  -e PRISMA_QUERY_ENGINE_LIBRARY=/app/prisma-binaries/libquery_engine-debian-openssl-3.0.x.so.node \
  -e PRISMA_SCHEMA_ENGINE_BINARY=/app/prisma-binaries/schema-engine-debian-openssl-3.0.x \
  -e PRISMA_ENGINES_CHECKSUM_IGNORE_MISSING=1 \
  -e PRISMA_SKIP_POSTINSTALL_GENERATE=1 \
  -e NEXT_TELEMETRY_DISABLED=1 \
  -e NEXT_SWC_DOWNLOAD_DISABLED=1 \
  -e DATABASE_URL="mysql://build:build@127.0.0.1:3306/build" \
  node:20-slim bash -c '
    set -euo pipefail
    apt-get update -qq
    apt-get install -y -qq openssl ca-certificates >/dev/null
    corepack enable
    corepack prepare pnpm@9 --activate
    rm -rf node_modules .next iran-bundle
    pnpm install --frozen-lockfile
    pnpm exec prisma generate
    pnpm run build
    mkdir -p iran-bundle/standalone iran-bundle/node_modules
    cp -a .next/standalone/. iran-bundle/standalone/
    cp -a .next/static iran-bundle/static
    cp -a public iran-bundle/public
    cp -a prisma-binaries iran-bundle/prisma-binaries
    # pnpm stores @prisma under .pnpm — resolve real paths
    PRISMA_CLIENT="$(node -e "console.log(require.resolve(\"@prisma/client/package.json\"))")"
    PRISMA_NM="$(dirname "$(dirname "$(dirname "$PRISMA_CLIENT")")")"
    cp -a "$PRISMA_NM/.prisma" iran-bundle/node_modules/
    cp -a "$PRISMA_NM/@prisma" iran-bundle/node_modules/
  '

echo "==> Packing archive..."
tar -czf "$ARCHIVE" -C "$ROOT" iran-bundle
SIZE="$(du -h "$ARCHIVE" | awk '{print $1}')"
echo ""
echo "Created: $ARCHIVE ($SIZE)"
echo ""
echo "Upload to server:"
echo "  scp \"$ARCHIVE\" root@193.105.234.35:/srv/nodecloud/apps/biztaghavisite/"
echo ""
echo "On server:"
echo "  cd /srv/nodecloud/apps/biztaghavisite"
echo "  git pull origin main"
echo "  bash scripts/server-deploy.sh"
