from systemd import journal
from revitalize import revitalize, parse_roomid
import sys

if len(sys.argv) != 2: # 2, because running the script looks like 'python [1]main.py [2]"..."'
    print("synapse-revitalization accepts only 1 argument")
    exit()
else:
    message = sys.argv[1]

if "Ignoring PDU for unknown room_id" in message:
    journal.send("[info] Got error message: %s" % message)
    roomid = message.rsplit(maxsplit=1)[1]
    x = revitalize(roomid, parse_roomid(roomid))
    if x == True:
        journal.send("[info] Successfully made all users rejoin {roomid} via {server}")
        journal.send("[info] {roomid} is available now")
    elif x == False:
        journal.send("ERROR! Couldn't make {roomid} available via {parse_roomid(roomid)}")

    
elif "as we're not in the room" in message:
    journal.send("[info] Got error message: %s" % message)
    roomid = message.split("'")[1]
    server = message.split("from server ")[1].split(" ")[0]
    for i in [server, parse_roomid(roomid)]:
        x = revitalize(roomid, i)
        if x == True:
            journal.send(f"[info] Successfully made all users rejoin {roomid} via {server}")
            journal.send(f"[info] {roomid} is available now")
            break
        elif x == False:
            journal.send(f"[WARNING] Couldn't make users rejoin {roomid} via {server}")
            if i == parse_roomid(roomid):
                journal.send(f"ERROR! Couldn't make {roomid} available via {server} nor {parse_roomid(roomid)}")
