#!/bin/bash
# Cantaloupe Sync — export + trigger staged import
# Runs every 6 hours via Hermes cron (no_agent mode)
set -euo pipefail

EXPORT_DIR="$HOME/cantaloupe-exports"
ADMIN_URL="http://127.0.0.1:8090"
LOG_TAG="[cantaloupe-sync]"

echo "$LOG_TAG Starting sync at $(date -Iseconds)"

# ── Step 1: Export from Cantaloupe ─────────────────────────────────
echo "$LOG_TAG Step 1/2: Exporting from mycantaloupe.com..."
cd "$HOME/projects/cantaloupe-downloader"

if python -m cantaloupe export --scheduled --output "$EXPORT_DIR" 2>&1; then
    echo "$LOG_TAG Export completed successfully."
else
    echo "$LOG_TAG Export failed (exit=$?). Will try to sync any existing export file."
fi

# ── Step 2: Trigger sync API ───────────────────────────────────────
echo "$LOG_TAG Step 2/2: Triggering admin server sync API..."

# Get a fresh auth token
TOKEN=$(curl -s -X POST "$ADMIN_URL/api/auth/login" \
    -H "Content-Type: application/json" \
    -d '{"username":"admin","password":"changeme"}' \
    | python3 -c "import sys,json; print(json.load(sys.stdin)['token'])" 2>/dev/null)

if [ -z "${TOKEN:-}" ]; then
    echo "$LOG_TAG ERROR: Could not obtain admin auth token."
    exit 1
fi

# Trigger sync
RESPONSE=$(curl -s -X POST "$ADMIN_URL/api/admin/cantaloupe/sync" \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d '{}' 2>&1)

echo "$LOG_TAG Sync API response: $RESPONSE"

# ── Summary ────────────────────────────────────────────────────────
if echo "$RESPONSE" | python3 -c "import sys,json; d=json.load(sys.stdin); print(f\"Batch: {d.get('batch_id','?')}, Rows: {d.get('total_rows','?')}, New: {d.get('new_rows','?')}, Changed: {d.get('changed_rows','?')}\")" 2>/dev/null; then
    echo "$LOG_TAG Sync complete."
else
    echo "$LOG_TAG Sync triggered (see response above)."
fi

echo "$LOG_TAG Done at $(date -Iseconds)"
