#!/usr/local/bin/python2.7

import os
import time
import locale
import sys
import getopt
import binascii
import __builtin__

try:
    import MAPI
    from MAPI.Util import *
    from MAPI.Time import *
    from MAPI.Struct import *
except ImportError, e:
    print "Not all modules can be loaded. The following modules are required:"
    print "- MAPI (Zarafa)"
    print ""
    print e
    sys.exit(1) 

PR_EC_OUTOFOFFICE                   = PROP_TAG(PT_BOOLEAN,    PR_EC_BASE+0x60)
PR_EC_OUTOFOFFICE_MSG               = PROP_TAG(PT_TSTRING,    PR_EC_BASE+0x61)
PR_EC_OUTOFOFFICE_SUBJECT           = PROP_TAG(PT_TSTRING,    PR_EC_BASE+0x62)

MODE_ENABLE = 1
MODE_DISABLE = 2
MODE_UPDATE_ONLY = 3

def print_help():
    print "Usage: %s -u [username of mailbox]" % sys.argv[0]
    print ""
    print "Manage out of office messages of users"
    print ""
    print "Required arguments:"
    print "   -u, --user          user to set out of office message for"
    print ""
    print "optional arguments:"
    print "   -m, --mode          0 to disable out of office (default), 1 to enable"
    print "   -t, --subject       specify the subject to be set in oof message"
    print "   -n, --message       text file containing body of out of office message"
    print "   -h, --host          Host to connect with. Default: file:///var/run/zarafa"
    print "   -s, --sslkey-file   SSL key file to authenticate as admin."
    print "   -p, --sslkey-pass   Password for the SSL key file."
    print "   --help              Show this help message and exit."
    print ""
    print ""
    print "Example:"
    print " Enable out of office message of mailbox user1 with subject 'test' and body from file /tmp/oof-message"
    print "  $ %s --user user1 --mode 1 --subject 'test' --message /tmp/oof-message" % sys.argv[0]
    print ""
    print " Enable out of office message of mailbox user1 with subject 'test' and body from file /tmp/oof-message in a multi-server-environment"
    print "  $ %s --user user1 --mode 1 --subject 'test' --message /tmp/oof-message --host https://127.0.0.1:237/zarafa --sslkey-file /etc/zarafa/ssl/client.pem --sslkey-pass password" % sys.argv[0]
    print ""
    print " Disable out of office message of mailbox user1 in a multi-server-environment"
    print "  $ %s --user user1 --mode 0 --sslkey-file /etc/zarafa/ssl/client.pem --host https://127.0.0.1:237/zarafa --sslkey-pass password" % sys.argv[0]

def PrintSubject(subject):
    if subject.ulPropTag == PR_EC_OUTOFOFFICE_SUBJECT:
        print "Current subject: '%s'" % subject.Value
    else:
        print "No subject set"
    
def main(argv = None):
    if argv is None:
        argv = sys.argv

    try:
        opts, args = getopt.gnu_getopt(argv, 'h:s:p:u:m:t:n', ['host=', 'sslkey-file=', 'sslkey-pass=', 'user=', 'mode=', 'subject=', 'message=', 'help'])
    except getopt.GetoptError, err:
        # print help information and exit:
        print str(err)
	print ""
        print_help()
        return 1

    # defaults
    host = os.getenv('ZARAFA_SOCKET','file:///var/run/zarafa')
    sslkey_file = None
    sslkey_pass = None
    mode = '-'
    username = None 
    subject = None
    
    for o, a in opts:
        if o in ('-h', '--host'):
	    host = a
        elif o in ('-s', '--sslkey-file'):
            sslkey_file = a
        elif o in ('-p', '--sslkey-pass'):
            sslkey_pass = a
        elif o in ('-u', '--user'):
            username = a
        elif o in ('-m', '--mode'):
		if a == '-':
			mode = MODE_UPDATE_ONLY
		elif a == '1':
			enabled = True
			mode = MODE_ENABLE
		else:
			enabled = False
			mode = MODE_DISABLE
        elif o in ('-t', '--subject'):
            subject = a
        elif o in ('-n', '--message'):
            message = a
        elif o == '--help':
            print_help()
            return 0
        else:
            assert False, ("unhandled option '%s'" % o)

    if not username:
	print "No username specified."
	print ""
	print_help()
	sys.exit(1)

    try:
        session = OpenECSession(username, '', host, sslkey_file = sslkey_file, sslkey_pass = sslkey_pass)
    except MAPIError, err:
        if err.hr == MAPI_E_LOGON_FAILED:
            print "Failed to logon. Make sure your SSL certificate is correct."
        elif err.hr == MAPI_E_NETWORK_ERROR:
            print "Unable to connect to server. Make sure you specified the correct server."
        else:
            print "Unexpected error occurred. hr=0x%08x" % err.hr
	sys.exit(1)


    st = GetDefaultStore(session)
    props = st.GetProps([PR_EC_OUTOFOFFICE, PR_EC_OUTOFOFFICE_SUBJECT], 0)
    if props[0].ulPropTag == PR_EC_OUTOFOFFICE:
        if props[0].Value == True and mode != MODE_DISABLE:
	    print "Not changing subject and message for user %s which already has out of office message enbled." % username
	    PrintSubject(props[1])
	    sys.exit(0)
        elif props[0].Value == False and mode == MODE_DISABLE:
	    print "Out of office is already disabled for user %s" % username
	    sys.exit(0)

    if mode != MODE_UPDATE_ONLY:
        st.SetProps([SPropValue(PR_EC_OUTOFOFFICE, enabled)])

    if mode != MODE_DISABLE:
	if subject:
		st.SetProps([SPropValue(PR_EC_OUTOFOFFICE_SUBJECT, subject)])
        if message:
	    try:
		f = open(message, 'rt')
	    except IOError:
		print "The specified file %s does not exist - Please specify a valid message file." % message
		sys.exit(1)

	    msg = f.read()
	    st.SetProps([SPropValue(PR_EC_OUTOFOFFICE_MSG, msg)])
	    f.close()

        if mode == MODE_ENABLE:
	    print "Out of office enabled for user %s" % username
        elif subject != u'':
	    print "Out of office updated for user %s" % username
        else:
	    print "Out of office not updated for user %s" % username

        props = st.GetProps([PR_EC_OUTOFOFFICE_SUBJECT], 0)
        PrintSubject(props[0])
    else:
        print "Out of office disabled for user %s" % username

if __name__ == '__main__':
    locale.setlocale(locale.LC_ALL, '')
    sys.exit(main())
