#!/usr/bin/python
'''
Created by andersk
Modified by pweaver
'''

help_msg = '''usage: create-list LIST_NAME
Your HTTPS_CERT_FILE and/or HTTPS_KEY_FILE are not set

To use create-list you will need a certificate
To set one add something like 
       export HTTPS_CERT_FILE=/mit/$USER/Private/.cert/$USER.pem
       export HTTPS_KEY_FILE=/mit/$USER/Private/.cert/$USER.pem
to your ~/.bash_environment file

You will also need to add a certificate to
/mit/$USER/Private/.cert/$USER.pem

You can get a .pem file from firefox

To get a .pem file from firefox, go to 
File -> Options -> Advanced -> Encryption -> View Certificates -> Your Certificates
Select the certificate and press backup.
Set a password.
Save the certificate somewhere in athena (it should be a .p12 file)
Run 
       openssl pkcs12 -in file.p12 -out /mit/$USER/Private/.cert/$USER.pem -nodes
Enter the password you set.

Note: you will be storing an unencrypted copy of your personal
certificate in you locker.  You can try this with out the -nodes
option and it will request a password every time you use creat-list
'''

import mechanize, sys, os
def main(args):
    try:
        os.environ['HTTPS_KEY_FILE']
        os.environ['HTTPS_CERT_FILE']
        
    except KeyError:
        print help_msg
        return
    
    if len(args) != 2:
        print "usage: create-list LIST_NAME"
        return
    (_, name) = args

    def is_post_action(action):
        return lambda f: f.method == 'POST' and f.action == action
    
    b = mechanize.Browser()
    b.add_client_certificate("https://idp.mit.edu:446",
                             os.environ['HTTPS_KEY_FILE'],
                             os.environ['HTTPS_CERT_FILE'])
    b.set_handle_robots(False)
    b.open("https://listmaker.mit.edu/lc/")

    if b.geturl().startswith('https://wayf.mit.edu/'):
        b.select_form(name='IdPList')
        b.submit()
        b.select_form(predicate=lambda f: f.action == 'https://idp.mit.edu:446/idp/Authn/Certificate')
        b.submit()
        b.select_form(predicate=lambda f: f.action == 'https://listmaker.mit.edu/Shibboleth.sso/SAML2/POST')
        b.submit()

    b.select_form(predicate=is_post_action("https://listmaker.mit.edu/lc/"))
    b["ltype"] = ["1"]
    b.submit()
    b.select_form(predicate=is_post_action("https://listmaker.mit.edu/lc/moira"))
    b["lname"] = name
    b["owner"] =  os.environ['USER']
    b.submit()
    try:
        b.select_form(predicate=is_post_action("https://listmaker.mit.edu/lc/confirm"))
        b.submit()
        print "List Created Sucessfully:"
    except mechanize.FormNotFoundError:
        print "List already Exists:"


    os.execlp("blanche", "blanche", "-i", name)


if __name__ == '__main__':
    main(sys.argv)
