#!/usr/bin/env python3
"""Hardlink every file created below <watch-dir>/<prefix>*, so it survives its creator deleting it.

Usage: eac-catch [seconds] [prefix] [watch-dir]
Defaults: 1800, EasyAntiCheat_EOS_Setup., /tmp. Copies land in <watch-dir>/.eac-catch/ (a hardlink
must stay on the same filesystem). Run it as the user who starts the game.
"""
import ctypes
import os
import select
import struct
import sys
import time

secs = float(sys.argv[1]) if len(sys.argv) > 1 else 1800
prefix = sys.argv[2] if len(sys.argv) > 2 else "EasyAntiCheat_EOS_Setup."
top = sys.argv[3] if len(sys.argv) > 3 else "/tmp"
stash = os.path.join(top, ".eac-catch")
IN_CLOSE_WRITE, IN_MOVED_TO, IN_CREATE, IN_ISDIR = 0x8, 0x80, 0x100, 0x40000000

libc = ctypes.CDLL(None, use_errno=True)
fd = libc.inotify_init1(os.O_CLOEXEC)
dirs = {}


def log(*args):
    print(time.strftime("%T"), *args, flush=True)


def grab(path):
    dst = os.path.join(stash, os.path.relpath(path, top))
    os.makedirs(os.path.dirname(dst), exist_ok=True)
    try:
        os.link(path, dst)
        log("caught", path)
    except FileExistsError:
        pass
    except OSError as e:
        log("missed", path, e.strerror)


def watch(path):
    wd = libc.inotify_add_watch(fd, path.encode(), IN_CREATE | IN_MOVED_TO | IN_CLOSE_WRITE)
    if wd < 0:
        log("cannot watch", path, os.strerror(ctypes.get_errno()))
        return
    dirs[wd] = path
    if path == top:
        return
    log("watching", path)
    # Entries created before the watch existed.
    for entry in os.scandir(path):
        watch(entry.path) if entry.is_dir(follow_symlinks=False) else grab(entry.path)


watch(top)
deadline = time.monotonic() + secs
while (left := deadline - time.monotonic()) > 0:
    if not select.select([fd], [], [], left)[0]:
        break
    buf, i = os.read(fd, 65536), 0
    while i < len(buf):
        wd, mask, _, n = struct.unpack_from("iIII", buf, i)
        name = buf[i + 16:i + 16 + n].rstrip(b"\0").decode(errors="replace")
        i += 16 + n
        parent = dirs.get(wd)
        if parent is None or not name:
            continue
        path = os.path.join(parent, name)
        if parent == top and not name.startswith(prefix):
            continue
        try:
            watch(path) if mask & IN_ISDIR else grab(path)
        except FileNotFoundError:
            log("gone before it was caught", path)
