#!/bin/bash
#
# auto.diod - executable automounter map for diod file systems
#
# Input: $1 is "key" (/d/key is accessed)
# Output: string of the form "-fstype=diod[,options] server:path" on stdout
# Stderr goes to the system logs
# See autofs(5)
#
# Note: sources $DIOD_SYSCONF and uses the following if set
#   DIOD_SERVERS     list of servers to try (space delimited)
#                    Server may be IP, HOST or /path/to/socket.
#   DIOD_TIMEOUT     time (in seconds) to wait for server connect (default 10)
#   DIOD_MOUNTOPTS   Add options to the mount command line
#
key="$1"
[ -n "$key" ] || exit 0

DIOD_MAP=/d
DIOD_SYSCONF=/etc/sysconfig/auto.diod
DIOD_DIODCAT=/usr/sbin/diodcat
DIOD_SERVERS=""
DIOD_MOUNTOPTS=""
DIOD_TIMEOUT=10

if [ -r $DIOD_SYSCONF ]; then
    . $DIOD_SYSCONF
fi
if [ -z "$DIOD_SERVERS" ]; then
    echo "auto.diod: DIOD_SERVERS is not set" >&2
    exit 1
fi
if ! [ -x $DIOD_DIODCAT ]; then
    echo "auto.diod: could not execute $DIOD_DIODCAT" >&2
    exit 1
fi

prefix="-fstype=diod${DIOD_MOUNTOPTS:+,$DIOD_MOUNTOPTS}"
dcatopts="${DIOD_TIMEOUT:+-t $DIOD_TIMEOUT}"

for server in $DIOD_SERVERS; do
    $DIOD_DIODCAT -s $server $dcatopts exports | awk '{print $1}' |\
    while read path; do
        if [ "$path" == "/" ]; then
            if [ "$key" == "ROOT" ]; then
                echo "$prefix $server:$path"
                exit 0
            fi
        elif [ "$key" == "$(echo $path|sed -e's/^\///' -e's/\//./g')" ] \
          || [ "$key" == "$(echo $path|sed -e's/^\///' -e's/\//_/g')" ] \
          || [ "$key" == "$(echo $path|sed -e's/^\///' -e's/\//-/g')" ] \
          || [ "$key" == "$(basename $path)" ]; then
            echo "$prefix $server:$path"
            exit 0
        fi
    done
done
