#!/bin/sh
###
# Wrapper for running Calamares on Synex live media
###

# ----------------------------------------------------------------------
# Select Synex installation mode before Calamares loads its modules.
#
# The Advanced ZFS installation mode is currently available only on
# the Synex 13 branch. Other Synex branches use the normal installation
# workflow directly.
# ----------------------------------------------------------------------

ZFS_MODE="grub"
SYNEX_BRANCH=""

if [ -r /etc/synex-release ]; then
    SYNEX_BRANCH="$(
        awk -F= '
            $1 == "SYNEX_BRANCH" {
                value = $2
                gsub(/^"/, "", value)
                gsub(/"$/, "", value)
                print value
                exit
            }
        ' /etc/synex-release
    )"
fi

if [ "$SYNEX_BRANCH" = "synex-13" ]; then
    if ! command -v kdialog >/dev/null 2>&1; then
        echo "ERROR: kdialog is required by the Synex installer launcher." >&2
        exit 1
    fi

    LOCALE_VALUE="${LC_ALL:-${LC_MESSAGES:-${LANG:-en}}}"

    case "$LOCALE_VALUE" in
        es|es_*|es.*)
            DIALOG_TITLE="Instalador de Synex"

            NORMAL_LABEL="Instalación normal"
            ZFS_LABEL="Instalación avanzada ZFS"

            DIALOG_TEXT="Bienvenido al asistente de instalación de Synex.

Antes de iniciar el instalador, seleccione el tipo de instalación que desea realizar.

Instalación normal
Permite utilizar los sistemas de archivos disponibles habitualmente en Synex y utiliza GRUB como gestor de arranque. Es la opción adecuada para una instalación convencional.

Instalación avanzada ZFS
Está destinada exclusivamente a instalaciones sobre ZFS. El instalador quedará limitado a ZFS y utilizará ZFSBootMenu como entorno de arranque. Durante el particionado podrá activar opcionalmente el cifrado nativo de OpenZFS.

La Instalación avanzada ZFS requiere una conexión a Internet activa y sólo está disponible en sistemas iniciados en modo UEFI.

Si no necesita específicamente las funciones avanzadas de ZFS, seleccione Instalación normal."
            ;;

        *)
            DIALOG_TITLE="Synex Installer"

            NORMAL_LABEL="Normal installation"
            ZFS_LABEL="Advanced ZFS installation"

            DIALOG_TEXT="Welcome to the Synex installation assistant.

Before starting the installer, select the type of installation you want to perform.

Normal installation
Allows you to use the filesystems normally available in Synex and uses GRUB as the bootloader. This is the appropriate option for a conventional installation.

Advanced ZFS installation
Intended exclusively for installations using ZFS. The installer will be restricted to ZFS and will use ZFSBootMenu as the boot environment. During partitioning, you may optionally enable OpenZFS native encryption.

Advanced ZFS installation requires an active Internet connection and is only available on systems booted in UEFI mode.

If you do not specifically need the advanced ZFS features, select Normal installation."
            ;;
    esac

    kdialog \
        --title "$DIALOG_TITLE" \
        --yes-label "$NORMAL_LABEL" \
        --no-label "$ZFS_LABEL" \
        --yesno "$DIALOG_TEXT"

    ANSWER=$?

    case "$ANSWER" in
        0)
            ZFS_MODE="grub"
            ;;
        1)
            ZFS_MODE="openzfs"
            ;;
        *)
            exit 0
            ;;
    esac
fi

# ----------------------------------------------------------------------
# Stale file left behind by live-build that messes with partitioning.
# ----------------------------------------------------------------------

if [ -e /etc/fstab ]; then
    sudo mv /etc/fstab /etc/fstab.orig.calamares
fi


# ----------------------------------------------------------------------
# Allow Calamares to scale the window for HiDPI displays.
# ----------------------------------------------------------------------

export QT_AUTO_SCREEN_SCALE_FACTOR=1


# ----------------------------------------------------------------------
# Access control to run Calamares as root for XWayland.
# Not needed on COSMIC: Calamares runs as a native Wayland client.
# ----------------------------------------------------------------------

if [ "$XDG_CURRENT_DESKTOP" != "COSMIC" ]; then
    xhost +si:localuser:root
fi


# ----------------------------------------------------------------------
# Detect desktop environment and set Qt theme accordingly.
# ----------------------------------------------------------------------

case "$XDG_CURRENT_DESKTOP" in
    KDE)
        QT_THEME="kde"
        ;;
    GNOME|ubuntu:GNOME|COSMIC)
        QT_THEME="gnome"
        ;;
    XFCE|LXDE|MATE|Cinnamon)
        QT_THEME="gtk2"
        ;;
    LXQt)
        QT_THEME="lxqt"
        ;;
    *)
        QT_THEME="gtk3"
        ;;
esac


# ----------------------------------------------------------------------
# Start Synex Calamares wrapper.
# ----------------------------------------------------------------------

if [ "$XDG_CURRENT_DESKTOP" = "COSMIC" ]; then
    pkexec env \
        QT_QPA_PLATFORM=wayland \
        WAYLAND_DISPLAY="$WAYLAND_DISPLAY" \
        XDG_RUNTIME_DIR="$XDG_RUNTIME_DIR" \
        XDG_CURRENT_DESKTOP="$XDG_CURRENT_DESKTOP" \
        QT_QPA_PLATFORMTHEME="$QT_THEME" \
        /usr/lib/calamares-settings-synex/calamares-zfs "$ZFS_MODE"
else
    pkexec env \
        DISPLAY="$DISPLAY" \
        XAUTHORITY="$XAUTHORITY" \
        XDG_RUNTIME_DIR="$XDG_RUNTIME_DIR" \
        XDG_CURRENT_DESKTOP="$XDG_CURRENT_DESKTOP" \
        QT_QPA_PLATFORMTHEME="$QT_THEME" \
        /usr/lib/calamares-settings-synex/calamares-zfs "$ZFS_MODE"

    xhost -si:localuser:root
fi


# ----------------------------------------------------------------------
# Restore stale fstab, for what it's worth.
# ----------------------------------------------------------------------

if [ -e /etc/fstab.orig.calamares ]; then
    sudo mv /etc/fstab.orig.calamares /etc/fstab
fi
