# some of this is derived from the google-api-python-client, so
# use the apache license...
import urlparse
import sys
import time
import json
import base64
from OpenSSL import crypto
import gdata.gauth
import gdata.apps.client
import gdata.apps.emailsettings.client
import atom.http_core

# Fill these in!
CLIENT_ID=u"1048532457982-4asdlkfjasdlkfjaskdlfjasdlfjkluluri@developer.gserviceaccount.com"
ADMIN='admin@domain'
TARGET='user'
DOMAIN='domain'

EMAILSETTINGS_SCOPE="https://apps-apis.google.com/a/feeds/emailsettings/2.0/"
PROVISIONING_SCOPE_1="https://apps-apis.google.com/a/feeds/user/#readonly"
PROVISIONING_SCOPE_2="https://apps-apis.google.com/a/feeds/user/"
SCOPE=EMAILSETTINGS_SCOPE
#SCOPE=PROVISIONING_SCOPE_1

def _urlsafe_b64encode(raw_bytes):
  return base64.urlsafe_b64encode(raw_bytes).rstrip('=')

def _urlsafe_b64decode(b64string):
  # Guard against unicode strings, which base64 can't handle.
  b64string = b64string.encode('ascii')
  padded = b64string + '=' * (4 - len(b64string) % 4)
  return base64.urlsafe_b64decode(padded)


def make_jwt_hdr():
    jwtd={}
    jwtd['alg']='RS256'
    jwtd['typ']='JWT'
    return json.dumps(jwtd)
def make_jwt_body(scope, user=None):
    t=int(time.time())
    jwtd={}
    jwtd[u'iss']=CLIENT_ID
    if user:
        jwtd[u'prn']=user
    jwtd[u'scope']=scope
    jwtd[u'aud']=u'https://accounts.google.com/o/oauth2/token'
    jwtd[u'exp']=t+600
    jwtd[u'iat']=t
    return json.dumps(jwtd)

def get_service_token(jwt):
    granturl=atom.http_core.Uri.parse_uri("https://accounts.google.com/o/oauth2/token")
    hr=atom.http_core.HttpRequest(uri=granturl, method="POST")
    tokparams=dict()
    tokparams['assertion']=jwt
    tokparams['grant_type']='urn:ietf:params:oauth:grant-type:jwt-bearer'
    hr.add_form_inputs(tokparams)
    response=atom.http_core.HttpClient().request(hr)
    if response.status == 400:
      print "Token request rejected"
      err=json.load(response)
      print err['error']
      return None
    if response.status != 200:
      print "Bad response to token request: {0}".format(response.reason)
      return none

    resp=json.load(response)
    return resp


h=make_jwt_hdr()
b=make_jwt_body(SCOPE, user=ADMIN)

keyfile=open(CLIENT_ID+".p12")
pkey = crypto.load_pkcs12(keyfile.read(), 'notasecret').get_privatekey()

signed=_urlsafe_b64encode(h) + "." + _urlsafe_b64encode(b)
signature=crypto.sign(pkey, signed, "sha256")
sjwt=_urlsafe_b64encode(h) + "." + _urlsafe_b64encode(b)+"."+_urlsafe_b64encode(signature)

#print sjwt


token_info=get_service_token(sjwt)
if token_info is None:
  sys.exit(0)
t=gdata.gauth.OAuth2Token(None, None, None, None, access_token=token_info['access_token'])

if SCOPE == EMAILSETTINGS_SCOPE:
  eclient=gdata.apps.emailsettings.client.EmailSettingsClient(DOMAIN, auth_token=t)
  labels=eclient.RetrieveLabels(TARGET)
  print "Labels for", TARGET, ":"
  for label in labels.entry:
    print label.GetName()
else:
  client= gdata.apps.client.AppsClient(DOMAIN, auth_token=t)
  user=client.RetrieveUser(TARGET)
  print user.name, user.login, user.quota
