#!/bin/sh
set -eu

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
  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 "$@"
