Home | History | Annotate | Line # | Download | only in hooks
02-wedgenames revision 1.5
      1 #!/bin/sh
      2 #
      3 # $NetBSD: 02-wedgenames,v 1.5 2021/01/09 14:00:05 mlelstv Exp $
      4 #
      5 # Try to maintain symlinks to wedge devices
      6 #
      7 
      8 export LC_ALL=C
      9 
     10 event="$1"
     11 shift
     12 devices=$@
     13 
     14 wedgedir=/dev/wedges
     15 
     16 recurse()
     17 {
     18 	test -d "$1" && ls -1af "$1" \
     19 	| while read n; do
     20 		case $n in
     21 		.|..) ;;
     22 		*)
     23 			echo "$1/$n"
     24 			if [ -L "$1/$n" ]; then
     25 				: #nothing
     26 			elif [ -d "$1/$n" ]; then
     27 				recurse "$1/$n"
     28 			fi
     29 			;;
     30 		esac
     31 	done
     32 }
     33 
     34 simple_readlink()
     35 {
     36 	local x
     37 
     38 	x=$(test -e "$1" && ls -ld "$1")
     39 	case $x in
     40 	*'-> '*) echo ${x#*-> };;
     41 	esac
     42 }
     43 
     44 ordtable=$(
     45 	for n1 in 0 1 2 3 4 5 6 7 8 9 a b c d e f; do
     46 	for n2 in 0 1 2 3 4 5 6 7 8 9 a b c d e f; do
     47 		echo "\$'\x$n1$n2') x=$n1$n2;;"
     48 	done
     49 	done
     50 )
     51 
     52 ord()
     53 {
     54 	local x
     55 	eval "case \$1 in $ordtable esac"
     56 	echo -n $x
     57 }
     58 
     59 encode()
     60 {
     61 	local a
     62 
     63 	a=$1
     64 	while [ -n "$a" ]; do
     65 		c="${a%"${a#?}"}"
     66 		a=${a#?}
     67 		case $c in
     68 		[[:alnum:]._:\;!^$\&~\(\)[\]{}=,+\-/])
     69 			;;
     70 		*)
     71 			c='%%'$(ord "$c")
     72 			;;
     73 		esac
     74 		echo -n "$c"
     75 	done
     76 }
     77 
     78 remove_wedge() {
     79 	recurse "$wedgedir" \
     80 	| while read w; do
     81 		t=$(simple_readlink "$w")
     82 		if [ x"$t" = x"/dev/$1" ]; then
     83 			rm -f "$w"
     84 			basedir=$(dirname "$w")
     85 			rmdir -p "$basedir" 2>/dev/null
     86 		fi
     87 	done
     88 }
     89 
     90 add_wedge() {
     91 	dkctl "$1" getwedgeinfo \
     92 	| while read l; do
     93 		case $l in
     94 		*': '*)
     95 			n="${l#*: }"
     96 			n=$(encode "$n")
     97 			test -d $wedgedir || mkdir -m 755 $wedgedir
     98 			basedir=$(dirname "$wedgedir/$n")
     99 			test -d "$basedir" || mkdir -p -m 755 "$basedir"
    100 			if oldlink=$(simple_readlink "$wedgedir/$n"); then
    101 				if [ x"$oldlink" != x"/dev/$1" ]; then
    102 					rm -f "$wedgedir/$n"
    103 					ln -s "/dev/$1" "$wedgedir/$n"
    104 				fi
    105 			else
    106 				ln -s "/dev/$1" "$wedgedir/$n"
    107 			fi
    108 			;;
    109 		esac
    110 		break
    111 	done
    112 }
    113 
    114 for device in $devices; do
    115 	case $device in
    116 	dk*)
    117 		case $event in
    118 		device-attach)
    119 			remove_wedge $device
    120 			add_wedge $device
    121 			;;
    122 		device-detach)
    123 			remove_wedge $device
    124 			;;
    125 		esac
    126 		;;
    127 	esac
    128 done
    129