#!/usr/bin/env bash
#
# Builds the upload bundles for a cPanel deployment (single merged Laravel app).
#
#   dist/public_html.zip   -> extract into ~/public_html (or domain docroot)
#   dist/<APP_DIR>.zip     -> extract into ~/  (OUTSIDE the document root)
#
# Run from anywhere; paths are resolved from the script's own location.

set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
OUT="$ROOT/deploy/cpanel/dist"

# Name of the application directory, created as a sibling of the document root.
APP_DIR="${APP_DIR:-domainsansar}"

rm -rf "$OUT"
mkdir -p "$OUT/docroot" "$OUT/$APP_DIR"

echo "==> Building frontend assets (Vite production build)"
(cd "$ROOT" && npm run build)

echo "==> Preparing public document root bundle"
cp -r "$ROOT/public/." "$OUT/docroot/"

# Remove sourcemaps from production bundle if present
find "$OUT/docroot" -name '*.map' -delete || true

echo "==> Rewriting public_html/index.php paths to point to ../$APP_DIR"
sed -i "s#__DIR__.'/..#__DIR__.'/../$APP_DIR#g" "$OUT/docroot/index.php"

echo "==> Prepending cPanel host prelude to .htaccess"
PRELUDE="$ROOT/deploy/cpanel/htaccess-host-prelude"
if [ -f "$PRELUDE" ]; then
    cat "$PRELUDE" "$ROOT/public/.htaccess" > "$OUT/docroot/.htaccess"
else
    cp "$ROOT/public/.htaccess" "$OUT/docroot/.htaccess"
fi

echo "==> Staging application files"
rsync -a \
    --exclude 'vendor/' --exclude '.env' --exclude '.git/' --exclude 'node_modules/' \
    --exclude '.phpunit.result.cache' --exclude 'storage/logs/*' \
    --exclude 'storage/framework/cache/data/*' --exclude 'storage/framework/sessions/*' \
    --exclude 'storage/framework/views/*' --exclude 'bootstrap/cache/*' \
    --exclude 'deploy/cpanel/dist/' \
    "$ROOT/" "$OUT/$APP_DIR/"

cp "$ROOT/deploy/cpanel/env.production.example" "$OUT/$APP_DIR/.env.example.cpanel"

echo "==> Installing production PHP dependencies"
(cd "$OUT/$APP_DIR" && composer install --no-dev --optimize-autoloader --no-interaction --no-progress)

echo "==> Rendering schema SQL fallback"
(cd "$ROOT" && php artisan schema:compile --driver=mysql) > "$OUT/schema-mysql.sql" || true

echo "==> Creating ZIP archives"
(cd "$OUT/docroot" && zip -qr9 "$OUT/public_html.zip" . -x '.DS_Store')
(cd "$OUT" && zip -qr9 "$OUT/$APP_DIR.zip" "$APP_DIR" -x '.DS_Store')

echo
echo "Bundles ready in $OUT:"
ls -lh "$OUT"/*.zip "$OUT/schema-mysql.sql" | awk '{print "  " $9 "  " $5}'
