#!/bin/sh

_help(){
echo
echo "This script applies the ported sensors framework from OpenBSD to FreeBSD 7.0-current"
echo "It's just a convenience script following the instructions from Constantine A. Murenin"
echo "It must be placed in your source tree root (usually /usr/src)"
echo "Usage:"
echo "./sensosrs_patch.sh option"
echo "-a	apply the patch"
echo "		Download the tarball and coretemp.c if neccessarry,"
echo "		make all addaitional directories, apply the patch"
echo "		and copy coretemp.c to sys/dev/coretemp/"
echo "-r	remove the modifications" 
echo "		Remove all additionally created files/directories which"
echo "		would break builworld after applying the patch again,"
echo "		revert the patch and resotre original coretemp.c"
echo "-i	Check if the patch is applied"
echo "-h	This help message"
}

_apply(){
if [ $stat = 1 ]; then
  echo "The sensors framework seems to be already applied to the source tree"
  echo "Cannot apply it twice!"
  exit 1
fi
if [ ! -f cnst-sensors.2007-08-20.patch ]; then
  fetch http://p4web.freebsd.org/depot/projects/soc2007/cnst-sensors/cnst-sensors.2007-08-20.patch
fi
if [ ! -f coretemp.c ]; then
  fetch http://p4web.freebsd.org/depot/projects/soc2007/cnst-sensors/sys.dev.coretemp/coretemp.c
fi
for n in sys/dev/lm  sys/modules/lm  usr.sbin/sensorsd; do
  if [ ! -d $n ]; then
    mkdir $n
  fi
done
cp sys/dev/coretemp/coretemp.c coretemp.c.orig
patch -i cnst-sensors.2007-08-20.patch
cp coretemp.c sys/dev/coretemp/
echo --------------------------------
echo Ready for buildworld/buildkernel
echo
}

_remove(){
if [ $stat = 0 ]; then
  echo "The source tree doesn't seem to have sensors framework included"
  echo "Cannot remove the patch!"
  exit 1
fi
patch -R -i cnst-sensors.2007-08-20.patch
cp coretemp.c.orig sys/dev/coretemp/coretemp.c
rm etc/sensorsd.conf*
rm share/man/man4/lm.4*
rm share/man/man9/sensor_attach.9*
rm sys/kern/kern_sensors.c*
rm sys/sys/sensors.h*
rm usr.bin/systat/sensors.c*
rm -R sys/dev/lm
rm -R sys/modules/lm
rm -R usr.sbin/sensorsd
echo -----------------------------
echo Ready for csup/applying again
echo
}

_info(){
if [ $stat = 1 ]; then
  echo "The sensors framework seems to be applied to the source tree."
fi
if [ $stat = 0 ]; then
  echo "The source tree doesn't seem to have sensors framework included."
fi
}

if [ $# != 1 ]; then
  _help
  exit 1
fi

if [ -f sys/modules/lm/Makefile ]; then
  stat=1
else
  stat=0
fi


case $1 in
	-a)	_apply;;
	-r)	_remove;;
	-i)	_info;;
	*)	_help;;
esac
