"""
Log into nersc machine and get newt session id
"""

import argparse
import getpass
import requests

nersc_url = 'https://newt.nersc.gov/newt'


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Login to obtain newt session id')
    parser.add_argument('--machine', '-m', default='cori', help='cori or edison')
    parser.add_argument('--user', '-u', default='johnt', help='user name')

    args = parser.parse_args()
    # print(args)

    print('Username: {}'.format(args.user))
    print('Machine:  {}'.format(args.machine))

    password = getpass.getpass(prompt='Password: ')

    # One time password for MFA
    otp = input('Enter one time password (for MFA)')
    # print('ready')

    credentials = {
        'username': args.user,
        'password': password + str(otp)
    }

    url = '{}/login/'.format(nersc_url)
    r = requests.post(url, data=credentials)
    r.raise_for_status()

    js = r.json()
    if js.get('auth'):
        session_id = js.get('newt_sessionid')
        print('newt_sessionid: {}'.format(session_id))
    else:
        print('NOT authenticated, response:')
        print(r.text)






