#!/usr/bin/python3 # Copyright 2012 Canonical Ltd. This software is licensed under the GNU # General Public License version 3 (see the file LICENSE). from optparse import OptionParser import os import sys from rscalib import ( api_versions, UserError, ) class Usage(UserError): status = 1 def get_sso_credentials(args, stream): """Determine SSO credentials from the args and stream.""" if stream.isatty(): raise Usage('Password must be provided on stdin.') if len(args) == 0: raise Usage('Email must be provided as the first argument.') password = sys.stdin.read().rstrip('\n') username = args[0] return username, password def get_json_error(error_message): return '{ "Error": "%s" }' % error_message def main(args): """Request data for the specified SSO credentials from the server. Prints the data in JSON format on success and a JSON error in the case of a failure. Exit status summary: 0 Success 1 Usage error 2 Authentication error 3 Connection error 4 SSL Certificate verification error 100 All other errors. """ parser = OptionParser() parser.add_option('--skip-ssl-verify', action='store_true') options, args = parser.parse_args(args) verify_ssl = not options.skip_ssl_verify try: username, password = get_sso_credentials(args, sys.stdin) server_root = os.environ.get('SERVER_ROOT') api = api_versions[os.environ.get('API_VERSION', 'default')] sys.stdout.write(api.run(username, password, server_root, verify_ssl)) except UserError as e: sys.stderr.write(str(e) + '\n') sys.stdout.write(get_json_error(str(e)) + '\n') sys.exit(e.status) except Exception as e: sys.stderr.write('Exception: ' + str(type(e)) + '\n' + str(e) + '\n') sys.stdout.write(get_json_error('Contact your administrator')+ '\n') sys.exit(100) else: sys.exit(0) if __name__ == '__main__': main(sys.argv[1:])