#!/usr/bin/env bash
#
# Author: Dmitry Razumov <asmeron@ublinux.com>
# Copyright (c) 2021-2025 UBLinux <support@ublinux.com>
#
# Initial script for Linux UBLinux
# This script are launching before starting init from initrd script
# Current dir allways must be set to root (/)
# All system path must be relative, except initrd dirs

ENABLED=yes
[[ ${ENABLED} == "yes" ]] || exit 0
DEBUGMODE=no

PATH=.:/:/usr/bin:/usr/local/bin:/usr/local/sbin

[[ -d /usr/lib/ublinux ]] && { ROOTFS= ; CMD_CHROOT= ; } || { [[ -d /sysroot ]] && ROOTFS="/sysroot" || ROOTFS="."; CMD_CHROOT="chroot ${ROOTFS}"; }
SOURCE=${ROOTFS}/usr/lib/ublinux/functions; [[ -f ${SOURCE} ]] && . ${SOURCE} 2>/dev/null || exit 0
SOURCE=${ROOTFS}/usr/lib/ublinux/default; [[ -f ${SOURCE} ]] && . ${SOURCE} 2>/dev/null || exit 0
debug_mode "$0" "$@"

SYSCONF="${ROOTFS}${SYSCONF}"
SOURCE=${SYSCONF}/config; [[ -f ${SOURCE} ]] && . ${SOURCE} 2>/dev/null

if [[ -n "$(cmdline_parameter ub.osinstall)" ]]; then
    TTY_N=2
    EXEC_START="/usr/bin/ubinstall.cli"
    sed -i "s/.*NAutoVTs=6.*/NAutoVTs=0/" ${ROOTFS}/etc/systemd/logind.conf
    sed -i "s/.*ReserveVT=6.*/ReserveVT=0/" ${ROOTFS}/etc/systemd/logind.conf
    mkdir -p ${ROOTFS}/etc/systemd/system/getty@tty${TTY_N}.service.d
    echo "[Service]" > ${ROOTFS}/etc/systemd/system/getty@tty${TTY_N}.service.d/override.conf
    echo "ExecStart=" >> ${ROOTFS}/etc/systemd/system/getty@tty${TTY_N}.service.d/override.conf
    FONT=$(grep "FONT" ${ROOTFS}/etc/vconsole.conf | cut -d= -f2)
    [[ -z ${FONT} ]] && FONT=${CONSOLE_FONT:-cyr-sun16}
    echo "ExecStart=-bash -c \". /etc/locale.conf; export LANG; setfont ${FONT}; ${EXEC_START}\"" >> ${ROOTFS}/etc/systemd/system/getty@tty${TTY_N}.service.d/override.conf
    echo "StandardInput=tty"  >> ${ROOTFS}/etc/systemd/system/getty@tty${TTY_N}.service.d/override.conf
    echo "StandardOutput=tty"  >> ${ROOTFS}/etc/systemd/system/getty@tty${TTY_N}.service.d/override.conf
    mkdir -p ${ROOTFS}/etc/systemd/system/getty.target.wants
    ln -sf /usr/lib/systemd/system/getty@.service ${ROOTFS}/etc/systemd/system/getty.target.wants/getty@tty${TTY_N}.service
    ln -sf /dev/null ${ROOTFS}/etc/systemd/system/getty.target.wants/getty@tty1.service
fi

