#!/usr/bin/env bash
# Pull prod into the already merged local repricer database (archive not needed). Safe to run any number of times.
#   ~/projects/new-repricer/sync/sync.sh          production sync
#   ~/projects/new-repricer/sync/sync.sh --test   small test run (all phases, one small chunk of each kind)
# 1) checks  2) plan (what and how much will be downloaded)  3) type yes  4) sync in the background (bg-sync...)
# 5) opens the monitor right away. Ctrl-C closes only the monitor, the sync keeps running.
#    Reopen the monitor: ~/projects/new-repricer/sync/watch.sh 15 sync
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" "$@"; }
MODE="${1:-}"
[ -z "$MODE" ] || [ "$MODE" = "--test" ] || { echo "Usage: $0 [--test]"; exit 1; }

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
if docker exec repricer-db mysql --defaults-extra-file=/secrets/prod.cnf -N -e "select 1" >/dev/null 2>&1; then
  echo "  prod: reachable"
else
  echo "  prod: UNREACHABLE, stopping"; exit 1
fi
echo "  disk: $(df -h --output=avail "$W" | tail -1 | tr -d ' ') free"
echo "  streams: prod 4; link cap ${MERGE_NET_CAP:-150} Mbit/s"
echo
echo "== Plan (takes ~1 min, read-only)"
python3 sync.py --plan || { echo "Plan failed, stopping"; exit 1; }
echo
if [ "$MODE" = "--test" ]; then
  echo "TEST: one small chunk of each kind (real prod rows, harmless to load again later)."
else
  echo "Sync: new and changed prod rows -> local database. Rows deleted on prod stay locally."
fi
read -r -p "Type yes to start: " ans
[ "$ans" = "yes" ] || { echo "Cancelled."; exit 0; }

name=sync; [ "$MODE" = "--test" ] && name=sync-test
bgrun -n "$name" "cd $D && python3 sync.py $MODE"
sleep 3
exec "$D/watch.sh" 15 sync
