

# <20260802.1529.57>

# -*- coding: utf-8 -*-, mode: python -*--

# This code was generated by "Google AI mode" with guidance and testing by
# Tom Turkey.
# Modified to support optional "-noecho" command-line argument.

import os, pty, sys, select, errno, termios

def clean_spawn(args, noecho=False):
    # Manually open the PTY to get explicit control over both ends
    master_fd, slave_fd = pty.openpty()
    
    pid = os.fork()
    
    if pid == 0: # Child process
        os.close(master_fd) # Child doesn't need the master
        os.login_tty(slave_fd) # Connect this process to the PTY slave
        
        if noecho:
            try:
                # Get current terminal attributes
                mode = termios.tcgetattr(sys.stdin.fileno())
                # Turn off ECHO
                mode[3] = mode[3] & ~termios.ECHO
                # Apply the new settings immediately
                termios.tcsetattr(sys.stdin.fileno(), termios.TCSANOW, mode)
            except termios.error:
                pass

        try:
            os.execvp(args[0], args)
        except FileNotFoundError:
            os._exit(1)
    else:
        # PARENT FIX: Close the slave end immediately. 
        # Now only the child holds the slave end. When it dies, fd will throw EIO.
        os.close(slave_fd)
        
        watch_list = [master_fd, sys.stdin.fileno()]
        exit_status = 0  # Track the child's exit status
        
        try:
            while watch_list:
                # 1.0s timeout allows checking if child (pid) is a zombie
                rfds, _, _ = select.select(watch_list, [], [], 1.0)
                
                # Non-blocking check for child exit
                pid_gone, status = os.waitpid(pid, os.WNOHANG)
                if pid_gone != 0:
                    # Capture the actual exit code if the child terminated
                    if os.WIFEXITED(status):
                        exit_status = os.WEXITSTATUS(status)
                    return exit_status
                for r in rfds:
                    if r == master_fd:
                        try:
                            data = os.read(master_fd, 1024)
                            if data:
                                try:
                                    os.write(sys.stdout.fileno(), data)
                                    sys.stdout.flush()
                                except (BrokenPipeError, OSError) as e:
                                    if isinstance(e, BrokenPipeError) or\
                                       getattr(e, 'errno', 0) == errno.EPIPE:
                                        return exit_status
                        except OSError as e:
                            if e.errno == errno.EIO:
                                return exit_status
                            raise
                    
                    elif r == sys.stdin.fileno():
                        data = os.read(r, 1024)
                        if data:
                            os.write(master_fd, data)
                        else:
                            # Tcl closed its output pipe. Send Ctrl+D (EOF) once.
                            try:
                                os.write(master_fd, b'\x04') # Send Ctrl+D
                            except OSError:
                                pass
                            # Stop watching stdin so select() blocks correctly
                            watch_list.remove(r)
        finally:
            os.close(master_fd)
            try:
                # Final cleanup to prevent zombies and grab status if we haven't
                _, status = os.waitpid(pid, 0)
                if os.WIFEXITED(status):
                    exit_status = os.WEXITSTATUS(status)
            except OSError:
                pass
            
        return exit_status

def main():
    args = sys.argv[1:]
    noecho = False
    
    # Check for and strip out the -noecho flag anywhere in the arguments
    if "-noecho" in args:
        noecho = True
        args = [arg for arg in args if arg != "-noecho"]

    if not args:
        print(f"Usage: {sys.argv[0]} [-noecho] <command> [args...]", file=sys.stderr)
        sys.exit(1)
        
    final_status = clean_spawn(args, noecho=noecho)
    sys.exit(final_status)

if __name__ == "__main__":
    main()

