#!/bin/bash
#
# Extract certain mails from a mbox file.
#
# 
#
# Using Scenario and Example:
# When using Thunderbird or Evolution, you need to copy all the email which  mail from
# *@example.org to another mail folder, you can use command like this:
#       xmailfromBox /path/to/your/Sent /path/you/want/use/example.sent 'example.org' 1
# Another example: you have multiple email accounts, all mails stored in the same Inbox,
# you now want to separate them. Firstly, try to identify some pattern of mails from
# the same mail server, say, the 4th line contains '(HELO example.org)', then:
#       xmailfromBox /path/to/your/Inbox example.inbox '(HELO example.org)' 4
#
# History:
# Jan 7 2011 twinhorse
# - first edition
#
USAGE=false
if [ -z "$1" ]; then
	USAGE=true
elif [ -z "$2" ]; then
	USAGE=true
elif [ -z "$3" ]; then
	USAGE=true
fi
if $USAGE ; then
	echo "Usage: $0  <input mbox file>  <output mbox file>  <containing pattern>  [line number]"
	exit
fi
if [ -z "$4" ]; then
	LINENUM=1;
else
	LINENUM=$4;
fi
START=1
STOP=-1
rm -f $2
while read line ; do
	START=$( expr $STOP + 1 )
	STOP=$( expr $line - 1 )
	echo "An email from line $START to line $STOP"
	EMAILCONTENT=$(sed -n "$START,$STOP p" $1)
	echo "$EMAILCONTENT"  | awk "NR==$LINENUM"
	if [ ! -z "$(echo "$EMAILCONTENT" | awk "NR==$LINENUM" | grep "$3" )" ]; then
		echo "$EMAILCONTENT" >> $2
		echo '' >> $2
	fi
done < <(perl -ne '{/^From / and print $.,"\n"}' $1)
	START=$( expr $STOP + 1 )
	STOP=$( wc -l "$1" | cut -d ' ' -f 2 )
	echo "An email from line $START to line $STOP"
	EMAILCONTENT=$(sed -n "$START,$STOP p" $1)
	echo "$EMAILCONTENT"  | awk "NR==$LINENUM"
	if [ ! -z "$(echo "$EMAILCONTENT" | awk "NR==$LINENUM" | grep "$3" )" ]; then
		echo "$EMAILCONTENT" >> $2
		echo '' >> $2
	fi

