#!/bin/sh

# This script assists in running multiple instances of fetchmail; such as is 
# required for running IMAP IDLE on more than one server concurrently. It 
# searches for subdirectories of $HOME/etc/fetchmail, and considers each as a
# directory to run fetcmail from. The config should be stored as "fetchmailrc"
# within this directory; without the leading ".". Networks can be started and
# stopped independently, or all together. See the --help option for detail on
# invoking the script.

FETCHMAILROOT=~/etc/fetchmail

cd "$FETCHMAILROOT"

ACTION="start"

while [ "$1" ]; do
  ARG="$1"
  case "$ARG" in
    -k|--kill) ACTION="kill" ;;
    -l|--list) ACTION="list" ;;
    -h|--help) ACTION="help" ;;
    --) shift; break ;;
    -*) echo "Unknown argument $ARG"; exit 1 ;;
    *) break ;;
  esac
  shift
done

WHICH="$1"

function find_fetchmail_homes() {
  # Find directories immediately off FETCHMAILROOT
  for ENT in *; do
    if [ -d "$ENT" ]; then
      echo "$ENT"
    fi
  done
}

case "$ACTION" in
  help)
    echo "$0: [options..] [network]"
    echo "Options are:"
    echo " -h, --help:    This text"
    echo " -k, --kill:    Stop network"
    echo " -l, --list:    List networks, running or not"
    echo "If a network is named, the action applies only to that network"
    exit 0
    ;;
  start)
    for ENT in `find_fetchmail_homes`; do
      if [ "$WHICH" -a "$ENT" != "$WHICH" ]; then continue; fi
      export FETCHMAILHOME=`pwd`/$ENT
      
      fetchmail $EXTRAOPTS $ENT
    done
    ;;
  list)
    for ENT in `find_fetchmail_homes`; do
      if [ "$WHICH" -a "$ENT" != "$WHICH" ]; then continue; fi
      export FETCHMAILHOME=`pwd`/$ENT
      FETCHMAILPID=$FETCHMAILHOME/fetchmail.pid
      
      echo "Config $ENT in $FETCHMAILHOME"
      if [ -r $FETCHMAILPID ]; then
	echo "  running as PID `cat $FETCHMAILPID`"
      else
	echo "  not running"
      fi
    done
    ;;
  kill)
    for ENT in `find_fetchmail_homes`; do
      if [ "$WHICH" -a "$ENT" != "$WHICH" ]; then continue; fi
      export FETCHMAILHOME=`pwd`/$ENT
      FETCHMAILPID=$FETCHMAILHOME/fetchmail.pid
      
      echo "Config $ENT in $FETCHMAILHOME"
      if [ -r $FETCHMAILPID ]; then
	fetchmail -q $ENT
      fi
    done
    ;;
  *)
    echo "Ahh; unknown action $ACTION"
    exit 1
    ;;
esac
