#!/usr/bin/env python3
#
# Someone's Mattermost scripts.
#  Copyright (c) 2016-2020 by Someone <someone@somenet.org> (aka. Jan Vales <jan@jvales.net>)
#  published under MIT-License
#
# consider running as cronjob
#   0 * * * *  (cd /home/someone/mattermost/management; python3 -u account_handling.py)
#

import mattermost
import re
import config
import time
import pprint
import sys

from inspect import cleandoc

import config


def confine_guest(user):
    #print("confine_guest()")
    global mm, all_team_ids

    for team_id in config.guest_team_ids:
        mm.add_user_to_team(team_id, user["id"])

    user_pub_chans = set()
    for team_id in all_team_ids:
        try:
            user_pub_chans = user_pub_chans.union({c["id"] for c in mm.get_channels_for_user(user["id"], team_id, exc=True) if c["type"]=="O"})
        except mattermost.ApiException as e:
            pass
            
    to_add = config.guest_channels - user_pub_chans
    #pprint.pprint(to_add)
    for chan_id in to_add:
        mm.add_user_to_channel(chan_id, user["id"])
        
    to_kick = user_pub_chans - config.guest_channels
    #pprint.pprint(to_kick)
    for chan_id in to_kick:
        mm.remove_user_from_channel(chan_id, user["id"])


cnt = 0
cnt_g = 0
cnt_u = 0
cnt_u2g = 0
cnt_g2u = 0
TS_START = time.time()
rex = re.compile(config.allowed_emails_regex)

mm = mattermost.MMApi(config.mm_api_url)
mm.login(config.mm_user, config.mm_user_pw)
print("* ["+("%07.6g"%round(time.time() - TS_START, 5))+"] login")

all_team_ids = [t["id"] for t in mm.get_teams()]
print("* ["+("%07.6g"%round(time.time() - TS_START, 5))+"] list all team_ids")

for user in mm.get_users():
    cnt += 1
    if "system_user" in user["roles"]:
        cnt_u += 1

        if not rex.match(user["email"]):
            cnt_u2g += 1
            u2g = user

            #print("demote")
            #pprint.pprint(mm.demote_a_user(user["id"]))
            mm.demote_a_user(user["id"])
            confine_guest(user)

            c = mm.create_dm_channel_with(user["id"])
            mm.create_post(c["id"], cleandoc("""
                ### ``Confirm your student email to get full access to Mattermost``
                As previously announced your account has been converted to a [guest account](https://docs.mattermost.com/deployment/guest-accounts.html), which means you will be restricted to three channels:
                * Beratung
                * Guest-Talk
                * Aufnahmeverfahren

                Mattermost has a dedicated channel for every course, to access them you need to go to your Account Settings and change your email to ``eXXXXXXXX@student.tuwien.ac.at`` and then click on the link in the confirmation email. You will then get full access within an hour.

                Sorry for the inconvenience, we hope to see you soon!
                If something seems off, contact my master @someone by mentioning him in the ``Guest-Talk`` channel.
                """))

        else:
            pass
            # todo: inform of guest status and to change email


    elif "system_guest" in user["roles"]:
        cnt_g += 1
        if rex.match(user["email"]):
            cnt_g2u += 1
            g2u = user

            # convert account to user.
            #print("promote")
            #pprint.pprint(mm.promote_a_guest(user["id"]))
            mm.promote_a_guest(user["id"])
            c = mm.create_dm_channel_with(user["id"])
            mm.create_post(c["id"], cleandoc("""
                ### ``Your account has been converted to a FULL-USER account!``
                You are now able to use all the features mattermost and this instance has to offer!
                """))
        else:
            # re-confine guests
            confine_guest(user)
            
    else:
        print("weird user")
        pprint.pprint(user)
        
    print("* ["+("%07.6g"%round(time.time() - TS_START, 5))+"] cnt:", cnt, " cnt_u:", cnt_u, " cnt_g:", cnt_g, " cnt_u2g:", cnt_u2g, " cnt_g2u:", cnt_g2u)

mm.logout()
