#!/usr/bin/python
from urllib import urlencode
import httplib2
import re
import sys
import os
import os.path
try:
    # For c speedups
    from simplejson import loads, dumps
except ImportError:
    from json import loads, dumps

client_id = sys.argv[1];
http = httplib2.Http(disable_ssl_certificate_validation=True)
http.follow_redirects = False
url = "https://localhost/request?client_id=" + client_id \
      + "&response_type=code&redirect_uri=/cmd"
headers, content = http.request(url, "GET")
code = re.search('code=(\d+)',content)
code = code.group(1)
url = "https://localhost//token?grant_type=authorization_code&client_id=" \
      + client_id + "&redirect_uri=/cmd&code=" + code
headers, content = http.request(url, "GET")
accesstoken = re.search('access_token":(\d+)',content)
accesstoken = accesstoken.group(1);
refreshtoken = re.search('refresh_token":(\d+)',content)
refreshtoken = refreshtoken.group(1);
PATH='./credentials.csv'
if os.path.isfile(PATH) and os.access(PATH, os.R_OK):
    print PATH+" exists and is readable"
else:
    print PATH+" is missing or is not readable"
with open("./credentials.csv") as f:
    for line in f:
        items=line.split(',');
data = {'cmd': [['aws_configure',items[1],items[2]],
                ['cmd','hostname'],
                ['cwd','/bin'],
                ['cmd_raw','export HELLO=hello'],
                ['cmd','echo $HELLO'],
                ['cmd','pwd']]}
bearer  = "Bearer "+accesstoken
headers = {'Content-Type': 'application/json','Authorization': bearer }
url     = 'https://localhost/cmd'
headers, content = http.request(url, "POST", body=dumps(data), headers=headers)
print content

