#!/usr/bin/env bash
# Download a pinned Apache ECharts build next to this script (echarts.min.js).
# Fail-fast: non-zero exit if download or write fails.
set -euo pipefail

VERSION="5.5.1"
# jsDelivr npm mirror of the official package
URL="https://cdn.jsdelivr.net/npm/echarts@${VERSION}/dist/echarts.min.js"

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
OUT="${SCRIPT_DIR}/echarts.min.js"
TMP="${OUT}.tmp.$$"

cleanup() { rm -f "${TMP}"; }
trap cleanup EXIT

echo "fetching ECharts ${VERSION} …"
echo "  ${URL}"

if command -v curl >/dev/null 2>&1; then
  curl -fsSL --connect-timeout 30 --max-time 120 "${URL}" -o "${TMP}"
elif command -v wget >/dev/null 2>&1; then
  wget -q -O "${TMP}" "${URL}"
else
  echo "error: need curl or wget" >&2
  exit 1
fi

size="$(wc -c < "${TMP}" | tr -d ' ')"
if [[ "${size}" -lt 100000 ]]; then
  echo "error: download too small (${size} bytes); refusing to install" >&2
  exit 1
fi
# License header is long; sample further into the file for real code markers.
if ! head -c 5000 "${TMP}" | grep -q 'echarts\|!function'; then
  echo "error: download does not look like echarts.min.js" >&2
  exit 1
fi

mv -f "${TMP}" "${OUT}"
trap - EXIT
echo "wrote ${OUT} (${size} bytes)"
