#!/bin/tcsh

### START SETTINGS

set user="user"
set passwd="password"
set host="host.domain.com"
set ssl=1
set awk="/usr/bin/gawk"

# SSL encrypted (requires stunnel version 3!)
set connecttool="/usr/sbin/stunnel -c -D 3 -r ${host}:993"    

# SSL encrypted with openssl (slower than stunnel) 
#set connecttool="/usr/bin/openssl s_client -quiet -connect ${host}:993"    

# No encryption
#set connecttool="/bin/nc -q 120 ${host} 143"

### END SETTINGS

unset printexitvalue


fping -q $host || exit

set mboxes=(inbox \
	    mail/foo \
	    mail/bar )

echo ""

( echo "checkimap.sh LOGIN ${user} ${passwd}" ; \
  echo $mboxes | tr -t " " "\n" | xargs -i"{}" echo "+{{}} EXAMINE {}" ; \
  echo "checkimap.sh LOGOUT" ) | \
   $connecttool | \
   tr -t "\r\n" " %" | \
   sed -e 's/EXAMINE completed/\n/g' | \
   sed -n -e '/{.*}/s/^.*\* \([0-9]*\) EXISTS.*\* \([0-9]*\) RECENT.*{\(.*\)}.*$/\1 \2 \3/p' | \
   $awk '{ print $1 " messages (" $1-$2 " seen) for '$user' at '$host' (folder " $3 ")"}' 
