#!/usr/bin/env bash
# One-shot: refresh ~/EtherGold/sync from Dropbox (bypasses broken local rclone filter).
#
# Usage:
#   cd ~/EtherGold/sync
#   bash refresh_sync_from_dropbox.sh

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

if [[ "$(id -un)" == root ]]; then
  echo "FATAL: do not run as root/sudo — rclone config is under ~topbox." >&2
  exit 1
fi

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "${ROOT}"

ENV_FILE="${ROOT}/rclone.env"
if [[ ! -f "${ENV_FILE}" ]]; then
  echo "FATAL: missing ${ENV_FILE}" >&2
  exit 1
fi

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

REMOTE="${RCLONE_REMOTE:?}:${DROPBOX_FIXTURE_ROOT:?}/sync/"
echo "refresh_sync_from_dropbox: ${REMOTE} → ${ROOT}"
rclone copy "${REMOTE}" "${ROOT}/" --exclude rclone.env -v --stats-one-line
chmod +x "${ROOT}/"*.sh 2>/dev/null || true
ls -la "${ROOT}/stop_fixture_gremlins.sh"
grep -c _fixture_env_export_all "${ROOT}/source_fixture_env.sh" && echo "OK source_fixture_env export fix"
