#!/bin/sh
#
# This attempts to build and install the i2c-pseudo Linux kernel module.
# Installs a udev rule making i2c-pseudo devices read-write by users in plugdev.

set -e
cd "$(dirname "$0")"

make clean
make
ret=0
sudo make modules_install || ret="$?"

# Only install udev rule if plugdev group exists.
if getent group plugdev > /dev/null; then
  sudo cp -iv 50-i2c-pseudo.rules /etc/udev/rules.d/ \
    || echo 1>&2 "NOTICE: Failed to copy udev rules file."
fi

if [ "$ret" -eq 0 ]; then
  make clean
  sudo depmod -a
  sudo modprobe i2c-pseudo
  echo "SUCCESS: installed and loaded i2c-pseudo module"
else
  echo 1>&2 "WARNING: make modules_install failed with exit status $ret."
  echo 1>&2 "The module has not been installed for future reuse."
  echo 1>&2 "Will still attempt to load the module, using insmod instead of "\
"modprobe."
  ret=0
  sudo insmod i2c-pseudo.ko || ret="$?"
  if [ "$ret" -ne 0 ]; then
    make clean
    exit "$ret"
  fi
  echo "PARTIAL SUCCESS: loaded i2c-pseudo module (not installed)"
  make clean
fi
