#!/bin/bash
### BEGIN INIT INFO
# Provides:          boot-xconf
# Required-Start:    $remote_fs
# Required-Stop:
# Default-Start:     S
# Default-Stop:
# Short-Description: Creates a XF86Config during boot-time
# Description:       Creates a XF86Config during boot-time for
#                    lessdisks-clients.  It's possible to pressed using
#                    MAC address and IP address
### END INIT INFO

XF86CONF=/var/state/lessdisks/etc/XF86Config
DEBUG=
IFACE=eth0
CREATECONF=

if [ -f /etc/default/boot_xconf ] ; then 
  . /etc/default/boot_xconf 
fi


debug () {
  [ "$DEBUG" ] && echo $1
}

iptohex () {
    IP=$1

    HEXIP=$(for ALL in $(echo "$IP" | tr "." " ") ; do 
      if [ $ALL -lt 16 ] ; then 
	echo -n "0$(echo -e "obase=16\n$ALL" | bc)"
      else
	echo -n "$(echo -e "obase=16\n$ALL" | bc)"
      fi 
    done  
    echo )

    LENGTH=8
    while [ $LENGTH -gt 0 ] ; do  
      echo $HEXIP
      LENGTH=$(expr $LENGTH - 1)
      HEXIP=$(echo $HEXIP | cut -c -$LENGTH)
    done
}

while [ $# -gt 0 ] ; do 
  case "$1" in 
    -dorun) CREATECONF=true ;;
    -debug) DEBUG=true ;;
    -iface) IFACE=$2 ; shift ;;
    *) COMMAND="$1" ;; 
  esac
  shift
done 

if [ "$CREATECONF" != "true" ] ; then 
  debug "$0 not set to run, exiting"
  exit 0
fi

IP=$(/sbin/ifconfig $IFACE | sed -ne 's/.*inet addr:\(.*\) Bcast.*/\1/p')
MACADDR=$(/sbin/ifconfig $IFACE | sed -n 's/.*HWaddr //p')

case "$COMMAND" in 
  start)
    for CONFSEARCH in $MACADDR $IP $(iptohex $IP) default ; do 
      debug "Looking for /etc/lessdisks/terminals/XF86Config-4.$CONFSEARCH"
      if [ -f /etc/lessdisks/terminals/XF86Config-4.$CONFSEARCH ] ; then 
        ln -s /etc/lessdisks/terminals/XF86Config-4.$CONFSEARCH $XF86CONF
        break 
      fi 
    done
    if [ ! -f $XF86CONF ] ; then
      debug "Running /usr/sbin/xdebconfigurator -di "
      /usr/sbin/xdebconfigurator -di 

      for CONFSEARCH in default $(iptohex $IP | tac) $IP $MACADDR ; do 
        debug "looking for debconf-*.$CONFSEARCH in /etc/lessdisks/terminals/"
        ALLDEBCONF=$(find /etc/lessdisks/terminals/ -type f -name "debconf-*.$CONFSEARCH")
        for DEBCONF in $ALLDEBCONF ; do 
          debug "Preseeding with $DEBCONF"
          debconf-set-selections $DEBCONF
        done
      done
      debug "creating $XF86CONF with dexconf"
      /usr/bin/dexconf -o $XF86CONF
    fi
    ;;
  stop)
    ;;
  restart)
        echo "restart for boox_xconf is unsupported, please use start" >&2
        exit 1
    ;;
  force-reload)
        echo "force-reload for boox_xconf is unsupported, please use start" >&2
        exit 1
    ;;
  *)
    echo "Usage: $0 {start|stop|restart|force-reload}"
    exit 2
    ;;
esac
