#!/bin/sh
# Companion to openchamber-setup.mdx. Linux x86-64 and ARM64.
set -u

TOOLS_PREFIX="${TOOLS_PREFIX:-/home/openchamber/.tools}"
TOOLS_BIN="$TOOLS_PREFIX/bin"
PATH="$TOOLS_BIN:$PATH"
NPM_CONFIG_PREFIX="$TOOLS_PREFIX"
MSB_HOME="${MSB_HOME:-$TOOLS_PREFIX/msb-home}"
export PATH NPM_CONFIG_PREFIX MSB_HOME

# Reference versions from the original environment. Existing tools are skipped;
# changing these pins does not upgrade an already populated tools directory.
GH_VERSION=2.101.0
OPENSPEC_VERSION=1.13.2
MSB_VERSION=0.7.4

log() { printf '[tools] %s\n' "$*"; }
mkdir -p "$TOOLS_BIN" "$MSB_HOME" || log 'WARNING: cannot create tool directories'

if [ ! -x "$TOOLS_BIN/gh" ]; then
  # The image includes Python, but not curl or wget. Download the official
  # release over HTTPS. This minimal example does not verify release checksums.
  if python3 - "$GH_VERSION" "$TOOLS_BIN" <<'PY'
import io
import os
import platform
import shutil
import sys
import tarfile
import urllib.request

version, destination = sys.argv[1:]
architecture = {"x86_64": "amd64", "aarch64": "arm64", "arm64": "arm64"}[platform.machine()]
release = f"gh_{version}_linux_{architecture}"
url = f"https://github.com/cli/cli/releases/download/v{version}/{release}.tar.gz"
with urllib.request.urlopen(url, timeout=120) as response:
    payload = response.read()
with tarfile.open(fileobj=io.BytesIO(payload), mode="r:gz") as archive:
    source = archive.extractfile(f"{release}/bin/gh")
    if source is None:
        raise RuntimeError("GitHub CLI binary missing from archive")
    temporary = os.path.join(destination, ".gh-download")
    with source, open(temporary, "wb") as output:
        shutil.copyfileobj(source, output)
os.chmod(temporary, 0o755)
os.replace(temporary, os.path.join(destination, "gh"))
PY
  then
    log 'gh installed'
  else
    log 'WARNING: gh installation failed; continuing'
  fi
fi

if [ ! -x "$TOOLS_BIN/openspec" ]; then
  npm install -g --prefix "$TOOLS_PREFIX" "@fission-ai/openspec@$OPENSPEC_VERSION" \
    || log 'WARNING: OpenSpec installation failed; continuing'
fi

case "$(uname -m)" in
  x86_64) platform_package=@superradcompany/microsandbox-linux-x64-gnu ;;
  aarch64|arm64) platform_package=@superradcompany/microsandbox-linux-arm64-gnu ;;
  *) platform_package="" ;;
esac

if [ -n "$platform_package" ]; then
  if [ ! -x "$TOOLS_BIN/microsandbox-mcp" ] || \
     [ ! -x "$TOOLS_BIN/msb" ] || \
     ! "$TOOLS_BIN/msb" --version >/dev/null 2>&1; then
    npm install -g --prefix "$TOOLS_PREFIX" \
      "microsandbox@$MSB_VERSION" \
      "microsandbox-mcp@$MSB_VERSION" \
      "$platform_package@$MSB_VERSION" \
      || log 'WARNING: microsandbox installation failed; continuing'
  fi
else
  log 'WARNING: unsupported microsandbox architecture'
fi

if [ -r /dev/kvm ] && [ -w /dev/kvm ]; then
  log 'KVM is accessible; verify with an actual sandbox boot'
else
  log 'WARNING: KVM inaccessible; check the device mapping and supplementary group'
fi

exec sh /home/openchamber/openchamber-entrypoint.sh
