#!/bin/sh
set -eu

# Wait for postgres to be ready before running migrations
echo "Waiting for postgres..."
until pg_isready -h "${POSTGRES_HOST:-postgres}" -p "${POSTGRES_PORT:-5432}" -q; do
  sleep 1
done
echo "Postgres is ready."

# Regenerate Prisma client (needed after bind-mount overlays the image layer)
pnpm --filter @capakraken/db db:generate

# Run pending migrations so a fresh checkout boots against a current schema
pnpm --filter @capakraken/db db:migrate:deploy

pnpm check:exports
pnpm check:imports

repo_home="/tmp/capakraken-dev-home"

# Cross-platform stat: GNU stat uses -c, BSD/macOS stat uses -f
if stat -c '%u' /app >/dev/null 2>&1; then
  repo_uid="$(stat -c '%u' /app)"
  repo_gid="$(stat -c '%g' /app)"
else
  repo_uid="$(stat -f '%u' /app)"
  repo_gid="$(stat -f '%g' /app)"
fi

mkdir -p /app/apps/web/.next
mkdir -p "$repo_home/.config/pnpm"
chown -R "$repo_uid:$repo_gid" /app/apps/web/.next
chown -R "$repo_uid:$repo_gid" "$repo_home"

# Cross-platform privilege drop: setpriv (Linux) or su (macOS/BSD)
if command -v setpriv >/dev/null 2>&1; then
  exec setpriv --reuid="$repo_uid" --regid="$repo_gid" --clear-groups \
    env HOME="$repo_home" XDG_CONFIG_HOME="$repo_home/.config" \
    pnpm --filter @capakraken/web exec next dev -H 0.0.0.0 -p 3100
else
  exec su -s /bin/sh "#${repo_uid}" -c \
    "HOME='$repo_home' XDG_CONFIG_HOME='$repo_home/.config' pnpm --filter @capakraken/web exec next dev -H 0.0.0.0 -p 3100"
fi
