#!/usr/bin/env python

# Copyright 2018 Johannes Oertel
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

# Sets the displayname in a matrix room

if __name__ == "__main__":
    import argparse, getpass, json, requests, sys

    parser = argparse.ArgumentParser(description='Set the displayname in a matrix room.')
    parser.add_argument('room_id', help='The matrix room ID')
    parser.add_argument('displayname', help='The displayname to set')
    parser.add_argument('mxid', help='The matrix user ID (MXID)')
    parser.add_argument('password', nargs='?', help='The password for the MXID')

    args = parser.parse_args()

    if not args.password:
        args.password = getpass.getpass()

    [username, server] = args.mxid.split(':')
    username = username[1:]
    base_url = "https://{}/_matrix/client/r0".format(server)

    login = requests.post("{}/login".format(base_url),
                          json = { 'type': 'm.login.password',
                                   'user': username,
                                   'password': args.password })
    if login.status_code != 200:
        print("Login on matrix server {} failed!".format(server))
        print(login.text)
        sys.exit(1)

    access_token = login.json()['access_token']
    params = { 'access_token': access_token }

    room_member = requests.put("{}/rooms/{}/state/m.room.member/{}"
                               .format(base_url, args.room_id, args.mxid),
                               params = params,
                               json = { 'membership': 'join',
                                        'displayname': args.displayname})

    if room_member.status_code != 200:
        print("Failed to update displayname in room {}!".format(args.room_id))
        print(room_member.text)

    logout = requests.post("{}/logout".format(base_url), params = params)
