#!/usr/bin/env bash
# Download and install the OpenHarmony SDK (linux/native component only).
#
# Mirrors the relevant parts of openharmony-rs/setup-ohos-sdk for the v6.x
# release layout: the upstream archive is a tar.gz that contains per-OS
# directories of zipped components; for v6.0/v6.1 it is not pre-stripped, so
# `tar -xf` lands files at `./linux/<component>.zip` etc.
set -euo pipefail

: "${SDK_VERSION:?SDK_VERSION (e.g. v6.1) must be set}"
SDK_DIR="${SDK_DIR:-/opt/ohos-sdk}"

BASE_URL="https://github.com/openharmony-rs/ohos-sdk/releases/download/${SDK_VERSION}"
ARCHIVE="ohos-sdk-windows_linux-public.tar.gz"

WORK_DIR="$(mktemp -d)"
trap 'rm -rf "${WORK_DIR}"' EXIT

echo "Fetching OpenHarmony SDK ${SDK_VERSION} chunks from ${BASE_URL}"
curl --fail --location --silent --show-error \
  -o "${WORK_DIR}/${ARCHIVE}.aa" "${BASE_URL}/${ARCHIVE}.aa"
curl --fail --location --silent --show-error \
  -o "${WORK_DIR}/${ARCHIVE}.ab" "${BASE_URL}/${ARCHIVE}.ab"
curl --fail --location --silent --show-error \
  -o "${WORK_DIR}/${ARCHIVE}.sha256" "${BASE_URL}/${ARCHIVE}.sha256"

cat "${WORK_DIR}/${ARCHIVE}.aa" "${WORK_DIR}/${ARCHIVE}.ab" > "${WORK_DIR}/${ARCHIVE}"
(
  cd "${WORK_DIR}"
  # The .sha256 file contains just the digest; pair it with the filename for sha256sum -c.
  echo "$(cat "${ARCHIVE}.sha256")  ${ARCHIVE}" | sha256sum --check --status
)
echo "Checksum OK."

mkdir -p "${SDK_DIR}"
echo "Extracting tarball into ${SDK_DIR}"
tar -C "${SDK_DIR}" -xf "${WORK_DIR}/${ARCHIVE}"

# Drop the windows/ tree; we only need the linux toolchain inside the container.
rm -rf "${SDK_DIR}/windows" "${SDK_DIR}/ohos"

cd "${SDK_DIR}/linux"
# Unzip only the native toolchain; other components (ets, js, previewer,
# toolchains) bloat the image and are not used by ohos-sys workflows.
native_zip=( native-linux-x64-*.zip )
if [[ ! -f "${native_zip[0]}" ]]; then
  echo "Expected native-linux-x64-*.zip inside ${SDK_DIR}/linux but found none." >&2
  ls -la
  exit 1
fi
unzip -q "${native_zip[0]}"
rm -f -- *.zip

# Sanity checks — fail fast if the layout drifts.
test -d "${SDK_DIR}/linux/native/sysroot" \
  || { echo "Sysroot missing after extraction." >&2; exit 1; }
test -x "${SDK_DIR}/linux/native/llvm/bin/aarch64-unknown-linux-ohos-clang" \
  || { echo "aarch64-unknown-linux-ohos-clang missing after extraction." >&2; exit 1; }
test -f "${SDK_DIR}/linux/native/oh-uni-package.json" \
  || { echo "oh-uni-package.json missing after extraction." >&2; exit 1; }

API_VERSION="$(jq -r .apiVersion "${SDK_DIR}/linux/native/oh-uni-package.json")"
SDK_PKG_VERSION="$(jq -r .version "${SDK_DIR}/linux/native/oh-uni-package.json")"
echo "Installed OpenHarmony SDK ${SDK_PKG_VERSION} (API ${API_VERSION}) at ${SDK_DIR}/linux/native"
