#!/bin/sh
# postinst script for simbamond
#
# see: dh_installdeb(1)

set -e

# summary of how this script can be called:
#        * <postinst> `configure' <most-recently-configured-version>
#        * <old-postinst> `abort-upgrade' <new version>
#        * <conflictor's-postinst> `abort-remove' `in-favour' <package>
#          <new-version>
#        * <postinst> `abort-remove'
#        * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
#          <failed-install-package> <version> `removing'
#          <conflicting-package> <version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package

do_configure() {
  echo 'simbamond postinst: ensuring I2C is active...'

  # remove I2C from blacklist
  BLIST=/etc/modprobe.d/raspi-blacklist.conf
  if [ -r ${BLIST} ]
  then
    cp ${BLIST} ${BLIST}.bak
    if grep -q "^[ ]*blacklist[ ]*i2c-bcm2708" ${BLIST}
    then
      sed -i 's/[ ]*blacklist[ ]*i2c-bcm2708/# blacklist i2c-bcm2708/g' ${BLIST}
    fi
  fi
  # uncomment to debug: echo "I2C in ${BLIST}: "; grep i2c- ${BLIST} || :

  # add to /etc/modules
  MODS=/etc/modules
  if [ -r ${MODS} ]
  then
    if ! grep -q "i2c-dev" ${MODS}
    then
      cp ${MODS} ${MODS}.bak1
      echo i2c-dev >> ${MODS}
    fi
    if ! grep -q "i2c-bcm2708" ${MODS}
    then
      cp ${MODS} ${MODS}.bak2
      echo i2c-bcm2708 >> ${MODS}
    fi
  fi
  # uncomment to debug: echo "I2C in ${MODS}: "; grep i2c ${MODS} || :

  # load the modules
  modprobe i2c-dev || {
    echo "warning: failed to modprobe i2c-dev - reboot and retry?" >&2
  }
  modprobe i2c-bcm2708 || {
    echo "warning: failed to modprobe i2c-bcm2708 - reboot and retry?" >&2
  }
  # uncomment to debug: echo "I2C in /proc/modules: "; grep i2c_ /proc/modules || :

  echo "...done (simbamond postinst)"
}

case "$1" in
    configure) do_configure
    ;;

    abort-upgrade|abort-remove|abort-deconfigure)
    ;;

    *)
        echo "postinst called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0
