#!/usr/bin/env bash
# Start OMNL services from /srv/zardasht-portal inside PCT
set -euo pipefail

ROOT="${OMNL_PORTAL_ROOT:-/srv/zardasht-portal}"
LOG_DIR="${OMNL_BANK_LOG_DIR:-/var/log/omnl-bank}"
NGINX_TEMPLATE="${ROOT}/deploy/nginx/omnl-lxc-portal.conf"
mkdir -p "$LOG_DIR"

export SETTLEMENT_MIDDLEWARE_CONFIG="${ROOT}/config/settlement-middleware.production.v1.json"
export DBIS_EXCHANGE_CONFIG="${ROOT}/config/dbis-exchange.production.v1.json"
export OMNL_SUPPORTED_CHAINS_CONFIG="${ROOT}/config/omnl-supported-chains.v1.json"
export OMNL_M2_TOKEN_REGISTRY="${ROOT}/config/omnl-m2-token-registry.v1.json"

start() {
  local name="$1" dir="$2" cmd="$3"
  cd "${ROOT}/${dir}"
  pkill -f "${ROOT}/${dir}" 2>/dev/null || true
  nohup env \
    SETTLEMENT_MIDDLEWARE_CONFIG="$SETTLEMENT_MIDDLEWARE_CONFIG" \
    DBIS_EXCHANGE_CONFIG="$DBIS_EXCHANGE_CONFIG" \
    OMNL_SUPPORTED_CHAINS_CONFIG="$OMNL_SUPPORTED_CHAINS_CONFIG" \
    OMNL_M2_TOKEN_REGISTRY="$OMNL_M2_TOKEN_REGISTRY" \
    OMNL_API_KEY="${OMNL_API_KEY:-}" \
    OMNL_FINERACT_BASE_URL="${OMNL_FINERACT_BASE_URL:-}" \
    OMNL_FINERACT_TENANT="${OMNL_FINERACT_TENANT:-omnl}" \
    OMNL_FINERACT_USERNAME="${OMNL_FINERACT_USERNAME:-}" \
    OMNL_FINERACT_USER="${OMNL_FINERACT_USER:-}" \
    OMNL_FINERACT_PASSWORD="${OMNL_FINERACT_PASSWORD:-}" \
    OMNL_PUBLIC_MONEY_SUPPLY="${OMNL_PUBLIC_MONEY_SUPPLY:-1}" \
    bash -c "$cmd" >"${LOG_DIR}/${name}.log" 2>&1 &
  echo $! >"${LOG_DIR}/${name}.pid"
}

start token-aggregation services/token-aggregation "npm run start"
sleep 2
start settlement-middleware services/settlement-middleware "npm run start"
sleep 2
start dbis-exchange services/dbis-exchange "npm run start"
sleep 2

FRONTEND_PORT="${OMNL_BANK_FRONTEND_PORT:-3002}"
pkill -f "serve -s.*${FRONTEND_PORT}" 2>/dev/null || true
if [ -f "${LOG_DIR}/nginx.pid" ]; then
  nginx -s quit -g "pid ${LOG_DIR}/nginx.pid;" 2>/dev/null || true
fi
fuser -k "${FRONTEND_PORT}/tcp" 2>/dev/null || true
sleep 1

if command -v nginx >/dev/null 2>&1 && [ -f "$NGINX_TEMPLATE" ]; then
  sed "s|/srv/zardasht-portal|${ROOT}|g; s|/srv/ali-portal|${ROOT}|g" "$NGINX_TEMPLATE" > "${LOG_DIR}/nginx.conf"
  nginx -t -c "${LOG_DIR}/nginx.conf"
  nohup nginx -c "${LOG_DIR}/nginx.conf" >"${LOG_DIR}/frontend.log" 2>&1 &
  echo $! >"${LOG_DIR}/frontend.pid"
  echo "OMNL banking portal started under ${ROOT} (nginx :${FRONTEND_PORT})"
else
  cd "${ROOT}/frontend-dapp"
  nohup npx --yes serve -s dist -l "$FRONTEND_PORT" >"${LOG_DIR}/frontend.log" 2>&1 &
  echo $! >"${LOG_DIR}/frontend.pid"
  echo "OMNL banking portal started under ${ROOT} (serve :${FRONTEND_PORT})"
fi
