#!/usr/bin/python3 -I
"""Privileged, fixed-purpose writer; called through an auth_admin polkit action."""
import fcntl
import os
from pathlib import Path
import sys
import tempfile

CHOICES = (1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 3.0)

def updated(text, value):
    out = []
    for line in text.splitlines(keepends=True):
        if line.split("=", 1)[0].strip() != "UI_SCALE":
            out.append(line)
    text = "".join(out)
    return text + ("\n" if text and not text.endswith("\n") else "") + f"UI_SCALE={value:g}\n"

def main():
    if os.geteuid() != 0:
        sys.exit("Administrator authentication is required.")
    try:
        value = float(sys.argv[1]) if len(sys.argv) == 2 else None
    except ValueError:
        value = None
    if value not in CHOICES:
        sys.exit("Choose one of the supported display sizes.")
    path = Path("/etc/ekklesia-classroom/device.conf")
    with open("/run/lock/ekklesia-display-settings.lock", "w") as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        info = path.stat()
        text = updated(path.read_text(), value)
        fd, name = tempfile.mkstemp(prefix=".device-scale-", dir=path.parent)
        try:
            with os.fdopen(fd, "w") as handle:
                os.fchown(handle.fileno(), info.st_uid, info.st_gid)
                os.fchmod(handle.fileno(), info.st_mode & 0o777)
                handle.write(text)
                handle.flush()
                os.fsync(handle.fileno())
            os.replace(name, path)
        finally:
            if os.path.exists(name):
                os.unlink(name)
    print("Display size saved for this room.")

if __name__ == "__main__":
    main()
