#!/usr/bin/env bash
# sync.sh — pull Jacqui's OneDrive "Health - Agent" into this mirror.
#
# SAFE BY DEFAULT: refuses to run until an rclone remote named
# "jacqui-onedrive" exists. Uses `rclone bisync` with --dry-run unless
# you pass --live. Never runs `rclone sync --delete-*` implicitly.

export PATH="/opt/data/bin:$PATH"
export RCLONE_CONFIG="/opt/data/.config/rclone/rclone.conf"
set -euo pipefail

REMOTE_NAME="jacqui-onedrive"
REMOTE_PATH="Documents/My Cabinets/Personal/Health - Agent"
LOCAL_PATH="/opt/data/synced/Health-Agent"
MODE="dry-run"

for arg in "$@"; do
  case "$arg" in
    --live) MODE="live" ;;
    --resync) RESYNC=1 ;;
    -h|--help)
      echo "Usage: $0 [--live] [--resync]"
      echo "  --live    perform the sync (default is dry-run)"
      echo "  --resync  first-time baseline for bisync (pass ONCE)"
      exit 0
      ;;
  esac
done

command -v rclone >/dev/null || { echo "rclone not installed"; exit 1; }

if ! rclone listremotes | grep -qx "${REMOTE_NAME}:"; then
  cat <<EOF
Refusing to run: rclone remote "${REMOTE_NAME}" is not configured.

To set it up (one-time, interactive):
  rclone config
    n) new remote
    name> ${REMOTE_NAME}
    Storage> onedrive
    (follow prompts, choose "OneDrive Personal" and auth as Jacqui)

Then rerun:
  $0                 # dry-run preview
  $0 --resync --live # first live baseline
  $0 --live          # subsequent runs
EOF
  exit 2
fi

FLAGS=(--create-empty-src-dirs --track-renames)
[[ "$MODE" == "dry-run" ]] && FLAGS+=(--dry-run)
[[ "${RESYNC:-0}" == "1" ]] && FLAGS+=(--resync)

echo "Running rclone bisync in ${MODE} mode..."
rclone bisync \
  "${REMOTE_NAME}:${REMOTE_PATH}" \
  "${LOCAL_PATH}" \
  "${FLAGS[@]}"
