#!/bin/bash
# Author: Steven Shiau, <steven _at_ nchc org tw>
# License: GPL

# Load DRBL setting and functions
DRBL_SCRIPT_PATH="${DRBL_SCRIPT_PATH:-/usr/share/drbl}"

. $DRBL_SCRIPT_PATH/sbin/drbl-conf-functions
#
export LC_ALL=C

Usage() {
  echo "Get the NFS server IP address of some IP address from DRBL setting." 
  echo "Normally this command is used in DRBL clients."
  echo "Usage:"
  echo "$(basename $0) IP_ADDRESS"
  echo "Ex: $(basename $0) 192.168.1.1"
}

#
while [ $# -gt 0 ]; do
  case "$1" in
    -*)	echo "${0}: ${1}: invalid option" >&2
	Usage >&2
	exit 2 ;;
    *)	break ;;
  esac
done

# Load config file
if [ -f /etc/diskless-image/config ]; then
 . /etc/diskless-image/config
 mode="client"
elif [ -f $drbl_common_root/etc/diskless-image/config ]; then
 . $drbl_common_root/etc/diskless-image/config
 mode="server"
else
 exit 1
fi

IP=$1
[ -z "$IP" ] && exit 1

# On client side, just use route to get the default gw, and it's nfsserver
# On server side, get a table to grep.
case "$mode" in
  "client")
    # On client side
    # 1st: try to use the mount status to get the nfs server, e.g.
    #      192.168.120.183:/tftpboot/node_root /
    # 2nd: Try to use gateway as NFS server
    nfsserver_cand="$(LC_ALL=C findmnt -nr -o source --target / | awk -F":" '{print $1}')"
    gateway="$(LC_ALL=C route -n | awk '/^0.0.0.0/ {print $2}')"
    if `is_valid_IPv4_add "$nfsserver_cand"`; then
      nfsserver="$nfsserver_cand"
    elif [ -n "$gateway" ]; then
      nfsserver="$gateway"
    else
      echo "NFSSERVER is not found, use default one: \"$nfsserver_default\"." 1>&2
      nfsserver=$nfsserver_default
    fi
    ;;
  "server")
    for i in $NFSSERVER_LIST; do
      if [ -n "$(grep -Ew "$IP" $drbl_syscfg/clients-of-${i}.txt 2>/dev/null)" ]; then
        nfsserver="$i"
	break 
      fi
    done
    ;;
esac

if [ -n "$nfsserver" ]; then
  echo $nfsserver
  exit 0
else
  exit 1
fi
