#!/usr/bin/bash
#
# Author: Dmitry Razumov <asmeron@ublinux.com>
# Copyright (c) 2021-2025 UBLinux <support@ublinux.com>
#
# SPDX-License-Identifier: AGPL-3.0-or-later
#
# Initial script for 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" ]] || { return 0 2>/dev/null && return 0 || exit 0; }
DEBUGMODE=no

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

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

exec_unblock_pacman(){
    # Снимаем блокировку с пакетного менеджера
    if [[ -n ${ROOTFS} ]]; then
        rm -f ${ROOTFS}/var/lib/pacman/db.lck
    else
        while [[ -f /var/lib/pacman/db.lck ]]; do sleep 5; done
    fi
}

exec_install_pkg_tar(){
    LIST_PKG=$(find /memory/layer-base/*/install/preinit -type f -name "*.pkg.tar*[!sig]" -print 2>/dev/null)
    if [[ -n ${ROOTFS} && -n ${LIST_PKG} ]]; then
        mount -t proc /proc /${ROOTFS}/proc
        mount -t sysfs /sys /${ROOTFS}/sys
        mount --bind /dev/ /${ROOTFS}/dev
        LC_ALL=C LD_LIBRARY_PATH="${ROOTFS}/usr/lib" ${ROOTFS}/usr/bin/pacman --sysroot ${ROOTFS} -U --noprogressbar --noconfirm ${LIST_PKG}
        umount /${ROOTFS}/dev
        umount /${ROOTFS}/sys
        umount /${ROOTFS}/proc
    elif [[ -n ${LIST_PKG} ]]; then
        pacman -U --noprogressbar --noconfirm ${LIST_PKG}
    fi
}

################
##### MAIN #####
################

    # Если файл подключен как ресурс с функциями, то выйти
    return 0 2>/dev/null && return 0

    exec_unblock_pacman
    exec_install_pkg_tar
