diff --git a/mac-receiver/bin/cp0-mac-receiver b/mac-receiver/bin/cp0-mac-receiver new file mode 100755 index 0000000..03242f1 --- /dev/null +++ b/mac-receiver/bin/cp0-mac-receiver @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""Daemon entrypoint for the CardputerZero Mac photo receiver.""" + +from __future__ import annotations + +import argparse +import logging +import os +import signal +import sys +import threading +from logging.handlers import RotatingFileHandler +from pathlib import Path + + +def _ensure_package_on_path() -> None: + package_root = str(Path(os.path.realpath(__file__)).resolve().parents[1]) + if package_root not in sys.path: + sys.path.insert(0, package_root) + + +_ensure_package_on_path() + +from cp0_mac_receiver.cli import LOG_BACKUP_COUNT, LOG_MAX_BYTES, default_log_path # noqa: E402 +from cp0_mac_receiver.config import default_config_path, load_mac_config # noqa: E402 +from cp0_mac_receiver.server import MacReceiverServer # noqa: E402 + + +def _configure_logging(log_path: Path) -> None: + log_path.parent.mkdir(parents=True, exist_ok=True) + handler = RotatingFileHandler( + log_path, + maxBytes=LOG_MAX_BYTES, + backupCount=LOG_BACKUP_COUNT, + encoding="utf-8", + ) + formatter = logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s") + handler.setFormatter(formatter) + + root = logging.getLogger() + root.setLevel(logging.INFO) + root.handlers.clear() + root.addHandler(handler) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Run the CardputerZero Mac HTTP photo receiver.") + parser.add_argument("--config", type=Path, default=None, help="Path to config.json.") + parser.add_argument("--log-file", type=Path, default=None, help="Path to rotating log file.") + args = parser.parse_args(argv) + + cfg_path = args.config.expanduser() if args.config is not None else default_config_path() + log_path = args.log_file.expanduser() if args.log_file is not None else default_log_path() + _configure_logging(log_path) + + cfg = load_mac_config(cfg_path) + Path(cfg.dest_root).expanduser().mkdir(parents=True, exist_ok=True) + + server = MacReceiverServer(config_path=cfg_path) + stop_event = threading.Event() + + def _handle_signal(signum: int, _frame: object) -> None: + logging.getLogger(__name__).info("Received signal %s; shutting down", signum) + stop_event.set() + + signal.signal(signal.SIGINT, _handle_signal) + signal.signal(signal.SIGTERM, _handle_signal) + + logging.getLogger(__name__).info( + "Starting MacReceiverServer on %s:%d (dest_root=%s)", + cfg.listen_host, + server.server_port, + cfg.dest_root, + ) + server.start() + try: + stop_event.wait() + finally: + server.shutdown() + server.server_close() + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/mac-receiver/bin/cp0-mac-sync b/mac-receiver/bin/cp0-mac-sync new file mode 100755 index 0000000..81606fc --- /dev/null +++ b/mac-receiver/bin/cp0-mac-sync @@ -0,0 +1,23 @@ +#!/usr/bin/env python3 +"""CLI entrypoint for CardputerZero Mac photo sync management.""" + +from __future__ import annotations + +import os +import sys +from pathlib import Path + + +def _ensure_package_on_path() -> None: + package_root = str(Path(os.path.realpath(__file__)).resolve().parents[1]) + if package_root not in sys.path: + sys.path.insert(0, package_root) + + +_ensure_package_on_path() + +from cp0_mac_receiver.cli import run_cli # noqa: E402 + + +if __name__ == "__main__": + sys.exit(run_cli(sys.argv[1:])) diff --git a/mac-receiver/cp0_mac_receiver/cli.py b/mac-receiver/cp0_mac_receiver/cli.py new file mode 100644 index 0000000..201daa7 --- /dev/null +++ b/mac-receiver/cp0_mac_receiver/cli.py @@ -0,0 +1,335 @@ +"""CLI and macOS LaunchAgent management for CardputerZero photo sync.""" + +from __future__ import annotations + +import argparse +import json +import os +import plistlib +import shutil +import subprocess +import sys +from collections import deque +from pathlib import Path +from subprocess import CompletedProcess +from typing import Any, Callable +from urllib.error import URLError +from urllib.request import urlopen + +from .config import ENV_CONFIG_PATH, default_config_path, load_mac_config, save_mac_config + +LAUNCH_AGENT_LABEL = "com.cardputerzero.photosync" +LOG_MAX_BYTES = 5 * 1024 * 1024 +LOG_BACKUP_COUNT = 2 + + +def default_log_path() -> Path: + """Return the default rotating log file path for the receiver service.""" + return Path.home() / "Library" / "Logs" / "cp0-mac-sync.log" + + +def default_plist_path() -> Path: + """Return the default macOS LaunchAgent plist path.""" + return Path.home() / "Library" / "LaunchAgents" / f"{LAUNCH_AGENT_LABEL}.plist" + + +def default_receiver_bin() -> Path: + """Locate the cp0-mac-receiver executable script.""" + repo_bin = Path(os.path.realpath(__file__)).resolve().parents[1] / "bin" / "cp0-mac-receiver" + if repo_bin.exists(): + return repo_bin + in_path = shutil.which("cp0-mac-receiver") + return Path(in_path) if in_path else repo_bin + + +def _launchd_domain() -> str: + return f"gui/{os.getuid()}" + + +def _service_target() -> str: + return f"{_launchd_domain()}/{LAUNCH_AGENT_LABEL}" + + +def _default_runner(cmd: list[str], **kwargs: Any) -> CompletedProcess[str]: + kwargs.setdefault("text", True) + return subprocess.run(cmd, **kwargs) + + +def render_launch_agent_plist(receiver_bin: Path, log_path: Path, config_path: Path) -> str: + """Render the macOS LaunchAgent plist XML for cp0-mac-receiver.""" + payload = { + "Label": LAUNCH_AGENT_LABEL, + "ProgramArguments": [sys.executable, str(receiver_bin)], + "RunAtLoad": True, + "KeepAlive": True, + "StandardOutPath": str(log_path), + "StandardErrorPath": str(log_path), + "EnvironmentVariables": { + ENV_CONFIG_PATH: str(config_path), + }, + } + return plistlib.dumps(payload, sort_keys=False).decode("utf-8") + + +def _resolve_path(path: Path | None, fallback: Callable[[], Path]) -> Path: + return Path(path).expanduser() if path is not None else fallback() + + +def _cmd_set_dir(args: argparse.Namespace, cfg_path: Path) -> int: + dest = Path(args.path).expanduser().resolve() + if dest.exists() and not dest.is_dir(): + print(f"Error: {dest} exists and is not a directory", file=sys.stderr) + return 1 + try: + dest.mkdir(parents=True, exist_ok=True) + except OSError as exc: + print(f"Error creating directory {dest}: {exc}", file=sys.stderr) + return 1 + + cfg = load_mac_config(cfg_path) + cfg.dest_root = str(dest) + save_mac_config(cfg, cfg_path) + print(f"Destination directory set to {dest}") + return 0 + + +def _cmd_set_port( + args: argparse.Namespace, + cfg_path: Path, + plist_path: Path, + runner: Callable[..., CompletedProcess[str]], +) -> int: + try: + port = int(args.port) + except ValueError: + print(f"Error: invalid port {args.port!r}", file=sys.stderr) + return 2 + + if not (1 <= port <= 65535): + print(f"Error: port must be between 1 and 65535 (got {port})", file=sys.stderr) + return 2 + + cfg = load_mac_config(cfg_path) + cfg.listen_port = port + save_mac_config(cfg, cfg_path) + + if plist_path.exists(): + res = runner(["launchctl", "kickstart", "-k", _service_target()], capture_output=True, check=False) + if res.returncode != 0: + res = runner( + ["launchctl", "bootstrap", _launchd_domain(), str(plist_path)], + capture_output=True, + check=False, + ) + if res.returncode != 0: + err = (res.stderr or "").strip() or f"launchctl exited with {res.returncode}" + print(f"Warning: updated port to {port}, but failed to restart service: {err}", file=sys.stderr) + return res.returncode + + print(f"Listen port set to {port}") + return 0 + + +def _cmd_install_service( + cfg_path: Path, + plist_path: Path, + log_path: Path, + runner: Callable[..., CompletedProcess[str]], +) -> int: + if not cfg_path.exists(): + save_mac_config(load_mac_config(cfg_path), cfg_path) + + plist_path.parent.mkdir(parents=True, exist_ok=True) + try: + log_path.parent.mkdir(parents=True, exist_ok=True) + except OSError: + pass + + plist_xml = render_launch_agent_plist(default_receiver_bin(), log_path, cfg_path) + plist_path.write_text(plist_xml, encoding="utf-8") + + runner(["launchctl", "bootout", _service_target()], capture_output=True, check=False) + res = runner( + ["launchctl", "bootstrap", _launchd_domain(), str(plist_path)], + capture_output=True, + check=False, + ) + if res.returncode != 0: + err = (res.stderr or "").strip() or f"launchctl bootstrap exited with {res.returncode}" + print(f"Error installing LaunchAgent: {err}", file=sys.stderr) + return res.returncode + + print(f"Installed LaunchAgent at {plist_path}") + return 0 + + +def _cmd_uninstall_service( + plist_path: Path, + runner: Callable[..., CompletedProcess[str]], +) -> int: + runner(["launchctl", "bootout", _service_target()], capture_output=True, check=False) + plist_path.unlink(missing_ok=True) + print(f"Uninstalled LaunchAgent ({LAUNCH_AGENT_LABEL})") + return 0 + + +def _probe_health(port: int) -> dict[str, Any] | None: + try: + with urlopen(f"http://127.0.0.1:{port}/health", timeout=2.0) as resp: + if resp.status != 200: + return None + data = json.loads(resp.read().decode("utf-8")) + return data if isinstance(data, dict) else None + except (URLError, OSError, ValueError, json.JSONDecodeError): + return None + + +def _probe_tailscale(runner: Callable[..., CompletedProcess[str]]) -> str: + try: + res = runner(["tailscale", "status", "--json"], capture_output=True, check=False) + except OSError: + return "unavailable (tailscale CLI not found)" + + if res.returncode != 0 or not res.stdout: + return "not connected" + + try: + data = json.loads(res.stdout) + except json.JSONDecodeError: + return "unknown (invalid tailscale JSON)" + + self_node = data.get("Self") + if not isinstance(self_node, dict): + return "unknown" + + dns_name = str(self_node.get("DNSName") or "").rstrip(".") + ips = self_node.get("TailscaleIPs") or [] + ip_str = ", ".join(str(ip) for ip in ips if ip) + if dns_name and ip_str: + return f"{dns_name} ({ip_str})" + return dns_name or ip_str or "connected" + + +def _probe_launchctl(runner: Callable[..., CompletedProcess[str]]) -> str: + try: + res = runner(["launchctl", "print", _service_target()], capture_output=True, check=False) + except OSError: + return "unknown (launchctl unavailable)" + if res.returncode != 0: + return "not loaded" + + state = "loaded" + pid = None + for line in (res.stdout or "").splitlines(): + stripped = line.strip() + if stripped.startswith("state ="): + state = stripped.split("=", 1)[1].strip() + elif stripped.startswith("pid ="): + pid = stripped.split("=", 1)[1].strip() + return f"{state} (pid {pid})" if pid else state + + +def _cmd_status( + cfg_path: Path, + plist_path: Path, + runner: Callable[..., CompletedProcess[str]], +) -> int: + cfg = load_mac_config(cfg_path) + installed = plist_path.exists() + launchd_state = _probe_launchctl(runner) + health = _probe_health(cfg.listen_port) + tailscale_info = _probe_tailscale(runner) + + print(f"Service: {LAUNCH_AGENT_LABEL} ({'installed' if installed else 'not installed'}, {launchd_state})") + if health is not None: + print(f"Receiver: ok (listening on {cfg.listen_host}:{cfg.listen_port}, v{health.get('version', '?')})") + else: + print(f"Receiver: unreachable (configured {cfg.listen_host}:{cfg.listen_port})") + print(f"Destination: {cfg.dest_root}") + print(f"Tailscale: {tailscale_info}") + print(f"Config: {cfg_path}") + return 0 + + +def _cmd_logs( + args: argparse.Namespace, + log_path: Path, + runner: Callable[..., CompletedProcess[str]], +) -> int: + if args.follow: + if not log_path.exists(): + print(f"No log file found at {log_path}", file=sys.stderr) + return 1 + res = runner(["tail", "-n", str(args.lines), "-f", str(log_path)], check=False) + return res.returncode + + if not log_path.exists(): + print(f"No log file found at {log_path}") + return 0 + + with open(log_path, "r", encoding="utf-8", errors="replace") as handle: + recent = deque(handle, maxlen=args.lines) + for line in recent: + sys.stdout.write(line) + return 0 + + +def _build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="cp0-mac-sync", + description="Manage the CardputerZero Mac photo receiver service.", + ) + sub = parser.add_subparsers(dest="command", required=True) + + sub.add_parser("install-service", help="Install and start the LaunchAgent service.") + sub.add_parser("uninstall-service", help="Stop and remove the LaunchAgent service.") + + p_dir = sub.add_parser("set-dir", help="Set and create the destination photo directory.") + p_dir.add_argument("path", help="Destination root directory for synced photos.") + + p_port = sub.add_parser("set-port", help="Set the HTTP receiver listen port (1-65535).") + p_port.add_argument("port", help="TCP port number.") + + sub.add_parser("status", help="Show LaunchAgent, receiver health, and Tailscale status.") + + p_logs = sub.add_parser("logs", help="View receiver logs.") + p_logs.add_argument("-f", "--follow", action="store_true", help="Follow log output.") + p_logs.add_argument("-n", "--lines", type=int, default=100, help="Number of recent lines to display.") + + return parser + + +def run_cli( + argv: list[str], + config_path: Path | None = None, + plist_path: Path | None = None, + runner: Callable[..., CompletedProcess[str]] | None = None, + log_path: Path | None = None, +) -> int: + """Execute a cp0-mac-sync CLI invocation and return an integer exit status.""" + parser = _build_parser() + try: + args = parser.parse_args(argv) + except SystemExit as exc: + return exc.code if isinstance(exc.code, int) else 1 + + cfg_path = _resolve_path(config_path, default_config_path) + target_plist = _resolve_path(plist_path, default_plist_path) + target_log = _resolve_path(log_path, default_log_path) + exec_runner = runner or _default_runner + + if args.command == "set-dir": + return _cmd_set_dir(args, cfg_path) + if args.command == "set-port": + return _cmd_set_port(args, cfg_path, target_plist, exec_runner) + if args.command == "install-service": + return _cmd_install_service(cfg_path, target_plist, target_log, exec_runner) + if args.command == "uninstall-service": + return _cmd_uninstall_service(target_plist, exec_runner) + if args.command == "status": + return _cmd_status(cfg_path, target_plist, exec_runner) + if args.command == "logs": + return _cmd_logs(args, target_log, exec_runner) + + parser.print_help() + return 2 diff --git a/mac-receiver/tests/test_cli.py b/mac-receiver/tests/test_cli.py new file mode 100644 index 0000000..e75b49b --- /dev/null +++ b/mac-receiver/tests/test_cli.py @@ -0,0 +1,224 @@ +import io +import json +import os +import plistlib +import subprocess +import sys +import tempfile +import unittest +from contextlib import redirect_stderr, redirect_stdout +from pathlib import Path +from subprocess import CompletedProcess +from unittest.mock import patch + +from cp0_mac_receiver.cli import LAUNCH_AGENT_LABEL, render_launch_agent_plist, run_cli +from cp0_mac_receiver.config import MacConfig, load_mac_config, save_mac_config + +BIN_DIR = Path(__file__).resolve().parents[1] / "bin" + + +class TestMacCli(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.cfg_path = Path(self.tmp.name) / "config.json" + self.plist_path = Path(self.tmp.name) / "com.cardputerzero.photosync.plist" + self.log_path = Path(self.tmp.name) / "cp0-mac-sync.log" + self.calls = [] + + def tearDown(self): + self.tmp.cleanup() + + def _fake_runner(self, cmd, **kwargs): + self.calls.append(cmd) + return CompletedProcess(cmd, 0, stdout="", stderr="") + + def _run_quiet(self, argv, **kwargs): + out = io.StringIO() + err = io.StringIO() + with redirect_stdout(out), redirect_stderr(err): + rc = run_cli(argv, **kwargs) + return rc, out.getvalue(), err.getvalue() + + def test_set_dir_creates_directory_and_updates_config(self): + new_dir = Path(self.tmp.name) / "Photos" / "CP0" + rc, out, _ = self._run_quiet( + ["set-dir", str(new_dir)], + config_path=self.cfg_path, + plist_path=self.plist_path, + runner=self._fake_runner, + ) + self.assertEqual(rc, 0) + self.assertIn(str(new_dir.resolve()), out) + self.assertTrue(new_dir.is_dir()) + self.assertEqual(load_mac_config(self.cfg_path).dest_root, str(new_dir.resolve())) + + def test_install_and_uninstall_service_writes_and_removes_plist(self): + rc, _, _ = self._run_quiet( + ["install-service"], + config_path=self.cfg_path, + plist_path=self.plist_path, + runner=self._fake_runner, + log_path=self.log_path, + ) + self.assertEqual(rc, 0) + plist_text = self.plist_path.read_text(encoding="utf-8") + self.assertIn("com.cardputerzero.photosync", plist_text) + self.assertIn("KeepAlive", plist_text) + parsed = plistlib.loads(plist_text.encode("utf-8")) + self.assertEqual(parsed["Label"], LAUNCH_AGENT_LABEL) + self.assertTrue(parsed["RunAtLoad"]) + self.assertTrue(parsed["KeepAlive"]) + self.assertTrue(any("launchctl" in c[0] for c in self.calls)) + + rc2, _, _ = self._run_quiet( + ["uninstall-service"], + config_path=self.cfg_path, + plist_path=self.plist_path, + runner=self._fake_runner, + ) + self.assertEqual(rc2, 0) + self.assertFalse(self.plist_path.exists()) + + def test_set_port_validates_range_and_restarts_service(self): + self._run_quiet( + ["install-service"], + config_path=self.cfg_path, + plist_path=self.plist_path, + runner=self._fake_runner, + log_path=self.log_path, + ) + self.calls.clear() + for bad_port in ("99999", "0", "not-a-port"): + rc_bad, _, _ = self._run_quiet( + ["set-port", bad_port], + config_path=self.cfg_path, + plist_path=self.plist_path, + runner=self._fake_runner, + ) + self.assertNotEqual(rc_bad, 0) + + rc, _, _ = self._run_quiet( + ["set-port", "9100"], + config_path=self.cfg_path, + plist_path=self.plist_path, + runner=self._fake_runner, + ) + self.assertEqual(rc, 0) + self.assertEqual(load_mac_config(self.cfg_path).listen_port, 9100) + self.assertTrue(any("kickstart" in " ".join(c) or "bootstrap" in " ".join(c) for c in self.calls)) + + def test_render_launch_agent_plist_includes_expected_keys(self): + receiver_bin = Path("/opt/cp0/bin/cp0-mac-receiver") + xml = render_launch_agent_plist(receiver_bin, self.log_path, self.cfg_path) + data = plistlib.loads(xml.encode("utf-8")) + self.assertEqual(data["Label"], LAUNCH_AGENT_LABEL) + self.assertTrue(data["RunAtLoad"]) + self.assertTrue(data["KeepAlive"]) + self.assertIn(str(receiver_bin), data["ProgramArguments"]) + self.assertEqual(data["StandardOutPath"], str(self.log_path)) + self.assertEqual(data["StandardErrorPath"], str(self.log_path)) + self.assertEqual(data["EnvironmentVariables"]["CP0_MAC_CONFIG"], str(self.cfg_path)) + + def test_status_reports_config_tailscale_and_health(self): + save_mac_config( + MacConfig(dest_root=str(Path(self.tmp.name) / "Pics"), listen_port=8765), + self.cfg_path, + ) + + def _status_runner(cmd, **kwargs): + self.calls.append(cmd) + if cmd[0] == "tailscale": + payload = { + "Self": { + "DNSName": "my-mac.tail123.ts.net.", + "TailscaleIPs": ["100.64.0.10"], + } + } + return CompletedProcess(cmd, 0, stdout=json.dumps(payload), stderr="") + if cmd[0] == "launchctl": + return CompletedProcess(cmd, 0, stdout="state = running\npid = 4242\n", stderr="") + return CompletedProcess(cmd, 0, stdout="", stderr="") + + fake_health = { + "status": "ok", + "version": "1.0.0", + "hostname": "my-mac", + "dest_root": str(Path(self.tmp.name) / "Pics"), + } + + class _FakeResp: + status = 200 + + def __enter__(self): + return self + + def __exit__(self, *args): + return False + + def read(self): + return json.dumps(fake_health).encode("utf-8") + + with patch("cp0_mac_receiver.cli.urlopen", return_value=_FakeResp()): + rc, out, _ = self._run_quiet( + ["status"], + config_path=self.cfg_path, + plist_path=self.plist_path, + runner=_status_runner, + ) + self.assertEqual(rc, 0) + self.assertIn("8765", out) + self.assertIn("my-mac.tail123.ts.net", out) + self.assertIn("ok", out) + + def test_logs_prints_recent_lines_missing_and_follow(self): + rc_missing, out_missing, _ = self._run_quiet( + ["logs"], + config_path=self.cfg_path, + plist_path=self.plist_path, + runner=self._fake_runner, + log_path=self.log_path, + ) + self.assertEqual(rc_missing, 0) + self.assertIn("No log file", out_missing) + + self.log_path.write_text("line1\nline2\nline3\n", encoding="utf-8") + rc, out, _ = self._run_quiet( + ["logs"], + config_path=self.cfg_path, + plist_path=self.plist_path, + runner=self._fake_runner, + log_path=self.log_path, + ) + self.assertEqual(rc, 0) + self.assertIn("line1", out) + self.assertIn("line3", out) + + rc_follow, _, _ = self._run_quiet( + ["logs", "--follow"], + config_path=self.cfg_path, + plist_path=self.plist_path, + runner=self._fake_runner, + log_path=self.log_path, + ) + self.assertEqual(rc_follow, 0) + self.assertTrue(any(c[0] == "tail" and "-f" in c and str(self.log_path) in c for c in self.calls)) + + def test_bin_entrypoints_work_via_symlink_without_pythonpath(self): + clean_env = {k: v for k, v in os.environ.items() if k != "PYTHONPATH"} + for script_name in ("cp0-mac-sync", "cp0-mac-receiver"): + target = BIN_DIR / script_name + self.assertTrue(os.access(target, os.X_OK), f"{target} must be executable") + link = Path(self.tmp.name) / script_name + link.symlink_to(target) + res = subprocess.run( + [sys.executable, str(link), "--help"], + env=clean_env, + capture_output=True, + text=True, + check=False, + ) + self.assertEqual(res.returncode, 0, res.stderr) + + +if __name__ == "__main__": + unittest.main()