#!/usr/bin/env bash
# Apply pending migrations 084-089 to Erik production DB
# Run this script when Erik SSH is back online.
#
# Usage: ./scripts/apply-pending-migrations.sh

set -e

ERIK="root@82.165.222.127"
DOCKER_CMD="docker exec -i tip-postgres psql -U tip -d transceiver_db"
SQL_DIR="$(dirname "$0")/../sql"

PENDING=(
  "084-cisco-a9k-bulk-images.sql"
  "085-mixed-straggler-images.sql"
  "086-asterfusion-arista-ruckus-misc-images.sql"
  "087-cisco-a9k-license-variant-reuse.sql"
  "088-ubiquiti-phoenix-images.sql"
  "089-arista-cisco-juniper-images.sql"
)

echo "Checking Erik SSH..."
if ! ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no "$ERIK" "echo OK" 2>/dev/null; then
  echo "ERROR: Cannot reach Erik at $ERIK"
  exit 1
fi

echo "Erik is reachable. Applying pending migrations..."
echo ""

for sql_file in "${PENDING[@]}"; do
  path="${SQL_DIR}/${sql_file}"
  echo "==> Applying ${sql_file}..."
  result=$(cat "$path" | ssh "$ERIK" "$DOCKER_CMD" 2>&1)
  echo "$result" | grep -E "UPDATE|ERROR|error" || true
  echo "    Done."
done

echo ""
echo "All pending migrations applied."
echo ""
echo "=== Remaining uncovered models (query) ==="
ssh "$ERIK" "$DOCKER_CMD" << 'EOSQL'
SELECT vendors.name AS vendor, switches.model
FROM switches
LEFT JOIN vendors ON switches.vendor_id = vendors.id
WHERE switches.image_url IS NULL
ORDER BY vendors.name, switches.model;
EOSQL
