#!/bin/bash
#
# Copyright (c) 2015 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#

#
# This utility is a wrapper around mount, to provide a single script
# with preferred options for NFS mounting. It takes exactly two arguments:
# - network source path
# - local destination path
#

function show_help()
{
    cat >&2 << EOF
$(basename $0):
    Wrapper around "mount" to provide a set of default options for NFS mounts.
    This utility takes exactly two arguments:
    - network source path
    - local destination path

EOF
    exit 1
}

function get_proto()
{
    local host=$1

    # Check /etc/hosts for the hostname
    local ipaddr=$(cat /etc/hosts | awk -v host=$host '$2 == host {print $1}')
    if [[ "$ipaddr" =~ ^[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*$ ]]
    then
        echo "udp"
        return
    fi
    if [[ "$ipaddr" =~ ^[0-9a-z]*\:[0-9a-z\:]*$ ]]
    then
        echo "udp6"
        return
    fi
    # Try the DNS query
    ipaddr=$(dig +short ANY $host)
    if [[ "$ipaddr" =~ ^[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*$ ]]
    then
        echo "udp"
        return
    fi
    if [[ "$ipaddr" =~ ^[0-9a-z]*\:[0-9a-z\:]*$ ]]
    then
        echo "udp6"
        return
    fi

    # Use default of udp to avoid invalid option
    echo "udp"
    return
}


if [[ ${BASH_ARGC[0]} != 2 ]]
then
    show_help
fi

if mountpoint -q $2
then
    echo "$2 is already mounted. Not mounting."
    exit
fi

HOST=`echo $1|awk -F ':' '{print $1}'`
declare proto=`get_proto $HOST`
declare -i timeo=30
declare -i rw_size=1024
declare DEFAULT_OPTS="timeo=$timeo,proto=$proto,vers=3,rsize=$rw_size,wsize=$rw_size"

exec mount -t nfs -o $DEFAULT_OPTS $1 $2