#!/bin/bash
#
# Usage:
# /sbin/mount.9P spec dir [-fnrsvw] [-o options]

restricted=1

if [ $UID -eq 0 ] && [ $UID -eq $EUID ]; then
  restricted=0
fi

# mount(8) in restricted mode (for non-root users) does not allow to use any
# mount options, types or so on command line. We have to call mount(8) with
# mountpoint only.  All necessary options have to be defined in /etc/fstab.
#
if [ $restricted -eq 1 ]; then
  exec /bin/mount -i "$@"
fi


# "Custom" default values (different from kernel default)
access="user"
uname="root"
msize="65560"

# Command line building variables
opts=""
switch=""
IPADDR=""
MNT=""


# Options can sneak in anywhere, e.g. mount -o foo device -o bar dir -o meh
# This allows for various flags and takes the first two non-options as
# device and dir accordingly
while [[ $# -ge $OPTIND ]]; do
  if getopts ":o:fnrsvwh" opt; then
    case "$opt" in
      o)
        IN_OPTIONS="${OPTARG//,/ }"

        for OPT in $IN_OPTIONS; do
          case "${OPT%%=*}" in
            # pass known options through...
            version|ro|rw|remount|posixacl|debug|trans|rq|sq|timeout| \
            port|cache|loose|mmap|cachetag|noextend|privport|context)
              opts+="${OPT},"
              ;;
            access)
              access="${OPT#*=}"
              ;;
            uname)
              uname="${OPT#*=}"
              ;;
            msize)
              msize="${OPT#*=}"
              ;;
            *)
              echo "Invalid 9p option: $OPT"
              exit 1
              ;;
          esac
        done
        ;;
      f|n|r|s|w)
        switch+="-$opt "
	;;
      v)
        switch+="-$opt "
        VERBOSE=1
        ;;
      h)
        echo "Usage: $0 remotehost:remotedir dir [-fnrsvw] [-o options]"
        exit 1
        ;;
      \?)
        echo "Invalid mount option: -$OPTARG"
        exit 1
        ;;
    esac
  elif [[ -z "$IPADDR" ]]; then
    shift $((OPTIND-1))
    OPTIND=1
    REMOTE="$1"
    shift

    if [[ "$REMOTE" != *:* ]]; then
      echo "Mount destination $REMOTE should be server:path"
      exit 1
    fi

    SERVERID="${REMOTE%%:*}"
    aname="${REMOTE#*:}"

    if ! IPADDR=$(getent ahostsv4 "$SERVERID" 2>&1 | awk '/STREAM/ { print $1; exit }'); then
      echo "Hostname could not be resolved"
      exit 1
    fi
  elif [[ -z "$MNT" ]]; then
    shift $((OPTIND-1))
    OPTIND=1
    MNT="$1"
    shift
  else
    echo "Extra argument: ${!OPTIND}"
    exit 1
  fi
done

# the "-i" is mandatory to avoid looping on this helper
EXEC_STRING="/bin/mount -i $switch -t 9p $IPADDR $MNT -o ${opts}access=${access},uname=${uname},msize=${msize},aname=${aname}"
if [[ -n "$VERBOSE" ]]; then
  echo "$EXEC_STRING"
fi
exec $EXEC_STRING
