#!/bin/sh
# Benachrichtet über neue Mails per winpopup
# Als Parameter wird der Rechner erwartet an
# den die Nachricht geschickt werden soll.
#
# Autor Thorsten Gunkel <tgunkel@gmx.de>
#
# --- 24.03.2002 Thorsten Gunkel <tgunkel@gmx.de> ---
# * /bin/sh=!/bin/bash
# --- No older changelog available ---

do_send()
{
 echo " *** New mail(s) on `hostname` for $user *** "
 echo

 if [ $x_mailbox -gt 0 ]; then
  grep "$mailbox" -e ^From:'\|'^Subject:
 fi

 if [ $x_maildir -gt 0 ]; then
  find "$maildir" -type f -exec grep '{}' -e ^From:'\|'^Subject: ';'
 fi

 echo
 echo " *** "
}

# Get optional hostname as message destination
host="$1"

# Default is localhost
if [ "X$host" = "X" ]; then
 host=localhost
fi

# Whom may I serve (I don't differ user and real_user any more)?
real_user="`whoami`"; user="$real_user"

# I reject root (and should reject more?)
if [ \( "$user" = root \) -o \( "$real_user" = root \) ]; then
 echo "Hi root,"
 echo "put something like this in your crontab:"
 echo "0 * * * * USERNAME THISSCRIPT DESTHOST 1>/dev/null"
 echo "and replace the capital letter words with whatever you need."
 echo "Note that user \"root\" is rejected!"
 exit 1
fi

echo "Check mail for: $user"
echo "Inform winpopup at: $host"

# where to serach for new mails
mailbox="/var/spool/mail/$user"
maildir="/home/$user/Maildir/New"

# mails in mailbox? ?FIXME?: Differ old and new mails
if [ -s "$mailbox" ]; then x_mailbox=1; else x_mailbox=0; fi

# new mail in maildir?
x_maildir=`find "$maildir" -type f 2>/dev/null | wc -l`

# did we find something?
 if [ \( $x_maildir -gt 0 \) -o \( $x_mailbox -gt 0 \) ]; then x=1; else x=0; fi

# If yes continue
if [ $x -gt 0 ]; then
 # Is destination host availible? ?FIXME? telnet / smbcommand port vs ping
 ping -qc 1 "$host" > /dev/null 2>&1
 jemand_da=$?
 if [ $jemand_da -eq 0 ]; then
  echo "Connected."

  do_send | smbclient -M "$host" 2>&1 >/dev/null

 else
  echo "Connection failed."
  exit $jemand_da;
 fi
fi
