#! /bin/bash

IFS=$'\n'

is_tumbleweed=false

if test "$1" = "--tumbleweed"; then
    if test "$2" -gt 0; then
        is_tumbleweed=true
    fi
    shift 2
fi

if ! $is_tumbleweed; then
    trap 'rm -f "$tmp"' EXIT
    tmp=$(mktemp --suffix=.ko)
fi


while read f; do
    test -e "$f" || continue
    is_module=""
    case "$f" in
    *.debug)
        continue
        ;;
    */boot/vmlinu[xz]-*)
        version=${f##*/vmlinu[xz]-}
        version=${version%.[gx]z}
        inst_prefix="$(dirname $f)"
        inst_prefix="$(dirname $inst_prefix)"
        echo "kernel-uname-r = $version"
        builtin="$inst_prefix/lib/modules/$version/modules.builtin"
        if [ -e "$builtin" ] ; then
                while read modname ; do
                        echo "kmod($(basename "$modname" | tr '-' '_'))"
                done < "$builtin"
        else
                echo "Builtin modules for $f not available in $builtin" >&2
        fi
        flavor=${version##*-}
        ;;
    */lib/modules/*/*.ko | */lib/modules/*/*.ko.[gx]z | */lib/modules/*/*.ko.zst)
        is_module="1"
        modname="${f%%.[gx]z}"
	modname="${modname%%.zst}"
        echo "kmod($(basename "$modname" | tr '-' '_'))"
        ;;
    *)
        continue
    esac
    if $is_tumbleweed; then
        continue
    fi
    case "$f" in
    *.gz | */boot/vmlinuz*)
        gzip -cd "$f" > "$tmp"
        f=$tmp;;
    *.xz)
        xz -cd "$f" > "$tmp"
        f=$tmp;;
    *.zst)
	zstd -cd "$f" > "$tmp"
	f=$tmp;;
    esac
    if test -z "$flavor" -a -n "$is_module" ; then
        version=$(/sbin/modinfo -F vermagic "$f")
        version=${version%% *}
        flavor=${version##*-}
    fi
    if test -z "$flavor"; then
        echo "warning: cannot determine kernel flavor from $(/sbin/modinfo -F vermagic "$f" 2>&1)" >&2
        continue
    fi
    objdir=$(readlink /lib/modules/$version/build)
    objdir_build=$RPM_BUILD_ROOT$(readlink $RPM_BUILD_ROOT/lib/modules/$version/build)
    for i in $objdir_build $objdir ; do
            ksym_provides=$i/scripts/mod/ksym-provides
            [ -x "$ksym_provides" ] && break
    done
    if [ -x "$ksym_provides" ] ; then
            "$ksym_provides" $flavor $f
    else
            major=${version%%.*}
            sub=${version#*.}
            sub=${sub%%.*}
            if [ "$major" -gt 4 -o \( "$major" -eq 4 -a "$sub" -ge 10 \) ] ; then
                    echo "error: cannot determine ksym provides of $f - missing ksym-provides tool." >&2
            else
                    nm "$f" \
                            | sed -r -ne "s/^0*([0-9a-f]+) A __crc_(.+)/ksym($flavor:\\2) = \\1/p"
            fi
    fi
done \
| sort -u
