#!/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 lots of games and drivers
    from the actively booted TechLit system to make a smaller image
"
  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 "Uninstalling bigger and less-used programs"
run yay --noconfirm -Rs blender linux-t2-headers linux-firmware-marvell scratch3 scratchjr-desktop-git emacs-nox || :

say "Removing unneeded files and directories"
run sudo rm -rf /usr/share/doc/* || :
run sudo rm -rf /usr/lib/firmware/{nvidia,amdgpu} || :
run sudo rm -rf /usr/share/fonts/We-Fonts || :

say "Removing local pacman cache"
find /usr/local/src -type f \
  -not -name "mesa*" \
  -not -name "xf86-video-intel*" \
  -not -name "libxvmc*" \
  -delete

run sudo btrfs filesystem defragment -r -v -czstd /usr/local/src

say "Rebuilding initramfs with zstd"
run sudo cp "$ROOT"/roles/mini/mkinitcpio.conf /etc/mkinitcpio.conf
run sudo mkinitcpio -P

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
