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

APP_DIR="${1:-$(pwd)}"
OUTPUT_DIR="${2:-$APP_DIR/deploy/releases}"
VERSION="${BASKETLOOT_RELEASE_VERSION:-$(date +%Y%m%d-%H%M%S)}"
STAGE_DIR="$(mktemp -d)/basketloot"
ARCHIVE="$OUTPUT_DIR/basketloot-cpanel-$VERSION.zip"

cleanup() { rm -rf "$(dirname "$STAGE_DIR")"; }
trap cleanup EXIT

cd "$APP_DIR"
php artisan optimize:clear
php artisan test
npm run prod
composer validate --no-check-publish

mkdir -p "$STAGE_DIR" "$OUTPUT_DIR"
rsync -a ./ "$STAGE_DIR/" \
    --exclude='.env' --exclude='.git/' --exclude='.github/' --exclude='.claude/' \
    --exclude='.agents/' --exclude='.styleci.yml' --exclude='.phpunit.result.cache' \
    --exclude='phpunit.xml' --exclude='node_modules/' --exclude='tests/' \
    --exclude='database/seeders/DemoExperienceSeeder.php' \
    --exclude='storage/logs/*' --exclude='storage/framework/cache/*' \
    --exclude='storage/framework/sessions/*' --exclude='storage/framework/views/*' \
    --exclude='storage/app/backups/' --exclude='storage/app/import/' \
    --exclude='storage/app/face-verifications/' \
    --include='storage/app/public/' --include='storage/app/public/branding/' \
    --include='storage/app/public/branding/***' \
    --exclude='storage/app/public/*' \
    --exclude='database/*.sqlite' --exclude='deploy/releases/' \
    --exclude='test-results/' --exclude='playwright-report/'

mkdir -p "$STAGE_DIR/storage/framework/cache/data" "$STAGE_DIR/storage/framework/sessions" \
    "$STAGE_DIR/storage/framework/views" "$STAGE_DIR/storage/logs" \
    "$STAGE_DIR/storage/app/public" "$STAGE_DIR/bootstrap/cache"

cd "$STAGE_DIR"
composer install --no-dev --prefer-dist --no-interaction --optimize-autoloader
php artisan package:discover --ansi
find storage/framework storage/logs bootstrap/cache -type f ! -name '.gitignore' -delete

cd "$(dirname "$STAGE_DIR")"
zip -qry "$ARCHIVE" basketloot
shasum -a 256 "$ARCHIVE" > "$ARCHIVE.sha256"

echo "$ARCHIVE"
echo "$ARCHIVE.sha256"
