#!/bin/bash

# Usage: mutt2gmailcsv [.muttrc] > gmail.csv

# This script tries to find and export your mutt aliases to a CSV file that can
# be imported into your gmail address book. In other words, it's a mutt alias
# importer for gmail.
# 
# It makes some attempt to find aliases in included files, but if you have a
# weird mutt setup you'll need to tell this script where your file containing
# aliases is.
# 
# This is basically a hack. It ignores aliases with commas (eg ones with more
# than one email address in them) as I don't know what to do with those at the
# moment. I assume bash, GNU sed, etc
# 
# TODO, just noticed that I'm assuming
# 	alias foo Foo Bar <foo@mailinator.com>
# but mutt manual has
# 	alias foo foo@mailinator.com (Foo Bar)
# Too lazy to fix this now.
# 
# Iain Murray <i.murray+muttgmail / gmaildotcom> July 2004

if [ $# = 1 ] ; then
	muttrc=$1
else
	muttrc=$HOME/.muttrc
fi

if [ \! -e $muttrc ] ; then
	echo Can not find mutt setup file $muttrc 1>&2
	exit 1
fi

echo nickname, name, email
# This doesn't recurse below one level of .muttrc source statements. If this
# causes failure simply provide the file containing your aliases on the command
# line.
for a in "$muttrc" `sed -e 's/#.*//' -e '/\(source\|alias_file\)/!d' \
    -e 's/^[ 	]*\(source\|set[ 	]*alias_file\)[= 	][ 	]*\(.*\)$/\2/' "$muttrc"` ; do
    sed -e /,/d -e 's/#.*//' \
        -e '/^[ 	]*alias[ 	]*.*/!d' \
        -e 's/[ 	]*alias[ 	][ 	]*\([^ 	]*\)[ 	][ 	]*\([^<]*[^ 	<]\)[ 	][ 	]*<*\([^ 	<]*@[^ 	>]*\)>*/\1, \2, \3/' \
	-e 's/[ 	]*alias[ 	][ 	]*\([^ 	]*\)[ 	][ 	]*<*\([^ 	<]*@[^ 	>]*\)>*/\1, , \2/' \
        "${a/\~/$HOME}"
done | sort -u

