#!/usr/bin/env nix-shell
#!nix-shell -i python3 -p "python3.withPackages (ps: [  ])"
# vim: set filetype=python :

"""
launch some program, and redirect its output to appear as if it
were *input* by the user, on some TTY.
this allows piping into programs which expect to be running directly on a TTY (like `login`, or `sway`).

based on: <https://unix.stackexchange.com/a/345572>
"""
import fcntl
import subprocess
import sys
import termios

def write_to(text: bytes, dest_path: str) -> None:
    with open(dest_path, "w") as f:
        for byte in text:
            fcntl.ioctl(f.fileno(), termios.TIOCSTI, bytes([byte]))

def main(argv: list[str]):
    dest_path = argv[1]
    cmd = argv[2:]

    cmd_output = subprocess.check_output(cmd)
    write_to(cmd_output, dest_path)

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