Spaces:
Sleeping

File size: 2,406 Bytes
69d639b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
from __future__ import annotations

import argparse
import os
import plistlib
import shutil
import subprocess
from pathlib import Path


def main() -> None:
    parser = argparse.ArgumentParser(description="Install local launchd schedule for FTI tracker.")
    parser.add_argument("--hour", type=int, default=8)
    parser.add_argument("--minute", type=int, default=0)
    parser.add_argument("--label", default="com.fti.opportunity-tracker")
    parser.add_argument("--load", action="store_true", help="Run launchctl bootstrap after writing plist.")
    args = parser.parse_args()

    repo_root = Path(__file__).resolve().parents[1]
    logs_dir = repo_root / "logs"
    logs_dir.mkdir(exist_ok=True)

    uv_path = shutil.which("uv")
    if not uv_path:
        raise SystemExit("uv was not found on PATH.")
    plist = {
        "Label": args.label,
        "WorkingDirectory": str(repo_root),
        "ProgramArguments": [
            uv_path,
            "run",
            "fti-tracker",
            "crawl",
            "--send-alerts",
        ],
        "StartCalendarInterval": {"Hour": args.hour, "Minute": args.minute},
        "StandardOutPath": str(logs_dir / "launchd.out.log"),
        "StandardErrorPath": str(logs_dir / "launchd.err.log"),
        "EnvironmentVariables": {
            "PATH": _launchd_path(uv_path),
        },
    }

    launch_agents = Path.home() / "Library" / "LaunchAgents"
    launch_agents.mkdir(parents=True, exist_ok=True)
    plist_path = launch_agents / f"{args.label}.plist"
    with plist_path.open("wb") as fh:
        plistlib.dump(plist, fh, sort_keys=False)

    print(f"Wrote {plist_path}")
    if args.load:
        subprocess.run(["launchctl", "bootout", f"gui/{os.getuid()}", str(plist_path)], check=False)
        subprocess.run(["launchctl", "bootstrap", f"gui/{os.getuid()}", str(plist_path)], check=True)
        subprocess.run(["launchctl", "enable", f"gui/{os.getuid()}/{args.label}"], check=True)
        print(f"Loaded {args.label}")
    else:
        print("To load it now, rerun with --load or use launchctl bootstrap manually.")


def _launchd_path(uv_path: str) -> str:
    paths = [
        str(Path(uv_path).parent),
        "/opt/homebrew/bin",
        "/usr/local/bin",
        "/usr/bin",
        "/bin",
        "/usr/sbin",
        "/sbin",
    ]
    return ":".join(dict.fromkeys(paths))


if __name__ == "__main__":
    main()