#!/bin/sh
set -e

TEMPLATE="/app/template.db"
DB="/app/data/prod.db"

if [ ! -f "$DB" ]; then
  echo "[db] First run — creating database from template"
  cp "$TEMPLATE" "$DB"
  exec node server.js
fi

echo "[db] Syncing schema..."

# Schema already contains "CREATE TABLE IF NOT EXISTS" from Prisma.
# Only indexes need the IF NOT EXISTS addition.
sqlite3 "$TEMPLATE" ".schema" | \
  sed 's/CREATE INDEX /CREATE INDEX IF NOT EXISTS /g' | \
  sed 's/CREATE UNIQUE INDEX /CREATE UNIQUE INDEX IF NOT EXISTS /g' | \
  sqlite3 "$DB"

# Add missing columns to existing tables
for table in $(sqlite3 "$TEMPLATE" "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '_prisma%'"); do
  prod_cols=$(sqlite3 "$DB" "PRAGMA table_info('$table')" | cut -d'|' -f2)

  sqlite3 "$TEMPLATE" "PRAGMA table_info('$table')" | while IFS='|' read -r _cid name type notnull dflt _pk; do
    if ! echo "$prod_cols" | grep -qx "$name"; then
      alter="ALTER TABLE \"$table\" ADD COLUMN \"$name\" $type"
      [ -n "$dflt" ] && alter="$alter DEFAULT $dflt"
      sqlite3 "$DB" "$alter" && echo "[db] + $table.$name" || echo "[db] WARN: failed to add $table.$name"
    fi
  done
done

echo "[db] Schema sync complete"
exec node server.js
