"""
This script launches a container with mattermost preview. It is useful for developing
things without needing a remote mattermost instance.
"""

import shutil
from subprocess import CalledProcessError, check_call
from time import sleep

PODMAN_BIN = shutil.which("docker") or shutil.which("podman")
CONTAINER_NAME = "mattermost-preview"


def podman(*args: str):
    return check_call([PODMAN_BIN, *args])


def mmctl(*args):
    return podman("exec", CONTAINER_NAME, "mmctl", "--local", *args)


def create_user(username, teams, password="test12345"):
    mmctl(
        "user",
        "create",
        "--email",
        f"{username}@slidge.im",
        "--username",
        username,
        "--password",
        password,
    )
    for team in teams:
        mmctl("team", "users", "add", team, username)


def launch_mm_preview():
    podman(
        "run",
        "--rm",
        "--name",
        CONTAINER_NAME,
        "-d",
        "--publish",
        "127.0.0.1:8065:8065",
        "--env",
        "MM_SERVICESETTINGS_ENABLELOCALMODE=1",
        "docker.io/mattermost/mattermost-preview",
    )
    for _ in range(60):
        try:
            mmctl("user", "list")
        except CalledProcessError:
            print("instance is still not up, waiting a bit…")
            sleep(0.5)
        else:
            return
    raise RuntimeError


launch_mm_preview()
for i in range(1, 4):
    mmctl("team", "create", f"--name=team{i}", f"--display-name=Team {i}")
create_user("user1", ["team1"])
create_user("user2", ["team1", "team2"])
create_user("user3", ["team2", "team3"])

print("Open http://localhost:8065")
input("Press enter to quit")
podman("stop", CONTAINER_NAME)
