Command-line tool for obtaining authorization and credentials from a user.

    This tool uses the OAuth 2.0 Authorization Code grant as described
    in section 1.3.1 of RFC6749:
    https://tools.ietf.org/html/rfc6749#section-1.3.1

    This tool is intended for assist developers in obtaining credentials
    for testing applications where it may not be possible or easy to run a
    complete OAuth 2.0 authorization flow, especially in the case of code
    samples or embedded devices without input / display capabilities.

    This is not intended for production use where a combination of
    companion and on-device applications should complete the OAuth 2.0
    authorization flow to get authorization from the users.

def main(client_secrets, scope, save, credentials, headless):
    """Command-line tool for obtaining authorization and credentials from a user.

    This tool uses the OAuth 2.0 Authorization Code grant as described
    in section 1.3.1 of RFC6749:
    https://tools.ietf.org/html/rfc6749#section-1.3.1

    This tool is intended for assist developers in obtaining credentials
    for testing applications where it may not be possible or easy to run a
    complete OAuth 2.0 authorization flow, especially in the case of code
    samples or embedded devices without input / display capabilities.

    This is not intended for production use where a combination of
    companion and on-device applications should complete the OAuth 2.0
    authorization flow to get authorization from the users.

    """

    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets,
        scopes=scope
    )

    if not headless:
        creds = flow.run_local_server()
    else:
        creds = flow.run_console()

    creds_data = {
        'token': creds.token,
        'refresh_token': creds.refresh_token,
        'token_uri': creds.token_uri,
        'client_id': creds.client_id,
        'client_secret': creds.client_secret,
        'scopes': creds.scopes
    }

    if save:
        del creds_data['token']

        config_path = os.path.dirname(credentials)
        if config_path and not os.path.isdir(config_path):
            os.makedirs(config_path)

        with open(credentials, 'w') as outfile:
            json.dump(creds_data, outfile)

        click.echo('credentials saved: %s' % credentials)

    else:
        click.echo(json.dumps(creds_data))