#!/usr/bin/env python3
import re, time, sys
from mcrcon import MCRcon

RCON_HOST = "127.0.0.1"
RCON_PORT = 25565
RCON_PASS = "nigger123"
CHECK_EVERY = 60       # sek
IDLE_LIMIT_MIN = 10

idle = 0

def players_online(text: str) -> int:
    # Otsime mustriga: "There are X of a max ..." (Mojangi vanilla väljund)
    m = re.search(r"There are (\d+) of a max", text)
    return int(m.group(1)) if m else -1

while True:
    try:
        with MCRcon(RCON_HOST, RCON_PASS, port=RCON_PORT) as mcr:
            resp = mcr.command("list")
            n = players_online(resp)
            if n == 0:
                idle += 1
            elif n > 0:
                idle = 0

            if idle >= IDLE_LIMIT_MIN:
                mcr.command('say Server idle 10 min – shutting down...')
                mcr.command('stop')
                time.sleep(10)
                idle = 0  # ohutuse mõttes
    except Exception:
        # Kui RCON pole veel üleval, oota ja proovi uuesti
        pass

    time.sleep(CHECK_EVERY)
