import argparse
import centinel
import centinel.models
import centinel.views
import config
from OpenSSL import SSL
import os

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--adhoc', help='Use adhoc SSL key and certificate.',
                        action='store_true')
    return parser.parse_args()

if __name__ == "__main__":
    args = parse_args()
    db = centinel.db
    app = centinel.app
    db.create_all()

    Role = centinel.models.Role

    admin_role = db.session.query(Role).filter(Role.name=='admin').all()
    if len(admin_role) == 0:
        db.session.add(Role('admin'))

    client_role = db.session.query(Role).filter(Role.name=='client').all()
    if len(client_role) == 0:
        db.session.add(Role('client'))

    db.session.commit()
    if args.adhoc:
        context='adhoc'
    else:
        # default method should be TLS
        context = SSL.Context(SSL.TLSv1_METHOD)
        context.use_privatekey_file(config.ssl_key)
        context.use_certificate_file(config.ssl_cert)
        context.load_verify_locations(config.ssl_chain)

    # Also, I shouldn't have to say this, but *DO NOT COMMIT THE
    # KEY*. Under no circumstances should the key be committed
    app.run(host="0.0.0.0", port=8082, debug=True,
            ssl_context=context)

@@ -88,31 +88,340 @@
 fig%0A
-from OpenSSL import SSL
+%0Aimport sys%0Aif (2,7,9) %3E sys.version_info:%0A    print (%22WARNING: Python is older than 2.7.9, %22%0A           %22using older SSL version. This is %22%0A           %22incompatible with Werkzeug 0.10.x and %22%0A           %22will break if you use Werkzeug %3E 0.9.x%22)%0A    from OpenSSL import SSL%0A    py_279 = False%0Aelse:%0A    import ssl%0A    py_279 = True%0A
 %0Aimp
@@ -1191,16 +1191,181 @@
  be TLS%0A
+        if py_279:%0A            context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)%0A            context.load_cert_chain(config.ssl_cert, config.ssl_key)%0A        else:%0A    
         
@@ -1404,16 +1404,20 @@
 METHOD)%0A
+    
         
@@ -1460,32 +1460,36 @@
 sl_key)%0A        
+    
 context.use_cert
@@ -1518,16 +1518,17 @@
 l_cert)%0A
+%0A
         

support werkzeug 0.10.x and python 2.7.9 (backward-compatible)