
#!/bin/sh
# File	:  set_nfs_ro.sh
# By	: Maarten.deBoer@Atos.net, 191014
# Subject	: Script to set a NFS-export RO
PGM=`basename $0|cut -d\. -f1`
VER="0.1"
TMP="/tmp/${PGM}.$$"
LOG="${HOME}.log"
ETC="${HOME}/etc/${PGM}.exports"
SSH="/bin/ssh"
DATADIR="${HOME}/data/${PGM}"
DATI=`date +%Y%d%m-%H%M%S`

if [ ! -f ${ETC} ]; then
  echo "  Input-file (${ETC}) NOT found. Exiting..."
  exit 2
fi
if [ ! -d ${DATADIR} ]; then
  echo "  DATA-dir (${DATADIR}) not available. Please create. Exiting..."
  exit 3
fi

echo "  Saving exports data first (into data/${PGM}/<filer>_<vfiler>_${DATI}) ..."
cat ${ETC}|grep -v ^#|awk '{print $1}'|sort -u|while read FILER
do
  cat ${ETC}|grep -v ^#|awk '{print $2}'|sort -u|while read VFILER
  do
    echo "  ${FILER}/${VFILER} ..."
    ${SSH} ${FILER} "exportfs" > ${DATADIR}/${FILER}_${VFILER}_${DATI}.exports-save
  done  # VFILER
done  # FILER

touch ${TMP}
# A 3 round (FILER, VFILER, EXPORTS) is needed
cat ${ETC}|grep -v ^#|awk '{print $1}'|sort -u|while read FILER
do
  cat ${ETC}|grep -v ^#|awk '{print $2}'|sort -u|while read VFILER
  do
    echo "  ${FILER}/${VFILER} ..."
    cp ${DATADIR}/${FILER}_${VFILER}_${DATI}.exports-save ${TMP}

    cat ${ETC}|grep -v ^#|grep ${FILER}|while read LINE
    do
      EXPORT=`echo ${LINE}|awk '{print $3}'`
      echo "|${FILER}|${VFILER}|${EXPORT}|"
      cat ${TMP}|grep -v "${EXPORT}" > ${DATADIR}/${FILER}_${DATI}.exports-new
      cat ${TMP}|grep "${EXPORT}" |sed 's/rw=/ro=/g' >> ${DATADIR}/${FILER}_${DATI}.exports-new
      cp ${DATADIR}/${FILER}_${DATI}.exports-new ${TMP}
    done  # LINE
    cp ${TMP} ${DATADIR}/${FILER}_${VFILER}_${DATI}.exports-new

  done  # VFILER

done # FILER

echo "  Using NEW exports ..."
cat ${ETC}|grep -v ^#|awk '{print $1}'|sort -u|while read FILER
do
  cat ${ETC}|grep -v ^#|awk '{print $2}'|sort -u|while read VFILER
  do
    echo "  ${FILER}/${VFILER} ..."
#  cat ${DATADIR}/${FILER}_${DATI}.exports-new
    cat ${DATADIR}/${FILER}_${VFILER}_${DATI}.exports-new|${SSH} ${FILER} 'wrfile /etc/exports'
echo "  rdfile /etc/exports ..."
    ${SSH} ${FILER} "rdfile /etc/exports"
echo "  exportfs -a ..."
  ${SSH} ${FILER} "exportfs -a"
done  # cat ETC

echo "  Checking LIVE FILERS ..."
cat ${ETC}|grep -v ^#|while read LINE
do
  FILER=`echo ${LINE}|awk '{print $1}'`
  VFILER=`echo ${LINE}|awk '{print $2}'`
  EXPORT=`echo ${LINE}|awk '{print $3}'`
  echo "  ${FILER} ${VFILER} ${EXPORT} ... "

#  cat ${DATADIR}/${FILER}_${DATI}.exports-new|grep ${EXPORT}
  ${SSH} -n ${FILER} "exportfs"|grep ${EXPORT}

done  # cat ETC



exit 0

