#!/bin/bash
#
# Copyright (C) 2023 MOXA Inc. All rights reserved.
# This software is distributed under the terms of the MOXA SOFTWARE NOTICE.
# See the file LICENSE for details.
#
# Authors:
#       2023  Wilson YS Huang  <wilsonys.huang@moxa.com>

drv::is_loaded() {
        local drv_name
        drv_name="$1"

        lsmod | grep -wq "${drv_name}"
}

drv::is_ignored() {
        local module_name
        module_name="$1"

        modprobe --show-config | grep -qw "blacklist ${module_name}"
}

drv::add_blacklist() {
        local module_names
        local conf_file
        local is_added

        module_names="$1"
        conf_file="/lib/modprobe.d/$2"
        is_added=""

        if [[ ! -e "$conf_file" ]]; then
                touch "$conf_file"
        fi

        for mod in ${module_names}; do
                if ! drv::is_ignored "$mod"; then
                        echo "blacklist $mod" >>"$conf_file"
                        echo "install $mod /bin/false" >>"$conf_file"
                        is_added+=" $mod"
                fi
        done

        echo "$is_added"
}

drv::compress_module() {
        local ko_file
        local compress_type=""

        ko_file="$1"

        if [[ ! -f "$ko_file" ]]; then
                return 1
        fi

        # Debian don't need to compress kernel module due to unnecessary
        if grep -q "Debian GNU/Linux" /etc/os-release; then
                return 0
        fi

        if [[ $(util::get_kernel_config_value "CONFIG_MODULE_COMPRESS_GZIP") == "y" ]]; then
                compress_type="gz"
        elif [[ $(util::get_kernel_config_value "CONFIG_MODULE_COMPRESS_XZ") == "y" ]]; then
                compress_type="xz"
        elif [[ $(util::get_kernel_config_value "CONFIG_MODULE_COMPRESS_ZSTD") == "y" ]]; then
                compress_type="zst"
        else
                compress_type="none"
        fi

        case "$compress_type" in
        zst)
                zstd -f -q "$ko_file"
                ;;
        xz)
                xz -f -q "$ko_file"
                ;;
        gz)
                gzip -f -q "$ko_file"
                ;;
        esac
}
