#!/usr/bin/env python
import jppy
import getopt
import mx.DateTime
import sys
import cStringIO
import string
import rfc822


# Example procmail recipe

#:0
#* < 4000
#* ^TO_palmmemo@nickpiper.co.uk
#| /usr/local/bin/jp_add_memo --rfc822

#:0
#* < 32500
#* ^TO_palmmemo@nickpiper.co.uk
#| /usr/local/bin/jp_add_memo --rfc822 --32


def usage():
    print """
jp_add_memo [options] [memo_contents]
if memo_contents are not specified on the command line, memo is read from stdin.
  --rfc822     Treat data as an 822 message, and only store parts as the memo.
  --category n Specify category number to store memo under
"""

try:
    opts, args = getopt.getopt(sys.argv[1:], "hmpc", ["help","rfc822","32","category"])
except getopt.GetoptError:
    print "Arguments could not be understood..."
    usage()
    sys.exit(2)
mail = None
cat = 0
for o, a in opts:
    if o in ("-h", "--help"):
        usage()
        sys.exit()
    if o in ("-m", "--rfc822"):
        mail = 1
    if o in ("-c", "--category"):
        cat = int(a)


env = jppy.environment.Environment()

memo = env.memoList.new()

if mail:
    if not args:
        msg = rfc822.Message(sys.stdin)
    else:
        msg = rfc822.Message(cStringIO.StringIO(string.join(args)))
    memo['text'] = "%s\nDate: %s\n\n%s" % (
        msg.getheader('Subject'),
        msg.getheader('Date'),        
        msg.fp.read())
else:
    if not args:
        memo['text'] = sys.stdin.read()
    else:
        memo['text'] = string.join(args)

memo.category = cat
print "Adding %s" % memo
env.memoList.save(memo)

