#!/bin/sh
# Usage xf86cfgedit.sh XF86-conf-file elocalX-output-file
#
#----------------------------------------------------------

CONF_FILE=$1
ELO_CALIBRATION_FILE=$2
X11_INPUT_MODULES_DIR=/usr/X11R6/lib/modules/input
TMP_FILE=tmp.$$
TMP_FILE_1=tmp1.$$
TMP_COPY=copy.$$
BAK_FILE=$1.$$

get_section_start() {

awk '
/^Section \"'$2'\"/ { print NR }
' <$1

}

get_section_end() {

awk '
BEGIN               { section=0 }
/^Section \"'$2'\"/ { section=1 }
/^EndSection/       { if (section == 1) {section =0; print NR} } 
' <$1

}

get_identifier() {

awk '
BEGIN               { section=0 }
/^Section \"Input[dD]evice\"/ { section=1 }
/^[ \t]*Identifier/  {  if (section == 1 )  {section =0; printf $2 } } 
' <$1
}

get_input_driver_name() {

awk '
BEGIN               { section=0 }
/^Section \"Input[dD]evice\"/ { section=1 }
/^[ \t]*Identifier/ && /'$2'/  {  if (section == 1 )  {section = 2} } 
/^[ \t]*Driver/          { if (section == 2) { section = 1; printf $2}  } 
/^EndSection/       { if (section == 1) section =0 } 
' <$1
}


get_input_device_name() {

awk '
BEGIN               { section=0 }
/^Section \"'$2'\"/ { section=1 }
/^[ \t]InputDevice/ { if (section == 1)  print $2  } 
/^EndSection/       { if (section == 1) section =0 } 
' <$1
}



DEVICE_ID=`get_identifier ${ELO_CALIBRATION_FILE}` 

if [ -z "${DEVICE_ID}" ]; then
echo "Can't find the Identifier for section. Abort."
exit 1
fi

LINE=`get_section_end ${CONF_FILE} ServerLayout` 
if [ -z "${LINE}" ]; then
echo "Can't find section ServerLayout in ${CONFIG_FILE}"
exit 1
fi

cp ${CONF_FILE} ${TMP_COPY}

echo ${LINE} >${TMP_FILE}
echo i >>${TMP_FILE}

echo "   "InputDevice ${DEVICE_ID} \"SendCoreEvents\"  >>${TMP_FILE}
echo . >>${TMP_FILE}
echo w >>${TMP_FILE}
echo q >>${TMP_FILE}

ed ${TMP_COPY} <${TMP_FILE} >/dev/null 2>&1

LINE=`get_section_end ${TMP_COPY} InputDevice | tail -1` 
if [ -z "${LINE}" ]; then
echo "Can't find section(s) InputDevice  in ${CONFIG_FILE}"
rm -f ${TMP_COPY} ${TMP_FILE} ${TMP_FILE_1}
exit 1
fi

echo ${LINE} >${TMP_FILE}
echo a >>${TMP_FILE}

cat ${TMP_FILE} ${ELO_CALIBRATION_FILE} >${TMP_FILE_1}
echo >>${TMP_FILE_1}
echo . >>${TMP_FILE_1}
echo w >>${TMP_FILE_1}
echo q >>${TMP_FILE_1}

ed ${TMP_COPY} <${TMP_FILE_1} >/dev/null 2>&1

DRV_NAME=`get_input_driver_name ${ELO_CALIBRATION_FILE} ${DEVICE_ID} | tr -d \"`
if [ -z "${DRV_NAME}" ]; then
echo "Can't find input driver name  in ${ELO_CALIBRATION_FILE}"
rm -f ${TMP_COPY} ${TMP_FILE} ${TMP_FILE_1}
exit 1
fi

if [ ! -f ${X11_INPUT_MODULES_DIR}/${DRV_NAME}_drv.o ]; then
echo "WARNING! Driver ${X11_INPUT_MODULES_DIR}/${DRV_NAME}_drv.o not exists."
fi

echo Update ${CONF_FILE}, previous saved in the ${BAK_FILE} file...
mv -f ${CONF_FILE} ${BAK_FILE}
mv -f ${TMP_COPY} ${CONF_FILE}
rm -f ${TMP_COPY} ${TMP_FILE} ${TMP_FILE_1}
