#!/bin/bash
# SPDX-FileCopyrightText: 2026 The NazoOS Contributors
# SPDX-License-Identifier: GPL-3.0-or-later
#
# NazoOS: last installer step, runs inside the installed system (chroot).
# Called by Calamares (modules/shellprocess-nazoos.conf).
# Arguments: device type from the device page (desktop | handheld) and
# the name of the user created by the installer.

set -euxo pipefail

device=${1:-desktop}
user=${2:-}

# First, before any step can fail: the live user's passwordless sudo
# (excluded in unpackfs.conf too) must not survive a failed install
rm -f /etc/sudoers.d/nazoos-live

# The live medium's base image has no /etc/mtab (systemd creates it at
# boot); snapper and other tools need it inside the installer chroot
[ -e /etc/mtab ] || ln -s ../proc/self/mounts /etc/mtab

btrfs_opts="noatime,compress=zstd:1"
root_uuid=$(findmnt -no UUID /)
# Encrypted install (ADR 0006): / sits on a dm-crypt device. findmnt
# shows btrfs as "/dev/mapper/luks-…[/@]"
root_dev=$(findmnt -no SOURCE / | sed 's/\[.*//')
root_crypt=""
if [ "$(lsblk -no TYPE "$root_dev" 2>/dev/null)" = crypt ]; then
  root_crypt=yes
fi

# 1. / follows the btrfs default subvolume instead of a fixed subvol=/@.
#    snapper rollback switches the default subvolume, so this is what
#    makes a rollback take effect on the next boot.
sed -i -E '\|^\S+\s+/\s+btrfs\s| s#subvol=/@,?##' /etc/fstab
btrfs subvolume set-default "$(btrfs inspect-internal rootid /)" /

# 2. Snapper config for / (creates the subvolume @/.snapshots).
#    No timeline snapshots, like openSUSE: zypper takes pre/post snapshots.
if [ ! -e /etc/snapper/configs/root ]; then
  snapper --no-dbus -c root create-config /
fi
snapper --no-dbus -c root set-config TIMELINE_CREATE=no
# .snapshots must be mounted explicitly: after a rollback / is a snapshot
# and no longer contains @/.snapshots
if ! grep -qE '\s/\.snapshots\s' /etc/fstab; then
  echo "UUID=$root_uuid /.snapshots btrfs subvol=/@/.snapshots,$btrfs_opts 0 0" >> /etc/fstab
fi

# 3. Remove live-only packages before the initrd is built
live_pkgs=()
for p in calamares calamares-lang dracut-kiwi-live; do
  rpm -q --quiet "$p" && live_pkgs+=("$p")
done
if [ ${#live_pkgs[@]} -gt 0 ]; then
  rpm -e --nodeps "${live_pkgs[@]}"
fi

# Live session leftovers: autologin of the live user (KIWI live profile)
# and the live dracut config (also excluded in unpackfs.conf)
sed -i 's/^DISPLAYMANAGER_AUTOLOGIN=.*/DISPLAYMANAGER_AUTOLOGIN=""/' \
  /etc/sysconfig/displaymanager
rm -f /etc/dracut.conf.d/02-livecd.conf

# 3b. One image for every device: adapt it to the device page's choice
#     (after the live autologin is cleared above)
case $device in
  handheld)
    # Start in Steam's gaming mode (autologin of the new user); handheld
    # packages stay. nazoos-deck adds the desktop shortcut and the
    # on-screen keyboard at the first desktop login.
    /usr/libexec/nazoos-session/nazoos-session-ctl boot-mode gaming "$user"
    ;;
  *)
    # Desktop/laptop: remove what only handhelds need (the live medium
    # carries it for handheld installs). The list is nazoos-deck's own
    # Recommends, read before it is removed, so a new handheld package
    # needs no change here. One by one, so a package that something else
    # still needs simply stays.
    # Desktops and laptops use these too (2-in-1 laptops: on-screen
    # keyboard, auto-rotation).
    readonly KEEP_ON_DESKTOP="maliit-keyboard iio-sensor-proxy"
    handheld_pkgs=()
    if rpm -q --quiet nazoos-deck; then
      while read -r name _; do
        # Rich dependencies "(a if b)" are not package names
        [[ -z $name || $name == \(* ]] && continue
        [[ " $KEEP_ON_DESKTOP " == *" $name "* ]] && continue
        handheld_pkgs+=("$name")
      done < <(rpm -q --recommends nazoos-deck)
      rpm -e nazoos-deck
    fi
    # Opt-in from NazoOS Welcome, so not a Recommends of nazoos-deck
    handheld_pkgs+=(jupiter-dock-updater-bin)
    for p in "${handheld_pkgs[@]}"; do
      if rpm -q --quiet "$p"; then
        rpm -e "$p" || echo "kept $p (needed by another package)"
      fi
    done
    ;;
esac

# 3c. Keyboard: systemd >= 258 keeps the X11 layout in /etc/vconsole.conf
#     (XKBLAYOUT=…), read by localed, KWin and SDDM. Calamares still writes
#     the chosen layout to xorg.conf.d/00-keyboard.conf and only KEYMAP to
#     vconsole.conf, so the image's layout (KIWI keytable) stayed active on
#     the desktop. Copy Calamares' choice over and derive the console
#     keymap from it (its own guess turned "de nodeadkeys" with the image's
#     model "microsoftpro" into the Mac keymap). Before dracut: the initrd
#     asks for a LUKS passphrase with this keymap when GRUB does not
#     hand over the key.
kbd_x11=/etc/X11/xorg.conf.d/00-keyboard.conf
vconsole=/etc/vconsole.conf
xkb() {
  sed -n "s/^[[:space:]]*Option[[:space:]]*\"$1\"[[:space:]]*\"\(.*\)\"/\1/p" \
    "$kbd_x11" | head -n 1
}
set_vconsole() {
  sed -i "/^$1=/d" "$vconsole"
  if [ -n "$2" ]; then echo "$1=$2" >> "$vconsole"; fi
}
if [ -f "$kbd_x11" ]; then
  layout=$(xkb XkbLayout)
  variant=$(xkb XkbVariant)
  model=$(xkb XkbModel)
  if [ -n "$layout" ]; then
    touch "$vconsole"
    set_vconsole XKBLAYOUT "$layout"
    set_vconsole XKBVARIANT "$variant"
    set_vconsole XKBMODEL "${model:-pc105}"
    keymap=${layout%%,*}
    first_variant=${variant%%,*}
    if [ -n "$first_variant" ] && \
       ls /usr/share/kbd/keymaps/xkb/"$keymap-$first_variant".map* >/dev/null 2>&1; then
      keymap="$keymap-$first_variant"
    fi
    set_vconsole KEYMAP "$keymap"
  fi
fi

# 3d. Language: zypper installs translations (-lang packages, dictionaries,
#     …) only for the languages in /var/lib/zypp/RequestedLocales. The
#     image was built with "en" only, so apps installed later stayed
#     English. Request the installer's language (localecfg wrote
#     /etc/locale.conf). --no-packages: no download here; the desktop's
#     translations are already on the medium (nazoos-translations, ADR 0027)
lang=$(sed -n 's/^LANG=//p' /etc/locale.conf 2>/dev/null | tr -d '"' | head -n 1)
lang=${lang%%.*}
if [ -n "$lang" ] && [ "$lang" != C ] && [ "$lang" != POSIX ]; then
  locales=("${lang%%_*}")
  [ "$lang" != "${lang%%_*}" ] && locales+=("$lang")
  zypper --non-interactive --no-refresh addlocale --no-packages "${locales[@]}" \
    || echo "could not request locale $lang"
fi

# 4. initrd for the installed system. Must exist before the GRUB config
#    is generated, otherwise grub2-mkconfig writes entries without initrd
#    (the live medium keeps its initrd on the ISO, not in /boot)
dracut --regenerate-all --force

# 5. Bootloader: GRUB with shim (Secure Boot) via openSUSE's perl-Bootloader.
#    SUSE_BTRFS_SNAPSHOT_BOOTING lets GRUB find /boot in the default
#    subvolume and offer snapshots in the boot menu (grub2-snapper-plugin).
#    GRUB_DISABLE_BOOTNEXT: grub2 2.16 lists every UEFI boot option
#    (31_efi_bootnext) above the snapshot entry, which then falls off the
#    bottom of the theme's menu (VM 2026-10-19); the firmware's own boot
#    menu and "UEFI Firmware Settings" still reach them.
cat > /etc/default/grub <<GRUB
GRUB_DISTRIBUTOR="NazoOS"
GRUB_DEFAULT=saved
GRUB_TIMEOUT=5
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash preempt=full fbcon=nodefer"
GRUB_CMDLINE_LINUX=""
GRUB_TERMINAL_OUTPUT="gfxterm"
GRUB_GFXMODE="auto"
GRUB_DISABLE_OS_PROBER="false"
SUSE_BTRFS_SNAPSHOT_BOOTING="true"
GRUB_DISABLE_BOOTNEXT="true"
GRUB
# /boot is inside the encrypted root: GRUB unlocks it itself (LUKS1 /
# PBKDF2, ADR 0006). openSUSE's grub2 turns /etc/crypttab into
# crypttab_entry lines and hands the key to the initrd, so the
# passphrase is asked once
if [ -n "$root_crypt" ]; then
  echo 'GRUB_ENABLE_CRYPTODISK="y"' >> /etc/default/grub
fi
# NazoOS GRUB theme (nazoos-branding-grub2): copy to /boot, GRUB_THEME
if [ -x /usr/share/grub2/themes/nazoos/activate-theme ]; then
  /usr/share/grub2/themes/nazoos/activate-theme
fi
cat > /etc/sysconfig/bootloader <<BOOT
LOADER_TYPE="grub2-efi"
SECURE_BOOT="yes"
TRUSTED_BOOT="no"
UPDATE_NVRAM="yes"
BOOT
update-bootloader --reinit


# 6. This package is live-only too; the running script stays readable
rpm -e nazoos-calamares-config
