#!/usr/bin/env bash
#
# Builds the zip to upload to a shared hosting (cPanel): production vendor, built assets, no secrets, no dev files.
#
#   scripts/build-cpanel-package.sh            # -> dist/varrootlet-cpanel-<date>-<commit>.zip
#
# Needs on THIS machine: git, composer, node + npm, zip. Nothing is uploaded and no server is touched.
# The package is built from the COMMITTED files (git archive), never from the working folder: a local .env, logs, uploaded
# photos or a database file cannot get in. Uncommitted changes are therefore NOT in the package (the script says so).

set -euo pipefail

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

for tool in git composer npm zip unzip php; do
    command -v "$tool" >/dev/null 2>&1 || { echo "Missing tool: $tool" >&2; exit 1; }
done

SHA="$(git rev-parse --short HEAD)"
STAMP="$(date +%Y%m%d)"
NAME="varrootlet-cpanel-${STAMP}-${SHA}"
OUT="$ROOT/dist"
STAGE="$(mktemp -d "${TMPDIR:-/tmp}/varrootlet-package.XXXXXX")"
trap 'rm -rf "$STAGE"' EXIT

if [ -n "$(git status --porcelain --untracked-files=no)" ]; then
    echo "WARNING: uncommitted changes exist. The package contains only what is committed (HEAD ${SHA})." >&2
fi

echo "==> Exporting committed files (HEAD ${SHA})"
git archive --format=tar HEAD | tar -x -C "$STAGE"

cd "$STAGE"

echo "==> composer install --no-dev --optimize-autoloader"
composer install --no-dev --optimize-autoloader --no-interaction --prefer-dist --no-progress

echo "==> npm ci && npm run build"
npm ci --no-audit --no-fund --loglevel=error

# npm bug: a lockfile written on another platform may lack the native binding of rolldown (the bundler) for THIS machine.
# Only when the bundler does not load, the matching binding is added (not saved anywhere: the lockfile stays as it is).
if ! node -e "import('rolldown').then(() => process.exit(0), () => process.exit(1))" 2>/dev/null; then
    case "$(uname -s)-$(uname -m)" in
        Darwin-arm64) BINDING="darwin-arm64" ;;
        Darwin-x86_64) BINDING="darwin-x64" ;;
        Linux-x86_64) BINDING="linux-x64-gnu" ;;
        Linux-aarch64) BINDING="linux-arm64-gnu" ;;
        *) echo "ERROR: rolldown does not load and this platform is not known to the script." >&2; exit 1 ;;
    esac
    ROLLDOWN_VERSION="$(node -p "require('./node_modules/rolldown/package.json').version")"
    echo "==> rolldown native binding missing, installing @rolldown/binding-${BINDING}@${ROLLDOWN_VERSION} (not saved)"
    npm install --no-save --no-package-lock --no-audit --no-fund --loglevel=error "@rolldown/binding-${BINDING}@${ROLLDOWN_VERSION}"
fi

npm run build

if [ ! -f public/build/manifest.json ]; then
    echo "ERROR: public/build/manifest.json is missing, the asset build did not produce output." >&2
    exit 1
fi

echo "==> Adding the hosting files"
cp deploy/cpanel/user.ini public/.user.ini

# The shortest PHP version the installed packages accept (composer writes it into vendor/composer/platform_check.php).
PHP_MIN="$(grep -o 'PHP_VERSION_ID >= [0-9]*' vendor/composer/platform_check.php | head -1 | grep -o '[0-9]*$' || true)"
PHP_MIN_TEXT="unknown"
if [ -n "$PHP_MIN" ]; then
    PHP_MIN_TEXT="$((PHP_MIN / 10000)).$(((PHP_MIN / 100) % 100)).$((PHP_MIN % 100))"
fi

cat > BUILD-INFO.txt <<EOF
Varrootlet cPanel package
commit:      $(git -C "$ROOT" rev-parse HEAD)
built:       $(date -u +%Y-%m-%dT%H:%M:%SZ)
php minimum: ${PHP_MIN_TEXT} (from the installed packages)
EOF

echo "==> Removing everything the server must not get"
rm -rf node_modules tests docker docs .superpowers .github \
    docker-compose.yml docker.env.example Makefile phpunit.xml package.json package-lock.json vite.config.js \
    AGENTS.md CLAUDE.md README.md .env .env.example
rm -f storage/logs/*.log
rm -rf public/hot

echo "==> Safety check"
# Names that must never be in the package. Every .env* file is refused except the example, whatever its suffix; the match is case-insensitive.
FORBIDDEN='(^|/)(\.env[^/]*|\.git|node_modules|tests|docker|auth\.json)(/|$)|\.(sqlite|sqlite3|sql|log|pem|key)$'
if find . -path ./vendor -prune -o -print | sed 's|^\./||' | grep -iE "$FORBIDDEN" | grep -vE '^(storage/.*\.gitignore|\.env\.production\.example)$'; then
    echo "ERROR: a forbidden file is in the package (listed above)." >&2
    exit 1
fi
# Secrets in the application files (vendor is third party code and is not scanned). `export` and leading blanks do not hide a line.
SECRET='^[[:space:]]*(export[[:space:]]+)?(APP_KEY|GEMINI_API_KEY|DB_PASSWORD|MAIL_PASSWORD|AWS_SECRET_ACCESS_KEY)[[:space:]]*=[[:space:]]*[^[:space:]]'
if grep -rIEl --exclude-dir=vendor --exclude='.env.production.example' -e 'AIza[0-9A-Za-z_-]{35}' -e "$SECRET" . ; then
    echo "ERROR: a file looks like it holds a secret (listed above)." >&2
    exit 1
fi
# The one env file is the example: its secret keys are empty or an obvious CHANGE-ME placeholder.
if grep -E '^[[:space:]]*(export[[:space:]]+)?(APP_KEY|GEMINI_API_KEY|DB_PASSWORD|MAIL_PASSWORD|AWS_SECRET_ACCESS_KEY)[[:space:]]*=' .env.production.example \
    | grep -vE '=[[:space:]]*(CHANGE-ME)?[[:space:]]*$'; then
    echo "ERROR: .env.production.example holds a real value for a secret key (listed above)." >&2
    exit 1
fi

mkdir -p "$OUT"
ZIP="$OUT/${NAME}.zip"
rm -f "$ZIP"

echo "==> Zipping"
zip -qr -X "$ZIP" . -x '.DS_Store' '*/.DS_Store'

cd "$ROOT"
echo
echo "Package:      dist/${NAME}.zip"
echo "Size:         $(du -h "$ZIP" | cut -f1) ($(unzip -l "$ZIP" | tail -1 | awk '{print $2}') files)"
echo "PHP minimum:  ${PHP_MIN_TEXT}"
echo "Top level:"
unzip -Z1 "$ZIP" | awk -F/ 'NF>1 {print $1"/"} NF==1 {print $1}' | sort -u | sed 's/^/  /'
echo "Contains public/build: $(unzip -Z1 "$ZIP" | grep -c '^public/build/') files, vendor: $(unzip -Z1 "$ZIP" | grep -c '^vendor/') files"
