#!/usr/bin/env bash
# Repoint rclone.env from legacy Hardware Development Dropbox folder → OHD workspace.
#
# Run on each Pi once (safe to re-run):
#   cd ~/EtherGold/4-Board\ Test\ Fixture/sync
#   bash migrate_dropbox_paths.sh
#
# Or pull latest sync/ from Dropbox first, then:
#   bash pull_fixture_shared_from_dropbox.sh   # runs install_sync → auto-migrates

if grep -q $'\r' "${BASH_SOURCE[0]}" 2>/dev/null; then
  sed -i 's/\r$//' "${BASH_SOURCE[0]}"
  exec bash "${BASH_SOURCE[0]}" "$@"
fi

set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ENV_FILE="${ROOT}/rclone.env"
PATHS="${ROOT}/dropbox_paths.sh"

if [[ ! -f "${PATHS}" ]]; then
  echo "Missing ${PATHS} — pull sync/ from Dropbox first." >&2
  exit 1
fi

# shellcheck source=dropbox_paths.sh
source "${PATHS}"

if [[ ! -f "${ENV_FILE}" ]]; then
  if [[ -f "${ROOT}/rclone.env.example" ]]; then
    cp "${ROOT}/rclone.env.example" "${ENV_FILE}"
    echo "Created ${ENV_FILE} from example (already uses OHD workspace path)."
  else
    echo "Missing ${ENV_FILE}" >&2
    exit 1
  fi
fi

if grep -q $'\r' "${ENV_FILE}" 2>/dev/null; then
  sed -i 's/\r$//' "${ENV_FILE}"
fi

# shellcheck source=/dev/null
source "${ENV_FILE}"

echo "=== migrate_dropbox_paths ==="
echo "Hostname: $(hostname -s 2>/dev/null || hostname)"
echo ""

if grep -qF "${DROPBOX_FIXTURE_ROOT_LEGACY}" "${ENV_FILE}" 2>/dev/null; then
  echo "Before:"
  grep -E '^(DROPBOX_DEST|DROPBOX_FIXTURE_ROOT)=' "${ENV_FILE}" || true
  sed -i "s|${DROPBOX_FIXTURE_ROOT_LEGACY}|${DROPBOX_FIXTURE_ROOT_CANON}|g" "${ENV_FILE}"
  echo ""
  echo "Migrated legacy Hardware Development path → OHD workspace."
else
  echo "No legacy path in ${ENV_FILE} (already migrated or fresh install)."
fi

bash "${ROOT}/install_sync.sh"

echo ""
echo "After install_sync:"
grep -E '^(DROPBOX_DEST|DROPBOX_FIXTURE_ROOT)=' "${ENV_FILE}" || true

if command -v rclone >/dev/null 2>&1 && [[ -n "${RCLONE_REMOTE:-}" ]]; then
  # shellcheck source=/dev/null
  source "${ENV_FILE}"
  REMOTE="${RCLONE_REMOTE}:${DROPBOX_DEST}"
  echo ""
  echo "Verify remote folder exists:"
  if rclone lsd "${REMOTE}" >/dev/null 2>&1; then
    echo "  OK  ${REMOTE}"
  else
    echo "  WARN  rclone cannot list ${REMOTE}" >&2
    echo "  Check Dropbox desktop sync created the folder on PC, or run:" >&2
    echo "    rclone lsd ${RCLONE_REMOTE}:\"${DROPBOX_FIXTURE_ROOT_CANON}\"" >&2
  fi
fi

echo ""
echo "Dry-run upload (optional):"
echo "  DRY_RUN=1 bash ${ROOT}/sync_to_dropbox.sh"
