#!/usr/bin/env bash
# vim:et:ts=2:sts=2:sw=2

# Get absolute repository root (especially when symlinked)
ROOT="$(realpath "$(dirname "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")")")"

# Load accompanying bash library
source "$ROOT/lib/lib.bash"

if [ -n "$HELP" ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
  say "
  USAGE:
    $(g "${BASH_SOURCE##*/}")

  DESCRIPTION:
    $(g "${BASH_SOURCE##*/}") uninstalls the linux-t2 kernel
    and repositories from the actively booted TechLit system
"
  exit 1
fi

# Exit now if run as root user
assert-is-user

say "This script will need root access via $(c sudo)"
sudo echo thank you

say "Removing T2 Repositories"
run sudo cp "$ROOT/roles/mac/pacman.conf" "/etc/pacman.conf"

say "Removing $(c apple-bce) from $(c mkinitcpio.conf)"
run sudo sed -e 's/apple-bce//' -i "/etc/mkinitcpio.conf"

say "Installing mainline kernel and firmware"
run yay --noconfirm -Sy linux linux-headers linux-firmware

say "Removing T2 kernel and firmware"
run yay --noconfirm -Rs linux-t2 linux-t2-headers b43-firmware apple-bcm-firmware

say "Reinstalling b43-firmware"
run yay --noconfirm -S b43-firmware

say "Handing off to $(c tl-sys-personalize)..."
run sudo "$ROOT/bin/tl-sys-personalize" "/var/btrfs"

# Unmount system and quiet exit hook
# shellcheck disable=SC2218
cleanup
cleanup() { :; }

say "Rebooting..."
sudo reboot
