#!/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

##
## Fix autostart Kaspersky Endpoint Security for Linux
##

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
SOURCE=${SYSCONF}/system; [[ -f ${SOURCE} ]] && . ${SOURCE} 2>/dev/null

exec_kesl_timer(){
    create_kesl_timer(){
        [[ -e ${ROOTFS}/etc/systemd/system/${KESL_TIMER_NAME} ]] \
        || cat <<EOF > "${ROOTFS}/etc/systemd/system/${KESL_TIMER_NAME}"
#  SPDX-License-Identifier: LGPL-2.1-or-later
#
#  This file is part of systemd.
#
#  systemd is free software; you can redistribute it and/or modify it
#  under the terms of the GNU Lesser General Public License as published by
#  the Free Software Foundation; either version 2.1 of the License, or
#  (at your option) any later version.

[Unit]
Description=Daily kesl on boot

[Timer]
OnBootSec=1min
OnUnitActiveSec=1d
AccuracySec=1h
RandomizedDelaySec=30s

[Install]
WantedBy=timers.target
EOF
    }
    remove_kesl_timer(){
        [[ -e "${ROOTFS}/etc/systemd/system/${KESL_TIMER_NAME}" ]] && rm -f "${ROOTFS}/etc/systemd/system/${KESL_TIMER_NAME}" 2>/dev/null
        [[ -e "${ROOTFS}/etc/systemd/system/timers.target.wants/${KESL_TIMER_NAME}" ]] && rm -f "${ROOTFS}/etc/systemd/system/timers.target.wants/${KESL_TIMER_NAME}" 2>/dev/null
    }
    enable_kesl_timer(){
        [[ -d ${ROOTFS}/etc/systemd/system/timers.target.wants ]] || install -dm0755 "${ROOTFS}/etc/systemd/system/timers.target.wants"
        [[ -e "${ROOTFS}/etc/systemd/system/timers.target.wants/${KESL_TIMER_NAME}" ]] || ln -sf "/etc/systemd/system/${KESL_TIMER_NAME}" "${ROOTFS}/etc/systemd/system/timers.target.wants/${KESL_TIMER_NAME}" 2>/dev/null
    }
    KESL_SERVICE_NAME="kesl.service"
    KESL_TIMER_NAME="kesl.timer"
    # Если Касперский не установлен, то удалить kesl.timer
    [[ ! -e ${ROOTFS}/var/opt/kaspersky/kesl/install-current ]] && remove_kesl_timer && return 0
    ISSYSTEMD=$(readlink -fq ${ROOTFS}/usr/bin/init | grep "lib/systemd/systemd$")
    [[ -n ${ISSYSTEMD} ]] || return 0
    # Поиск включеного сервиса kesl.service
    KESL_SERVICE_FIND=$(find ${ROOTFS}/etc/systemd/system/multi-user.target.wants -iname "${KESL_SERVICE_NAME}" 2>/dev/null)
    if [[ -n ${KESL_SERVICE_FIND} ]]; then
        rm -f ${KESL_SERVICE_FIND} 2>/dev/null
        create_kesl_timer
        enable_kesl_timer
    elif [[ "${SERVICES_ENABLE}" =~ (^|,)+("${KESL_SERVICE_NAME%%.*}"|"${KESL_SERVICE_NAME}"|"${KESL_TIMER_NAME}")(,|$| )+ ]]; then
        # Если указан автозапуск сервиса в конфигурации, то меняем на kesl.timer
        sed -E "/SERVICES_ENABLE=/s/(=|,|\")+(${KESL_SERVICE_NAME}|${KESL_SERVICE_NAME%%.*})(,|$|\")+/\1${KESL_TIMER_NAME}\3/g" -i ${SYSCONF}/system
        create_kesl_timer
        enable_kesl_timer
    fi
}

## Копировать касперский в кеш каталог реальной файловой системы, для использования в режимах песочници
## Оценить необходимость, нужно тестировать
#exec_bind_mount(){
#    return 0
#    if [[ -d ${ROOTFS}/var/opt/kaspersky ]]; then
#        if [[ -d ${ROOTFS}/mnt/livedata/ublinux-data]; then
#            if [[ ! -d ${ROOTFS}/mnt/livedata/ublinux-data/cache/kaspersky ]]; then
#                mkdir -p ${ROOTFS}/mnt/livedata/ublinux-data/cache/kaspersky
#                cp -pr ${ROOTFS}/var/opt/kaspersky/* ${ROOTFS}/mnt/livedata/ublinux-data/cache/kaspersky || exit 1
#            fi
#            mount --bind ${ROOTFS}/mnt/livedata/ublinux-data/cache/kaspersky ${ROOTFS}/var/opt/kaspersky
#        fi
#    fi
#}

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

    exec_kesl_timer $@
