#!/bin/bash
# Script:      chroot-install
# Title:       Astra Linux Chroot Installer
# Description: This script runs within the chroot environment during the live image build
#              process. It configures the system, installs packages, sets up users, and
#              performs other essential tasks within the chroot.

set -e          # exit on error
set -o pipefail # exit on pipeline error
set -u          # treat unset variable as error

# The purpose of these variables is described in the help for the toggle_shell_options function in libastralive.
SET_E=""
SET_U=""

# Source configuration files or exit if they don't exist
. /config || exit 1
. /libastralive || exit 1

# Set the text domain for gettext
export TEXTDOMAIN="live-build-astra"
export TEXTDOMAINDIR="/usr/share/locale"

console_colors

# Set the host name
echo "${HOST_NAME}" >/etc/hostname

# Define debconf settings
DEBCONF_SETTINGS=(
    "keyboard-configuration keyboard-configuration/layoutcode string us,ru"
    "keyboard-configuration keyboard-configuration/variant select Russian"
    "keyboard-configuration keyboard-configuration/toggle select Alt+Shift"
    "tzdata tzdata/Zones/Europe select Moscow"
    "locales locales/default_environment_locale select ru_RU.UTF-8"
    "locales locales/locales_to_be_generated multiselect ru_RU.UTF-8 UTF-8, en_US.UTF-8 UTF-8"
    "openssh-server openssh-server/password-authentication boolean false"
    "openssh-server openssh-server/permit-root-login boolean false"
    "console-setup console-setup/codeset47 select Guess optimal character set"
    "console-setup console-setup/store_defaults_in_debconf_db boolean true"
    "console-setup console-setup/codesetcode string guess"
    "console-setup console-setup/fontsize string 8x16"
    "console-setup console-setup/fontsize-fb47 select 8x16"
    "console-setup console-setup/fontsize-text47 select 8x16"
    "console-setup console-setup/charmap47 select UTF-8"
    "console-setup console-setup/fontface47 select Fixed"
)

# Apply debconf settings
for SETTING in "${DEBCONF_SETTINGS[@]}"; do
    echo "${SETTING}" | debconf-set-selections -v
done

LINUX_IMAGE="linux-image-latest-generic"

# Update and upgrade packages
apt-get update
apt-get -y dist-upgrade

# Install specific packages if needed
if [[ " ${GENERATE_IMAGES[@]} " =~ " iso " ]] || [[ " ${GENERATE_IMAGES[@]} " =~ " raw " ]] || [[ " ${GENERATE_IMAGES[@]} " =~ " qcow2 " ]] || [[ " ${GENERATE_IMAGES[@]} " =~ " vmdk " ]]; then
    apt-get -y install -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" --no-install-suggests \
        ${LINUX_IMAGE} \
        systemd-sysv \
        whiptail \
        console-setup \
        keyboard-configuration
fi

touch /packages.list

if [[ " ${GENERATE_IMAGES[@]} " =~ " iso " ]]; then
    printf '\n%s\n' live-boot live-config live-config-systemd >>/packages.list
elif [[ " ${GENERATE_IMAGES[@]} " =~ " raw " || " ${GENERATE_IMAGES[@]} " =~ " qcow2 " || " ${GENERATE_IMAGES[@]} " =~ " vmdk " ]]; then
    case "${ARCHITECTURE}" in
    amd64)
        printf '\n%s\n' grub-efi grub-pc-bin >>/packages.list
        ;;
    arm64)
        printf '\n%s\n' grub-efi >>/packages.list
        ;;
    esac
fi

# Check if the /packages.list file exists and process it
if [ -f "/packages.list" ]; then
    declare -a PACKAGES_TO_CHECK
    while IFS= read -r LINE; do
        [[ ${LINE} =~ ^#.*$ || -z ${LINE} ]] && continue
        PACKAGES_TO_CHECK+=("${LINE}")
    done <"/packages.list"

    declare -a PACKAGES_TO_INSTALL
    declare -a PACKAGES_TO_HOLD

    toggle_shell_options e
    for PACKAGE in "${PACKAGES_TO_CHECK[@]}"; do
        if ! check_package "${PACKAGE}"; then
            warning "$(gettext "Package") ${CYAN}${PACKAGE%%=*}${ENDCOLOR} $(gettext "is not available in the repository. Skip.")"
            continue
        fi
        if [[ ${PACKAGE} == *"="* ]]; then
            if ! LANG=C apt-cache show "${PACKAGE%%=*}" | grep -q "Version: ${PACKAGE#*=}" >/dev/null 2>&1; then
                echo -e "${YELLOW}${BOLD}$(gettext "Warning:")${ENDCOLOR} $(gettext "Package") ${CYAN}${PACKAGE%%=*}${ENDCOLOR} $(gettext "version") ${CYAN}${PACKAGE#*=}${ENDCOLOR} $(gettext "is not available. Installing without version.")"
                PACKAGES_TO_INSTALL+=("${PACKAGE%%=*}")
            else
                PACKAGES_TO_INSTALL+=("${PACKAGE}")
                PACKAGES_TO_HOLD+=("${PACKAGE%%=*}")
            fi
        else
            PACKAGES_TO_INSTALL+=("${PACKAGE}")
        fi
    done
    toggle_shell_options e

    apt-get -y install -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" --no-install-suggests "${PACKAGES_TO_INSTALL[@]}"

    toggle_shell_options u
    if [ -n "${PACKAGES_TO_HOLD[0]}" ]; then
        apt-mark hold "${PACKAGES_TO_HOLD[@]}"
    fi
    toggle_shell_options u
fi

# Default password hash (existing hash)
DEFAULT_PASSWORD_HASH='U6aMy0wojraho'

# Check if a custom password hash is provided; otherwise use default
PASSWORD_HASH="${USER_PASSWORD_HASH:-$DEFAULT_PASSWORD_HASH}"

# Additional setup for specific image types
if [[ " ${GENERATE_IMAGES[@]} " =~ " iso " ]]; then
    cat <<EOF >>/etc/live/config.conf
LIVE_CONFIG_CMDLINE="boot=live components"
LIVE_HOSTNAME="astra"
LIVE_USERNAME="${USER_NAME}"
LIVE_USER_FULLNAME="Astra Live System User"
LIVE_USER_DEFAULT_GROUPS="dialout,cdrom,floppy,audio,video,plugdev,users,fuse,weston-launch,kvm,libvirt,libvirt-qemu,vboxusers,astra-admin,astra-console,lpadmin"
LIVE_LOCALES="ru_RU.UTF-8,en_US.UTF-8"
LIVE_TIMEZONE="Europe/Moscow"
LIVE_KEYBOARD_MODEL="pc105"
LIVE_KEYBOARD_LAYOUTS="us,ru"
LIVE_KEYBOARD_VARIANTS=","
LIVE_CONFIG_DEBUG="true"
EOF

    if ! getent group astra-admin >/dev/null; then
        groupadd --system astra-admin
    fi

    if ! getent group astra-console >/dev/null; then
        if getent group 333 >/dev/null; then
            groupadd --system astra-console
        else
            groupadd --gid 333 astra-console
        fi
    fi

    if [ "${USER_NAME}" == "root" ]; then
        usermod -p "${PASSWORD_HASH}" root
    else
        sed -i "s|^\(\s*\)_PASSWORD=.*|\1_PASSWORD=\'${PASSWORD_HASH}\'|" /lib/live/config/0030-live-debconfig_passwd
        sed -i "s|^\(\s*\)_PASSWORD=.*|\1_PASSWORD=\'${PASSWORD_HASH}\'|" /lib/live/config/0030-user-setup
    fi
elif [[ " ${GENERATE_IMAGES[@]} " =~ " raw " ]] || [[ " ${GENERATE_IMAGES[@]} " =~ " qcow2 " ]] || [[ " ${GENERATE_IMAGES[@]} " =~ " vmdk " ]]; then
    if [ -f /etc/adduser.conf ]; then
        sed -i 's/^#ADD_EXTRA_GROUPS=.*/ADD_EXTRA_GROUPS=1/' /etc/adduser.conf
        sed -i 's/^#EXTRA_GROUPS=.*/EXTRA_GROUPS="dialout cdrom floppy audio video plugdev users fuse weston-launch kvm libvirt libvirt-qemu vboxusers"/' /etc/adduser.conf
        sed -i 's/^ADD_EXTRA_GROUPS=.*/ADD_EXTRA_GROUPS=1/' /etc/adduser.conf
        sed -i 's/^EXTRA_GROUPS=.*/EXTRA_GROUPS="dialout cdrom floppy audio video plugdev users fuse weston-launch kvm libvirt libvirt-qemu vboxusers"/' /etc/adduser.conf
    fi
    if [ "${USER_NAME}" == "root" ]; then
        usermod -p "${PASSWORD_HASH}" root
    else
        useradd -p "${PASSWORD_HASH}" -m -s /bin/bash ${USER_NAME}
    fi

    if ! getent group astra-admin >/dev/null; then
        groupadd --system astra-admin
    fi

    if ! getent group astra-console >/dev/null; then
        if getent group 333 >/dev/null; then
            groupadd --system astra-console
        else
            groupadd --gid 333 astra-console
        fi
    fi

    DESIRED_GROUPS="dialout cdrom floppy audio video plugdev users fuse weston-launch kvm libvirt libvirt-qemu vboxusers astra-admin astra-console lpadmin"
    IFS=' ' read -ra ADDR <<<"${DESIRED_GROUPS}"
    EXISTING_GROUPS=""
    for GROUP in "${ADDR[@]}"; do
        if grep -q ${GROUP} "/etc/group"; then
            EXISTING_GROUPS+="${GROUP},"
        fi
    done
    EXISTING_GROUPS=${EXISTING_GROUPS%?}
    if [ "${USER_NAME}" != "root" ]; then
        usermod -aG ${EXISTING_GROUPS} ${USER_NAME}
    fi
fi

# Uncomment the following line to set the password for the root user
#usermod -p "${PASSWORD_HASH}" root

# Enable autologin if specified
if [ "${AUTOLOGIN}" = "true" ]; then
    if [ -f /etc/X11/fly-dm/fly-dmrc ]; then
        sed -e 's/#\?AutoLoginEnable=.*/AutoLoginEnable=true/' -i /etc/X11/fly-dm/fly-dmrc
        sed -e "s/#\?AutoLoginUser=.*/AutoLoginUser=${USER_NAME}/" -i /etc/X11/fly-dm/fly-dmrc
        sed -e 's/#\?AutoLoginDelay=.*/AutoLoginDelay=0/' -i /etc/X11/fly-dm/fly-dmrc
    fi

    if [ -f /usr/share/fly-wm/theme/default.themerc ]; then
        sed -e 's/ScreenSaverDelay=.*/ScreenSaverDelay=0/' -i /usr/share/fly-wm/theme/default.themerc
    fi

    if [ -f /usr/bin/fly-first-start.sh ]; then
        sed -i '3i exit 0' /usr/bin/fly-first-start.sh
    fi
fi
