#!/bin/sh
set -e

# Generate settings.json from template using environment variables
envsubst < /app/docker/settings.json.tmpl > /app/settings.json

MODE="${1:-web}"

case "$MODE" in
  web)
    # Initialize DB collections/stats document before starting workers
    # (equivalent to what prestart.js does before launching pm2/forever)
    node -e "
      const db = require('./lib/database');
      db.connect(null, function() {
        db.initialize_data_startup(function() {
          process.exit(0);
        });
      });
    "
    exec node --stack-size=10000 ./bin/cluster
    ;;

  sync-blocks)
    echo "[sync-blocks] Starting block sync loop (interval: ${SYNC_BLOCKS_INTERVAL:-120}s)"
    while true; do
      node --stack-size=10000 ./scripts/sync.js index update || true
      sleep "${SYNC_BLOCKS_INTERVAL:-120}"
    done
    ;;

  sync-markets)
    echo "[sync-markets] Starting market sync (runs in internal loop)"
    exec node --stack-size=10000 ./scripts/sync.js market
    ;;

  sync-peers)
    echo "[sync-peers] Starting peer sync loop (interval: ${SYNC_PEERS_INTERVAL:-300}s)"
    while true; do
      node --stack-size=10000 ./scripts/sync.js peers || true
      sleep "${SYNC_PEERS_INTERVAL:-300}"
    done
    ;;

  reindex)
    echo "[reindex] Running full reindex..."
    exec node --stack-size=10000 ./scripts/sync.js index reindex
    ;;

  check-blocks)
    echo "[check-blocks] Checking for missing transactions..."
    exec node --stack-size=10000 ./scripts/sync.js index check
    ;;

  *)
    exec "$@"
    ;;
esac
