#!/bin/sh
# Summarize the Nvidia devices from DSDT/dmidecode/lspci tarballs from
# https://bugs.launchpad.net/bugs/752542
#
# Invoke with ./has-audio-problems.sh */
# where the subdirs are extracted tarballs (having dmidecode.txt and lspci.txt).
# Had to manually fix one dmidecode.txt and folder name for Notebook-N15_17RD,
# it reported "# SMBIOS implementations newer than version 2.8 are not".

set -u

warn() {
    printf 'WARNING: %s\n' "$1"
}


get_audio() {
    grep -i 'Audio device.*NVIDIA' lspci.txt
}

get_video() {
    grep -iE '(VGA compatible|3D controller).*NVIDIA' lspci.txt
}

bios_date() {
    grep bios-release-date dmidecode.txt
}

has_pr3() {
    local i
    if ls | grep -q '\.dsl$'; then
        grep -q _PR3 -w *.dsl
    elif [ -e acpidump.txt ]; then
        grep -q _PR3 -w acpidump.txt
    else
        warn "No ACPI info available!"
    fi
}


check_bad() {
    printf "%03d %s\n" $((1+count)) "${PWD##*/}"
    #vdev=$(get_video) || warn "No video device found"
    adev=$(get_audio) # || warn "No audio device found"
    date=$(bios_date) || warn "No bios date found"
    echo "$vdev"
    echo "${adev:-(No audio device found)}"
    echo "Date: $date"
    has_pr3 && echo "Got _PR3!" || echo "Use _DSM!"
    echo
}

# hacks for sorted output
tmpdir=$(mktemp -d)
outfile="$tmpdir/.out"
trap 'rm -rf "$tmpdir"' EXIT
# Without sorting
#post_move() { cat "$outfile"; }
post_move() {
    # Assume mm/dd/yyyy
    sedexpr='/^Date: /{s,.* ([0-9]+)/([0-9]+)/([0-9]+),\3-\1-\2,;p}'
    name=$(sed -r -n "$sedexpr" "$outfile")
    [ -n "$name" ] || return
    cat "$outfile" > "$tmpdir/$name"
}


check_dir() {
    local dir="$1"

    #(cd "$dir" && adev=$(get_audio) && check_bad)
    (cd "$dir" && vdev=$(get_video) && check_bad) >"$outfile" && post_move
}

count=0
for dir; do
    check_dir "$dir" && ((count++))
done


# With sorting
nr=1
for i in "$tmpdir"/[0-9]*; do
    seqno=$(printf %03d $nr)
    sed -r "1s/^[0-9]+ /$seqno /" "$i"
    ((nr++))
done


echo Done >&2
