#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
IMAGE="${DOCKER_IMAGE:-node:20-bookworm-slim}"
ARTIFACT_NAME="${ARTIFACT_NAME:-abelbirdnest-release.tar.gz}"
NODE_MEMORY_MB="${NODE_MEMORY_MB:-4096}"

cd "$ROOT_DIR"

docker run --rm \
  -v "$ROOT_DIR":/src:ro \
  -v "$ROOT_DIR":/out \
  -w / \
  "$IMAGE" \
  bash -lc '
    set -euo pipefail
    apt-get update >/dev/null
    apt-get install -y --no-install-recommends openssl >/dev/null
    rm -rf /work
    mkdir -p /work
    cp -R /src/. /work/
    chmod -R u+w /work
    cd /work
    npm ci
    npx prisma generate
    NODE_OPTIONS="--max-old-space-size='"$NODE_MEMORY_MB"'" npm run build
    rm -rf .deploy-release
    mkdir -p .deploy-release
    cp -R .next/standalone/. .deploy-release/
    mkdir -p .deploy-release/.next
    cp -R .next/static .deploy-release/.next/static
    cp -R public .deploy-release/public
    cp -R prisma .deploy-release/prisma
    tar -czf /out/'"$ARTIFACT_NAME"' -C .deploy-release .
  '

echo "Artifact created at $ROOT_DIR/$ARTIFACT_NAME"
