#!/usr/bin/env bash
# Host wrapper: build androidcast-ci image and run build + OTA staging publish.
#
# Usage:
#   export OTA_BASE_URL=https://apps.f0xx.org
#   ./scripts/docker-build-ota.sh
#
# Artifacts: ./out/android_cast-latest.apk  ./out/ota/v0/ota/...
#
# Deploy to BE (example — adjust host/path):
#   rsync -av ./out/ota/v0/ user@be:/var/www/localhost/htdocs/v0/
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
IMAGE="${ANDROIDCAST_CI_IMAGE:-androidcast-ci:latest}"

docker build -t "$IMAGE" -f "${ROOT}/Dockerfile" "${ROOT}"

mkdir -p "${ROOT}/out"

docker run --rm \
  -v "${ROOT}:/workspace" \
  -w /workspace \
  -e OTA_BASE_URL="${OTA_BASE_URL:-}" \
  -e OTA_CHANNEL="${OTA_CHANNEL:-staging}" \
  -e GRADLE_TASK="${GRADLE_TASK:-assembleDebug}" \
  -e SKIP_NATIVE="${SKIP_NATIVE:-0}" \
  -e SKIP_TESTS="${SKIP_TESTS:-0}" \
  -e RELEASE_NOTES="${RELEASE_NOTES:-}" \
  -e OUT_DIR=/workspace/out \
  "$IMAGE" \
  ./scripts/ci-build-and-publish-ota.sh

echo ""
echo "Done. APK: ${ROOT}/out/android_cast-latest.apk"
if [[ -f "${ROOT}/out/BUILD_INFO.json" ]]; then
  echo "OTA channel URL:"
  sed -n 's/.*"channelUrl": "\([^"]*\)".*/\1/p' "${ROOT}/out/BUILD_INFO.json" | head -1
fi
