#!/usr/bin/env bash
#
# Builds an upload-ready zip of a standalone (single-institution) install for
# cPanel / shared hosting, where there is usually no Composer, Node or SSH.
#
#   scripts/standalone/build-release.sh [output-dir]
#
# The zip contains the app with production vendor/ and built front-end assets,
# plus a .env (from .env.standalone.example) with a fresh APP_KEY — edit its
# DB_* and APP_URL values on the server. Your working copy is not touched:
# everything is built in a temporary directory. See docs/DEPLOY-CPANEL.md.

set -euo pipefail

ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
OUT_DIR="${1:-$ROOT/dist}"
STAMP="$(date +%Y%m%d-%H%M)"
BUILD="$(mktemp -d)"
APP="$BUILD/app"

trap 'rm -rf "$BUILD"' EXIT

echo "→ Copying project (working tree, including uncommitted changes)"
mkdir -p "$APP"
rsync -a "$ROOT/" "$APP/" \
    --exclude '.git' --exclude 'node_modules' --exclude 'vendor' \
    --exclude 'dist' --exclude 'tests' --exclude '.env' --exclude '.env.*' \
    --exclude 'public/build' --exclude 'public/hot' --exclude 'public/storage' \
    --exclude 'database/database.sqlite' --exclude 'storage/logs/*' \
    --exclude 'storage/framework/cache/data/*' --exclude 'storage/framework/sessions/*' \
    --exclude 'storage/framework/views/*' --exclude 'storage/app/private/*' \
    --exclude 'storage/app/public/*' --exclude 'bootstrap/cache/*.php' \
    --exclude '.phpunit.cache' --exclude '.DS_Store'
cp "$ROOT/.env.standalone.example" "$APP/.env.standalone.example"

echo "→ Installing production PHP dependencies"
(cd "$APP" && composer install --no-dev --optimize-autoloader --no-interaction --no-progress --quiet)

echo "→ Building front-end assets"
(cd "$APP" && npm ci --silent && npm run build --silent && rm -rf node_modules)

echo "→ Writing .env with a fresh APP_KEY"
KEY="base64:$(php -r 'echo base64_encode(random_bytes(32));')"
sed "s|^APP_KEY=.*|APP_KEY=$KEY|" "$ROOT/.env.standalone.example" > "$APP/.env"

# Empty runtime directories must exist (and be writable) on the server.
for dir in storage/logs storage/framework/cache/data storage/framework/sessions \
           storage/framework/views storage/app/public storage/app/private bootstrap/cache; do
    mkdir -p "$APP/$dir"
    touch "$APP/$dir/.gitkeep"
done

mkdir -p "$OUT_DIR"
ZIP="$OUT_DIR/corpo-edu-standalone-$STAMP.zip"
echo "→ Zipping to $ZIP"
(cd "$APP" && zip -qr "$ZIP" . -x '*.DS_Store')

echo
echo "Done: $ZIP ($(du -h "$ZIP" | cut -f1))"
echo "Next: follow docs/DEPLOY-CPANEL.md"
