#!/usr/bin/env bash
# Builds the site on a host without root or Docker. Needs Node 20+ and a filled-in .env.
#   bash deploy/setup.sh      (run again after copying new code)
set -euo pipefail
cd "$(dirname "$0")/.."

[ -f .env ] || { echo "Copy .env.example to .env and fill it in first."; exit 1; }
node -e 'process.exit(+process.versions.node.split(".")[0] >= 20 ? 0 : 1)' \
  || { echo "Node 20 or newer is required (found $(node -v))."; exit 1; }

set -a; . ./.env; set +a

npm ci
# Webpack instead of Turbopack: Turbopack needs native bindings that older
# Linux hosts (glibc < 2.29) can't load. NODE_ENV is pinned because some
# hosting panels set a non-standard value.
npx prisma generate
NODE_ENV=production npx next build --webpack
npx prisma migrate deploy
# The standalone server serves static files from its own folder.
cp -r public .next/standalone/
cp -r .next/static .next/standalone/.next/

# Image watermarking (sharp) needs glibc 2.28 or newer.
if ! node -e 'require("sharp")' 2>/dev/null; then
  echo
  echo "WARNING: the image library (sharp) can't load on this server ($(ldd --version | head -1))."
  echo "The site will run, but photo uploads and watermarked previews will fail."
fi

echo
echo "Built. Start the site with:  bash deploy/start.sh"
echo "Create the admin login with:  npm run db:seed"
