#!/bin/sh
# Copyright (C) 2019 tribe29 GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.

# Reason for this no-op: shellcheck disable=... before the first command disables the error for the
# entire script.
:

# Disable unused variable error (needed to keep track of version)
# shellcheck disable=SC2034
CMK_VERSION="2.1.0p19"

_data_items() {
    #  size                 must be multiplied with block size (512byte)
    #  uuid
    #  device/address       can be bus address, e.g. 0000:21:00.0
    #  device/firmware_rev
    #  device/model         can be "SAMSUNG MZVLB512HAJQ-00000", "LOGICAL VOLUME"
    #  device/serial
    #  device/type          can be "0", "MMC", "SD"
    #  device/vendor        can be "ATA  ", "HP  ", "QEMU "
    # Excluded data_items
    #  dev
    #  wwid                 world wide ID
    #  nguid
    #  device/dev           what is second `dev` for?
    #  device/name          found at some mmc devices
    #  device/wwid          world wide ID?
    cat <<HERE
    size
    uuid
    device/address
    device/firmware_rev
    device/model
    device/serial
    device/type
    device/vendor
HERE
}

_distro_files() {
    cat <<HERE
    /etc/oracle-release
    /etc/debian_version
    /etc/gentoo-release
    /etc/lsb-release
    /etc/redhat-release
    /etc/SuSE-release
    /etc/os-release
    /usr/share/cma/version
HERE
}

_load_config() {
    [ -r "${1}" ] || return
    # shellcheck source=../cfg_examples/mk_inventory.cfg
    . "${1}"
}

_load_config "${MK_CONFDIR}/mk_inventory.cfg"

# Default to four hours
INTERVAL="${INVENTORY_INTERVAL:-14400}"

FLAGFILE="$MK_VARDIR/mk_inventory.last.$REMOTE"
LAST_RUN="$(stat -c %Y "${FLAGFILE}")"
NOW="$(date +%s)"
UNTIL=$((NOW + INTERVAL + 600))

if [ $((NOW - LAST_RUN)) -ge "${INTERVAL}" ]; then
    touch "${FLAGFILE}"

    # List of DEB packages
    if type dpkg-query >/dev/null; then
        echo "<<<lnx_packages:sep(124):persist($UNTIL)>>>"
        dpkg-query --show --showformat='${Package}|${Version}|${Architecture}|deb|-|${Summary}|${Status}\n'
    fi

    # List of RPM packages in same format
    if type rpm >/dev/null; then
        echo "<<<lnx_packages:sep(9):persist($UNTIL)>>>"
        rpm -qa --qf '%{NAME}\t%{VERSION}\t%{ARCH}\trpm\t%{RELEASE}\t%{SUMMARY}\t-\n'
    fi

    # List Gentoo packages
    if type equery >/dev/null; then
        echo "<<<lnx_packages:sep(124):persist($UNTIL)>>>"
        equery -C list --format "\$category/\$name|\$fullversion|\$mask2|ebuild|Repository \$repo|installed" \* | head -n -1
    fi

    # Information about distribution
    echo "<<<lnx_distro:sep(124):persist($UNTIL)>>>"
    _distro_files | while read -r f; do
        [ -e "$f" ] || continue
        echo "[[[$f]]]"
        tr \\n \| <"$f" | sed 's/|$//'
        echo
    done

    # CPU Information. We need just the first one
    if [ -e /proc/cpuinfo ]; then
        echo "<<<lnx_cpuinfo:sep(58):persist($UNTIL)>>>"
        sed 's/[[:space:]]*:[[:space:]]*/:/' </proc/cpuinfo
    fi

    # Information about main board, memory, etc.
    if type dmidecode >/dev/null; then
        echo "<<<dmidecode:sep(58):persist($UNTIL)>>>"
        dmidecode -q | sed 's/\t/:/g'
    fi

    # Information about kernel architecture
    if type uname >/dev/null; then
        echo "<<<lnx_uname:persist($UNTIL)>>>"
        uname -m
        uname -r
    fi

    # Collect VGAs if they are present
    vgas="$(lspci | grep VGA | cut -d" " -f 1)"
    if [ -n "$vgas" ]; then
        echo "<<<lnx_video:sep(58):persist($UNTIL)>>>"
        lspci -v -s "$vgas"
    fi

    # Some networking information
    if type ip >/dev/null; then
        echo "<<<lnx_ip_r:persist($UNTIL)>>>"
        ip r
        ip -6 r
    fi

    # Kernel configuration
    if type sysctl >/dev/null; then
        echo "<<<lnx_sysctl:persist($UNTIL)>>>"
        sysctl -ae
    fi

    # Block devices
    (# This subshell is for scoping UEVENT_FILE and DEVICE_DIR
        # use sep=0 rather than 124 in order to be more flexible in the parse function
        echo "<<<lnx_block_devices:sep(0):persist($UNTIL)>>>"
        find "/sys/block/" -maxdepth 1 -type f -o -type l | while read -r DEVICE; do
            UEVENT_FILE="$(realpath "${DEVICE}")/uevent"
            DEVICE_DIR="$(dirname "${UEVENT_FILE}")"

            grep "DEVTYPE=disk" -q "${UEVENT_FILE}" || continue
            [ "${UEVENT_FILE#*"devices/virtual/"}" = "${UEVENT_FILE}" ] || continue

            # use pipe as delimiter - also to mark begin of lines for consitency check
            echo "|device|${DEVICE_DIR}|"

            _data_items | while read -r item; do
                [ -f "$DEVICE_DIR/${item}" ] && echo "|${item}|$(cat "$DEVICE_DIR/${item}")|"
            done
        done 2>/dev/null
    )
fi
