#!/usr/bin/env bash
# Configure rclone.env for THIS Pi: DROPBOX_DEST=.../logs/N from FIXTURE_POS or hostname.
# Fixture UART/capture upload only — not production IIS log offload.
# Production logs use Enrollment.csv Path + asset-UTC names (log_offload.sh → 51709).
# Safe to re-run after pull — updates DROPBOX_DEST and clears PI_LABEL for flat PC landing.
#
# Override detection: FIXTURE_POS=3 (or 41 for a copper witness) in rclone.env, or
# FIXTURE_POS=41 ./install_sync.sh
# Seat hostnames topbox1..topbox6 → logs/1..6.
# Local copper witnesses: topboxNw / topboxN1 → logs/N1 (11,21,31,41,51).
# Do NOT misread topbox35 as seat 5. topbox6 is St. Thomas Rev E capture (not GA 1-5).
#
# Usage:
#   cd ~/EtherGold/sync
#   bash install_sync.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

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

if [[ -f "${ROOT}/pi_normalize.sh" ]]; then
  sh "${ROOT}/pi_normalize.sh"
fi

ENV_FILE="${ROOT}/rclone.env"
EXAMPLE="${ROOT}/rclone.env.example"
PATHS="${ROOT}/dropbox_paths.sh"

if [[ -f "${PATHS}" ]]; then
  # shellcheck source=dropbox_paths.sh
  source "${PATHS}"
fi

migrate_legacy_dropbox_paths() {
  local file="$1"
  [[ -n "${DROPBOX_FIXTURE_ROOT_CANON:-}" ]] || return 0
  if [[ -n "${DROPBOX_FIXTURE_ROOT_LEGACY:-}" ]] \
    && grep -qF "${DROPBOX_FIXTURE_ROOT_LEGACY}" "${file}" 2>/dev/null; then
    sed -i "s|${DROPBOX_FIXTURE_ROOT_LEGACY}|${DROPBOX_FIXTURE_ROOT_CANON}|g" "${file}"
    echo "install_sync: migrated Dropbox path (Hardware Dev → OHD workspace)"
  fi
  if [[ -n "${DROPBOX_FIXTURE_ROOT_LEGACY_OHD:-}" ]] \
    && grep -qF "${DROPBOX_FIXTURE_ROOT_LEGACY_OHD}" "${file}" 2>/dev/null; then
    sed -i "s|${DROPBOX_FIXTURE_ROOT_LEGACY_OHD}|${DROPBOX_FIXTURE_ROOT_CANON}|g" "${file}"
    echo "install_sync: migrated Dropbox path (4-Board Test Fixture → flat EtherGold)"
  fi
  # Catch-all: strip stale trailing '/4-Board Test Fixture' from remote-root keys.
  if grep -qE '/4-Board Test Fixture(/[1-5])?"?$' "${file}" 2>/dev/null; then
    sed -i -E 's|/4-Board Test Fixture(/[1-5])?("?)$|\1\2|' "${file}"
    echo "install_sync: stripped stale '/4-Board Test Fixture' from remote root"
  fi
  # Capture landing must stay workshop EtherGold/logs/N — never under To Deploy.
  if grep -qE '^DROPBOX_DEST=.*To Deploy/EtherGold/logs/' "${file}" 2>/dev/null; then
    sed -i 's|To Deploy/EtherGold/logs/|EtherGold/logs/|g' "${file}"
    echo "install_sync: migrated DROPBOX_DEST (To Deploy/logs → workshop EtherGold/logs)"
  fi
}

if [[ ! -f "${EXAMPLE}" ]]; then
  echo "Missing ${EXAMPLE}" >&2
  exit 1
fi

if [[ ! -f "${ENV_FILE}" ]]; then
  cp "${EXAMPLE}" "${ENV_FILE}"
  echo "Created ${ENV_FILE} from example."
fi

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

migrate_legacy_dropbox_paths "${ENV_FILE}"

# CLI/env override wins over a stale FIXTURE_POS already in rclone.env
# (FIXTURE_POS=6 bash install_sync.sh). Hostname is used only when unset.
POS_OVERRIDE="${FIXTURE_POS:-}"

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

if [[ -n "${POS_OVERRIDE}" ]]; then
  FIXTURE_POS="${POS_OVERRIDE}"
fi

detect_fixture_pos() {
  local host short

  # 1..99 — seats 1..5 plus copper witnesses (e.g. 51 = pos5 listen-only).
  if [[ -n "${FIXTURE_POS:-}" ]] && [[ "${FIXTURE_POS}" =~ ^[1-9][0-9]?$ ]] \
    && (( FIXTURE_POS >= 1 && FIXTURE_POS <= 99 )); then
    echo "${FIXTURE_POS}"
    return 0
  fi

  host="$(hostname -s 2>/dev/null || hostname)"
  short="${host%%.*}"

  # Local copper witness: topboxNw or topboxN1 → POS N1 (11,21,31,41,51).
  if [[ "${short}" =~ ^topbox([1-5])w$ ]]; then
    echo $((BASH_REMATCH[1] * 10 + 1))
    return 0
  fi
  if [[ "${short}" =~ ^topbox([1-5])1$ ]]; then
    echo $((BASH_REMATCH[1] * 10 + 1))
    return 0
  fi

  # Exact seat hostnames only (topbox1..topbox6). Do NOT match topbox35 → 5.
  if [[ "${short}" =~ ^topbox([1-6])$ ]]; then
    echo "${BASH_REMATCH[1]}"
    return 0
  fi

  if [[ "${short}" =~ ^([1-5])$ ]]; then
    echo "${BASH_REMATCH[1]}"
    return 0
  fi

  return 1
}

set_env_quoted() {
  local key="$1"
  local val="$2"
  local file="$3"
  local line="${key}=\"${val}\""

  if grep -q "^${key}=" "${file}" 2>/dev/null; then
    sed -i "s|^${key}=.*|${line}|" "${file}"
  else
    echo "${line}" >> "${file}"
  fi
}

set_env_raw() {
  local key="$1"
  local val="$2"
  local file="$3"
  local line="${key}=${val}"

  if grep -q "^${key}=" "${file}" 2>/dev/null; then
    sed -i "s|^${key}=.*|${line}|" "${file}"
  else
    echo "${line}" >> "${file}"
  fi
}

POS="$(detect_fixture_pos)" || {
  echo "FATAL: could not detect fixture position from hostname '$(hostname -s 2>/dev/null || hostname)'." >&2
  echo "Set FIXTURE_POS=1..99 in ${ENV_FILE} (seat 1..6, or witness e.g. 51) or run: FIXTURE_POS=51 ./install_sync.sh" >&2
  exit 1
}
# Persist detected/override pos so re-runs do not fall back to hostname.
set_env_raw FIXTURE_POS "${POS}" "${ENV_FILE}"

if [[ -z "${DROPBOX_FIXTURE_ROOT:-}" ]]; then
  if [[ -n "${DROPBOX_FIXTURE_ROOT_CANON:-}" ]]; then
    DROPBOX_FIXTURE_ROOT="${DROPBOX_FIXTURE_ROOT_CANON}"
  fi
fi

if [[ -z "${DROPBOX_FIXTURE_ROOT:-}" ]]; then
  echo "FATAL: set DROPBOX_FIXTURE_ROOT in ${ENV_FILE}" >&2
  exit 1
fi

# Capture upload ≠ pull root. Pull = To Deploy/EtherGold; landing = workshop EtherGold/logs/N.
CAPTURE_ROOT="${DROPBOX_WORKSHOP_ETHERGOLD:-}"
if [[ -z "${CAPTURE_ROOT}" ]]; then
  echo "FATAL: DROPBOX_WORKSHOP_ETHERGOLD unset — update dropbox_paths.sh on this Pi." >&2
  exit 1
fi
NEW_DEST="${CAPTURE_ROOT}/logs/${POS}"
OLD_DEST="${DROPBOX_DEST:-}"

set_env_quoted DROPBOX_FIXTURE_ROOT "${DROPBOX_FIXTURE_ROOT}" "${ENV_FILE}"
set_env_quoted DROPBOX_DEST "${NEW_DEST}" "${ENV_FILE}"

# Flat PC landing: rclone uploads to .../N/data/ (not .../N/topboxN/data/).
set_env_raw PI_LABEL "" "${ENV_FILE}"

if [[ -z "${PULL_SCOPE:-}" ]]; then
  set_env_raw PULL_SCOPE timing "${ENV_FILE}"
fi

# Flat layout: bench captures live under ~/EtherGold/dev/data|logs/
set_env_quoted SYNC_SOURCE "dev" "${ENV_FILE}"

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

echo "install_sync: hostname=$(hostname -s 2>/dev/null || hostname) → FIXTURE_POS=${POS}"
echo "  DROPBOX_DEST=${DROPBOX_DEST}"
if [[ -n "${OLD_DEST}" ]] && [[ "${OLD_DEST}" != "${DROPBOX_DEST}" ]]; then
  echo "  (was: ${OLD_DEST})"
fi
echo "  PI_LABEL=${PI_LABEL}"
echo "  PULL_SCOPE=${PULL_SCOPE}"
