#!/usr/bin/env python3
# tmuxsave - save and restore a tmux session layout (best effort)
# Usage: tmuxsave save SESSION [FILE] | tmuxsave restore FILE [--dry-run] | tmuxsave list
import argparse, os, shutil, subprocess, sys

def save_dir():
    return os.path.expanduser("~/.tmux-sessions")

def run(args):
    return subprocess.run(args, capture_output=True, text=True)

def do_save(session, path):
    if not shutil.which("tmux"):
        print("tmuxsave: tmux is not installed.", file=sys.stderr); return 1
    r = run(["tmux", "has-session", "-t", session])
    if r.returncode != 0:
        print("tmuxsave: no such tmux session: %s" % session, file=sys.stderr); return 1
    r = run(["tmux", "list-windows", "-t", session, "-F",
             "#{window_index}\t#{window_name}\t#{window_layout}"])
    if r.returncode != 0:
        print("tmuxsave: cannot list windows: %s" % r.stderr.strip(), file=sys.stderr); return 1
    lines = ["# tmuxsave layout for session %s" % session]
    for line in r.stdout.splitlines():
        idx, name, _layout = line.split("\t")
        lines.append("WINDOW %s %s" % (idx, name))
        p = run(["tmux", "list-panes", "-t", "%s:%s" % (session, idx), "-F",
                 "#{pane_index}\t#{pane_current_path}\t#{pane_current_command}"])
        for pline in p.stdout.splitlines():
            pidx, ppath, pcmd = pline.split("\t")
            lines.append("PANE %s %s %s %s" % (idx, pidx, ppath, pcmd))
    os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
    with open(path, "w") as f:
        f.write("\n".join(lines) + "\n")
    print("tmuxsave: saved session %s (%d windows) to %s" %
          (session, len([l for l in lines if l.startswith("WINDOW")]), path))
    return 0

def parse_layout(path):
    session = None
    windows = []  # (idx, name, [(pidx, path, cmd)])
    cur = None
    for line in open(path):
        line = line.rstrip("\n")
        if line.startswith("# tmuxsave layout for session "):
            session = line.split("session ", 1)[1].strip()
        elif line.startswith("WINDOW "):
            _w, idx, name = line.split(" ", 2)
            cur = (idx, name, [])
            windows.append(cur)
        elif line.startswith("PANE ") and cur is not None:
            parts = line.split(" ", 4)
            if len(parts) == 5:
                cur[2].append((parts[2], parts[3], parts[4]))
    return session, windows

def restore_cmds(session, windows):
    cmds = [["tmux", "new-session", "-d", "-s", session]]
    first = True
    for idx, name, panes in windows:
        if first:
            cmds.append(["tmux", "rename-window", "-t", "%s:0" % session, name])
            first = False
        else:
            cmds.append(["tmux", "new-window", "-t", session, "-n", name])
        for j, (_pidx, ppath, _cmd) in enumerate(panes):
            if j > 0:
                cmds.append(["tmux", "split-window", "-t", "%s:%s" % (session, idx),
                             "-c", ppath])
            else:
                cmds.append(["tmux", "send-keys", "-t", "%s:%s" % (session, idx),
                             "cd %s" % ppath, "Enter"])
    return cmds

def do_restore(path, dry_run):
    if not os.path.exists(path):
        print("tmuxsave: no such layout file: %s" % path, file=sys.stderr); return 1
    session, windows = parse_layout(path)
    if not windows:
        print("tmuxsave: no windows in %s" % path, file=sys.stderr); return 1
    session = session or os.path.splitext(os.path.basename(path))[0]
    cmds = restore_cmds(session, windows)
    if dry_run:
        print("tmuxsave: dry-run restore of session %s from %s:" % (session, path))
        for c in cmds:
            print("  " + " ".join(c))
        return 0
    if not shutil.which("tmux"):
        print("tmuxsave: tmux is not installed.", file=sys.stderr); return 1
    for c in cmds:
        r = run(c)
        if r.returncode != 0:
            print("tmuxsave: failed: %s: %s" % (" ".join(c), r.stderr.strip()), file=sys.stderr)
            return 1
    print("tmuxsave: restored session %s (%d windows)." % (session, len(windows)))
    return 0

def selftest():
    import tempfile
    with tempfile.TemporaryDirectory() as d:
        layout = os.path.join(d, "demo.txt")
        with open(layout, "w") as f:
            f.write("# tmuxsave layout for session demo\n")
            f.write("WINDOW 0 editor\nPANE 0 0 /root bash\nPANE 0 1 /tmp bash\n")
            f.write("WINDOW 1 logs\nPANE 1 0 /var/log bash\n")
        out = subprocess.run([sys.executable, os.path.abspath(__file__), "restore", layout,
                              "--dry-run"], capture_output=True, text=True)
        assert out.returncode == 0, out.stderr
        assert "new-session" in out.stdout and "editor" in out.stdout and "logs" in out.stdout
        assert "split-window" in out.stdout
        print("tmuxsave selftest: PASS")
    return 0

def main():
    ap = argparse.ArgumentParser(prog="tmuxsave",
        description="Save and restore a tmux session layout (best effort).")
    sub = ap.add_subparsers(dest="cmd")
    ps = sub.add_parser("save", help="save a session layout to a file")
    ps.add_argument("session", help="tmux session name")
    ps.add_argument("file", nargs="?", help="layout file (default ~/.tmux-sessions/<session>.txt)")
    pr = sub.add_parser("restore", help="restore a session from a layout file")
    pr.add_argument("file", help="layout file")
    pr.add_argument("--dry-run", action="store_true", help="print the tmux commands instead of running them")
    sub.add_parser("list", help="list saved layouts")
    ap.add_argument("--selftest", action="store_true", help="run built-in self-test and exit")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    if a.cmd == "save":
        path = a.file or os.path.join(save_dir(), a.session + ".txt")
        return do_save(a.session, path)
    if a.cmd == "restore":
        return do_restore(a.file, a.dry_run)
    if a.cmd == "list":
        d = save_dir()
        files = sorted(os.listdir(d)) if os.path.isdir(d) else []
        if not files:
            print("tmuxsave: no saved layouts in %s" % d); return 0
        for f in files:
            print("  %s" % f)
        return 0
    ap.print_help()
    return 2

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