#!/usr/bin/env bash
set -euo pipefail
REMOTE_HOST="root@143.198.27.163"
REMOTE_DIR="/tmp/gemma4-llamacpp"
REMOTE_FILE="$REMOTE_DIR/gemma-4-e4b-it-Q4_K_M.gguf"
REMOTE_PID_FILE="/tmp/gemma4-relay.pid"
LOCAL_DIR="$HOME/models/gemma4-llamacpp"
LOCAL_FILE="$LOCAL_DIR/gemma-4-e4b-it-Q4_K_M.gguf"
mkdir -p "$LOCAL_DIR"

echo "Relay sync for Gemma4 GGUF"
echo "Remote: $REMOTE_HOST:$REMOTE_FILE"
echo "Local:  $LOCAL_FILE"
echo

while true; do
  REMOTE_SIZE=$(ssh "$REMOTE_HOST" "python3 - <<'PY'
from pathlib import Path
p=Path('$REMOTE_FILE')
print(p.stat().st_size if p.exists() else 0)
PY" 2>/dev/null || echo 0)
  if [ "${REMOTE_SIZE:-0}" -gt 0 ]; then
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Remote file exists: $REMOTE_SIZE bytes"
    rsync -avP "$REMOTE_HOST:$REMOTE_FILE" "$LOCAL_DIR/"
  else
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Waiting for remote file..."
  fi

  REMOTE_ALIVE=$(ssh "$REMOTE_HOST" "test -f '$REMOTE_PID_FILE' && kill -0 \$(cat '$REMOTE_PID_FILE') 2>/dev/null && echo yes || echo no" 2>/dev/null || echo no)
  LOCAL_SIZE=$(python3 - <<'PY'
from pathlib import Path
p=Path.home()/'models'/'gemma4-llamacpp'/'gemma-4-e4b-it-Q4_K_M.gguf'
print(p.stat().st_size if p.exists() else 0)
PY
)

  echo "  local_size=$LOCAL_SIZE remote_alive=$REMOTE_ALIVE"

  if [ "$REMOTE_ALIVE" = "no" ] && [ "${REMOTE_SIZE:-0}" -gt 0 ] && [ "$LOCAL_SIZE" = "$REMOTE_SIZE" ]; then
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Relay complete."
    break
  fi

  sleep 30
done
