#!/usr/bin/python3
# Fernwartung: eine Shell in einer PTY für den Edge-Agenten (docs/edge-backend-protokoll.md, „Fernwartung“).
#
# Läuft je Verbindung als root (edge-agent-shell@.service, Socket auf stdin/stdout) und startet die Login-Shell als
# Benutzer SHELL_USER (Standard: UID 1000), nie als root. Rahmen in beide Richtungen: 1 Byte Art, 4 Byte Länge
# (Big Endian), Inhalt.
#   vom Agenten:  d Eingabe · r Fenstergröße "<cols> <rows>"
#   zum Agenten:  d Ausgabe · x Ende, Inhalt = Exitcode als Text
# Schließt der Agent den Socket, bekommt die Shell SIGHUP. Höchstdauer: SHELL_MAX_SEC (Standard 1800).
#
# Alles nicht blockierend mit Warteschlangen: Eine Eingabe, die die Shell gerade nicht liest (z. B. großes Einfügen in
# ein Programm ohne stdin), darf den Helfer nicht festhalten – sonst merkt er weder das Schließen noch die Höchstdauer.
# Gegendruck: Ist die Ausgabe zum Agenten voll, liest der Helfer die PTY nicht weiter; die Shell wartet dann.

import errno, fcntl, os, pwd, select, signal, struct, sys, termios, time

MAX_SEC = int(os.environ.get('SHELL_MAX_SEC', '1800'))
OUT_HIGH = 256 * 1024        # Ausgabe zum Agenten: darüber PTY nicht mehr lesen
IN_MAX = 1024 * 1024         # Eingabe an die Shell: darüber Verbindung beenden (Missbrauch)
FRAME_MAX = 1 << 20


def account():
    name = os.environ.get('SHELL_USER', '').strip()
    try:
        return pwd.getpwnam(name) if name else pwd.getpwuid(1000)
    except KeyError:
        sys.stderr.write('edge-agent-shell: Benutzer %s fehlt\n' % (name or 'mit UID 1000'))
        sys.exit(1)


def set_size(fd, cols, rows):
    fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack('HHHH', rows, cols, 0, 0))


def frame(kind, payload):
    return kind + struct.pack('>I', len(payload)) + payload


def nonblocking(fd):
    fcntl.fcntl(fd, fcntl.F_SETFL, fcntl.fcntl(fd, fcntl.F_GETFL) | os.O_NONBLOCK)


def write_some(fd, buf):
    """Schreibt so viel wie geht; gibt den Rest zurück."""
    try:
        n = os.write(fd, buf)
        return buf[n:]
    except OSError as e:
        if e.errno in (errno.EAGAIN, errno.EWOULDBLOCK):
            return buf
        raise


def main():
    pw = account()
    if pw.pw_uid == 0 or pw.pw_gid == 0:
        sys.stderr.write('edge-agent-shell: keine Shell als root oder Gruppe root\n')
        sys.exit(1)
    sock = 0  # Socket auf stdin und stdout (StandardInput=socket)
    pid, master = os.forkpty()
    if pid == 0:
        os.setgid(pw.pw_gid)
        os.initgroups(pw.pw_name, pw.pw_gid)
        os.setuid(pw.pw_uid)
        shell = pw.pw_shell if pw.pw_shell and os.path.exists(pw.pw_shell) and not pw.pw_shell.endswith('nologin') else '/bin/bash'
        env = {
            'HOME': pw.pw_dir, 'USER': pw.pw_name, 'LOGNAME': pw.pw_name, 'SHELL': shell,
            'TERM': 'xterm-256color', 'LANG': os.environ.get('LANG', 'C.UTF-8'),
            'PATH': '/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin',
            'ALTITUDE_REMOTE_SHELL': '1',
        }
        try:
            os.chdir(pw.pw_dir)
        except OSError:
            os.chdir('/')
        os.execve(shell, ['-' + os.path.basename(shell)], env)

    set_size(master, 80, 24)
    nonblocking(master)
    nonblocking(sock)
    started = time.monotonic()
    inbuf = b''      # vom Agenten, noch nicht als Rahmen gelesen
    to_pty = b''     # Eingabe für die Shell
    to_sock = b''    # Ausgabe für den Agenten
    shell_done = False
    while True:
        if time.monotonic() - started > MAX_SEC:
            break
        rlist = [sock]
        if not shell_done and len(to_sock) < OUT_HIGH:
            rlist.append(master)
        wlist = []
        if to_pty and not shell_done:
            wlist.append(master)
        if to_sock:
            wlist.append(sock)
        if shell_done and not to_sock:
            break
        try:
            r, w, _ = select.select(rlist, wlist, [], 1.0)
        except InterruptedError:
            continue
        if master in r:
            try:
                out = os.read(master, 65536)
            except OSError as e:
                out = b'' if e.errno != errno.EAGAIN else None
            if out == b'':
                shell_done = True      # Shell beendet (EIO/EOF); Rest noch senden
            elif out:
                to_sock += frame(b'd', out)
        if sock in r:
            try:
                chunk = os.read(sock, 65536)
            except OSError as e:
                chunk = b'' if e.errno != errno.EAGAIN else None
            if chunk == b'':
                break                  # Agent hat geschlossen
            if chunk:
                inbuf += chunk
                bad = False
                while len(inbuf) >= 5:
                    kind, length = inbuf[:1], struct.unpack('>I', inbuf[1:5])[0]
                    if length > FRAME_MAX:
                        bad = True
                        break
                    if len(inbuf) < 5 + length:
                        break
                    payload, inbuf = inbuf[5:5 + length], inbuf[5 + length:]
                    if kind == b'd':
                        to_pty += payload
                    elif kind == b'r':
                        try:
                            cols, rows = (int(x) for x in payload.decode().split())
                            set_size(master, max(10, min(cols, 500)), max(4, min(rows, 200)))
                            os.kill(pid, signal.SIGWINCH)
                        except (ValueError, OSError):
                            pass
                if bad or len(to_pty) > IN_MAX:
                    break
        if master in w and to_pty:
            try:
                to_pty = write_some(master, to_pty)
            except OSError:
                shell_done = True
                to_pty = b''
        if sock in w and to_sock:
            try:
                to_sock = write_some(sock, to_sock)
            except OSError:
                break

    # Ende: Shell beenden (SIGHUP wie beim Auflegen), Exitcode melden
    try:
        os.kill(pid, signal.SIGHUP)
    except OSError:
        pass
    code = 0
    for _ in range(30):
        done, status = os.waitpid(pid, os.WNOHANG)
        if done:
            code = os.waitstatus_to_exitcode(status)
            break
        time.sleep(0.1)
    else:
        try:
            os.kill(pid, signal.SIGKILL)
            os.waitpid(pid, 0)
        except OSError:
            pass
        code = -9
    # Letzte Ausgabe und Exitcode, wenn der Agent noch liest (höchstens 2 s)
    rest = (to_sock if len(to_sock) < OUT_HIGH else b'') + frame(b'x', str(code).encode())
    end = time.monotonic() + 2
    try:
        while rest and time.monotonic() < end:
            select.select([], [sock], [], 0.2)
            rest = write_some(sock, rest)
    except OSError:
        pass


if __name__ == '__main__':
    main()
