#!/usr/bin/env python
#
#
import sys
import os
import string
import urllib2
import base64
import ssl

try:
    DEBUG=os.environ['DEBUG']
except KeyError:
    DEBUG=0

try:
    AUTHOK=os.environ['AUTHOK']
except KeyError:
    AUTHOK=False

if AUTHOK:
    sys.exit()

# read username and password from stdin
userline=sys.stdin.readline()
try:
    username,password=string.split(userline,' ',2)
    password=password.rstrip(os.linesep)
except ValueError:
    username=userline.rstrip(os.linesep)
    password=sys.stdin.readline()
    password=password.rstrip(os.linesep)

if DEBUG:
    print "[activesync-auth] Username:%s" % username
    print "[activesync-auth] Password:%s" % password

try:
    base_url=os.environ['activesync_url']
    if DEBUG:
        print "[activesync-auth] Base url: %s" % base_url
except KeyError, e:
    if DEBUG:
        print "[activesync-auth] Base url not given. Set to http://localhost."
    base_url='http://localhost'

url=base_url+'/Microsoft-Server-ActiveSync?User='+username+'&DeviceId=BennoMailArchive&DeviceType=BennoAuth&Cmd=Ping'
request=urllib2.Request(url)
base64string=base64.b64encode('%s:%s' % (username, password))
request.add_header("Authorization", "Basic %s" % base64string)

try:
    result=urllib2.urlopen(request)
    print "AUTH OK"
    print "ROLE USER"
    print "USERID %s" % username
    if DEBUG:
        print result.read()
except urllib2.HTTPError as e:
    print "ERROR ERR_AUTH"
    if DEBUG:
        print "ERRORMSG: %s" % e
except ssl.CertificateError as e:
    print "ERROR ERR_AUTH"
    if DEBUG:
        print "ERRORMSG SSL error: %s" % e

