#!/usr/bin/env bash

# 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"

# Must be run as root (or exit)
assert-is-root

DISK="$1"
if [ -z "$DISK" ] || [ -n "$HELP" ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
  say "
  $(r TODO:)
    $(r This command needs to be ported from Void to Artix)

  USAGE:
    $(g "${BASH_SOURCE##*/}")  $(c /dev/sdx)

  DESCRIPTION:
    $(g "${BASH_SOURCE##*/}") bootstraps a new TechLit artix system
    on $(c /dev/sdx) from scratch using either the upstream artix repos
    or a local cache.

  NOTE:
    Run $(g tl-provision-desktop) on $(c /dev/sdx) first to prepare the
    partition layout and required repo components before bootstrapping.
  "
  exit 1
fi

# Exit now if components are missing
assert-fetched void-mklive theme

# Mountpoint to use
PREFIX="${PREFIX:-"$(mktemp -d)"}"
TMP_PREFIX="${TMP_PREFIX:-"$(mktemp -d)"}"

# partition infix
[[ "$DISK" =~ mmc ]] || [[ "$DISK" =~ nvm ]] && p=p || p=

# Cache locations of foreign package
FOREIGN_CACHE="$ROOT/srv/.tl-repo/"

# Always use the default hostname
HOSTNAME="tl-0000"

# Roles to install
ROLES=(global hardware desktop)

# XBPS packages to install
PKGS=(
  base-system void-repo-nonfree
  socklog-void dbus
  elogind tlp

  fbv

  bash-completion
  tmux vim htop
  git curl rsync jq tar

  grub-i386-efi
  grub-x86_64-efi
  parted efibootmgr

  NetworkManager bind-utils openntpd runit-nftables
  lighttpd openssh ngircd

  nss-mdns avahi-utils

  acpi b43-firmware

  linux-firmware-amd
  mesa-dri
  vulkan-loader mesa-vulkan-radeon amdvlk
  xf86-video-amdgpu xf86-video-ati
  mesa-vaapi mesa-vdpau

  linux-firmware-intel
  mesa-dri
  vulkan-loader mesa-vulkan-intel
  intel-video-accel

  linux-firmware-nvidia
  xf86-video-nouveau

  xorg-minimal
  xorg-fonts
  xf86-input-libinput

  alsa-utils pulseaudio

  cinnamon feh
  nemo-preview nemo-fileroller
  conky

  xfce4-terminal
  hexchat
  sublime-text4

  firefox
  audacity
  blender
  olive

  gcompris-qt
  ktuberling

  minetest
)
# TODO: inkscape depends on glibc 12 somehow
# inkscape
# TODO: supertux* installs were broken
# supertux2 supertux2-data
# supertuxkart supertuxkart-data

# Foreign packages to install (AppImages, debian, etc.)
ONLYOFFICE_URL="https://github.com/ONLYOFFICE/appimage-desktopeditors/releases/download/v7.3.3/DesktopEditors-x86_64.AppImage"
SCRATCH_SR_URL="https://github.com/mikebarkmin/scratch-desktop/releases/download/3.6.0/Scratch.Desktop.3.6.0.AppImage"

# TODO: XBPS packages or AppImages for these
# SCRATCH_JR_URL="https://github.com/jfo8000/ScratchJr-Desktop/releases/download/v1.3.2/ScratchJr_1.3.2_amd64.deb"
# TUXMATH_URL="http://ftp.de.debian.org/debian/pool/main/t/tuxmath/tuxmath_2.0.3-8_amd64.deb"
# TUX4KIDS_URL="http://ftp.de.debian.org/debian/pool/main/t/t4kcommon/libt4k-common0_0.1.1-6_amd64.deb"


say "Gathering foreign packages"; {
  for url in "$ONLYOFFICE_URL" "$SCRATCH_SR_URL"; do
    name="$(basename "$url")"
    if [ -f "$FOREIGN_CACHE/$name" ]; then
      say " >> Cached: $(c "$name")"
    else
      say " >> Downloading: $(c "$name")"
      run curl "$url" -o "$FOREIGN_CACHE/$name.part"
      run mv "$FOREIGN_CACHE/$name"{.part,}
    fi
  done
}

mount_system() {
  say "Mounting system (and un-mounting on errors or exit)"; {
    cleanup() {
      say "Un-mounting system"
      tl-chroot-unmount
      run umount -qR "$PREFIX"
    }

    run mount "$DISK$p"4 -o subvol="@root" "$PREFIX"
    run mount "$DISK$p"4 -o subvol="@srv"  "$PREFIX/srv"
    run mount "$DISK$p"4                   "$PREFIX/var/btrfs"

    tl-chroot-mount
  }
}
mount_system

# Install & configure system packages
tl-bootstrap-xbps "${PKGS[@]}"

say "Configuring users"; {
  # Adding admin
  run root-chroot "groupadd -f -g $ADMIN_GID $ADMIN_GROUP"
  run root-chroot "useradd -g $ADMIN_GID -u $ADMIN_UID $ADMIN_USER"
  run root-chroot "groupadd -f audio"
  run root-chroot "groupadd -f network"
  run root-chroot "usermod -a -G wheel,network,audio $ADMIN_USER"

  # Adding guest
  run root-chroot "groupadd -f -g $GUEST_GID $GUEST_GROUP"
  run root-chroot "useradd -g $GUEST_GID -u $GUEST_UID $GUEST_USER"
  run root-chroot "groupadd -f nopasswdlogin"
  run root-chroot "usermod -a -G nopasswdlogin $GUEST_USER"

  # Locking accounts
  run root-chroot "passwd -dl root"
  run root-chroot "passwd -dl $GUEST_USER"
  pass="$(echo "$ADMIN_PASS" | openssl passwd -1 -stdin)"
  run root-chroot "echo '$ADMIN_USER:$pass' | chpasswd -e"
}

say "Removing cinnamon autostart applications"; {
  run mv "$PREFIX/etc/xdg/Xwayland-session"{.d,.disabled}

  run mv "$PREFIX/etc/xdg/autostart"{,.disabled}
  run mkdir "$PREFIX/etc/xdg/autostart"
  for svc in nm-applet pulseaudio; do
    run ln -sf "$PREFIX/etc/xdg/autostart"{.disabled,}"/$svc.desktop"
  done

  for exe in at-spi-bus-launcher at-spi2-registryd; do
    run mv "$PREFIX/usr/libexec/$exe"{,.disabled}
    run ln -sf "/bin/true" "$PREFIX/usr/libexec/$exe"
  done
}

say "Installing foreign packages"; {
  SRC="$FOREIGN_CACHE" DEST="$PREFIX"

  run tl-install "$(basename "$ONLYOFFICE_URL")" 0 0 755 "opt/onlyoffice/bin/onlyoffice"
  run write "$PREFIX/etc/profile.d/onlyoffice.sh" 'export PATH="$PATH:/opt/onlyoffice/bin"'
  run chmod 644 "$PREFIX/etc/profile.d/onlyoffice.sh"

  run tl-install "$(basename "$SCRATCH_SR_URL")" 0 0 755 "opt/scratch-sr/bin/scratch-sr"
  run write "$PREFIX/etc/profile.d/scratch-sr.sh" 'export PATH="$PATH:/opt/scratch-sr/bin"'
  run chmod 644 "$PREFIX/etc/profile.d/scratch-sr.sh"
}

say "Writing system version to $(c /etc/tl-desktop-version)"
run write "$PREFIX/etc/tl-desktop-version" "bootstrap"
run chmod 644 "$PREFIX/etc/tl-desktop-version"

# Installing TechLit roles
tl-bootstrap-roles "${ROLES[@]}"

# Prepare for bootloader
tl-bootstrap-kernel

# Handoff to write-theme
cleanup; cleanup() { :; }
run "$ROOT/bin/tl-write-theme" "$DISK"

mount_system
say "Baking guest homedir"; {
  fs="$PREFIX/var/btrfs"
  [ -d "$fs/@guest.prev" ] && run btrfs subvol delete "$fs/@guest.prev"
  run mv "$fs/@guest" "$fs/@guest.prev"
  run btrfs subvol snapshot "$fs/@root/home/guest" "$fs/@guest"
}

# Handoff to tl-hw-update-bootloader
cleanup; cleanup() { :; }
run "$ROOT/bin/tl-hw-update-bootloader" "$DISK"
