#!/bin/sh

set -eu

if [ "$TARGETARCH" != "arm64" ] ; then
  exit 0
fi

EMULATOR="${EMULATOR:-fex}"
apt-get update

if [ "$EMULATOR" = "fex" ] ; then
  # FEX-Emu: official PPA (arm64 builds), Ubuntu base required
  DEBIAN_FRONTEND=noninteractive apt-get install -y \
    software-properties-common \
    squashfs-tools \
    ca-certificates \
    curl

  add-apt-repository -y ppa:fex-emu/fex
  apt-get update

  # fex-emu is a virtual package; pick the explicit variant matching the CPU.
  # RK3588 (Cortex-A76) has ARMv8.2 features; fall back to armv8.0.
  FEX_PKG="fex-emu-armv8.2"
  apt-get install -y --no-install-recommends "$FEX_PKG" || FEX_PKG="fex-emu-armv8.0"
  DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends "$FEX_PKG" libjemalloc2

  # Thunks are optional but speed up glibc-heavy servers
  DEBIAN_FRONTEND=noninteractive apt-get install -y fex-emu-thunks 2>/dev/null || true

  # Bake the x86_64 RootFS into the image so the container is fully self-contained
  # (no FEXRootFSFetcher at first start, no network needed at runtime)
  ROOTFS_URL=$(curl -fsSL https://rootfs.fex-emu.gg/RootFS_links.json \
    | python3 -c "import json,sys; d=json.load(sys.stdin)['v1']; print(d['Ubuntu 24.04 (SquashFS)']['URL'])")
  echo "Fetching FEX RootFS from $ROOTFS_URL"
  curl -fsSL "$ROOTFS_URL" -o /tmp/fex-rootfs.sqsh

  # Extracted instead of mounted: works in containers without FUSE/SYS_ADMIN
  mkdir -p /opt/fex-emu-rootfs
  unsquashfs -q -d /opt/fex-emu-rootfs/rootfs /tmp/fex-rootfs.sqsh
  rm -f /tmp/fex-rootfs.sqsh
else
  # Box64 fallback
  DEBIAN_FRONTEND=noninteractive apt-get install -y debian-keyring

  curl -L https://ryanfortner.github.io/box64-debs/box64.list -o /etc/apt/sources.list.d/box64.list
  curl -L https://ryanfortner.github.io/box64-debs/KEY.gpg | gpg --dearmor | tee /etc/apt/trusted.gpg.d/box64-debs-archive-keyring.gpg

  apt-get update
  DEBIAN_FRONTEND=noninteractive apt-get install -y \
    "$BOX64_PACKAGE" \
    libjemalloc2
fi

apt-get clean
rm -rf /var/lib/apt/lists/*
