#!/usr/bin/env bash
# Rsync ./out/ota/v0 to a remote web root (staging OTA tree).
#
# Usage:
#   OTA_DEPLOY_TARGET=foxx@10.7.16.128:/var/www/localhost/htdocs/ \
#     ./scripts/deploy-ota-staging.sh
#
# Dry run:
#   OTA_DEPLOY_DRY_RUN=1 ./scripts/deploy-ota-staging.sh
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
SRC="${ROOT}/out/ota/v0"
TARGET="${OTA_DEPLOY_TARGET:?Set OTA_DEPLOY_TARGET=user@host:/path/to/web/root}"

if [[ ! -d "$SRC" ]]; then
  echo "Missing ${SRC} — run ./scripts/docker-build-ota.sh first" >&2
  exit 1
fi

RSYNC_OPTS=(-av --delete)
if [[ "${OTA_DEPLOY_DRY_RUN:-}" == "1" ]]; then
  RSYNC_OPTS+=(--dry-run -v)
fi

echo "Sync ${SRC}/ -> ${TARGET}/v0/"
rsync "${RSYNC_OPTS[@]}" "${SRC}/" "${TARGET%/}/v0/"

echo "Channel pointer (after deploy):"
if [[ -f "${ROOT}/out/BUILD_INFO.json" ]]; then
  grep channelUrl "${ROOT}/out/BUILD_INFO.json" || true
fi
