#!/bin/bash

## Copyright (C) 2026 - 2026 ENCRYPTED SUPPORT LLC <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

## AI-Assisted

## Shared plumbing for the VBox cowbuilder chroot scripts
## ('pbuilder-chroot-script-create-vbox-vm',
## 'pbuilder-chroot-script-export-vbox-vm'). Sourced from inside the cowbuilder
## chroot.
##
## style-ok: no-strict - file is not executed.

## This code runs as root inside the cowbuilder chroot (via 'cowbuilder
## --execute'), so 'sudo' to root is redundant and would break cowdancer.
## '$SUDO_TO_VBOX_TEMP' is deliberately not cleared here, because it must drop
## privileges to the 'dm-vbox-temp' account whose VirtualBox registry holds the
## VM.
SUDO_TO_ROOT=""

error() {
   printf '%s\n' "ERROR: $*" >&2
   exit 1
}

## Dump important chroot state info.
diagnostics_dump() {
   true "INFO: diagnostics: locale: LC_ALL='${LC_ALL:-}' LANG='${LANG:-}' LANGUAGE='${LANGUAGE:-}'"
   true "INFO: diagnostics: temp dir env: TMPDIR='${TMPDIR:-}' TMP='${TMP:-}'"

   true "INFO: diagnostics: disk space:"
   df --human-readable || true
   df --inodes || true

   true "INFO: diagnostics: memory:"
   head --lines=5 -- /proc/meminfo || true

   true "INFO: diagnostics: VirtualBox XPCOM IPC state under '/tmp':"
   find /tmp/ -mindepth 1 -maxdepth 2 -path '/tmp/.vbox*' -exec ls -l -a -d -- {} \; || true

   true "INFO: diagnostics: VirtualBox processes (as visible in this PID namespace):"
   pgrep --list-full -- "[Vv][Bb]ox" || true

   true "INFO: diagnostics: '${HOMEVAR_VBOX_TEMP}/.config/VirtualBox':"
   ls -l -a -- "${HOMEVAR_VBOX_TEMP}/.config/VirtualBox/" || true
   tail --lines=100 -- "${HOMEVAR_VBOX_TEMP}/.config/VirtualBox/VBoxSVC.log" || true
}

diagnostics_on_error() {
   if [ "${diagnostics_on_error_done}" = "true" ]; then
      return 0
   fi
   diagnostics_on_error_done=true

   true "ERROR-DIAG: a command failed; dumping chroot diagnostics."
   diagnostics_dump
}

diagnostics_on_error_done=false
trap diagnostics_on_error ERR

## Remove VirtualBox XPCOM IPC runtime state. We use unshare and a PID
## namespace to ensure lingering VBox processes are killed, and it doesn't
## break anything to remove these files/sockets. VirtualBox hardcodes '/tmp'
## as the directory to store these files in.
vbox_stale_ipc_cleanup() {
   safe-rm --recursive --force -- /tmp/.vbox-*-ipc
}

## Enable sudo's --chdir option and make sure locale variables are passed
## through correctly.
setup_vbox_temp_sudo() {
   printf '%s\n' "Defaults runcwd=*" 'Defaults env_keep += "LC_ALL LANG LANGUAGE"' \
      | SUDO_EDITOR="" VISUAL="" EDITOR=tee visudo -f /etc/sudoers.d/dm-vbox-temp-config >/dev/null

   ## Sanity test.
   visudo --strict --check /etc/sudoers.d/dm-vbox-temp-config
}
