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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
OUTPUT_PATH="${1:-"$ROOT_DIR/../zamfara-certificate-system-production.zip"}"

if [[ ! -f "$ROOT_DIR/vendor/autoload.php" ]]; then
  echo "Missing vendor/autoload.php. Install locked production dependencies first with: composer install --no-dev --optimize-autoloader" >&2
  exit 1
fi
if ! command -v zip >/dev/null 2>&1 || ! command -v unzip >/dev/null 2>&1; then
  echo "The zip and unzip utilities are required to build and verify the release." >&2
  exit 1
fi

mkdir -p "$(dirname "$OUTPUT_PATH")"
OUTPUT_PATH="$(cd "$(dirname "$OUTPUT_PATH")" && pwd)/$(basename "$OUTPUT_PATH")"
STAGING_DIR="$(mktemp -d)"
trap 'rm -rf "$STAGING_DIR"' EXIT
RELEASE_DIR="$STAGING_DIR/zamfara-certificate-system"
mkdir -p "$RELEASE_DIR"

for item in app database deploy public scripts storage tests vendor composer.json composer.lock README.md SECURITY_REVIEW.md .env.example .gitignore; do
  if [[ -e "$ROOT_DIR/$item" ]]; then
    cp -a "$ROOT_DIR/$item" "$RELEASE_DIR/"
  fi
done

# The localStorage role-switcher prototype is not part of a production website.
rm -f "$RELEASE_DIR/public/index.html" "$RELEASE_DIR/public/assets/app.js" "$RELEASE_DIR/.env"
# Package directories only; never include files uploaded to the development host.
for folder in private_uploads qr; do
  mkdir -p "$RELEASE_DIR/storage/$folder"
  find "$RELEASE_DIR/storage/$folder" -mindepth 1 ! -name '.gitkeep' -delete
done
find "$RELEASE_DIR" -type f \( -name '.env' -o -name '*.log' -o -name '.DS_Store' \) -delete

rm -f "$OUTPUT_PATH"
(
  cd "$STAGING_DIR"
  zip -qr "$OUTPUT_PATH" zamfara-certificate-system
)
unzip -tq "$OUTPUT_PATH"

if unzip -Z1 "$OUTPUT_PATH" | grep -Eq '^zamfara-certificate-system/(\.env|public/index\.html|public/assets/app\.js)$'; then
  echo "Release archive contains an excluded file." >&2
  exit 1
fi

sha256sum "$OUTPUT_PATH" > "$OUTPUT_PATH.sha256"
echo "Production release created and verified: $OUTPUT_PATH"
echo "SHA-256: $(cut -d' ' -f1 "$OUTPUT_PATH.sha256")"
