#!/bin/sh
#
# Executed during installation to implement hardware specific workarounds.

set -e

if [ -t 1 ] ; then
    MANUAL_RUN=true
else
    MANUAL_RUN=false
fi

info() {
    echo "info: $@" 1>&2
}

append_if_missing() {
    file="$1"
    string="$2"
    if [ -f "$file" ] && grep -q "$string" "$file" ; then
        :
    else
        (
            if [ -f "$file" ] ; then cat "$file" ; fi
	    echo "$string"
        ) > "$file.new" && mv "$file.new" "$file"
    fi
}

add_nonfree_pkg() {
    pkg="$1"
    codename=$(debian-edu-current-codename)

    info "Installing non-free package $pkg from $codename."
    if ! LC_ALL=C apt-cache show $binpkg 2>&1 | \
               grep -q 'E: No packages found' ; then
	echo deb http://http.debian.net/debian $codename non-free \
	    > /etc/apt/sources.list.d/$pkg.list
	chmod a+r /etc/apt/sources.list.d/$pkg.list
	apt-get -qq update
    fi
    apt-get -qq install -y $pkg
}

acpi_backlight_vendor() {
    append_if_missing /etc/default/grub \
	'GRUB_CMDLINE_LINUX_DEFAULT="$GRUB_CMDLINE_LINUX_DEFAULT acpi_backlight=vendor"'
    chmod a+r /etc/default/grub
    update-grub
}

i915_invert_brightness() {
    append_if_missing /etc/modprobe.d/i915.conf \
        "options i915 invert_brightness=1"
    chmod a+r /etc/modprobe.d/i915.conf
    update-initramfs -u -k all
}

info "looking for PCI device specific overrides"
for modaliasfile in /sys/bus/pci/devices/*/modalias; do
    modalias="$(cat $modaliasfile)"
    case "$modalias" in
        # Workaround for BTS report #710938 (Packard Bell EasyNote LV)
        # See http://www.linlap.com/packard_bell_easynote_lv
        pci:v00008086d00000156sv00001025sd00000688bc*)
            acpi_backlight_vendor
            ;;

        # Workaround for BTS report #714154 (Acer Aspire V3-771G model
        # VA70)
        pci:v00008086d00000166sv00001025sd00000686bc*)
            i915_invert_brightness
            ;;
    esac
done

info "looking for DMI manufacturer and product specific overrides"
manufacturer=$(dmidecode -s system-manufacturer)
productname=$(dmidecode -s system-product-name)

case "$manufacturer" in
    'Hewlett-Packard')
	case "$productname" in 
    	    'HP 2133')
		# Avoid white on white console.  See
		# http://wiki.debian.org/InstallingDebianOn/HP/HP2133
		# http://morethan.org/mini-note/xorg-mini.html
		append_if_missing /etc/default/acpi-support \
		    'SAVE_VBE_STATE=false'
		;;
	esac
	;;
esac

# Autodetect firmware packages and install them
isenkram-autoinstall-firmware
