#!/usr/bin/env python
"""Retrieve an Adobe ID from a Short Client Token."""
# This script doesn't import any code from circulation or core. It
# tests an integration based on HTTP.

import requests
import base64
import re
import sys

base_url = "https://circulation.librarysimplified.org"

if len(sys.argv) != 2:
    print "Usage: %s [Short Client Token]" % sys.argv[0]
    sys.exit()

client_token = sys.argv[1]

if client_token.count("|") != 3:
    print "%r doesn't look like a Short Client Token. It should look like this:\n[library code]|[timestamp]|[patron identifier]|[signature]" % client_token
    sys.exit()

# If the user input the entire <drm:clientToken> tag, strip off the
# tag and leave the token.
if client_token.startswith("<drm:clientToken>"):
    client_token = client_token[len("<drm:clientToken>"):]
if client_token.endswith("</drm:clientToken>"):
    client_token = client_token[:-len("</drm:clientToken>")]
    
library, timestamp, identifier, signature = client_token.split("|")
print "This Short Client Token looks good."
print " Library code: %s" % library
print " Timestamp: %s" % timestamp
print " Patron identifier: %s" % identifier
print " Signature: %s" % signature
print

username, password = client_token.rsplit("|", 1)
print "Dividing Short Client Token into two parts to use in the SignIn API."
print " Username: %s" % username
print " Password: %s" % password
print

print "Using SignIn to log in via username and password."
login_request = """<signInRequest method="standard" xmlns="http://ns.adobe.com/adept">
<username>%s</username>
<password>%s</password>
</signInRequest>""" % (username, password)
url = base_url + "/AdobeAuth/SignIn"
response = requests.post(url, data=login_request)
print url
print login_request
print "=>"
print response.content
print

m = re.compile("<user>([^<]+)</user>").search(response.content)
if m:
    print "Adobe ID for this patron is %s" % m.groups()[0]
else:
    print "Sorry, I couldn't turn this Short Client Token into an Adobe ID."
