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

project_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$project_dir"

if ! command -v php >/dev/null || ! command -v composer >/dev/null || ! command -v npm >/dev/null || ! command -v zip >/dev/null; then
  echo "This build requires PHP 8.3+, Composer, npm, and zip." >&2
  exit 1
fi

php scripts/check-platform.php
if [[ -f composer.lock ]]; then
  composer install --prefer-dist --no-interaction
else
  composer update --prefer-dist --no-interaction
fi
composer test
npm install --no-audit --no-fund
npm run build
composer install --no-dev --classmap-authoritative --prefer-dist --no-interaction

mkdir -p dist
stage="$(mktemp -d)"
trap 'rm -rf "$stage"' EXIT
mkdir -p "$stage/release"
tar -C . \
  --exclude='./.git' --exclude='./node_modules' --exclude='./dist' --exclude='./.env' \
  --exclude='./tests' --exclude='./phpunit.xml' --exclude='./public/hot' \
  --exclude='./storage/logs/*.log' -cf - . | tar -C "$stage/release" -xf -
rm -f dist/SMS-Operations-Hub-Release.zip
(cd "$stage" && zip -qr "$project_dir/dist/SMS-Operations-Hub-Release.zip" release)
echo "Release package created at dist/SMS-Operations-Hub-Release.zip"
