#!/bin/sh
#
#  Guralp Systems Ltd.
#
#  LCDproc setup
#
#  Copyright (c) 2008-2009 Guralp Systems Limited.  www.guralp.com
#  Author:   R.J.Dunlop    <rdunlop@guralp.com>
#
#  Released under the GNU GPLv3. See file COPYING or
#  http://www.gnu.org/copyleft/gpl.html for details.
#

# Called by udev we check and if necessary tweak several parameters
# in the LCPproc config file

CFGBASE="/etc/lcdproc/LCDd.conf"
CFGFILE="${CFGBASE}.local"
TPLFILE="${CFGBASE}.tpl"

log_error() {
	logger -t lcdproc-setup "$*"
}

# If the config file doesn't exist, create the default from the template
[ ! -e "${CFGFILE}" -a -e "${TPLFILE}" ] && cp "${TPLFILE}" "${CFGFILE}"

# If we still don't have a config file, give up.
if [ ! -e "${CFGFILE}" ]
then
	log_error "No configuration file $CFGFILE to work with."
	exit 1
fi


# udev sets several environment variables for us.  First thing we
# check is that this is an add action, this also acts as a safety
# against users running the command directly.  This "safety" is
# applied late so a default configuration will always be created.
[ "$ACTION" != "add" ] && exit 0

# Decode the module type
case "$LCD_MODULE" in
CF631)
	lcdmodel="631"
	lcdsize="20x2"
	lcdspeed="115200"
	;;
CF633)
	lcdmodel="633"
	lcdsize="16x2"
	lcdspeed="19200"
	;;
CF635)
	lcdmodel="635"
	lcdsize="20x4"
	lcdspeed="19200"
	;;
*)
	log_error "Unknown LCD module type $LCD_MODULE"
	exit 1
	;;
esac


# Nothing to do if the module matches that in the config file
if grep -q "^Model=$lcdmodel\$" "${CFGFILE}"
then
	:
else
	# We need to edit the file
	sed -i -e "s/^Driver=.*/Driver=CFontzPacket/" \
		-e "s/^Model=.*/Model=$lcdmodel/" \
		-e "s/^Size=.*/Size=$lcdsize/" \
		-e "s/^Speed=.*/Speed=$lcdspeed/" $CFGFILE
fi

sleep 1
svc lcdproc start
svc lcd-statuswatch start

# Done
