
#!/bin/sh
# File	: cdot_mod_mss03_access.sh
# By	: Maarten.deBoer@Atos.net, 211111
# Subject	: Script to generate access to nlnafsmss03
#(0.2),210118	: Copied from create_mss01_access.sh
#(0.3),210504	: DO_NEWPWD
#(0.4),211111,MdB	: Copied from modify_mss01_access.sh
#(0.5),220111,MdB	: Add -l (vserver-userlist)
#(0.6),220111,MdB	: Add -d delete
#(0.7),220113,MdB	: Add MAIL
#(0.8),220113,MdB	: Add -s 
#(0.9),220113,MdB	: Mod. -c with -d <username> to overrule DONELIST
#(0.10),220117,MdB	: Mod. mailtext
#(0.11),220118,MdB	: Added ${USER} ${USERLIST} at -s
#(0.12),231213,MdB	: Added ASC, HOSTNAME
PGM=`basename $0|cut -d\. -f1`
VER="0.12"
TMP="/tmp/${PGM}.$$"
LOG="${HOME}/log/${PGM}.log"
ASC="/tmp/${PGM}.asc"
SSH="/usr/bin/ssh -n"
MAILTO="maarten.deboer@atos.net"
MAIL=""
HOSTNAME=`hostname |cut -d\. -f1`

USERLIST="${HOME}/etc/mss03_access.userlist"
DONELIST="${HOME}/data/mss03_access.donelist"
CLUSTER="nlnaf103"
VSERVER="nlnafsmss03"
NEWPWD="Welkom2MSS!"
GROUP="Administrators"
DO_NEWPWD=""

FUSERNAME="[?]*"
CHK_GROUPS=""
CREATE_USERS=""
LIST_USERS=""
DELETE_USER=""
DELETING_FROM_USERLIST=""
SHOW_SESSIONS=""


USAGE()
{
  echo "Usage: ${PGM} <options>"
  echo "  Version: ${VER}"
  echo "  options       :"
  echo "    -c          : Create user(s) based on USERLIST (${USERLIST}). When -u <username> this check of USERLIST is overruled."
  echo "    -d          : Delete users (-u NEEDED)"
  echo "    --deleting  : Deleting from diff between curr & USERLIST (${USERLIST})"
  echo "    -l          : List of users at vserver (${VSERVER})"
  echo "    -m          : Mail output (to ${MAILTO})"
  echo "    -n          : New password (-u NEEDED)"
  echo "    -g          : check Groupsnames"
  echo "    -s          : show Sessions"
  echo "    -u          : filter Username (${FUSERNAME})"
  echo "    -h|--help   : this help"
  echo "    -V          : Version"
  echo "    -x          : set -x"
}
# Check options
if [ $# -le 0 ]; then
  USAGE 
  echo "NO options selected. Please provide. Exiting."
  exit 1
fi
while [ $# -gt 0 ]
  do
  case $1 in
    -c) CREATE_USERS=1; MAIL=1 ;;
    -l) LIST_USERS=1 ;;
    -d) DELETE_USER=1 ;;
    --deleting) DELETING_FROM_USERLIST=1 ;;
    -m) MAIL=1 ;;
    -n) DO_NEWPWD=1; MAIL=1 ;;
    -u) FUSERNAME="${2}"; shift ;;
    -g) CHK_GROUPS=1 ;;
    -s) SHOW_SESSIONS=1 ;;
    -h | --help) USAGE; exit 1 ;;
    -V) echo "${PGM}: v${VER}"; exit 3 ;;
    -x)  set -x ;;
    *)  echo "Option $1 not known."; USAGE; exit 1 ;;
  esac
    shift
done

echo "`date` ${PGM} v${VER} started."|tee -a ${LOG}
echo "CHK_GROUPS=${CHK_GROUPS}"
echo "CLUSTER=${CLUSTER}"
echo "CREATE_USERS=${CREATE_USERS}"
echo "DELETE_USER=${DELETE_USER}"
echo "DELETING_FROM_USERLIST=${DELETING_FROM_USERLIST}"
echo "DONELIST=${DONELIST}"
echo "DO_NEWPWD=${DO_NEWPWD}"
echo "FUSERNAME=${FUSERNAME}"
echo "LIST_USERS=${LIST_USERS}"
echo "MAIL=${MAIL}"
echo "MAILTO=${MAILTO}"
echo "USERLIST=${USERLIST}"
echo "SHOW_SESSIONS=${SHOW_SESSIONS}"
echo "VSERVER=${VSERVER}"
sleep 1

if [ ! -f ${USERLIST} ]; then
  echo "  NO USERLIST (${USERLIST}) found. Exiting ..."|tee -a ${LOG}
  exit 3
fi
if [ ${DO_NEWPWD} ]; then
  if [ "${FUSERNAME}" = "[?]*" ]; then
    echo "  With -n (New password), a Username (-u) is NEEDED too. Exiting ..."|tee -a ${LOG}
    exit 4
  fi
fi

if [ ${DELETE_USER} ]; then
  if [ "${FUSERNAME}" = "[?]*" ]; then
    echo "  With -d (Delete user), a Username (-u) is NEEDED too. Exiting ..."|tee -a ${LOG}
    exit 5
  fi
fi

touch ${TMP}.mail ${TMP}.done

# ------------------------------------
if [ ${CREATE_USERS} ]; then
  echo "  Creating (new) users based on USERLIST (${USERLIST}) ..."|tee -a ${LOG}

# Create NEW user
# And check is not already DONE. Based on UserNAME
# When NO -u (FUSERNAME) is used
  if [ "${FUSERNAME}" = "[?]*" ]; then
    cat ${DONELIST}|cut -d\; -f1|sort -u > ${TMP}.done
  else
    echo "" > ${TMP}.done
  fi  # FUSERNAME

  cat ${USERLIST}| grep -v ^#|grep -vf ${TMP}.done|while read LINE REST
  do
    UNAME=`echo ${LINE}|awk -F\; '{print $1}'`  # UserNAME
# Filter @atos.net 
    MNAME=`echo ${LINE}|awk -F\; '{print $2}'|grep "@atos.net"`  # MailNAME
    GNAMES=`echo ${LINE}|awk -F\; '{print $3}'`  # GroupNAMES
# Check also for not empty UNAME & MNAME
    if [ "${UNAME}" != "" ] && [ "${MNAME}" != "" ]; then
# UNAME not found. So, continue
      echo "  |${UNAME}|${MNAME}|${GNAMES}|"
# 
      ANSW=`${SSH} ${CLUSTER} "vserver cifs users-and-groups local-user show -vserver ${VSERVER} -user-name ${UNAME} -field user-name"|grep "no entries matching"`
      if [ "${ANSW}" != "" ]; then
        echo "   ${UNAME} : User does not exist. Will be created. With (new)PWD."|tee -a ${LOG}

# Create (new) user & password
        NEWPWD="Welkom2MSS!`date +%H%M%S`"
        (sleep 3;echo "${NEWPWD}";sleep 2;echo "${NEWPWD}";sleep 2)|ssh ${CLUSTER} "vserver cifs users-and-groups local-user create -vserver ${VSERVER} -user-name ${UNAME}"

        ${SSH} ${CLUSTER} "vserver cifs users-and-groups local-group add-members -vserver ${VSERVER} -group ${GNAMES} -member-names ${UNAME}"

#        U_VSERVER=`echo "${VSERVER}"|tr [:lower:] [:upper:]`
#        (sleep 3;echo "${NEWPWD}";sleep 2;echo "${NEWPWD}";sleep 2) | ${SSH} ${CLUSTER} "vserver cifs users-and-groups local-user set-password -vserver ${VSERVER} -user-name ${U_VSERVER}\\${UNAME} " 
      fi  # ANSW

      ANSW=`${SSH} ${CLUSTER} "vserver cifs users-and-groups local-user show -vserver ${VSERVER} -user-name ${UNAME} -field user-name"|grep "no entries matching"`
      if [ "${ANSW}" = "" ]; then
        echo "     User ${UNAME} enabled."|tee -a ${LOG}
        echo "Hello ${UNAME}" > ${TMP}.mail
        echo "As part of the migration from MSS01 to MSS03" >> ${TMP}.mail
        echo "You get access to the NLNAFVMSS03-shares at 161.89.52.119 (via URA-FR !) with username ${UNAME}" >> ${TMP}.mail
        echo "and password will follow in seperate mail." >> ${TMP}.mail
        echo "" >> ${TMP}.mail
        echo "You can connect a drive(letter) to the share by using" >> ${TMP}.mail
        echo "- Windows-File-Explorer:" >> ${TMP}.mail
        echo "    Map Network Drive" >> ${TMP}.mail
        echo "    Drive: O:" >> ${TMP}.mail
        echo "    Folder: \\\161.89.52.119\mss_operations" >> ${TMP}.mail
        echo "- CLI command: " >> ${TMP}.mail
        echo "    net use O: \\\161.89.52.119\mss_operations /PERSISTENT:YES /USER:\\${UNAME} <password>" >> ${TMP}.mail
        echo "" >> ${TMP}.mail
        echo "" >> ${TMP}.mail
        echo "This mail is (auto-)generated at `hostname`" >> ${TMP}.mail
        echo "Questions can be send to ${MAILTO}" >> ${TMP}.mail
        echo "" >> ${TMP}.mail
        if [ ${MAIL} ]; then
          cat ${TMP}.mail | mailx -s "Created access to MSS03-shares [${PGM} v${VER}]" ${MAILTO} ${MNAME}
          echo "${NEWPWD}" | mailx -s " " ${MNAME}
          echo "${UNAME};${MNAME};${GNAMES};`date`;" >> ${DONELIST}
          echo "   ${UNAME} and NEW password mailed to ${MNAME} (and ${MAILTO})"|tee -a ${LOG}
        fi  # MAIL
      fi  # STATUS
    else
      echo "  ${UNAME} (${MNAME}) already done. Or Username | Mail-name is empty."
    fi  # CHECK
# For generating diff NEWPWD's (based on H:M:S)
    sleep 2
  done  # cat ${USERLIST}
fi  # CREATE_USERS

# ------------------------------------
if [ ${CHK_GROUPS} ]; then
# Check useradmin user -g with USERLIST
  echo "  Check GROUPS ..."|tee -a ${LOG}
  cat ${USERLIST}| grep -v ^#|grep "${FUSERNAME}"|while read LINE REST
  do
    UNAME=`echo ${LINE}|awk -F\; '{print $1}'`  # UserNAME
    MNAME=`echo ${LINE}|awk -F\; '{print $2}'|grep "@atos.net"`  # MailNAME
    GNAMES=`echo ${LINE}|awk -F\; '{print $3}'`  # GroupNAMES
    echo "  ;${UNAME};${MNAME};${GNAMES};"
    V_GROUPS=`${SSH} ${FILER} "vfiler run -q ${VFILER} useradmin user list -x ${UNAME}"|grep "Groups:"|awk -F\: '{print $2}'|sed "s/ //g"|grep "${GNAMES}"`
    echo "    ;${V_GROUPS};"
    if [ "${V_GROUPS}" = "" ]; then
# Groups in file (GNAMES) are not same as in Vfiler (V_GROUPS).
# Then modify
      echo "    Groups are NOT the same. Modifying at Vfiler ..."|tee -a ${LOG}
      ${SSH} ${FILER} "vfiler run -q ${VFILER} useradmin user modify ${UNAME} -g \"${GNAMES}\" "
      echo "${UNAME};${MNAME};${GNAMES};`date`" >> ${DONELIST}
    fi  # V_GROUPS
  done  # cat ${USERLIST}
fi  # CHK_GROUPS


# ------------------------------------
if [ ${DO_NEWPWD} ]; then
  echo "  NEW password for ${FUSERNAME} ..."|tee -a ${LOG}
  ANSW=`grep ^${FUSERNAME} ${USERLIST}`
  if [ "${ANSW}" = "" ]; then
    echo "  Username (${FUSERNAME}) NOT found in USERLIST. Exiting ..."|tee -a ${LOG}
    exit 5
  fi
#  ANSW=`${SSH} ${FILER} "vfiler run -q ${VFILER} useradmin user list ${FUSERNAME}" 2>&1 |grep "User does not exist"`
  ANSW=`${SSH} ${CLUSTER} "vserver cifs users-and-groups local-user show-member -vserver ${VSERVER} -user-name ${FUSERNAME} -field user-name,membership"|grep ${FUSERNAME}`
# Check if "User exist". So, when NOT EMPTY, user exists
  if [ "${ANSW}" != "" ]; then
#    U_VSERVER=`echo "${VSERVER}"|tr [:lower:] [:upper:]`
    MNAME=`grep ^${FUSERNAME} ${USERLIST}|awk -F\; '{print $2}'|grep "@atos.net"`  # MailNAME
    NEWPWD="Welkom2MSS-`date +%H%M%S`"
#    ${SSH} ${FILER} "vfiler run ${VFILER} useradmin user modify ${FUSERNAME} -p ${NEWPWD}"
#    (sleep 3;echo "${NEWPWD}";sleep 2;echo "${NEWPWD}";sleep 2) | ssh ${CLUSTER} "vserver cifs users-and-groups local-user set-password -vserver ${VSERVER} -user-name ${U_VSERVER}\\${FUSERNAME} " 
    (sleep 3;echo "${NEWPWD}";sleep 2;echo "${NEWPWD}";sleep 2) | ssh ${CLUSTER} "vserver cifs users-and-groups local-user set-password -vserver ${VSERVER} -user-name ${FUSERNAME}" 

    echo "Hello ${FUSERNAME}" > ${TMP}.mail
    echo "You have access to the NLNAFVMSS03-shares at 161.89.52.119 (via URA-FR !) with username ${FUSERNAME}" >> ${TMP}.mail
    echo "and password will follow in seperate mail." >> ${TMP}.mail
    echo "" >> ${TMP}.mail
    echo "You can connect a drive(letter) to the share by using" >> ${TMP}.mail
    echo "- Windows-File-Explorer:" >> ${TMP}.mail
    echo "    Map Network Drive" >> ${TMP}.mail
    echo "    Drive: O:" >> ${TMP}.mail
    echo "    Folder: \\\161.89.52.119\mss_operations" >> ${TMP}.mail
    echo "- CLI command: " >> ${TMP}.mail
    echo "    net use O: \\\161.89.52.119\mss_operations /PERSISTENT:YES /USER:\\${FUSERNAME} <password>" >> ${TMP}.mail
    echo "" >> ${TMP}.mail
    echo "" >> ${TMP}.mail
    echo "This mail is (auto-)generated at `hostname`" >> ${TMP}.mail
    echo "Questions can be send to ${MAILTO}" >> ${TMP}.mail
    echo "" >> ${TMP}.mail
    if [ ${MAIL} ]; then
      cat ${TMP}.mail | mailx -s "Re-set password of MSS03-shares [${PGM} v${VER}]" ${MAILTO} ${MNAME}
      echo "${NEWPWD}" | mailx -s " " ${MNAME}
      echo "${FUSERNAME};${MNAME};newpwd;`date`;" >> ${DONELIST}
      echo "     Password of ${FUSERNAME} re-set. Sended 2 mails to ${MNAME} ..."|tee -a ${LOG}
    fi  # MAIL

  fi  # ANSW}" = ""
fi  # DO_NEWPWD

# List users
if [ ${LIST_USERS} ]; then
  echo "  LIST_USERS" |tee -a ${LOG}
  echo "vserver cifs users-and-groups local-user show -vserver ${VSERVER} -user-name * " > ${TMP}
  ${SSH} ${CLUSTER} "vserver cifs users-and-groups local-user show -vserver ${VSERVER} -user-name * " |tee -a ${TMP}

  echo "vserver cifs users-and-groups local-user show-member -vserver ${VSERVER} -user-name * -field user-name,membership"  >> ${TMP}
  ${SSH} ${CLUSTER} "vserver cifs users-and-groups local-user show-member -vserver ${VSERVER} -user-name * -field user-name,membership" |tee -a ${TMP}

  if [ ${MAIL} ]; then
    cp ${TMP} ${ASC}
    echo "`date` ${PGM} v${VER}" |mailx -a ${ASC} -s ":${HOSTNAME}: List of users at ${VSERVER} [${PGM} v${VER}]" ${MAILTO} 
    echo "  Mailed list of users at ${VSERVER} to ${MAILTO}"|tee -a ${LOG}
  fi  # MAIL
  rm ${TMP}
fi  # LIST_USERS

# Deleting user from diff of curr & USERLIST
if [ ${DELETING_FROM_USERLIST} ]; then

  echo "  Removing users based on diff of user-list (${USERLIST}) & current at ${VSERVER}"|tee -a ${LOG}

#ssh nlnaf103 "vserver cifs users-and-groups local-user show-member -vserver nlnafsmss03 -field user-name"|grep nlnafsmss03|grep -iv administrator|awk '{print $2}'|cut -d\\ -f2
  ${SSH} ${CLUSTER} "vserver cifs users-and-groups local-user show-member -vserver ${VSERVER} -field user-name" |grep "${VSERVER}"|grep -iv administrator |awk '{print $2}' |cut -d\\ -f2 |while read USERNAME

  do
    USER_IN_LIST=`grep "${USERNAME}" ${USERLIST}|grep -v ^#|cut -d\; -f1`
    DELETING_FROM_LIST=`grep "${USERNAME}" ${USERLIST}`
    echo "  USERNAME=${USERNAME} USER_IN_LIST=${USER_IN_LIST} "

    if [ "${USER_IN_LIST}" == "" ]; then
      echo "  Deleting AND removing session of user ${DELETING_FROM_LIST} at ${VSERVER}"|tee -a ${LOG}
# node;vserver;session-id;connection-id;windows-user;
        LINE=`${SSH} ${CLUSTER} "set -showseparator \";\" ; vserver cifs session show -vserver ${VSERVER} -field windows-user,connection-id,node"| grep "${USERNAME}"`
      echo "  LINE=${LINE}"
      NODE=`echo "${LINE}"|awk -F\; '{print $1}'`
      CONNECTION_ID=`echo "${LINE}"|awk -F\; '{print $4}'`
      echo "  NODE=${NODE} CONNECTION_ID=${CONNECTION_ID}"

      if [ "${NODE}" != "" ] && [ "${CONNECTION_ID}" != "" ]; then
        ${SSH} ${CLUSTER} "vserver cifs session close -vserver ${VSERVER} -node ${NODE} -connection-id ${CONNECTION_ID}"
      fi  # NODE}" != ""

      ANSW=`${SSH} ${CLUSTER} "vserver cifs users-and-groups local-user show -vserver ${VSERVER} -user-name ${USERNAME} -field user-name"|grep ${USERNAME}`
      if [ "${ANSW}" != "" ]; then

        echo "  Deleting user ${USERNAME} at ${VSERVER}"|tee -a ${LOG}
        ${SSH} ${CLUSTER} "vserver cifs users-and-groups local-user delete -vserver ${VSERVER} -user-name ${USERNAME}"

        ${SSH} ${CLUSTER} "vserver cifs users-and-groups local-user show -vserver ${VSERVER} -user-name ${USERNAME}"
      fi  # ANSW}" != ""

    fi  # USER_IN_LIST}" == ""
  done  # USERNAME

fi  # DELETING_FROM_USERLIST

# Show session(s) -s
if [ ${SHOW_SESSIONS} ]; then
# Node;Vserver;Session ID;Connection ID;Workstation IP address;Windows User;Open Shares;Open Files;User Authenticated as;
  echo "# node;vserver;session-id;connection-id;address;windows-user;shares;files;connected-time;idle-time;user-type;" |tee ${TMP}.csv
  ${SSH} ${CLUSTER} "set -showseparator \";\" ; vserver cifs session show -vserver ${VSERVER} -field windows-user,vserver,session,connection-id,files,address,node,user-type,shares,connected-time,idle-time"|grep ${VSERVER}|tee -a ${TMP}.csv

  cat ${TMP}.csv | grep ${VSERVER}|awk -F\; '{print $6}'|cut -d\\ -f2| while read USER
  do
#    echo "  USER=${USER}"
    grep -i ${USER} ${USERLIST}|awk -F\; '{print $1,$2}'
  done

#| while read LINE
#  do
#    USERNAME=`echo ${LINE}|awk -F\; '{print $6}'|sed 's/NLNAFSMSS03//g'`
#    NAME=`grep ${USERNAME} ${USERLIST}|awk -F\; '{print $2}'`
#    echo "${LINE};${NAME};"|tee -a ${TMP}.csv
#  done

  if [ ${MAIL} ]; then
    echo "`date`" | mailx -a ${TMP}.csv -s "Show sessions at ${VSERVER} [${PGM} v${VER}]" ${MAILTO} 
    echo "  Mailed session list at ${VSERVER} to ${MAILTO}"|tee -a ${LOG}
  fi  # MAIL
  rm ${TMP}.csv
fi  # SHOW_SESSIONS


rm ${TMP}.mail ${TMP}.done
echo "`date` ${PGM} v${VER} finished."|tee -a ${LOG}
exit 0

