#!/bin/bash

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

## Static-analysis waivers: 'command -v' (the 'has' helper is not present
## inside the cowbuilder chroot) and 'rm' of a specific sudoers file.
## style-ok: no-has
## style-ok: no-safe-rm

## TODO: Functional but not enabled by default yet.
## This script gets executed by 'build-steps.d/*_cowbuilder-setup'.

## Install VirtualBox inside the chroot using 'dist-installer-cli'.
## Useful for running 'vboxmanage' inside a clean 'cowbuilder' chroot.

set -x
set -o errexit
set -o nounset
set -o pipefail
set -o errtrace
shopt -s inherit_errexit
shopt -s shift_verbose

## 'help-steps/pre' (which defines 'error') is not available inside the
## pbuilder chroot where this script runs, so define a local 'error'
## (mirrors 'pbuilder-chroot-script-create-vbox-vm').
error() {
   printf '%s\n' "ERROR: $*" >&2
   exit 1
}

## colors is not available in the pbuilder chroot where this
## script runs, so plain (uncolored) log messages.
true "INFO: Currently running cowbuilder VirtualBox chroot script."

## /usr/share/doc/pbuilder/examples/D10tmp
## https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=725434;msg=45
if [ -n "${TMP:-}" ]; then
   [ -d "$TMP" ] || mkdir -p -- "$TMP" || true
   chmod 1777 -- "$TMP" || true
fi
if [ -n "${TMPDIR:-}" ]; then
   [ -d "$TMPDIR" ] || mkdir -p -- "$TMPDIR" || true
   chmod 1777 -- "$TMPDIR" || true
fi

#declare -p | awk '{print $3}' | sort

## Debugging.
cat -- "/home/$user_name/pbuilder_config_file"

source "/home/$user_name/pbuilder_config_file"

## virtualbox-installer / dist-installer-cli refuses to run as 'root'.
## Hence run virtualbox-installer / dist-installer-cli under account 'dm-vbox-temp'.

## {{ code duplication
##    - prepare-build-machine
##    - pbuilder-chroot-script-virtualbox
adduser --system --group --home "$HOMEVAR_VBOX_TEMP" -- "dm-vbox-temp" || true
mkdir --parents -- "$HOMEVAR_VBOX_TEMP"
chown --recursive -- "dm-vbox-temp:dm-vbox-temp" "$HOMEVAR_VBOX_TEMP"
## Debugging.
groups -- "dm-vbox-temp" || true
ls -la -- "$HOMEVAR_VBOX_TEMP"
## Sanity test.
test -d "/"
ls -la -- "$HOMEVAR_VBOX_TEMP"
## }}

chown --recursive -- "dm-vbox-temp" "/home/dm-vbox-temp"

adduser "dm-vbox-temp" sudo
printf "%s\n" "dm-vbox-temp ALL=(ALL:ALL) NOPASSWD:ALL" | SUDO_EDITOR="" VISUAL="" EDITOR=tee visudo -f "/etc/sudoers.d/dm-vbox-temp_nopassword" >/dev/null

## Debugging.
cat /etc/sudoers.d/dm-vbox-temp_nopassword

## Sanity test.
visudo --strict --check /etc/sudoers.d/dm-vbox-temp_nopassword

## Debugging.
## sudo test.
sudo --non-interactive test -d /usr

## Debugging.
sudo --non-interactive -u "dm-vbox-temp" -- test -x /usr/bin/dist-installer-cli-standalone
sudo --non-interactive -u "dm-vbox-temp" -- ls -la /usr/bin/dist-installer-cli-standalone

printf '%s\n' "DIST_APTGETOPT_SERIALIZED:"
printf '%s\n' "--------------------"
printf '%s\n' "$DIST_APTGETOPT_SERIALIZED"
printf '%s\n' "--------------------"

## Not yet needed but useful as a sanity test.
mapfile -t DIST_APTGETOPT <<< "$DIST_APTGETOPT_SERIALIZED"
printf "%s\n" "DIST_APTGETOPT: ${DIST_APTGETOPT[*]}"

## NOTE: Code duplication in build-step prepare-build-machine
## NOTE: Code duplication in help-step pbuilder-chroot-script-virtualbox
dist_installer_cli_arguments=()
dist_installer_cli_arguments+=("--non-interactive")
dist_installer_cli_arguments+=("--virtualbox-only")
dist_installer_cli_arguments+=("--log-level=debug")
## Speed up the build? Not possible.
## `apt-get update` is actually needed to fetch
## VirtualBox from Debian 'unstable' repository.
## Option '--noupdate' should is not safe here, because if the installer adds a repository,
## then running 'apt update' is crucial for APT to learn about the new packages.
#dist_installer_cli_arguments+=("--noupdate")
##
## Run virtualbox-installer with '--noupgrade' because the system has been updated earlier.
## This is to avoid a race condition where an update is made available shortly after
## to avoid breaking the build.
dist_installer_cli_arguments+=("--noupgrade")
dist_installer_cli_arguments+=("--ci")
## Redundant.
dist_installer_cli_arguments+=("--no-boot")
## Redundant.
dist_installer_cli_arguments+=("--no-import")
## NOTE: End code duplication.

success="true"
## virtualbox-installer / dist-installer-cli
if ! sudo --non-interactive -u "dm-vbox-temp" DIST_APTGETOPT_SERIALIZED="$DIST_APTGETOPT_SERIALIZED" bash -x /usr/bin/dist-installer-cli-standalone "${dist_installer_cli_arguments[@]}" ; then
  success=false
fi

#last_run_integer="$(printf '%s ' "/home/dm-vbox-temp/dist-installer-cli-download/logs/"/* | awk '{print NF}')"

## Debugging.
ls -la -- "/home/dm-vbox-temp/dist-installer-cli-download" || true
#ls -la -- "/home/dm-vbox-temp/dist-installer-cli-download/logs" || true
#ls -la -- "/home/dm-vbox-temp/dist-installer-cli-download/logs/$last_run_integer" || true

## No longer required because running 'dist-installer-cli-standalone' using 'bash -x'.
#cat -- "/home/dm-vbox-temp/dist-installer-cli-download/logs/$last_run_integer/debug.log"
#cat -- "/home/dm-vbox-temp/dist-installer-cli-download/logs/$last_run_integer/user.log"

true "INFO: dist-installer-cli-standalone success: $success"
if [ "${success:-}" = "false" ];then
  error "VirtualBox installer failed inside cowbuilder chroot."
fi

## Check if VirtualBox really got installed.
command -v vboxmanage >/dev/null

rm -f -- "/etc/sudoers.d/dm-vbox-temp_nopassword"

true "INFO: End of script cowbuilder VirtualBox chroot script."
