#!/bin/bash

. ${TOOLKIT}-functions.sh

myself=`uname -n`
myself_short=`uname -n | sed -e 's/\..*//'`

# must work in a safe environment to avoid expansion
# of '*' during match tests, so must create an empty
# work directory
#
dir=`mktemp -d /tmp/kusa-XXXXXX`
here=`pwd`
cd $dir

for link in `jtconf --list links.`
do
	temp=`		jtconf $link.link	2>/dev/null` || continue
	action=`	jtconf $link.action	2>/dev/null` || :
	exclude=`	jtconf $link.exclude	2>/dev/null` || :
	include=`	jtconf $link.include	2>/dev/null` || :

	set $temp
	source=$1
	target=$2

	[ "$target" ] || continue

	# is include?
	must_include=false
	for match in `echo "$include" | tr ',' ' '`
	do
		case $myself_short in
			$match) must_include=true ; break ;;
		esac
		case $myself in
			$match) must_include=true ; break ;;
		esac
	done
	$must_include || continue	# next entry


	# is excluded?
	must_exclude=false
	for match in `echo "$exclude" | tr ',' ' '`
	do
		case $myself_short in
			$match) must_exclude=true ; break ;;
		esac
		case $myself in
			$match) must_exclude=true ; break ;;
		esac
	done
	$must_exclude && continue	# next entry


	[ "$action" = "remove" ] && {
		if [ -L "$target" ]
		then
			echo "  remove link $target"
			rm -f "$target"
		else
			[ -f "$target" -o -d "$target" ] && {
				echo "  can't remove $target: not a symlink"
			}
		fi
		continue
	}

	#[ -d $source -o -f $source ] || continue

	updatelink $source $target || exit $?
done

cd $here
rmdir $dir

exit 0
