#!/bin/bash

# The MIT License

# Copyright (c) 2019 Dusty Mabe

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

set -eu

# The behaviour of KVC depends on the container runtime 
# podman     - for day-1 out-of-tree drivers
# kubernetes - for day-2 out-of-tree drivers
get_container_context() {
        if awk -F/ '$2 == "kubepods.slice"' /proc/self/cgroup | read non_empty_input; then
                echo kubernetes
        else 
                echo podman
        fi
}

# Check if the module only uses whitelisted symbols
kabi_check_module() {
    LIBM="/lib/modules"
    ARCHITECTURE=$(uname -m)

    KRNM=$(modinfo $1 | grep filename | awk '{ print $2 }')
    SYMBOLS=$(mktemp)
    WHITELIST=$(mktemp)
    KABIS=$(ls -d ${LIBM}/kabi-rhel*)

    for KABI in ${KABIS}
    do
            tail -n +2 ${KABI}/kabi_whitelist_${ARCHITECTURE} > ${WHITELIST}
            readelf -sW ${KRNM} | sed -nre 's:.*UND (.*):\1:p' | awk NF > ${SYMBOLS}

            echo "Comparing kernel module symbols $(basename ${KRNM}) against kabi whitelist $(basename ${KABI})"
            DIFF=$(join -v 1 <(sort ${SYMBOLS}) <(sort ${WHITELIST}))
            if [ ! -z "${DIFF}" ]; then
                    echo "WARNING: Non whitelisted symbols:"
            fi
    done
}

# Helper functions for running containers
# Use set -x to print out the runtime CLI to log
# Run in a subshell so we don't also see `set +x`
kvc_c_run()   { (set -x; $KVC_CONTAINER_RUNTIME run -i --rm $@ ); }
kvc_c_build() { (set -x; $KVC_CONTAINER_RUNTIME build  $@ ); }
kvc_c_images(){ (set -x; $KVC_CONTAINER_RUNTIME images $@ ); }
kvc_c_rmi()   { (set -x; $KVC_CONTAINER_RUNTIME rmi    $@ ); }
kvc_c_env()   { (set -x; get_container_context)}

# Define these functions in your library file
build_kmods() {
    echo "build_kmods is unimplemented for ${KVC_SOFTWARE_NAME}!" 2>&1
    return 1
}
load_kmods() {
    echo "load_kmods is unimplemented for ${KVC_SOFTWARE_NAME}!" 2>&1
    return 1
}
unload_kmods() {
    echo "unload_kmods is unimplemented for ${KVC_SOFTWARE_NAME}!" 2>&1
    return 1
}
wrapper() {
    echo "wrapper is unimplemented for ${KVC_SOFTWARE_NAME}!" 2>&1
    return 1
}

KVC_ACTION=$1; shift
KVC_SOFTWARE_NAME=$1; shift
KVC_KVER=$1; shift
echo "KVC: ${KVC_ACTION} ${KVC_SOFTWARE_NAME} for ${KVC_KVER}"

# Source in configuration for the KVC framework
source "/etc/kvc/kmods-via-containers.conf"
# Source in the library that defines {build,load,unload}_kmods,wrapper
# must be in one of /usr/{,local/}lib/kvc/${KVC_SOFTWARE_NAME}-lib.sh
for instance_library in /usr/{local/,}lib/kvc/${KVC_SOFTWARE_NAME}-lib.sh; do
    if [ -f "${instance_library}" ]; then
        source "${instance_library}"
        found=1
    fi
done
if [ "${found-}" != 1 ]; then
    echo "KVC requires an instance library" \
         "to define significant functionality" 2>&1
    echo "No instance library found in one of required locations" \
         /usr/{local/,}lib/kvc/${KVC_SOFTWARE_NAME}-lib.sh 2>&1
    exit 1
fi

case "${KVC_ACTION}" in
    build)
        build_kmods
    ;;
    load)
        load_kmods
    ;;
    unload)
        unload_kmods
    ;;
    reload)
        build_kmods
        unload_kmods
        load_kmods
    ;;
    wrapper)
        # wraps/runs executables from within the kernel module container
        wrapper $@
    ;;
    *)
        echo "Unknown command. Exiting."
        echo "Usage:"
        echo ""
        echo "build       Build kernel module(s) via container"
        echo "load        Load kernel module(s)"
        echo "unload      Unload kernel module(s)"
        echo "reload      Build and reload kernel module(s)"
        echo "wrapper     Run userspace tools from within the container"
        exit 1
esac



