#!/bin/sh
#
# Look up modalias in package-modalias mapping file(s), and report the
# matching packages.
#
# If no argument is given, look up all modalias entries found in /sys.
# If an argument is given, look up the modalias given on th command
# line.

set -e

ubuntu_lists() {
    ubmirror=http://ftp.uninett.no/ubuntu
    suite=raring
    arch=i386
    for section in main restricted multiverse universe
    do
	GET $ubmirror/dists/$suite/$section/binary-$arch/Packages.bz2 | bunzip2
    done
}

debian_lists() {
    mirror=http://http.debian.net/debian
    suite=sid
    arch=i386
    for section in main contrib non-free
    do
	GET $mirror/dists/$suite/$section/binary-$arch/Packages.bz2 | bunzip2
    done
    echo $scriptdir
    if [ -r $scriptdir/modaliases ] ; then cat $scriptdir/modaliases; fi
    if [ -r /usr/share/isenkram/modaliases ] ; then
	cat /usr/share/isenkram/modaliases
    fi
    GET 'http://anonscm.debian.org/gitweb/?p=collab-maint/isenkram.git;a=blob_plain;f=modaliases;hb=HEAD'
}

trim_packages() {
    grep -E '^Package: |^Modaliases: |^$' \
    | tr "\n" "#" \
    | sed "s/##/\n/g" \
    | grep -E 'Modaliases: ' \
    | tr "\n" "%" | sed "s/%/\n\n/g" \
    | tr "#" "\n"
}

# To generate a list of packages
#debian_lists | trim_packages
#exit 0

get_lists() {
    #ubuntu_lists
    debian_lists
}

# Make sure file names do not contain slash by mapping % -> %25 and / -> %2F
escape() {
    sed -e 's:%:%25:g' -e 's:/:%2F:g'
}

pkglookup() {
    while read package modaliases ; do
	for alias in $(echo $modaliases | tr ")" "\n" | cut -d"(" -f2 | sed "s/, /\n/g" | escape); do
#	    echo "$package $alias" 1>&2
	    if ls "$alias" >/dev/null 2>&1 ; then
		echo $package
	    fi
	done
    done | sort -u
}

scriptdir=$(cd $(dirname $0); pwd)

dir=$(mktemp -d)
cd $dir

# First, find all relevant modalias entries for the current machine,
# and create a file with the alias name.
if [ "$1" ] ; then
    touch "$*"
else
    for id in $(find /sys -name modalias -print0 | xargs -0 cat | egrep '^(usb|pci|acpi|dmi):' | sort -u | escape ); do
	touch "$id"
    done
fi

# Next, extract package name and modalias glob list, and look up
# packages using shell globbing to match the current systems hardware.
get_lists \
    | grep -E '^Package: |^Modaliases: |^$' \
    | tr "\n" "#" \
    | sed "s/##/\n/g" \
    | tr "#" " " \
    | grep Modaliases: \
    | sed -e 's/^Package: //' -e 's/ Modaliases: / /g' \
    | pkglookup

cd /
rm -rf $dir
