#!/bin/sh
# Scan /lib/lvm-* for new binaries and set up symlinks for /sbin/lvmiopversion
# for them.

tmpfile="`tempfile`"
tmpfile2="`tempfile`"
trap 'rm -f "$tmpfile" "$tmpfile2" 2>/dev/null' EXIT QUIT INT TERM HUP

if [ "x$1" = "x-x" ]; then
	# Remove all lvmiopversion symlinks
	find /sbin -maxdepth 1 -type l > $tmpfile
	while read f; do
		[ "x`readlink "$f"`" = "xlvmiopversion" ] && rm -f -- "$f"
	done < $tmpfile
	rm -f $tmpfile $tmpfile2
	exit 0
fi

if [ ! -x /sbin/lvmiopversion ]; then
	echo 'lvm-bin-scan: /sbin/lvmiopversion not found; exiting!' >&2
	rm -f $tmpfile $tmpfile2
	exit 1
fi

# Find new ones
find /lib -maxdepth 1 -type d -name 'lvm-*' > $tmpfile2
while read i; do
	find "$i" -maxdepth 1 -follow -type f -maxdepth 1 > $tmpfile
	while read f; do
		s="/sbin/`basename "$f"`"
		[ ! -e "$s" ] && ln -sf -- lvmiopversion $s
	done < "$tmpfile"
done < $tmpfile2
# Remove old ones
find /sbin -maxdepth 1 -type l > $tmpfile
while read n; do
	b="`basename "$n"`"
	if [ "x`readlink $n`" = "xlvmiopversion" ] && \
		! find /lib -maxdepth 2 -follow -regex '^/lib/lvm-.*/'"$b" -type f -perm +0111 2>/dev/null \
		| grep -q '/lib'; then
		rm -f -- "$n"
	fi
done < "$tmpfile"

rm -f $tmpfile $tmpfile2
exit 0
