#!/bin/bash

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

sudo wget https://pi-apps-coders.github.io/box86-debs/box86.list -O /etc/apt/sources.list.d/box86.list
if [ $? != 0 ];then
  sudo rm -f /etc/apt/sources.list.d/box86.list
  error "Failed to add box86.list file!"
fi

sudo rm -f /usr/share/keyrings/box86-debs-archive-keyring.gpg /etc/apt/trusted.gpg.d/box86-debs-archive-keyring.gpg
sudo mkdir -p /etc/apt/trusted.gpg.d
wget -qO- https://pi-apps-coders.github.io/box86-debs/KEY.gpg | sudo gpg --dearmor -o /etc/apt/trusted.gpg.d/box86-debs-archive-keyring.gpg > /dev/null

if [ $? != 0 ];then
  sudo rm -f /etc/apt/sources.list.d/box86.list
  error "Failed to add KEY.gpg to APT keyring!"
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
