#!/bin/sh
#
. /opt/HAC/bin/rsf.sh

EXPORTSD="/etc/exports.d/"
TN_EXPORT_DIR=".tn_nfs"

service=${RSF_SERVICE:-"service_name"}
script="`basename $0`"

case "${1}" in

'start')
        if [ -f /data/freenas-v1.db ] ; then
          THISHOST=`hostname -s | tr '[:upper:]' '[:lower:]'`
          dated_echo "=========  Enabling TrueNAS NFS shares on: ${THISHOST}  ========="

          SERVICES=`/opt/HAC/RSF-1/bin/rsfcli list|awk '{print $1}'|sed '/^$/d'`
          if [ ! -z "${SERVICES}" ] ; then
            for svc in ${SERVICES}
            do
              #
              # Service is starting here so we force it's location (otherwise it will be '-' as it has
              # not fully started.
              if [ "${svc}" = "${service}" ] ; then
                LOCATION=${THISHOST}
              else
                LOCATION=`/opt/HAC/RSF-1/bin/rsfcli locate ${svc} | awk -F. '{print $1}' | tr '[:upper:]' '[:lower:]'`
              fi

              if [ "${LOCATION}" = "${THISHOST}" ] ; then
                EDIR="/mnt/${svc}/${TN_EXPORT_DIR}"

                #
                # Do not try to combine the two if's with a -a because the (ls...)
                # will be resolved BEFORE the comparision and can result in 'no such
                # file or drirectory' messages.
                if [ -d "${EDIR}" ] ; then
                  if [ "$(ls -A ${EDIR})" ] ; then
                    dated_echo "Copying export files from ${EDIR} to ${EXPORTSD}"
                    chattr -i ${EXPORTSD}
                    cp ${EDIR}/* ${EXPORTSD}
                  else
                    dated_echo "No exports file in ${EDIR}"
                  fi
                fi
              fi
            done
          fi

          chattr +i ${EXPORTSD}
          exportfs -av
        fi
        rc_exit ${service} ${RSF_OK}
        ;;

'stop')
        rc_exit ${service} ${RSF_OK}
        ;;

'check')
        exit ${RSF_CHECK_NORESRC}
        ;;

*)
        rc_exit ${service} ${RSF_WARN} "usage: $0 <start|stop|check>"
        ;;

esac
