#! /bin/sh
#
# /usr/share/dahdi/span_config
#
# Called by UDEV when a dahdi span is added/removed
#

me=`basename $0`
dir=`dirname $0`
LOGGER="logger -i -t '$me'"
NAME=`basename "$DEVPATH" | tr -c 'A-Za-z0-9-' '_'`

exec 2> /dev/null
# Always redirect stderr somewhere, otherwise the shell script will die
# when it tries to do I/O related stuff on closed file descriptor.
# Our default is to throw it down the bit-bucket.
#exec 2> /dev/console
## If you wish to trace this script:
#exec 2> "/tmp/${me}.$NAME" 1>&2

# Our directory in the beginning, so we can use local lab setup
PATH="$dir:/usr/sbin:/sbin:/usr/bin:/bin"

set -e

#echo >&2 "$0($ACTION): DEBUG($# args): '$*'"

# Can we pass a different value so we can use
# alternate (testing) configuration?
# Meanwhile, make it hard-coded.
DAHDICONFDIR='/etc/dahdi'
export DAHDICONFDIR

is_cfg_tmp=false

gen_dahdi_cfg() {
	local cfg_file=`mktemp dahdi_system_XXXXXX.cfg`
	DAHDI_CONF_FILE="$cfg_file" dahdi_genconf system 1>&2
	echo "$cfg_file"
}

run_dahdi_cfg() {
	span_devpath="$1"
	# Sanity check
	checkit=`"dahdi_cfg" --help 2>&1 | grep -- '-S' | wc -l`
	if [ "$checkit" != 1 ]; then
		$LOGGER "Bad dahdi_cfg (no -S support). Skipping"
		exit 0
	fi
	cfg_file="$DAHDICONFDIR/system.conf"
	if [ ! -r "$cfg_file" ]; then
		cfg_file=`gen_dahdi_cfg`
		is_cfg_tmp=true
	fi
	spanno=`echo "$span_devpath" | sed 's,.*/span-,,'`
	basechan=`cat "$span_devpath/basechan"`
	channels=`cat "$span_devpath/channels"`
	endchan=`expr "$basechan" + "$channels" - 1`
	echo "dahdi_cfg: span $spanno <$basechan-$endchan>"
	dahdi_cfg \
		-c "$DAHDICONFDIR/system.conf" \
		-S "$spanno" \
		-C "$basechan-$endchan"
	if $is_cfg_tmp; then
		rm "$cfg_file"
	fi
	asterisk -rx "dahdi create channels $basechan $endchan"
}

case "$ACTION" in
add)
	echo "$ACTION: $DEVPATH" | $LOGGER
	# Can have alternate dahdi configuration directory for debugging
	# export DAHDICONFDIR="/tmp/xortel/dahdi"

	run_dahdi_cfg "/sys$DEVPATH" 2>&1 | $LOGGER
	;;
remove)
	# Nothing to do yet...
	echo "$ACTION: $DEVPATH" | $LOGGER
	;;
*)
	echo "UNHANDLED: $ACTION: $DEVPATH" | $LOGGER
	;;
esac

