#!/usr/bin/env bash
set -euo pipefail

script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
cd "$script_dir"

if [[ $(uname -m) != aarch64 ]]; then
  echo "This package must be built natively on aarch64." >&2
  exit 1
fi

if ! tr '\0' '\n' </proc/device-tree/compatible 2>/dev/null | grep -qx 'apple,j293'; then
  echo "Expected the Apple J293 / MacBookPro17,1 hardware." >&2
  exit 1
fi

if [[ ! -e /etc/pacman.conf ]]; then
  echo "This installer is for Asahi Arch/ALARM, not Fedora." >&2
  exit 1
fi

available_kib=$(df --output=avail -k "$script_dir" | tail -n 1 | tr -d ' ')
required_kib=$((35 * 1024 * 1024))
if (( available_kib < required_kib )); then
  echo "At least 35 GiB free is required for the kernel build." >&2
  exit 1
fi

echo "Installing the official Asahi kernel build dependencies..."
sudo pacman -Syu --needed \
  base-devel bc dtc kmod libelf pahole cpio perl rustup rust-bindgen \
  tar xz xmlto python

echo "Installing the Rust toolchain required by Asahi 7.1.6..."
rustup toolchain install 1.93.1 --profile minimal --component rust-src
export RUSTUP_TOOLCHAIN=1.93.1

echo "Building the Pacman-managed Fairydust package..."
makepkg --cleanbuild --force

mapfile -t packages < <(
  find "$script_dir" -maxdepth 1 -type f \
    -name 'linux-asahi-fairydust-[0-9]*-aarch64.pkg.tar.*' -print | sort
)
if (( ${#packages[@]} != 1 )); then
  echo "Expected exactly one Fairydust kernel package; found ${#packages[@]}." >&2
  exit 1
fi

sudo pacman -U --needed "${packages[0]}"
sudo mkinitcpio -P

fairydust_modules=$(find /usr/lib/modules -mindepth 1 -maxdepth 1 -type d \
  -name '*fairydust*' -print | sort -V | tail -n 1)
if [[ -z $fairydust_modules || ! -d $fairydust_modules/dtbs ]]; then
  echo "The installed Fairydust module/DTB directory was not found." >&2
  exit 1
fi

# m1n1 stage 2 must contain the DTBs that include the Fairydust Alt Mode nodes.
# Asahi ALARM packages the DTBs directly in dtbs/, not in dtbs/apple/.
sudo env DTBS="$fairydust_modules/dtbs/*.dtb" update-m1n1
sudo grub-mkconfig -o /boot/grub/grub.cfg

echo
echo "Fairydust installed alongside stock linux-asahi."
echo "Reboot, choose the Fairydust kernel in GRUB, then run ./verify.sh."
