#!/usr/bin/env bash
# PRODUCTION merge of repricer (prod + archive) FROM SCRATCH.
#   ~/projects/new-repricer/sync/run.sh
# 1) checks  2) confirmation  3) wipe the local database and full load in the background (bg-merge-full)
# 4) opens the live monitor (watch.sh) right away. Ctrl-C closes only the monitor, the merge keeps running.
#    Reopen the monitor: ~/projects/new-repricer/sync/watch.sh
set -u
D="$(cd "$(dirname "$0")" && pwd)"                                    # code (repo)
W="${REPRICER_DB_DIR:-$HOME/projects/new-repricer-db}"                 # database, credentials, reports
cd "$D"
dc() { docker compose -f "$D/docker-compose.yml" --env-file "$W/.env" "$@"; }

echo "== Checks"
if pgrep -u "$USER" -f '^python3 (merge|sync)\.py' | grep -q .; then
  echo "A merge or sync is already running:"; pgrep -u "$USER" -af '^python3 (merge|sync)\.py'; exit 1
fi
if ! docker ps --format '{{.Names}}' | grep -qx repricer-db; then
  echo "Container repricer-db is not running, starting it..."; dc up -d || exit 1
fi
for i in $(seq 1 40); do
  docker exec repricer-db mysql --defaults-extra-file=/secrets/local.cnf -N -e "select 1" >/dev/null 2>&1 && break; sleep 3
done
for s in prod arch; do
  if docker exec repricer-db mysql --defaults-extra-file=/secrets/$s.cnf -N -e "select 1" >/dev/null 2>&1; then
    echo "  $s: reachable"
  else
    echo "  $s: UNREACHABLE, stopping"; exit 1
  fi
done
echo "  disk: $(df -h --output=avail "$W" | tail -1 | tr -d ' ') free (needs ~200G)"
echo "  streams: prod 4, archive 4; link cap ${MERGE_NET_CAP:-150} Mbit/s"
echo
echo "WARNING: the local repricer database will be DROPPED and loaded from scratch (prod + archive)."
echo "Prod and archive are only read. Takes ~5-6 hours."
read -r -p "Type yes to start: " ans
[ "$ans" = "yes" ] || { echo "Cancelled."; exit 0; }

bgrun -n merge-full "cd $D && python3 merge.py --fresh"
sleep 3
exec "$D/watch.sh" 15
