#!/bin/sh
set -eu

# Files this app writes (the SQLite DB + WAL/SHM, backups, exports) hold financial
# data and encrypted secrets (SimpleFIN token, sessions, SMTP/OIDC). Create them
# owner-only (600 files / 700 dirs) — not world-readable. Inherited by the exec'd
# node process so SQLite's -wal/-shm are locked too. (QA-B16-02)
umask 077

APP_USER="${APP_USER:-bill}"
APP_GROUP="${APP_GROUP:-bill}"
DATA_DIR="${DATA_DIR:-/data}"
BACKUP_DIR="${BACKUP_PATH:-/data/backups}"
DB_FILE="${DB_PATH:-/data/db/bills.db}"
DB_DIR="$(dirname "$DB_FILE")"

mkdir -p "$DATA_DIR" "$DB_DIR" "$BACKUP_DIR" /app/backups

if [ "$(id -u)" = "0" ]; then
  chown -R "$APP_USER:$APP_GROUP" "$DATA_DIR" /app/backups
  chmod 700 "$DB_DIR" "$BACKUP_DIR" /app/backups
  # Lock any pre-existing DB files that were created world-readable (644) before
  # this umask fix — otherwise they keep their old mode across an upgrade.
  chmod 600 "$DB_FILE" "$DB_FILE"-wal "$DB_FILE"-shm 2>/dev/null || true
  if [ "${RUN_DB_MIGRATIONS:-true}" = "true" ]; then
    su-exec "$APP_USER:$APP_GROUP" node scripts/migrate-db.js
  fi
  exec su-exec "$APP_USER:$APP_GROUP" "$@"
fi

if [ "${RUN_DB_MIGRATIONS:-true}" = "true" ]; then
  node scripts/migrate-db.js
fi

exec "$@"
