#!/usr/bin/python -u

# Copyright 2014 Stefan Jakobs <projects AT localside.net>
#####################################################################
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
######################################################################

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)

def print_help():
	print "Usage: %s -u [username of mailbox]" % sys.argv[0]
	print ""
	print "Delete all rules for a specified user"
	print ""
	print "Required arguments:"
	print "   -u, --user          remove all filter rules from this account"
	print "   -h, --host          Host to connect with. Default: file:///var/run/zarafa"
	print "   -s, --sslkey-file   SSL key file to authenticate as admin. Default: /etc/zarafa/ssl/client.pem"
	print "   -p, --sslkey-pass   Password for the SSL key file."
	print ""
	print "optional arguments:"
	print "   --help              Show this help message and exit."

def UnixTimeToCOleDateTime(unixtime):
    days = (float(unixtime)/(60*60*24))+25569
    cOleDateTime = struct.pack("d", days)
    return cOleDateTime

def main(argv = None):
	if argv is None:
		argv = sys.argv

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

	host = 'file:///var/run/zarafa'
	sslkey_file = '/etc/zarafa/ssl/client.pem'
	sslkey_pass = None
	username = 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 == '--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)
		store = GetDefaultStore(session)
		inboxeid = store.GetReceiveFolder('IPM', 0)[0]
		inbox = store.OpenEntry(inboxeid, None, MAPI_BEST_ACCESS)
		inbox.DeleteProps([PR_RULES_TABLE])

	except MAPIError, err:
		if err.hr == MAPI_E_LOGON_FAILED:
		    print "Failed to logon. Make sure your credentials are 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)

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