#!/usr/bin/python3
"""Korak nakon pravila (tossos-policyd): Thunderbird ide na stalno ime poste organizacije.

Racuni koje je carobnjak slozio prije TossOS-a 0.9.9 imaju adresu posluzitelja u meshu
(100.64.x.y). Kad paket pravila donese ime poste, ova skripta u user.js i logins.json
korisnika zamijeni tu adresu imenom, pa racun radi i nakon selidbe poste na server.
Lozinka se ne dira (u logins.json je sifrirana, mijenja se samo hostname), a Thunderbird
koji je otvoren preuzima novo ime kod sljedeceg pokretanja.
"""
import glob, json, os, re, sys

MESH = re.compile(r"^100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.\d{1,3}\.\d{1,3}$")
POSTAVKE = re.compile(r'^user_pref\("(mail\.server\.server1\.hostname|mail\.smtpserver\.smtp1\.hostname|'
                      r'mail\.outgoingserver\.smtp1\.hostname)", "([^"]+)"\);$')


def prepisi(profil, ime):
    uj = os.path.join(profil, "user.js")
    redovi, stare = [], set()
    for red in open(uj).read().splitlines():
        m = POSTAVKE.match(red)
        if m and MESH.match(m.group(2)):
            stare.add(m.group(2))
            red = f'user_pref("{m.group(1)}", "{ime}");'
        redovi.append(red)
    if not stare:
        return False
    st = os.stat(uj)
    with open(uj + ".novo", "w") as f:
        f.write("\n".join(redovi) + "\n")
    os.chown(uj + ".novo", st.st_uid, st.st_gid)
    os.replace(uj + ".novo", uj)
    lj = os.path.join(profil, "logins.json")
    if os.path.exists(lj):
        d = json.load(open(lj))
        for l in d.get("logins", []):
            for polje in ("hostname", "httpRealm"):
                v = l.get(polje) or ""
                for s in stare:
                    for shema in ("imap", "smtp"):
                        if v == f"{shema}://{s}":
                            l[polje] = f"{shema}://{ime}"
        st = os.stat(lj)
        fd = os.open(lj + ".novo", os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
        with os.fdopen(fd, "w") as f:
            json.dump(d, f)
        os.chown(lj + ".novo", st.st_uid, st.st_gid)
        os.replace(lj + ".novo", lj)
    return True


def main():
    posta = json.loads(os.environ.get("TOSSOS_USLUGE") or "{}").get("posta") or {}
    ime = posta.get("ime", "")
    if not re.match(r"^posta\.[a-z0-9.-]+\.internal$", ime):
        return
    # Clanovi su korisnici Kanidma, koje NSS ne nabraja, pa se traze kucne mape.
    for profil in sorted(glob.glob("/home/*/.thunderbird/tossos.default")):
        if os.stat(profil).st_uid < 1000 or not os.path.isfile(os.path.join(profil, "user.js")):
            continue
        try:
            if prepisi(profil, ime):
                print(f"Thunderbird {profil.split('/')[2]}: posta na {ime}")
        except (OSError, ValueError) as e:
            print(f"Thunderbird {profil.split('/')[2]}: {e}", file=sys.stderr)


if __name__ == "__main__":
    main()
