#!/bin/bash
set -Eeuo pipefail

readonly DM_DATA_DIR="/opt/dmdbms/data"
readonly SEED_DATA_DIR="/seed-data"
readonly DM_INI_RELATIVE_PATH="DAMENG/dm.ini"

if [[ ! -f "${DM_DATA_DIR}/${DM_INI_RELATIVE_PATH}" ]]; then
  if [[ ! -f "${SEED_DATA_DIR}/${DM_INI_RELATIVE_PATH}" ]]; then
    echo "ERROR: base-data seed is incomplete: ${SEED_DATA_DIR}/${DM_INI_RELATIVE_PATH} not found" >&2
    exit 1
  fi

  mkdir -p "${DM_DATA_DIR}"
  if [[ -n "$(find "${DM_DATA_DIR}" -mindepth 1 -maxdepth 1 -print -quit)" ]]; then
    echo "ERROR: ${DM_DATA_DIR} is not empty but does not contain ${DM_INI_RELATIVE_PATH}; refusing to overwrite it" >&2
    exit 1
  fi

  echo "Initializing empty DM data directory from the built-in WJBD base-data seed..."
  cp -a "${SEED_DATA_DIR}/." "${DM_DATA_DIR}/"
  sync
  echo "Base-data seed copied successfully."
fi

exec /opt/startup.sh
