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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
BUILD_DIR="$ROOT_DIR/build"
STAGE_DIR="$BUILD_DIR/remotematch-codecanyon"
ZIP_FILE="$BUILD_DIR/remotematch-codecanyon.zip"

if ! command -v rsync >/dev/null 2>&1; then
    echo "rsync is required to build the package." >&2
    exit 1
fi

if ! command -v zip >/dev/null 2>&1; then
    echo "zip is required to build the package." >&2
    exit 1
fi

rm -rf "$STAGE_DIR" "$ZIP_FILE"
mkdir -p "$STAGE_DIR"

rsync -a "$ROOT_DIR/" "$STAGE_DIR/" \
    --exclude='.git' \
    --exclude='.env' \
    --exclude='.DS_Store' \
    --exclude='/build/' \
    --exclude='node_modules' \
    --exclude='vendor' \
    --exclude='public/hot' \
    --exclude='.phpunit.result.cache' \
    --exclude='bootstrap/cache/*.php' \
    --exclude='storage/logs/*' \
    --exclude='storage/app/private/*' \
    --exclude='storage/app/public/*' \
    --exclude='storage/app/remotematch-installed.json' \
    --exclude='storage/framework/cache/*' \
    --exclude='storage/framework/sessions/*' \
    --exclude='storage/framework/testing/*' \
    --exclude='storage/framework/views/*' \
    --exclude='tests/.phpunit.result.cache'

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

touch \
    "$STAGE_DIR/storage/app/public/.gitkeep" \
    "$STAGE_DIR/storage/framework/cache/.gitkeep" \
    "$STAGE_DIR/storage/framework/sessions/.gitkeep" \
    "$STAGE_DIR/storage/framework/testing/.gitkeep" \
    "$STAGE_DIR/storage/framework/views/.gitkeep" \
    "$STAGE_DIR/storage/logs/.gitkeep"

(
    cd "$BUILD_DIR"
    zip -qr "$ZIP_FILE" remotematch-codecanyon
)

echo "Package created: $ZIP_FILE"
