#!/bin/bash
# monitor-nmbd.sh
# David Mcanulty March 31, 2010
#
# Program checks that your nmbd server is still the master browser for your workgroup
# If it is not it will force a re-election and send you an email
# Requires:
#       Samba package V3.0 + (tested on 3.0.28)
#       mail program (sendmail/postfix)
#       Cron (for automation)
#
#User Configurable settings
SAMBA_TOOLS="/usr/local/samba/bin"   #The full path to your samba userspace toolkit
WORKGROUP_NAME="workgroup"           #The name of your windows network
SERVER_IP="192.168.0.1"              #The ipaddress or hostname of your samba server
EMAIL=""                             #Optional email address to send alerts to

#Gets the current workgroup
CURRENT_WORKGROUP=$(${SAMBA_TOOLS}/nmblookup -U ${SERVER_IP} -R "${WORKGROUP_NAME}#1B" |tail -n 1;exit ${PIPESTATUS[0]})
if [[ $? -ne 0 ]]; then
   echo "Error: ${SAMBA_TOOLS}/nmblookup failed to execute, exiting script, no harm done"
   exit 1
fi

#Check that the current workgroup is correct and tell us if it is not
if [[ ${CURRENT_WORKGROUP} != "${SERVER_IP} ${WORKGROUP_NAME}<1b>" ]]; then
   MESSAGE1="Current workgroup is (${CURRENT_WORKGROUP[$N]}) which does not match (${SERVER_IP} ${WORKGROUP_NAME}<1b>) forcing election!"
   MESSAGE2=$(${SAMBA_TOOLS}/smbcontrol nmbd force-election)
   if [[ -n ${EMAIL} ]]; then
      echo "${MESSAGE1} ${MESSAGE2}" |mail -s ${HOSTNAME}:${0} ${EMAIL}
   fi
   echo "${MESSAGE1} ${MESSAGE2}"
   ${SAMBA_TOOLS}/smbcontrol nmbd force-election fi