#!/bin/sh
set -e

# set up variables and check existence of chroot system
if [ -z "${CHROOT_PATH}" ]; then
    echo "Need to set CHROOT_PATH!"
    exit 1
fi
wizard_filename="reform-setup"
cleanup_script_filename="cleanup.sh"
repo_path_wizard="./target/debug/${wizard_filename}"
repo_path_cleanup_script="./${cleanup_script_filename}"
chroot_dir_root="${CHROOT_PATH}/root"
chroot_path_wizard="./root/${wizard_filename}"
if [ ! -d "${chroot_dir_root}" ]; then
    echo "Can't find ${chroot_dir_root}, suspecting no system for chrooting set up."
    echo "To set it up, run something like this:"
    echo "# mkdir -p ${CHROOT_PATH}"
    echo "# debootstrap unstable ${CHROOT_PATH} http://deb.debian.org/debian/"
    exit 1
fi

# ensure the current variants of the needed executables are inside the chrooted system
sudo cp "${repo_path_wizard}" "${chroot_dir_root}/"
sudo cp "${repo_path_cleanup_script}" "${chroot_dir_root}/"

# packages needed for GTK4
sudo chroot "${CHROOT_PATH}" /bin/apt remove -y libssl3
sudo chroot "${CHROOT_PATH}" /bin/apt install -y libgtk-4-1 libadwaita-1-0

# packages needed for keyboard configuration (?)
sudo chroot "${CHROOT_PATH}" /bin/apt install -y keyboard-configuration locales

sudo chroot "${CHROOT_PATH}" /bin/sh -c 'echo locales locales/locales_to_be_generated multiselect en_US.UTF-8 | debconf-set-selections'
sudo chroot "${CHROOT_PATH}" dpkg-reconfigure --frontend noninteractive locales

# xhost +/- allows the Wizard to access the X Server for display
xhost +
sudo chroot "${CHROOT_PATH}" /bin/bash -c "CHROOT_MODE=1 ${chroot_path_wizard}"
xhost -

exit 0
