#!/bin/sh
#
# by ymc-dabe
# Adds/removes an entry in /etc/exports
#

. /usr/lib/lib-fliwi/ymc-common.sh || exit 1

fliwiCommand=$4
USAGE="usage: $0 pathToSourceDirForExport subDirToExportRelativeToNfsRoot exportOptions {start|stop|status}";
exportSourcePath=$1
exportPath=$(echo $2 | sed -r 's|^/||')
exportOptions=$3
nfsExportRoot="/fileserver/nfsexport"

fliwiScriptName=$(basename $0)

usage()
{
    echo $USAGE >&2
}

if [ $# != 4 ]; then
    usage
    exit 1
fi


nfsv4_status()
{
    if [ $(cat /etc/exports | grep -c -F "$exportPath $exportOptions") -gt 0 ]; then
      echo "running"
    else
      echo "stopped"
    fi
}

nfsv4_add()
{
  if [ ! -e "$exportSourcePath" ]; then
    return 0
  fi

  ### Add the nfs4-root (if needed)
  nfsRootExportEntry="$nfsExportRoot 10.0.0.0/255.0.0.0(ro,sync,fsid=0,crossmnt,no_subtree_check)"
  if [ $(grep -c -F "$nfsRootExportEntry" /etc/exports) -le 0 ]; then
    echo "" >> /etc/exports
    fliwi_modify_file_add_block_start /etc/exports "Added by $fliwiScriptName"
    echo "$nfsRootExportEntry" >> /etc/exports
    fliwi_modify_file_add_block_end /etc/exports "Added by $fliwiScriptName"
  fi

  ### Create subdir in nfs-export-root (if needed)
  if [ ! -d "$nfsExportRoot/$exportPath" ]; then
    mkdir -p $nfsExportRoot/$exportPath
  fi

  ### Bind mount the source in the nfs-export-root
  if [ $(cat /proc/mounts | cut -d " " -f 2 | grep -c -E -e "^$nfsExportRoot/$exportPath\$") -le 0 ]; then
    mount -o bind $exportSourcePath/$exportPath $nfsExportRoot/$exportPath
  fi

  ### Add an entry in /etc/exports //start
  fliwi_modify_file_add_block_start /etc/exports "Added by $fliwiScriptName"
  echo "$nfsExportRoot/$exportPath $exportOptions" >> /etc/exports
  fliwi_modify_file_add_block_end /etc/exports "Added by $fliwiScriptName"
  ### Add an entry in /etc/exports //end
}

nfsv4_remove()
{
  umount $nfsExportRoot/$exportPath

  ### Wash out possibly existing entries added by this script in /etc/exports
  fliwi_modify_file_remove_added_block /etc/exports "Added by $fliwiScriptName"
}



case $fliwiCommand in
  start)        nfsv4_add;;
  stop)         nfsv4_remove;;
  status)       nfsv4_status;;
  *)            usage
                exit 1
                ;;
esac

