#!/usr/bin/env bash
set -e

SQL_DIR="/docker-entrypoint-initdb.d/sql"
FIXTURE_DIR="/docker-entrypoint-initdb.d/fixture"
DOMAIN="${POSTGRES_DOMAIN:?POSTGRES_DOMAIN env required}"

psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" \
  -f "$SQL_DIR/common/update_updated_at_column.sql"

for f in "$SQL_DIR/$DOMAIN"/*.sql; do
  [ -f "$f" ] || continue
  psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" -f "$f"
done

if [ -f "$FIXTURE_DIR/$DOMAIN.sql" ]; then
  psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" \
    -f "$FIXTURE_DIR/$DOMAIN.sql"
fi
