#!/bin/bash

PAGE_SIZE="$(getconf PAGE_SIZE)"
if [[ "$PAGE_SIZE" == "16384" ]]; then
   error "User error (reporting allowed): 16K pagesize not supported on box86 and your system is currently running a 32bit ARM OS. Consider opening an issue on Box86 GitHub."
fi

if dpkg -l box86 &>/dev/null ;then
  sudo apt purge -y --allow-change-held-packages box86*
fi

add_external_repo "box86" "https://pi-apps-coders.github.io/box86-debs/KEY.gpg" "https://Pi-Apps-Coders.github.io/box86-debs/debian" "./" || exit 1

apt_update
if [ $? != 0 ]; then
  rm_external_repo "box86"
  error "Failed to perform apt update after adding box86 repository."
fi

# obtain SOC_ID
get_model
if [[ "$SOC_ID" == "tegra-x1" ]] || [[ "$SOC_ID" == "tegra-x2" ]]; then
  install_packages box86-tegrax1 || exit 1
elif [[ "$SOC_ID" == "rk3399" ]]; then
  install_packages box86-rk3399 || exit 1
elif [[ "$SOC_ID" == "bcm2711" ]]; then
  install_packages box86-rpi4arm64 || exit 1
elif [[ "$SOC_ID" == "bcm2837" ]]; then
  install_packages box86-rpi3arm64 || exit 1
elif cat /proc/cpuinfo | grep -q aes; then
  warning "There is no box86 pre-build for your device $SOC_ID $model"
  warning "Installing the generic arm box86 build as a fallback (crypto extensions enabled)"
  install_packages box86-generic-arm || exit 1
else
  warning "There is no box86 pre-build for your device $SOC_ID $model"
  warning "Installing the RPI4 tuned box86 build as a fallback (no crypto extensions enabled)"
  install_packages box86-rpi4arm64 || exit 1
fi
