#!/usr/bin/python3 -I
"""Asistente con privilegios de Firemold (se ejecuta con pkexec).

Operaciones permitidas, y nada más:
  install profile|local NOMBRE ORIGEN  → /etc/firejail/NOMBRE.profile|.local
  link NOMBRE                          → /usr/local/bin/NOMBRE -> /usr/bin/firejail
  unlink NOMBRE                        → quita ese enlace (solo si apunta a firejail)
  remove profile|local NOMBRE          → borra /etc/firejail/NOMBRE.profile|.local (solo si es de Firemold)

Nunca sobrescribe un perfil oficial: un .profile existente solo se reemplaza
si lleva la marca de Firemold («Generado por» o «Editado con», en español o inglés),
y solo se borran los que la llevan (en el .local va dentro de «Ajustes locales para X — …»).
"""
import os
import re
import shutil
import stat
import sys
import tempfile

NAME_RE = re.compile(r"^[A-Za-z0-9_+][A-Za-z0-9._+-]{0,127}$")
CFG = "/etc/firejail"
BIN = "/usr/local/bin"
MAX_SIZE = 256 * 1024
TAGS = ("# Generado por Firemold", "# Generated by Firemold", "# Editado con Firemold", "# Edited with Firemold")


def die(msg, code=1):
    print(msg, file=sys.stderr)
    sys.exit(code)


def firejail_path():
    for p in ("/usr/bin/firejail", "/usr/local/bin/firejail"):
        if os.path.isfile(p) and not os.path.islink(p):
            return p
    die("firejail no está instalado")


def check_name(name):
    if not NAME_RE.fullmatch(name) or name in (".", ".."):
        die(f"nombre no válido: {name!r}")


def read_source(path, uid):
    try:
        fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
    except OSError as e:
        die(f"no se puede abrir el origen: {e}")
    st = os.fstat(fd)
    if not stat.S_ISREG(st.st_mode):
        die("el origen no es un archivo normal")
    if uid is not None and st.st_uid != uid:
        die("el origen no pertenece al usuario que lo solicita")
    if st.st_size > MAX_SIZE:
        die("el origen es demasiado grande")
    with os.fdopen(fd, "rb") as fh:
        data = fh.read(MAX_SIZE + 1)
    if b"\x00" in data:
        die("el origen contiene datos binarios")
    try:
        data.decode("utf-8")
    except UnicodeDecodeError:
        die("el origen no es texto UTF-8")
    return data


def install(kind, name, source, uid):
    if kind not in ("profile", "local"):
        die("tipo no válido")
    check_name(name)
    data = read_source(source, uid)
    target = os.path.join(CFG, f"{name}.{kind}")
    if kind == "profile" and os.path.exists(target):
        with open(target, "r", encoding="utf-8", errors="replace") as fh:
            lines = {ln.strip() for ln in fh.read().splitlines()}
            if not lines & set(TAGS):
                die(f"{target} es un perfil oficial: se usará un .local en su lugar")
    fd, tmp = tempfile.mkstemp(dir=CFG, prefix=".firemold-")
    try:
        with os.fdopen(fd, "wb") as fh:
            fh.write(data)
        os.chmod(tmp, 0o644)
        os.replace(tmp, target)
    finally:
        if os.path.exists(tmp):
            os.unlink(tmp)
    print(target)


def has_mark(path):
    """La marca de Firemold en un comentario (sola en el .profile, tras «Ajustes locales…» en el .local)."""
    phrases = tuple(t[2:] for t in TAGS)
    with open(path, "r", encoding="utf-8", errors="replace") as fh:
        return any(ln.startswith("#") and any(p in ln for p in phrases) for ln in fh.read(MAX_SIZE).splitlines())


def remove(kind, name):
    if kind not in ("profile", "local"):
        die("tipo no válido")
    check_name(name)
    target = os.path.join(CFG, f"{name}.{kind}")
    if os.path.islink(target) or not os.path.isfile(target):
        die(f"{target} no existe o no es un archivo normal")
    if not has_mark(target):
        die(f"{target} no lo ha creado Firemold: no se borra")
    os.unlink(target)
    print(target)


def link(name):
    check_name(name)
    fj = firejail_path()
    if not any(os.path.exists(os.path.join(d, name)) for d in ("/usr/bin", "/bin", "/usr/games")):
        die(f"no existe un programa del sistema llamado {name}")
    target = os.path.join(BIN, name)
    if os.path.lexists(target):
        if os.path.islink(target) and os.path.realpath(target) == os.path.realpath(fj):
            print(target)
            return
        die(f"{target} ya existe y no es un enlace a firejail")
    os.makedirs(BIN, exist_ok=True)
    os.symlink(fj, target)
    print(target)


def unlink(name):
    check_name(name)
    target = os.path.join(BIN, name)
    if os.path.islink(target) and os.path.basename(os.path.realpath(target)) == "firejail":
        os.unlink(target)
        print(target)
    else:
        die(f"{target} no es un enlace a firejail")


def main(argv):
    if os.geteuid() != 0:
        die("debe ejecutarse con pkexec", 2)
    uid = os.environ.get("PKEXEC_UID")
    uid = int(uid) if uid and uid.isdigit() else None
    if len(argv) == 4 and argv[0] == "install":
        install(argv[1], argv[2], argv[3], uid)
    elif len(argv) == 2 and argv[0] == "link":
        link(argv[1])
    elif len(argv) == 2 and argv[0] == "unlink":
        unlink(argv[1])
    elif len(argv) == 3 and argv[0] == "remove":
        remove(argv[1], argv[2])
    else:
        die(__doc__, 2)


if __name__ == "__main__":
    main(sys.argv[1:])
