import shutil
import os
import stat
import tempfile

FLY_DMRC = "/etc/X11/fly-dm/fly-dmrc"
X11_TRUSTED = "/etc/X11/trusted"

if __name__ == "__main__":
    patched1 = False
    patched2 = False

    if os.path.exists(FLY_DMRC):
        print("Check fly-dmrc..")

        with open(FLY_DMRC, "rb") as s:
            lines = s.readlines()
            tmpFlyDMRC = tempfile.NamedTemporaryFile(delete=False)
            with tmpFlyDMRC as t:
                for line in lines:
                    if (
                        line.startswith(b"ServerArgsLocal")
                        and b"+extension RECORD" not in line
                    ):
                        print("Add RECORD extendion")
                        line = line.strip() + b" +extension RECORD" + b"\n"
                        patched1 = True
                    t.write(line)
                    t.flush()

    if os.path.exists(X11_TRUSTED):
        with open(X11_TRUSTED, "rb") as s:
            print("Check trusted..")
            content = s.read()
            tmpTrusted = tempfile.NamedTemporaryFile(delete=False)
            with tmpTrusted as t:
                if b"/usr/bin/rudesktop(KBD_R)" not in content:
                    content = content.strip() + b"\n/usr/bin/rudesktop(KBD_R)\n"
                    t.write(content)
                    t.flush()
                    print("Add RuDesktop to trusted")
                    patched2 = True

    if patched1:
        shutil.move(FLY_DMRC, FLY_DMRC + ".bak")
        shutil.move(tmpFlyDMRC.name, FLY_DMRC)

    if patched2:
        shutil.move(X11_TRUSTED, X11_TRUSTED + ".bak")
        shutil.move(tmpTrusted.name, X11_TRUSTED)

    if os.path.exists(FLY_DMRC):
        os.chmod(FLY_DMRC, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)
    if os.path.exists(X11_TRUSTED):
        os.chmod(X11_TRUSTED, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)

    if patched1 or patched2:
        print("Display manager config updated. Please reboot workstation.")
