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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
IMAGE="${DOCKER_IMAGE:-node:20-alpine}"
RELEASE_STAMP="${RELEASE_STAMP:-$(date +%Y%m%d-%H%M%S)}"
ARTIFACT_NAME="${ARTIFACT_NAME:-abelbirdnest-release-${RELEASE_STAMP}.tar.gz}"
NODE_MEMORY_MB="${NODE_MEMORY_MB:-4096}"

cd "$ROOT_DIR"

if ! command -v docker >/dev/null 2>&1; then
  echo "Docker is required to build the Alpine Linux release artifact." >&2
  exit 1
fi

docker run --rm \
  -v "$ROOT_DIR":/src:ro \
  -v "$ROOT_DIR":/out \
  -w / \
  "$IMAGE" \
  sh -lc '
    set -eu
    apk add --no-cache 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"
