"""`mld prepare ` : installe les runtimes manquants (Homebrew), copie la config ngrok, active pm2 au démarrage, pose le marqueur.""" import os import shlex from . import config, nodes, ssh def _sudo_pw(): if os.path.exists(config.SUDO_PW_FILE): return open(config.SUDO_PW_FILE).read().strip() return None def prepare(alias, runtimes=None, ka_helpers=False): ip = nodes.ip_of(alias) if not ip: raise SystemExit("nœud %s injoignable" % alias) info = nodes.probe(alias, ip) have = info.get("runtimes", {}) want = runtimes or ["node", "pnpm", "pm2", "ngrok", "python@3.14", "python@3.13", "uv", "git"] print("prepare %s (%s) — présents : %s" % (alias, ip, ", ".join(k for k, v in have.items() if v))) if not have.get("brew"): print(" ✗ Homebrew absent : bootstrap requis (Xcode CLT). Lancer d'abord : mld bootstrap %s" % alias) return False missing = [r for r in want if not have.get(r)] script = "" for r in missing: if r in config.BREW_FORMULAE: fallback = " || npm install -g pm2 >/dev/null 2>&1" if r == "pm2" else "" script += "echo ' brew install %s'; brew install -q %s >/dev/null 2>&1%s || echo ' ! échec %s'\n" % (r, config.BREW_FORMULAE[r], fallback, r) elif r in config.BREW_CASKS: script += "echo ' brew install --cask ngrok'; brew install -q --cask ngrok >/dev/null 2>&1 || brew install -q ngrok/ngrok/ngrok >/dev/null 2>&1 || echo ' ! échec ngrok'\n" # config ngrok (authtoken) depuis la passerelle if "ngrok" in missing or not have.get("ngrok"): if os.path.exists(config.NGROK_CFG): rc0, _, _ = ssh.write_remote_file(ip, "/Users/%s/Library/Application Support/ngrok/ngrok.yml" % config.USER, open(config.NGROK_CFG).read(), mode="600") script += "echo ' ngrok.yml %s'\n" % ("copié" if rc0 == 0 else "ÉCHEC de copie") # marqueur script += "[ -f ~/.maclustr-node ] || echo %s > ~/.maclustr-node\n" % alias # pm2 startup (launchd) — nécessite sudo pw = _sudo_pw() script += "if ! ls ~/Library/LaunchAgents 2>/dev/null | grep -qi pm2; then cmd=$(pm2 startup launchd -u %s --hp /Users/%s 2>/dev/null | grep '^sudo' | head -1); if [ -n \"$cmd\" ]; then %s echo \" pm2 startup: $( ${cmd#sudo } >/dev/null 2>&1 && echo ok || echo 'à faire manuellement')\"; fi; fi\n" % ( config.USER, config.USER, ("echo %s | sudo -S -v 2>/dev/null;" % shlex.quote(pw)) if pw else "") rc, out, err = ssh.run(ip, script, timeout=1800) if ka_helpers: out += ka_helpers_install(alias, ip) print(out) if err.strip(): print(" stderr:", err.strip()[-300:]) info = nodes.probe(alias, ip) still = [r for r in want if not info.get("runtimes", {}).get(r)] print(" résultat : %s" % ("tout est là" if not still else "manquent encore " + ", ".join(still))) return not still def bootstrap(alias): """Installe Xcode CLT + Homebrew sans GUI. Active un sudo NOPASSWD temporaire (retiré à la fin). Long (plusieurs Go).""" ip = nodes.ip_of(alias) pw = _sudo_pw() if not pw: raise SystemExit("mot de passe sudo requis dans %s" % config.SUDO_PW_FILE) script = r''' export LC_ALL=C echo %s | sudo -S -p '' sh -c 'echo "%s ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/mld-bootstrap && chmod 440 /etc/sudoers.d/mld-bootstrap' trap 'sudo rm -f /etc/sudoers.d/mld-bootstrap' EXIT if ! xcode-select -p >/dev/null 2>&1; then echo ' installation Command Line Tools...' touch /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress PROD=$(softwareupdate -l 2>&1 | grep -oE 'Label: Command Line Tools for Xcode[^,]*' | sed 's/^Label: //' | sort -V | tail -1) echo " produit: ${PROD:-introuvable}" if [ -n "$PROD" ]; then sudo softwareupdate -i "$PROD" --verbose 2>&1 | tail -3; fi rm -f /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress sudo xcode-select --switch /Library/Developer/CommandLineTools 2>/dev/null || true fi if [ ! -x /opt/homebrew/bin/brew ]; then echo ' installation Homebrew...' NONINTERACTIVE=1 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" 2>&1 | tail -4 grep -q 'opt/homebrew/bin/brew shellenv' ~/.zprofile 2>/dev/null || echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.zprofile fi echo " CLT: $(xcode-select -p 2>/dev/null || echo absent) brew: $(/opt/homebrew/bin/brew --version 2>/dev/null | head -1 || echo absent)" ''' % (shlex.quote(pw), config.USER) rc, out, err = ssh.run(ip, script, timeout=5400) print(out) if err.strip(): print(" stderr:", err.strip()[-400:]) return rc == 0 def gateway_mdns(): import subprocess name = subprocess.run(["scutil", "--get", "LocalHostName"], capture_output=True, text=True).stdout.strip() return (name + ".local") if name else nodes.load_lan()["ips"].get(config.GATEWAY, "") def ka_helpers_install(alias, ip): """Pousseur Ka (launchd zsh → git push vers spbgit) + alias SSH `gitsrv` → passerelle + clé autorisée sur la passerelle.""" assets = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "assets") out = [" ka-helpers sur %s :" % alias] ssh.write_remote_file(ip, "/Users/%s/ka-pousseur.sh" % config.USER, open(os.path.join(assets, "ka-pousseur.sh")).read(), mode="755") ssh.write_remote_file(ip, "/Users/%s/Library/LaunchAgents/com.ka.pousseur.plist" % config.USER, open(os.path.join(assets, "com.ka.pousseur.plist")).read(), mode="644") mdns = gateway_mdns() block = "Host gitsrv\n HostName %s\n User %s\n IdentityFile ~/.ssh/ka_guardian_ed25519\n IdentitiesOnly yes\n ControlMaster no\n ControlPath none\n StrictHostKeyChecking no\n UserKnownHostsFile /dev/null\n LogLevel ERROR\n\n" % (mdns, config.USER) script = r""" mkdir -p ~/.ssh ~/ka-guardian-spool; touch ~/.ka-pousseur-repos; chmod 700 ~/.ssh [ -f ~/.ssh/ka_guardian_ed25519 ] || ssh-keygen -q -t ed25519 -N '' -C "ka-guardian@$(cat ~/.maclustr-node 2>/dev/null || hostname -s)" -f ~/.ssh/ka_guardian_ed25519 # alias gitsrv en TÊTE du config (avant Host *) — remplace un bloc existant python3 - <<'PYEOF' import os,re p=os.path.expanduser('~/.ssh/config'); s=open(p).read() if os.path.exists(p) else '' s=re.sub(r'(?ms)^Host gitsrv\n(?:[ \t]+.*\n?)*\n?', '', s) open(p,'w').write(%r + s); os.chmod(p, 0o600); print(' gitsrv -> %s') PYEOF cat ~/.ssh/ka_guardian_ed25519.pub launchctl bootout gui/$(id -u)/com.ka.pousseur >/dev/null 2>&1; launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.ka.pousseur.plist && echo ' pousseur launchd chargé' """ % (block, mdns) rc, o, e = ssh.run(ip, script, timeout=120) pub = [l for l in o.splitlines() if l.startswith("ssh-ed25519")] out += [" " + l for l in o.splitlines() if not l.startswith("ssh-ed25519")] if pub: ak = os.path.expanduser("~/.ssh/authorized_keys") cur = open(ak).read() if os.path.exists(ak) else "" if pub[0].split()[1] not in cur: with open(ak, "a") as f: f.write(pub[0].strip() + "\n") out.append(" clé %s autorisée sur la passerelle" % (pub[0].split()[-1] if len(pub[0].split()) > 2 else alias)) else: out.append(" clé déjà autorisée sur la passerelle") rc, o, e = ssh.run(ip, "ssh -o BatchMode=yes -o ConnectTimeout=6 gitsrv 'echo ok' 2>&1 | tail -1", timeout=30) out.append(" test ssh gitsrv : %s" % (o.strip() or e.strip()[-80:])) return "\n".join(out) + "\n"