#!/bin/sh
#
# $NetBSD: 02-wedgenames,v 1.1.12.2 2015/03/07 06:00:01 snj Exp $
#
# Try to maintain symlinks to wedge devices
#

event="$1"
shift
devices=$@

wedgedir=/dev/wedges

remove_wedge() {
	find $wedgedir -print \
	| sed -e 's# #\\ #g' \
	| while read w; do
		t=$(readlink "$w")
		if [ x"$t" = x"/dev/$1" ]; then
			rm -f "$w"
			basedir=$(dirname "$w")
			rmdir -p "$basedir" 2>/dev/null
		fi
	done
}

add_wedge() {
	n=$(dkctl "$1" getwedgeinfo \
		| sed -ne '1s#^[^:]*: ##p' \
		| awk -v GOOD='._:;!^$&~()[]{}=,+-/' '
		BEGIN {
			for (i=0; i<256; ++i)
				ord[sprintf("%c",i)] = i
		}
		{
			n = length($0)
			o = ""
			for (i=1; i<=n; ++i) {
				c = substr($0,i,1)
				if (c ~ /^[[:alnum:]]$/ || index(GOOD,c) > 0) {
					o = o c
				} else {
					o = o sprintf("%%%02x",ord[c])
				}
			}
			printf "%s",o
		}'
	)
	case $n in
	"") ;;
	*)
		test -d $wedgedir || mkdir -m 755 $wedgedir
		basedir=$(dirname "$wedgedir/$n")
		test -d "$basedir" || mkdir -p -m 755 "$basedir"
		if oldlink=$(readlink "$wedgedir/$n"); then
			if [ x"$oldlink" != "/dev/$1" ]; then
				rm -f "$wedgedir/$n"
				ln -s "/dev/$1" "$wedgedir/$n"
			fi
		else
			ln -s "/dev/$1" "$wedgedir/$n"
		fi
		;;
	esac
}

for device in $devices; do
	case $device in
	dk*)
		case $event in
		device-attach)
			remove_wedge $device
			add_wedge $device
			;;
		device-detach)
			remove_wedge $device
			;;
		esac
		;;
	esac
done
