#!/bin/sh
#---------------------------------------------------------------
# Project         : hardware4linux.info
# File            : hwreport
# Author          : Frederic Lepied
# Created On      : Fri Feb 17 22:48:06 2006
# Purpose         : gather hardware and os info and the store them
#                   in an archive file.
#---------------------------------------------------------------

if [ `whoami` != root ]; then
    echo "you need to be root to launch this program" 1>&2
    exit 1
fi

if [ $# != 1 ]; then
    cat <<EOF
usage: $0 <basename>
EOF
    exit 1
fi

set -e

BASE="$1"
DEST=`mktemp -d`

if [ ! -d "$DEST" ]; then
    echo "Unable to create temporary directory" 1>&2
    exit 1
fi

clean() {
    [ -d "$DEST" ] && rm -rf "$DEST"
}

trap clean 0

# step 0: verify integrity
PATH=`dirname $0`:$PATH
export PATH

for e in osinfo dmidecode scan-printers lspci lsmod; do
    if ! type $e > /dev/null 2>&1; then
	echo "$e not found. Aborting" 1>&2
	exit 1
    fi
done

# step 1: gather info

osinfo -x > "$DEST/osinfo.xml"

echo "version=0.9.2" > "$DEST/hwreport.info"
echo "date=`date +'%F,%T'`" >> "$DEST/hwreport.info"

mounted=
if [ ! -r /proc/bus/usb/devices ]; then
    mount -t usbfs none /proc/bus/usb && mounted=1 || :
fi

for d in /proc/bus/*; do
    f=`basename $d`
    if [ -r "$d/devices" ]; then
	cat $d/devices > "$DEST/$f.devices"
    fi
done

if [ -n "$mounted" ]; then
    umount /proc/bus/usb
fi

lspci -vn > "$DEST/lspci.out"

# report module related info only if the kernel
# has been compiled with module support...
if [ -f /proc/modules ]; then
    lsmod > "$DEST/lsmod.out"
    
    cp -p /lib/modules/`uname -r`/*map "$DEST/"
fi

scan-printers > "$DEST/printers.out"

for f in /proc/parport/[0-9]*/autoprobe /proc/sys/dev/parport/parport[0-9]*/autoprobe; do
    if [ -r $f ]; then
	echo -n "$f: " >> "$DEST/printers.out"
	while read l; do echo -n "$l"; done < $f >> "$DEST/printers.out"
	echo >> "$DEST/printers.out"
    fi
done

if [ -f /proc/cmdline ]; then
    cat /proc/cmdline > "$DEST/cmdline"
fi

dmidecode > "$DEST/dmidecode.out"

cat /proc/cpuinfo > "$DEST/cpuinfo"

if [ -r /proc/asound/cards ]; then
    cat /proc/asound/cards > "$DEST/asound.cards"
fi

# step 2: archive info

# try to guess which kind of archiver is available
if type tar > /dev/null 2>&1; then
    FILE="$BASE".tar
    tar cf "$FILE" -C "$DEST" .
    if type bzip2 > /dev/null 2>&1; then
	bzip2 -9f "$FILE"
	FILE="$FILE.bz2"
    elif type gzip > /dev/null 2>&1; then
	gzip -9f "$FILE"
	FILE="$FILE.gz"
    fi
elif type zip > /dev/null 2>&1; then
    FILE="$BASE".zip
    rm -f "$FILE"
    zip "$FILE" -9 -q -j -r "$DEST"
else
    echo "no way to store the files. Given up." 1>&2
    exit 1
fi

rm -f $FILES

echo "$FILE created successfully"

# hwreport ends here
