#!/bin/sh
#
#  Guralp Systems Ltd.
#
#  LCDproc setup
#
#  Copyright: ©2008–2012, Güralp Systems Ltd.
#  Author:   R.J.Dunlop    <rdunlop@guralp.com>
#  Author: Laurence Withers <lwithers@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, which 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



setup_cfontz() {
	lcddriver="$1"
	lcdmodel="$2"
	lcdsize="$3"
	lcdspeed="$4"

	# 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=$lcddriver/" \
			-e "s/^Model=.*/Model=$lcdmodel/" \
			-e "s/^Size=.*/Size=$lcdsize/" \
			-e "s/^Speed=.*/Speed=$lcdspeed/" $CFGFILE
	fi
}



setup_picolcdgraph() {
	# Nothing to do if the driver is already set
	if grep -q "^Driver=picolcdgraph" "${CFGFILE}"
	then
		:
	else
		sed -i "${CFGFILE}" \
			-e "s/^Driver=.*$/Driver=picolcdgraph/"
	fi
}



# Decode the module type
case "$LCD_MODULE" in
CF631)
	setup_cfontz "CFontzPacket" "631" "20x2" "115200"
	;;
CF632)
	setup_cfontz "CFontz" "632" "16x2" "19200"
	;;
CF633)
	setup_cfontz "CFontzPacket" "633" "16x2" "19200"
	;;
CF635)
	setup_cfontz "CFontzPacket" "635" "20x4" "19200"
	;;
picolcdgraph)
	setup_picolcdgraph
	;;
*)
	log_error "Unknown LCD module type $LCD_MODULE"
	exit 1
	;;
esac



# Force the service monitor to start a new instance. A simple "restart"
# wouldn't start the service from new; a "start || restart" wouldn't work
# because svc returns success even though the "start" fails. So, brute
# force approach…
svc lcdproc stop
sleep 1
svc lcdproc start
svc lcd-statuswatch start

# Done
