#!/usr/bin/env bash

set -euo pipefail

BASE_URL="${ZEROARM_CPP_SDK_BASE_URL:-https://robotic.forceease.tech/cpp-sdk/current}"
INSTALL_PREFIX="${1:-/usr/local}"

log() {
  printf '[zeroarm-cpp-sdk] %s\n' "$*"
}

fail() {
  printf '[zeroarm-cpp-sdk] ERROR: %s\n' "$*" >&2
  exit 1
}

require_command() {
  command -v "$1" >/dev/null 2>&1 || fail "missing required command: $1"
}

detect_arch() {
  case "$(uname -m)" in
    x86_64|amd64)
      printf 'x86_64\n'
      ;;
    aarch64|arm64)
      printf 'aarch64\n'
      ;;
    *)
      fail "unsupported architecture: $(uname -m); expected x86_64 or aarch64"
      ;;
  esac
}

require_command curl
require_command python3
require_command sha256sum
require_command stat
require_command tar

arch="$(detect_arch)"
tmp_dir="$(mktemp -d)"
trap 'rm -rf "${tmp_dir}"' EXIT

manifest_path="${tmp_dir}/manifest.json"
log "Downloading release manifest from ${BASE_URL}/manifest.json"
curl --fail --location --silent --show-error \
  --output "${manifest_path}" "${BASE_URL}/manifest.json"

mapfile -t release < <(
  python3 - "${manifest_path}" "${arch}" <<'PY'
import json
import pathlib
import sys

manifest = json.loads(pathlib.Path(sys.argv[1]).read_text(encoding="utf-8"))
arch = sys.argv[2]
expected_name = f"zeroArm_sdk-linux-{arch}.tar.gz"
matches = [item for item in manifest.get("artifacts", []) if item.get("name") == expected_name]
if len(matches) != 1:
    raise SystemExit(f"manifest must contain exactly one {expected_name} artifact")
artifact = matches[0]
version = str(manifest.get("version", "")).strip()
sha256 = str(artifact.get("sha256", "")).strip().lower()
size = artifact.get("size")
if not version:
    raise SystemExit("manifest version is missing")
if len(sha256) != 64 or any(ch not in "0123456789abcdef" for ch in sha256):
    raise SystemExit("manifest artifact SHA256 is invalid")
if not isinstance(size, int) or size <= 0:
    raise SystemExit("manifest artifact size is invalid")
print(version)
print(expected_name)
print(sha256)
print(size)
PY
)

[[ "${#release[@]}" -eq 4 ]] || fail "failed to parse release manifest"
version="${release[0]}"
artifact_name="${release[1]}"
expected_sha256="${release[2]}"
expected_size="${release[3]}"
artifact_path="${tmp_dir}/${artifact_name}"

log "Downloading ZeroArm C++ SDK ${version} for ${arch}"
curl --fail --location --show-error \
  --output "${artifact_path}" "${BASE_URL}/${artifact_name}"
actual_size="$(stat -c '%s' "${artifact_path}")"
[[ "${actual_size}" == "${expected_size}" ]] \
  || fail "SDK archive size mismatch: expected ${expected_size}, got ${actual_size}"
printf '%s  %s\n' "${expected_sha256}" "${artifact_path}" | sha256sum --check --status \
  || fail "SDK archive SHA256 does not match the release manifest"
log "Archive SHA256 verified: ${expected_sha256}"

tar --extract --gzip --file "${artifact_path}" --directory "${tmp_dir}"
package_dir="${tmp_dir}/zeroArm_sdk"
installer="${package_dir}/install_zeroarm_sdk.sh"
[[ -f "${package_dir}/VERSION" ]] || fail "SDK archive is missing VERSION"
[[ -f "${installer}" ]] || fail "SDK archive is missing install_zeroarm_sdk.sh"
[[ -f "${package_dir}/include/zero_arm_sdk/zero_arm_sdk.h" ]] \
  || fail "SDK archive is missing public headers"
[[ -f "${package_dir}/lib/libzeroArm_sdk.a" ]] \
  || fail "SDK archive is missing libzeroArm_sdk.a"

log "Installing to ${INSTALL_PREFIX}"
bash "${installer}" "${version}" "${INSTALL_PREFIX}"
log "Installation completed: ZeroArm C++ SDK ${version}"
