#!/bin/bash

#
# Licensed under GPL v2 or later at your option
# Copyright 2005 by John Tapsell <john.tapsell@kdemail.net>

PORT=$1;
SERVER=$2;
TARGET=$3;

FOLDER=$4;


if [ "$FOLDER" = "" ] ; then
  FOLDER="inbox"
fi


getmails()
{

  dcop kmail > /dev/null || {
    dcop $PORT default info "Sorry kmail is not running"
    exit
  }
  
  for f in $(dcop kmail KMailIface folderList) ; do
   MAILFOLDER=$(dcop $(dcop kmail KMailIface getFolder $f) "displayPath" | grep -i $FOLDER)
   if [ "$MAILFOLDER" != "" ] ; then
     FOUNDFOLDER=1
     MAILCOUNT=$(dcop $(dcop kmail KMailIface getFolder $f ) "unreadMessages()" )
     MAILTOTALCOUNT=$(dcop $(dcop kmail KMailIface getFolder $f ) "messages()" )
     MAILTOTALCOUNT=$(($MAILCOUNT + $MAILTOTALCOUNT))
     if [[ -z "$MAILCOUNT" ]] ; then MAILCOUNT = "0" ; fi
     if [ "$MAILCOUNT" != 0 ] ;  then
       FOUNDEMAIL=1
       echo "Email folder %B$MAILFOLDER%B has %B$MAILCOUNT%B unread messages, out of %B$MAILTOTALCOUNT%B"
     fi
   fi
  done

  if [[ -z "$FOUNDEMAIL" ]] ; then
    if [[ -z "$FOUNDFOLDER" ]] ; then
      dcop $PORT default info "No email folders were found that had a name containing '$FOLDER'"
      exit
    else
      echo "No new emails in any folders matching '$FOLDER'"
    fi
  fi

}

if [[ -z "$3" ]] ; then 
  echo "Scripts are not meant to be called from the command line."
  echo "This script should be installed to  $KDEDIR/share/apps/konversation/scripts"
  echo "Then executed with /script   from the konversation"
  echo
  echo The output is:
  getmails
  exit
fi

#LINECOUNT=$(getmails | wc -l)
#if [[ "$LINECOUNT" -gt 5 ]] ; then
#  dcop $PORT default info "There are more than 5 matches.  Cancelling to avoid flooding the server"
#  exit
#fi

getmails | head -n 3 | while read line; do dcop $PORT default say $SERVER "$TARGET" "$line"; done

