#!/bin/bash

if [ -z "$__cpu_op_mode_32" ]; then
  error "User error: Box86 requires a CPU capable of executing ARM32 instructions. Your CPU is only capable of executing ARM64 instructions."
fi

PAGE_SIZE="$(getconf PAGE_SIZE)"
if [[ "$PAGE_SIZE" == "16384" ]]; then
  #switch to 4K pagesize kernel
  if [ -f /boot/config.txt ] || [ -f /boot/firmware/config.txt ]; then
    if [ -f /boot/firmware/config.txt ]; then
      boot_config="/boot/firmware/config.txt"
    elif [ -f /boot/config.txt ]; then
      boot_config="/boot/config.txt"
    fi
    text="Raspberry Pi 5 PiOS images ship by default with a 16K PageSize Linux Kernel.
This kernel causes incompatibilities with some software including Box86 https://github.com/raspberrypi/bookworm-feedback/issues/107

Would you like to automatically switch to a 4K PageSize Linux Kernel?"
    userinput_func "$text" "No, keep 16K PageSize Kernel and Exit" "Yes, switch to 4K PageSize Kernel"
    if [ "$output" == "No, keep 16K PageSize Kernel and Exit" ]; then
      error "User error: Your current running kernel is built with 16K PageSize and is incompatible with Box86. You must switch to a 4K PageSize kernel (and chose to not do so automatically) before installing Box86."
    fi
    echo "" | sudo tee --append $boot_config >/dev/null
    echo "[pi5]" | sudo tee --append $boot_config >/dev/null
    echo "kernel=kernel8.img" | sudo tee --append $boot_config >/dev/null
    echo -e "The 4K PageSize Kernel has been enabled by adding 'kernel=kernel8.img' to $boot_config\nPlease reboot now and install the Box86 app again."
    sleep infinity
  else
    error "User error (reporting allowed): Your current running kernel is built with 16K PageSize and is incompatible with Box86. Changing kernels automatically cannot be done since no /boot/config.txt or /boot/firmware/config.txt file was found."
  fi
fi

function check-armhf() {
	ARMHF="$(dpkg --print-foreign-architectures | grep "armhf")"
}

#add armhf architecture (multiarch)
check-armhf
if [[ "$ARMHF" == *"armhf"* ]]; then
  echo "armhf arcitecture already added..."
else
  sudo dpkg --add-architecture armhf
  check-armhf
  if [[ "$ARMHF" != *"armhf"* ]]; then
    error "armhf architecture should be added by now, but it isn't!"
  fi
fi

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

#install box86 dependencies
unset rpi_arm_userspace
# only install the libraspberrypi0 arm32 package if the user already has the libraspberrypi0 arm64 package installed
if package_installed libraspberrypi0 ; then
  rpi_arm_userspace="libraspberrypi0:armhf"
fi

unset mesa_va_drivers
# only install the mesa-va-drivers arm32 package if the user already has the mesa-va-drivers arm64 package installed
if package_installed mesa-va-drivers ; then
  mesa_va_drivers="mesa-va-drivers:armhf"
fi

unset mesa_vulkan_drivers
# only install the mesa-vulkan-drivers arm32 package if the user already has the mesa-vulkan-drivers arm64 package installed
if package_installed mesa-vulkan-drivers ; then
  mesa_vulkan_drivers="mesa-vulkan-drivers:armhf"
fi

if [[ ! -z "$__os_original_id" ]]; then
  error "User error: Box86 cannot be installed on $__os_original_desc. Please use any official Ubuntu Flavor, Debian, or PiOS/Raspbian Bullseye."
elif [[ "$__os_codename" == "buster" ]]; then
  error "User error: Box86 cannot be installed on $__os_desc. Please use any official Ubuntu Flavor, Debian, or PiOS/Raspbian Bullseye."
fi

# libsdl2-mixer-2.0-0:armhf NOT included since it depends on libopusfile0 on newer distros (buster+ and focal+) which is NOT multiarch compatible

box86_depends=()
if package_available libcal3d12t64:armhf; then
  box86_depends+=('libcal3d12t64:armhf')
else
  box86_depends+=('libcal3d12v5:armhf')
fi
if package_available libcups2t64:armhf; then
  box86_depends+=('libcups2t64:armhf')
else
  box86_depends+=('libcups2:armhf')
fi
if package_available libcurl4t64:armhf; then
  box86_depends+=('libcurl4t64:armhf')
else
  box86_depends+=('libcurl4:armhf')
fi
if package_available libgtk2.0-0t64:armhf; then
  box86_depends+=('libgtk2.0-0t64:armhf')
else
  box86_depends+=('libgtk2.0-0:armhf')
fi
if package_available libgtk-3-0t64:armhf; then
  box86_depends+=('libgtk-3-0t64:armhf')
else
  box86_depends+=('libgtk-3-0:armhf')
fi
if package_available libpng16-16t64:armhf; then
  box86_depends+=('libpng16-16t64:armhf')
else
  box86_depends+=('libpng16-16:armhf')
fi
if package_available libsmpeg0t64:armhf; then
  box86_depends+=('libsmpeg0t64:armhf')
else
  box86_depends+=('libsmpeg0:armhf')
fi
if package_available libssl3t64:armhf; then
  box86_depends+=('libssl3t64:armhf')
elif package_available libssl3:armhf; then
  box86_depends+=('libssl3:armhf')
else
  box86_depends+=('libssl1.1:armhf')
fi

install_packages "${box86_depends[@]}" libc6:armhf libstdc++6:armhf \
  libx11-6:armhf \
  libgdk-pixbuf-2.0-0:armhf '|' libgdk-pixbuf2.0-0:armhf \
  libjpeg62:armhf \
  libopenal1:armhf osspd:armhf libvorbisfile3:armhf \
  libudev1:armhf \
  libsdl2-2.0-0:armhf libsdl2-image-2.0-0:armhf libsdl2-net-2.0-0:armhf libsdl2-ttf-2.0-0:armhf \
  libsdl1.2debian:armhf libsdl-mixer1.2:armhf libsdl-image1.2:armhf libsdl-net1.2:armhf libsdl-sound1.2:armhf libsdl-ttf2.0-0:armhf \
  libssh-4:armhf '|' libssh-gcrypt-4:armhf \
  libgssapi-krb5-2:armhf libkrb5-3:armhf \
  $rpi_arm_userspace $mesa_va_drivers $mesa_vulkan_drivers libegl1:armhf libglx-mesa0:armhf libgl1:armhf libgles2:armhf || exit 1

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:armhf || exit 1
elif [[ "$SOC_ID" == "rk3399" ]]; then
  install_packages box86-rk3399:armhf || exit 1
elif [[ "$SOC_ID" == "bcm2711" ]]; then
  install_packages box86-rpi4arm64:armhf || exit 1
elif [[ "$SOC_ID" == "bcm2837" ]]; then
  install_packages box86-rpi3arm64:armhf || 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:armhf || 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:armhf || exit 1
fi
