#!/bin/bash

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

set -x
set -e

true "INFO: Currently running script: $BASH_SOURCE $@"

MYDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "$MYDIR"

## XXX: hardcoded path
source "$HOME/derivative-maker/help-steps/pre"
source "$HOME/derivative-maker/help-steps/colors"
source "$HOME/derivative-maker/help-steps/variables"

error_handler_interactive-chroot-raw-shell() {
   trap "error_handler_interactive-raw" ERR INT TERM

   echo "${green}INFO${reset}: Exited (1) interactive shell."
   sync
}

error_handler_interactive-chroot-raw() {
   echo "
${red}${bold}BASH_COMMAND${reset}: $BASH_COMMAND
${red}${bold}ERROR $BASH_SOURCE: | caller: $(caller)${reset}
Unchrooting.. Unpreventing daemons from starting... Unmounting raw...
"

   "$dist_source_help_steps_folder"/unchroot-raw "$@"
   "$dist_source_help_steps_folder"/unprevent-daemons-from-starting "$@"
   "$dist_source_help_steps_folder"/unmount-raw "$@"

   echo "
${red}${bold}BASH_COMMAND${reset}: $BASH_COMMAND
${red}${bold}ERROR $BASH_SOURCE: | caller: $(caller)${reset}
"

   exit 1
}

main() {
   trap "error_handler_interactive-chroot-raw" ERR INT TERM

   "$dist_source_help_steps_folder"/mount-raw "$@"

   echo "${cyan}INFO: Trying to prevent daemons from starting, if /usr/sbin/ folder already exist (will fail open, if not)...${reset}"

   "$dist_source_help_steps_folder"/prevent-daemons-from-starting "$@" || true

   ## Networking should be available. Otherwise use the following.
   #export dist_chroot_mount_resolv_conf="0" "$dist_source_help_steps_folder"/chroot-raw
   "$dist_source_help_steps_folder"/chroot-raw "$@"

   sync

   ## Sanity tests.
   chroot_run mount
   chroot_run sync

   sync

   echo "${cyan}INFO: Trying to make local APT repository available inside chroot, if already available (will fail open, if not)...${reset}"

   "$dist_source_help_steps_folder"/create-local-temp-apt-repo "$@" || true

   sync

   ## Info.
   echo "${cyan}INFO: Entering interactive shell...${reset}"
   echo "${cyan}Recommendation: check /home/user if you are really inside the image and not on your host system."
   echo "    When you are done, do not forget to leave the shell using: exit 0${reset}"

   ## Run interactive shell.
   trap "error_handler_interactive-chroot-raw-shell" ERR INT TERM
   chroot_run "/bin/bash"

   echo "${green}INFO: Exited (0) interactive shell.${reset}"

   "$dist_source_help_steps_folder"/remove-local-temp-apt-repo "$@"

   chroot_run sync
   sync

   "$dist_source_help_steps_folder"/unchroot-raw "$@"
   "$dist_source_help_steps_folder"/unprevent-daemons-from-starting "$@"
   "$dist_source_help_steps_folder"/unmount-raw "$@"

   sync

   echo "${green}INFO: Terminated interactive chroot without any errors.${reset}"
}

main "$@"
