#!/usr/bin/env bash

# omarchy:summary=Install VirtualBox
# omarchy:requires-sudo=true

# Based: Debian carries no VirtualBox, so Oracle's signed apt repository for
# this release is added and its newest virtualbox-N.N installed, on amd64
# only, as the former dev tooling did. macOS takes the cask, which runs on
# Apple silicon too.

set -eo pipefail

echo "Installing VirtualBox..."

case $(omarchy-os) in
darwin)
  omarchy-pkg-add virtualbox cask=virtualbox
  ;;
*)
  if [[ $(dpkg --print-architecture) != amd64 ]]; then
    echo "VirtualBox has no Linux build for $(dpkg --print-architecture); nothing to install"
    exit 0
  fi
  if omarchy-cmd-missing virtualbox; then
    codename=$(. /etc/os-release && echo "${VERSION_CODENAME:-}")
    if [[ -z $codename ]]; then
      echo "Could not read this release's codename from /etc/os-release" >&2
      exit 1
    fi
    sudo install -d -m 755 /etc/apt/keyrings
    curl -fsSL https://www.virtualbox.org/download/oracle_vbox_2016.asc | sudo tee /etc/apt/keyrings/oracle-virtualbox-2016.asc >/dev/null
    echo "deb [arch=amd64 signed-by=/etc/apt/keyrings/oracle-virtualbox-2016.asc] https://download.virtualbox.org/virtualbox/debian $codename contrib" | sudo tee /etc/apt/sources.list.d/virtualbox.list >/dev/null
    sudo apt-get update
    package=$(apt-cache search --names-only '^virtualbox-[0-9]' | awk '{print $1}' | sort -V | tail -1)
    if [[ -z $package ]]; then
      echo "Oracle's repository carries no virtualbox package for $codename" >&2
      exit 1
    fi
    omarchy-pkg-add "$package"
  fi
  ;;
esac
