#!/usr/bin/env python
# moshdetach -- kill detached Mosh servers
import argparse
from nullroute.system.utmp import enum_utmp, UtType
import re
import subprocess

def hup(tty):
    res = subprocess.call(["pkill", "-HUP", "-t", tty])
    if res != 0:
        # Probably an entry that was just hup'd recently and its mosh-server is
        # still in the process of exiting.
        print("could not hup line %s (likely a stale entry)" % tty)

parser = argparse.ArgumentParser()
parser.description = "Hang up all terminals belonging to detached Mosh servers."
parser.add_argument("-n", "--dry-run",
                        action="store_true",
                        help="only print ttys that would be hung up")
parser.add_argument("-q", "--quiet",
                        action="store_true",
                        help="print nothing")
args = parser.parse_args()

found = 0
for ent in enum_utmp():
    if ent["type"] == UtType.USER_PROCESS:
        if re.match(r"^mosh \[\d+\]$", ent["host"]):
            if args.dry_run or not args.quiet:
                print("Detaching %(line)s (%(host)s)" % ent)
                found += 1
            if not args.dry_run:
                hup(ent["line"])
if not found:
    if not args.quiet:
        exit("moshdetach: no detached Mosh servers found in utmp")
