Commit f10557a
0
files
+0
added
-0
deleted
@@ -1,6229 +1,6266 @@
1 -#!/usr/bin/env python3
2 -"""
3 -╔══════════════════════════════════════════════════════════════════════════════╗
4 -║ PAG - Pagan Linux Package Manager v4.0.1 ║
5 -║ Produkcyjny menedżer pakietów – atomowy, bezpieczny, i18n ║
6 -╚══════════════════════════════════════════════════════════════════════════════╝
7 -
8 -KLUCZOWE CECHY:
9 - - Atomowa instalacja przez staging (tmpdir → rename) – brak pół-instalacji
10 - - Bezpieczne usuwanie – sprawdza czy plik nie jest współdzielony
11 - - SQLite dla bazy plików – miliony plików bez problemu
12 - - GPG: weryfikacja repo.json + podpisy pakietów + pinning fingerprintu
13 - - Hooki: pre/post-install, pre/post-remove (piaskownica env, timeout, audit)
14 - - Głęboka weryfikacja SHA256 per-plik
15 - - Pełny rollback – cofa fizyczne pliki
16 - - Blokada flock – tylko jedna instancja
17 - - Transakcje z migawkami + rejestr wykonanych hooków
18 - - Cache HTTP (ETag/If-Modified-Since)
19 - - Wielojęzyczność (i18n) – PL, EN
20 -
21 -FORMAT PAKIETU (.pag):
22 - ├── data.tar.xz – pliki + sums.json (SHA256 per plik)
23 - ├── metadata.json – nazwa, wersja, zależności
24 - └── hooks/ – pre-install, post-install, pre-remove, post-remove
25 -
26 -MODEL ZAUFANIA / BEZPIECZEŃSTWO:
27 - - Repozytorium MUSI być zaufane: podpisy GPG zweryfikowane; fingerprint
28 - klucza przypiętego do repo (TOFU przy pierwszym użyciu, potem pinning).
29 - - Hooki uruchamiają dowolny plik z pakietu jako ROOT (jak apt/pacman).
30 - Ograniczamy je (czyste env, timeout, PAG_NO_HOOKS=1, log do
31 - /var/log/pag/audit.log) i rejestrujemy w transakcji, ale ostatecznie
32 - instalujesz kod, któremu ufasz.
33 - - self-update: weryfikacja podpisu + SHA256 + składnia, atomowa podmiana.
34 -"""
35 -
36 -import os, sys, json, copy, shutil, hashlib, tarfile, tempfile, subprocess, time, fcntl, sqlite3, locale, re, difflib
37 -
38 -# Fix TLS trust inside the Pagan chroot: point Python at the CA bundle that
39 -# pag ships, otherwise urlopen() fails with "unable to get local issuer
40 -# certificate" (no default capath/cafile is resolved in the chroot).
41 -for _cafile in (
42 - "/etc/ssl/certs/ca-certificates.crt",
43 - "/etc/ssl/cert.pem",
44 -):
45 - if os.path.isfile(_cafile):
46 - os.environ["SSL_CERT_FILE"] = _cafile
47 - break
48 -
49 -from pathlib import Path
50 -from datetime import datetime, timezone
51 -from typing import Dict, List, Optional, Tuple, Set
52 -from concurrent.futures import ThreadPoolExecutor, as_completed
53 -from urllib.request import urlopen, Request
54 -import threading, itertools
55 -import uuid # serialNumber SBOM (CycloneDX)
56 -
57 -# Wersja klienta – do porównania z repo.json["pag_version"] (self-update)
58 -PAG_VERSION = "4.0.1"
59 -from urllib.error import URLError, HTTPError
60 -
61 -# =============================================================================
62 -# Pagan progress — animowany pasek „Drakkar” (własny motyw Pagan/Loki)
63 -# -----------------------------------------------------------------------------
64 -# Zamiast statycznego „█” pasek jest animowany: łódź wikingów płynie po
65 -# falującym morzu, a za nią ciągnie się smuga z wędrującym refleksem. Animacja
66 -# jest funkcją czasu, więc „płynie” nawet gdy postęp stoi w miejscu (długa
67 -# instalacja jednego pakietu, przerwa między fragmentami pobierania).
68 -#
69 -# Konfiguracja (zmienne środowiskowe):
70 -# PAG_NO_ANIM=1 – wyłącz animację (zostaje klasyczny statyczny pasek)
71 -# PAG_BAR_STYLE=<styl> – drakkar (domyślnie) | snake | classic
72 -# Poza TTY animacja jest automatycznie wyłączona (czyste logi w plikach).
73 -# =============================================================================
74 -
75 -_PAGAN_ANIM = os.environ.get("PAG_NO_ANIM", "") not in ("1", "true", "yes", "on")
76 -_PAGAN_STYLE = os.environ.get("PAG_BAR_STYLE", "drakkar").strip().lower()
77 -_DRAW_LOCK = threading.Lock() # serializacja zapisów wielu pasków
78 -
79 -# Dwie fazy fali – przesuwane w czasie dają wrażenie ruchu morza.
80 -_WAVE_PHASES = ("~_", "_~")
81 -
82 -
83 -def _classic_bar(pct: float, width: int) -> str:
84 - """Klasyczny statyczny pasek █/░ (fallback dla logów i PAG_NO_ANIM)."""
85 - filled = int(round(width * max(0.0, min(100.0, pct)) / 100.0))
86 - return "█" * filled + "░" * (width - filled)
87 -
88 -
89 -def _drakkar_bar(pct: float, width: int, t: float, filled: int) -> str:
90 - """Drakkar (łódź wikingów) płynący po falującym morzu.
91 -
92 - - przed łodzią: falujące morze (~ _ przesuwane w czasie),
93 - - dziób łodzi: » (kolumna = bieżący postęp),
94 - - za łodzią: smuga z wędrującym refleksem światła.
95 - """
96 - done = pct >= 100.0
97 - wave = _WAVE_PHASES[int(t * 6) % len(_WAVE_PHASES)]
98 - ship = min(filled, width - 1)
99 - glow = int(t * 10) % ship if ship > 0 else -1
100 - out = []
101 - for i in range(width):
102 - if done:
103 - out.append("»" if i == width - 1 else "█") # łódź zacumowana
104 - elif i < ship:
105 - out.append("█" if i == glow else "▓")
106 - elif i == ship:
107 - out.append("»")
108 - else:
109 - out.append(wave[i & 1])
110 - return "".join(out)
111 -
112 -
113 -def _snake_bar(pct: float, width: int, t: float, filled: int) -> str:
114 - """Jörmungandr – wąż sunący przez pasek (głowa @, łuski o/~, ogon ·)."""
115 - done = pct >= 100.0
116 - head = min(filled, width - 1)
117 - out = []
118 - for i in range(width):
119 - if done:
120 - out.append("@" if i == width - 1 else "o")
121 - elif i < head:
122 - out.append("o" if (i + int(t * 6)) & 1 else "~")
123 - elif i == head:
124 - out.append("@")
125 - else:
126 - out.append("·")
127 - return "".join(out)
128 -
129 -
130 -def _pagan_bar(pct: float, width: int = 30, t: float = 0.0,
131 - style: Optional[str] = None, animated: bool = True) -> str:
132 - """Zwraca jednoliniowy pasek postępu o STAŁEJ szerokości `width`.
133 -
134 - `pct` – postęp 0..100
135 - `t` – czas (s); różne `t` → inna klatka animacji
136 - `animated` – False wymusza klasyczny statyczny pasek (np. brak TTY)
137 - """
138 - width = max(6, int(width))
139 - pct = max(0.0, min(100.0, float(pct)))
140 - style = style or _PAGAN_STYLE
141 - if not animated or not _PAGAN_ANIM or style == "classic":
142 - return _classic_bar(pct, width)
143 - filled = int(round(width * pct / 100.0))
144 - if style == "snake":
145 - return _snake_bar(pct, width, t, filled)
146 - return _drakkar_bar(pct, width, t, filled)
147 -
148 -
149 -class _Bar:
150 - """Baza animowanych pasków: rysują JEDNĄ nadpisywaną linię na `stream`.
151 -
152 - Gdy mamy TTY, wątek w tle odświeża pasek ~10×/s, dzięki czemu morze faluje
153 - także wtedy, gdy postęp chwilowo się nie zmienia.
154 - """
155 - def __init__(self, width: int, stream=None):
156 - self.width = width
157 - self.stream = stream if stream is not None else sys.stderr
158 - self.tty = self.stream.isatty()
159 - self._lock = threading.RLock()
160 - self._last_len = 0
161 - self._stop = threading.Event()
162 - self._thread = None
163 -
164 - # -- wątek animacji -------------------------------------------------------
165 - def _start_anim(self):
166 - if _PAGAN_ANIM and self.tty and self._thread is None:
167 - self._thread = threading.Thread(target=self._anim_loop, daemon=True)
168 - self._thread.start()
169 -
170 - def _anim_loop(self):
171 - while not self._stop.wait(0.1):
172 - with self._lock:
173 - if self._stop.is_set():
174 - break
175 - self._write(self._line())
176 -
177 - def _stop_anim(self):
178 - self._stop.set()
179 - if self._thread is not None:
180 - self._thread.join(timeout=0.3)
181 - self._thread = None
182 -
183 - # -- rysowanie ------------------------------------------------------------
184 - def _write(self, line: str):
185 - clear = " " * max(0, self._last_len - len(line))
186 - with _DRAW_LOCK:
187 - self.stream.write(f"\r{line}{clear}")
188 - self.stream.flush()
189 - self._last_len = len(line)
190 -
191 - def _line(self) -> str:
192 - raise NotImplementedError
193 -
194 - def _clear_line(self):
195 - if self.tty and self._last_len:
196 - with _DRAW_LOCK:
197 - self.stream.write("\r" + " " * self._last_len + "\r")
198 - self.stream.flush()
199 - self._last_len = 0
200 -
201 - def _newline(self):
202 - if self.tty and self._last_len:
203 - self.stream.write("\n")
204 - self.stream.flush()
205 - self._last_len = 0
206 -
207 -
208 -class ProgressBar(_Bar):
209 - """Pasek postępu dla N elementów — animowany („drakkar”) na TTY."""
210 - def __init__(self, total: int, desc: str = "", unit: str = "", width: int = 30):
211 - super().__init__(width)
212 - self.total = max(total, 1)
213 - self.desc = desc
214 - self.unit = unit
215 - self.n = 0
216 - self.suffix = ""
217 - self.start = time.time()
218 - self._start_anim()
219 -
220 - def _line(self) -> str:
221 - pct = self.n / self.total * 100
222 - elapsed = time.time() - self.start
223 - speed = self.n / elapsed if elapsed > 0 else 0
224 - if self.n >= self.total:
225 - eta_str = "done"
226 - elif speed > 0:
227 - eta = (self.total - self.n) / speed
228 - eta_str = f"{eta:.0f}s" if eta < 60 else f"{eta/60:.1f}m"
229 - else:
230 - eta_str = "?..."
231 - bar = _pagan_bar(pct, self.width, time.time(), animated=self.tty)
232 - return f" {self.desc} [{bar}] {self.n}/{self.total} ({pct:.0f}%) ETA {eta_str}{self.suffix}"
233 -
234 - def update(self, n: Optional[int] = None, suffix: str = ""):
235 - with self._lock:
236 - if n is not None:
237 - self.n = n
238 - else:
239 - self.n += 1
240 - self.suffix = suffix
241 - if self.tty:
242 - self._write(self._line())
243 - elif (self.n == 1 or self.n >= self.total
244 - or self.n % max(1, self.total // 10) == 0):
245 - # Bez TTY – tylko kamienie milowe (czysty log)
246 - print(self._line(), file=self.stream)
247 -
248 - def close(self):
249 - self._stop_anim()
250 - with self._lock:
251 - self._newline()
252 -
253 - def __enter__(self):
254 - return self
255 -
256 - def __exit__(self, *args):
257 - self.close()
258 -
259 -
260 -class DownloadBar(_Bar):
261 - """Animowany pasek pobierania (na podstawie Content-Length)."""
262 - def __init__(self, filename: str, total_bytes: int):
263 - super().__init__(25)
264 - self.filename = filename
265 - self.total = total_bytes
266 - self.downloaded = 0
267 - self.start = time.time()
268 - self._start_anim()
269 -
270 - def _line(self) -> str:
271 - pct = self.downloaded / self.total * 100 if self.total > 0 else 0.0
272 - elapsed = time.time() - self.start
273 - speed = self.downloaded / elapsed if elapsed > 0 else 0
274 - if self.total > 0 and speed > 0:
275 - eta = (self.total - self.downloaded) / speed
276 - eta_str = f"{eta:.0f}s" if eta < 60 else f"{eta/60:.1f}m"
277 - else:
278 - eta_str = "?..."
279 - bar = _pagan_bar(pct, self.width, time.time(), animated=self.tty)
280 - sz = self._fmt_size(self.total)
281 - spd = self._fmt_size(int(speed))
282 - return f" ↓ {self.filename} [{bar}] {pct:.0f}% {sz} {spd}/s ETA {eta_str}"
283 -
284 - def update(self, chunk_size: int):
285 - with self._lock:
286 - self.downloaded += chunk_size
287 - if self.tty and self.total > 0:
288 - self._write(self._line())
289 -
290 - def close(self):
291 - self._stop_anim()
292 - with self._lock:
293 - if self.total > 0:
294 - self._newline()
295 -
296 - @staticmethod
297 - def _fmt_size(n: int) -> str:
298 - for unit in ("B", "KB", "MB", "GB"):
299 - if n < 1024:
300 - return f"{n:.1f} {unit}"
301 - n /= 1024
302 - return f"{n:.1f} TB"
303 -
304 -
305 -class _StepBar(_Bar):
306 - """Animowany pasek dla pętli „krok po kroku” (instalacja/aktualizacja).
307 -
308 - Pasek nie skacze skokowo co pakiet – między krokami łagodnie „dopełza”
309 - w stronę kolejnego progu (jak w instalatorach), więc rośnie w sposób
310 - ciągły. Wątek animacji odświeża go ~10×/s.
311 - """
312 - def __init__(self, total: int, icon: str = "", width: int = 25,
313 - creep_tau: float = 3.0):
314 - super().__init__(width)
315 - self.total = max(total, 1)
316 - self.icon = icon
317 - self.creep_tau = creep_tau # „stała czasu” dopełzania (s)
318 - self.idx = 0
319 - self.label = ""
320 - self.t0 = time.time()
321 - self._step_t = time.time() # start bieżącego pakietu
322 - self._start_anim()
323 -
324 - def _frac(self) -> float:
325 - """Ukończona część [0..1]: kroki + wygładzone dopełzanie w bieżącym."""
326 - done = max(0, self.idx - 1)
327 - if done >= self.total:
328 - return 1.0
329 - # 0.5 ** (dt/tau): 0 → ~1 asymptotycznie; cap 0.9, by krok był widoczny
330 - creep = 1.0 - 0.5 ** ((time.time() - self._step_t) / self.creep_tau)
331 - return (done + min(creep, 0.9)) / self.total
332 -
333 - def _line(self) -> str:
334 - pct = self._frac() * 100.0
335 - eta_s = ""
336 - if self.idx > 1:
337 - avg = (time.time() - self.t0) / (self.idx - 1)
338 - rem = avg * (self.total - self.idx + 1)
339 - eta_s = f" ~{rem:.0f}s" if rem < 60 else f" ~{rem/60:.1f}m"
340 - bar = _pagan_bar(pct, self.width, time.time(), animated=self.tty)
341 - return f" {self.icon}[{bar}] {self.idx}/{self.total} ({pct:.0f}%) {self.label}{eta_s}"
342 -
343 - def step(self, idx: int, label: str):
344 - with self._lock:
345 - self.idx = idx
346 - self.label = label
347 - self._step_t = time.time()
348 - if self.tty:
349 - self._write(self._line())
350 - else:
351 - print(self._line(), file=self.stream)
352 -
353 - def end(self):
354 - self._stop_anim()
355 - with self._lock:
356 - self._clear_line()
357 -
358 -# =============================================================================
359 -# GPG – BEZPIECZNE WYWOŁYWANIE (odporne na brak binarki gpg)
360 -# =============================================================================
361 -
362 -GPG_BINARY = shutil.which("gpg2") or shutil.which("gpg") or "gpg"
363 -GPG_HOME = "/etc/pag/gpg" # izolowany keyring (działa z keyboxd GPG 2.4+)
364 -
365 -def _ssl_ok() -> bool:
366 - """Czy Python ma działający moduł ssl (HTTPS w urllib).
367 -
368 - Bez niego urllib nie zna schematu https i każda operacja sieciowa kończy
369 - się „unknown url type: https” – myląco, bo wygląda jak błąd adresu.
370 - """
371 - try:
372 - import ssl # noqa: F401
373 - return True
374 - except Exception:
375 - return False
376 -
377 -
378 -def _gpg_run(*args, timeout: int = 30, **kwargs) -> subprocess.CompletedProcess:
379 - """
380 - Bezpieczne wywołanie GPG – przechwytuje FileNotFoundError,
381 - gdyby gpg/gpg2 nie było zainstalowane w minimalnym środowisku.
382 - Wymusza LC_ALL=C aby komunikaty GPG były zawsze po angielsku
383 - (niezależnie od locale systemu) – kluczowe dla parsowania stderr.
384 - """
385 - env = kwargs.pop("env", None) or os.environ.copy()
386 - env["LC_ALL"] = "C"
387 - env["GNUPGHOME"] = GPG_HOME
388 - try:
389 - return subprocess.run([GPG_BINARY, *args], timeout=timeout, env=env, **kwargs)
390 - except FileNotFoundError:
391 - # GPG nie jest dostępne – zwróć błąd z komunikatem
392 - # (szanuj text=True – inaczej caller dostaje bytes i może wybuchnąć TypeError)
393 - _text = bool(kwargs.get("text") or kwargs.get("universal_newlines"))
394 - _msg = f"GPG binary not found ({GPG_BINARY})"
395 - return subprocess.CompletedProcess(
396 - [GPG_BINARY, *args], 127,
397 - stdout=("" if _text else b""),
398 - stderr=(_msg if _text else _msg.encode()),
399 - )
400 - except subprocess.TimeoutExpired:
401 - return subprocess.CompletedProcess(
402 - [GPG_BINARY, *args], 124,
403 - stdout=b"", stderr=b"GPG operation timed out"
404 - )
405 -
406 -def _load_trust_db() -> dict:
407 - """Mapa repo_url → fingerprint klucza podpisującego (baza zaufania)."""
408 - try:
409 - with open(TRUST_DB) as f:
410 - return json.load(f)
411 - except (FileNotFoundError, json.JSONDecodeError):
412 - return {}
413 -
414 -
415 -def _save_trust_db(db: dict):
416 - os.makedirs(os.path.dirname(TRUST_DB), exist_ok=True)
417 - with open(TRUST_DB, "w") as f:
418 - json.dump(db, f, indent=2)
419 -
420 -
421 -def _gpg_verify_fp(sig_path: str, data_path: str, timeout: int = 30):
422 - """Weryfikuje podpis i odczytuje fingerprint podpisującego.
423 -
424 - Używa --status-fd=1 i linii VALIDSIG <fingerprint>. Zwraca (ok, fingerprint).
425 -
426 - FAIL-CLOSED: OK tylko gdy GPG zwrócił 0 ORAZ w statusie maszynowym jest
427 - linia VALIDSIG. Nie zakładamy sukcesu na podstawie samego kodu wyjścia –
428 - gdyby format --status-fd się zmienił, wolimy odrzucić podpis niż przyjąć
429 - niezaufany pakiet (wywołujący traktuje fp=None jako brak potwierdzenia).
430 - """
431 - env = os.environ.copy()
432 - res = _gpg_run("--verify", "--status-fd", "1", sig_path, data_path,
433 - capture_output=True, text=True, timeout=timeout, env=env)
434 - out = res.stdout or ""
435 - m = re.search(r"\[GNUPG:\]\s+VALIDSIG\s+([0-9A-Fa-f]{16,})", out)
436 - if not m:
437 - m = re.search(r"\bVALIDSIG\s+([0-9A-Fa-f]{16,})", out)
438 - if res.returncode != 0 or not m:
439 - return False, None
440 - return True, m.group(1).upper()
441 -
442 -
443 -def _verify_local_pkg_signature(pkg_path: str) -> bool:
444 - """Weryfikuje lokalny .pag tym samym kluczem co zaufane repo."""
445 - # PAG_INSECURE=1 – spójnie z _verify_repo_sig() i _verify_pkg_signature().
446 - # Potrzebne w środowisku BUILDA: instalator buduje własne .pag (np. `kernel`)
447 - # lokalnie, nie ma dla nich pliku .asc, a klucza prywatnego repo celowo NIE ma
448 - # na maszynie budującej. Wcześniej ta funkcja jako jedyna ignorowała
449 - # PAG_INSECURE, więc obejście używane przez resztę builda tu nie działało.
450 - if os.environ.get("PAG_INSECURE", "") == "1":
451 - print(" ⚠ PAG_INSECURE=1 – pomijam weryfikację podpisu pakietu lokalnego")
452 - return True
453 - sig_path = next((pkg_path + ext for ext in (".asc", ".sig")
454 - if os.path.isfile(pkg_path + ext)), "")
455 - if not sig_path:
456 - print(f" ❌ Brak podpisu dla pakietu: {pkg_path}")
457 - print(" Wymagany jest plik .pag.asc/.pag.sig z tego samego źródła.")
458 - return False
459 - ok, fingerprint = _gpg_verify_fp(sig_path, pkg_path)
460 - if not ok or not fingerprint:
461 - print(f" ❌ Nieprawidłowy podpis pakietu: {pkg_path}")
462 - return False
463 - expected = _repo_pinned_fp(DEFAULT_REPOS[0])
464 - if not expected:
465 - print(" ❌ Brak przypiętego klucza repo dla lokalnego pakietu.")
466 - print(" Uruchom najpierw: sudo pag sync")
467 - return False
468 - if fingerprint != expected.upper():
469 - print(" ❌ [SECURITY ERROR] Pakiet podpisano innym kluczem repo.")
470 - print(f" Oczekiwany: {expected}")
471 - print(f" Otrzymany: {fingerprint}")
472 - return False
473 - print(f" 🔐 Podpis pakietu OK ({fingerprint})")
474 - return True
475 -
476 -
477 -# =============================================================================
478 -# i18n – WIELOJĘZYCZNOŚĆ
479 -# =============================================================================
480 -
481 -LANG = os.environ.get("LANG", "en_US.UTF-8")[:2] # pl, en, de...
482 -COLOR = os.environ.get("NO_COLOR", "") == "" and sys.stdout.isatty()
483 -
484 -def _c(code: str, text: str) -> str:
485 - """Dodaje kody ANSI jeśli kolor jest włączony."""
486 - if not COLOR:
487 - return text
488 - colors = {
489 - "green": "\033[32m", "red": "\033[31m", "yellow": "\033[33m",
490 - "cyan": "\033[36m", "bold": "\033[1m", "dim": "\033[2m",
491 - "reset": "\033[0m",
492 - }
493 - return f"{colors.get(code,'')}{text}{colors['reset']}"
494 -
495 -T = {
496 - "en": {
497 - "root_required": "pag requires root privileges (sudo).",
498 - "db_locked": "Another pag instance is running.",
499 - "db_lock_hint": "If no other pag process is running, wait a moment and retry.",
500 - "no_index": "Cannot fetch repository indexes. Run 'pag update'.",
501 - "cache_ro": "Repo cache is read-only ({cache}) – using local index (may be outdated).\n Refresh as root: sudo pag sync",
502 - "all_installed": "All packages are already installed.",
503 - "to_install": "To install: {} packages ({:.2f} MB)",
504 - "new": "NEW",
505 - "continue_q": "Continue? [Y/n] ",
506 - "no_tty": "No TTY / stdin closed (EOF) – cancelling.",
507 - "cancelled": "Cancelled.",
508 - "not_found": "not found in repos",
509 - "pkg_not_found": "Package not found: {} (not in any repo)",
510 - "not_found_hint": "Check the spelling or run 'pag search <query>'.",
511 - "downloading": "Downloading",
512 - "download_fail": "download failed",
513 - "gpg_fail": "GPG verification failed",
514 - "sha256_mismatch": "SHA256 mismatch",
515 - "install_failed": "installation failed",
516 - "installed": "Installed {} packages.",
517 - "rollback_restored": "Restored previous state from snapshot.",
518 - "rollback_files": "Rolled back {} files.",
519 - "no_history": "No transaction history.",
520 - "pinned_list": "Pinned packages ({}):",
521 - "no_pinned": "No pinned packages.",
522 - "pinned_to": "pinned to",
523 - "unpinned": "unpinned.",
524 - "not_pinned": "was not pinned.",
525 - "repo_added": "Added repository: {}",
526 - "repo_exists": "Repository already exists: {}",
527 - "updated_done": "Index refresh complete. {} packages cached.",
528 - "indexes_refreshed": "Indexes refreshed.",
529 - "updates_available": "⚠ {} packages have updates – run: pag update",
530 - "upgrading": "Upgrading: {} packages",
531 - "all_up_to_date": "All packages are up to date.",
532 - "removing": "Removing",
533 - "orphans_found": "Orphaned dependencies ({}): {}",
534 - "flatpak_missing": "Flatpak is not installed.",
535 - "flatpak_adding": "Adding Flathub remote...",
536 - "flatpak_searching": "Searching Flathub for '{}'...",
537 - "flatpak_found": "Found {} results:",
538 - "flatpak_not_found": "not found on Flathub",
539 - "flatpak_install_prompt": "Install {}? [Y/n] ",
540 - "flatpak_installing": "Installing {}...",
541 - "flatpak_installed": "Flatpak {} installed.",
542 - "flatpak_removed": "Flatpak {} removed.",
543 - "flatpak_not_installed": "Flatpak {} is not installed.",
544 - "flatpak_info_id": "ID",
545 - "flatpak_info_version": "Version",
546 - "flatpak_info_branch": "Branch",
547 - "flatpak_info_origin": "Origin",
548 - "flatpak_info_size": "Installed size",
549 - "flatpak_info_desc": "Description",
550 - "flatpak_updated": "Flatpaks updated.",
551 - "flatpak_usage": "Usage: pag flatpak <search|install|remove|list|update|info> [args]",
552 - "flatpak_scope": "Installation",
553 - "flatpak_menu_hint": "Installed and verified, but this session may not show it in the menu: Flatpak exports are missing from XDG_DATA_DIRS.",
554 - "flatpak_menu_fix": "Add /var/lib/flatpak/exports/share to XDG_DATA_DIRS (and .../exports/bin to PATH) in your session, then re-login – PaganDE does this in session/pagande-session.",
555 - "key_imported": "Key imported successfully.",
556 - "key_removed": "Key removed: {}",
557 - "no_keys": "No trusted GPG keys.",
558 - "gpg_missing": "GNUPG MISSING – install gnupg and retry",
559 - "ssl_broken": "Python has no working ssl module (HTTPS impossible) – fix the python/openssl packages (e.g. sudo pag install -f python).",
560 - "key_add_failed": "Key import failed (gpg error) – key was NOT added.",
561 - "verify_ok": "All {} files intact.",
562 - "verify_errors": "{} problems found:",
563 - "cache_cleared": "{} files ({:.2f} MB) cleared from cache.",
564 - "deployments_list": "Deployments ({}):",
565 - "no_deployments": "No deployments.",
566 - "active_deployment": "ACTIVE",
567 - "deploy_rollback_ok": "Switched to deployment: {}",
568 - "deploy_rollback_fail": "No previous deployment.",
569 - "deploy_cleanup_ok": "Removed {} old deployments.",
570 - "deploy_cleanup_none": "No deployments to clean (minimum {}).",
571 - "why_explicit": "explicitly installed",
572 - "why_dependency": "dependency of",
573 - "why_not_installed": "not installed",
574 - "autoremove_ok": "Removed {} orphaned packages.",
575 - "autoremove_none": "No orphaned packages.",
576 - "downloaded": "Downloaded {} to cache ({:.2f} MB).",
577 - "provides_mapped": "{} → {} (provides)",
578 - "stats_title": "PAG Statistics",
579 - "stats_packages": "Installed packages",
580 - "stats_files": "Tracked files",
581 - "stats_size": "Total size",
582 - "stats_cache": "Cache size",
583 - "stats_history": "Transactions",
584 - "stats_last_update": "Last update",
585 - # Komunikaty bezpieczeństwa (baza EN; PL w tabeli "pl" jako sec_*_pl)
586 - "sec_downgrade": "Downgrade blocked: {pkg} {new} < {old}",
587 - "sec_suid": "SUID stripped from {path}",
588 - "sec_https": "HTTPS required for repos",
589 - "sec_badname": "Invalid package name: {name}",
590 - "sec_toobig": "Package too large: {size_mb}MB > {max_mb}MB",
591 - "sec_conflict": "File conflict: {path} owned by {owner}",
592 - "sec_audit": "{pkg} installed by {user}",
593 - "sec_locked": "Another pag process is running",
594 - # Konfiguracja (/etc) – zachowanie zmian użytkownika
595 - "conf_pacnew": "Modified config kept; new version saved as {path}",
596 - "conf_pacsave": "Modified config kept as {path}",
597 - # Zależności wirtualne (provides)
598 - "provides_conflict": "Multiple providers for '{name}' ({providers}) – using '{chosen}'",
599 -
600 - # Base baked into the ISO image (pag base / base adopt)
601 - "base_title": "Base from the ISO image",
602 - "base_no_manifest": "This system carries no base manifest (/usr/share/pag/base.json) – nothing to adopt.",
603 - "base_iso_version": "Image version",
604 - "base_total": "Base packages (from image)",
605 - "base_tracked": "Managed by pag",
606 - "base_adoptable": "Adoptable from repo",
607 - "base_unmatched": "No counterpart in repo",
608 - "base_adopt_hint": "Adopt them (image files get replaced by repo packages): sudo pag base adopt",
609 - "base_unmatched_hint": "These stay at the image version (no such package in repo):",
610 - "base_more": "more",
611 - "base_nothing_selected": "None of the given names is on the adopt list.",
612 - "base_all_managed": "Every base package is already managed by pag.",
613 - "base_adopt_plan": "Adopting {} base packages from the repo (~{:.0f} MB):",
614 - "base_dry_run": "Dry run – nothing was installed.",
615 - "base_unmanaged_hint": "{} packages from the ISO image are not managed by pag yet – 'sudo pag base adopt' replaces them with repo packages (only then does 'pag upgrade' update them).",
616 - "base_overwrite": "{} comes from the ISO image – its files will be replaced (backup kept for 'pag rollback').",
617 - "base_reboot_hint": "Base adopted from the repo – reboot before using the new libraries/toolchain.",
618 - "stats_base": "Base (image) managed",
619 - },
620 - "pl": {
621 - "root_required": "pag wymaga uprawnień root (sudo).",
622 - "db_locked": "Inna instancja pag jest uruchomiona.",
623 - "db_lock_hint": "Jeśli żaden inny proces pag nie działa, poczekaj chwilę i spróbuj ponownie.",
624 - "no_index": "Nie można pobrać indeksów repozytoriów. Uruchom 'pag update'.",
625 - "cache_ro": "Cache repozytoriów jest tylko-do-odczytu ({cache}) – używam lokalnego indeksu (może być nieaktualny).\n Odśwież jako root: sudo pag sync",
626 - "all_installed": "Wszystkie pakiety są już zainstalowane.",
627 - "to_install": "Do zainstalowania: {} pakietów ({:.2f} MB)",
628 - "new": "NOWY",
629 - "continue_q": "Kontynuować? [T/n] ",
630 - "no_tty": "Brak terminala (EOF) – anuluję.",
631 - "cancelled": "Anulowano.",
632 - "not_found": "brak w repozytoriach",
633 - "pkg_not_found": "Nie znaleziono pakietu: {} (brak w repozytoriach)",
634 - "not_found_hint": "Sprawdź pisownię lub uruchom 'pag search <fraza>'.",
635 - "downloading": "Pobieranie",
636 - "download_fail": "błąd pobierania",
637 - "gpg_fail": "błąd weryfikacji GPG",
638 - "sha256_mismatch": "niezgodność SHA256",
639 - "install_failed": "błąd instalacji",
640 - "installed": "Zainstalowano {} pakietów.",
641 - "rollback_restored": "Przywrócono poprzedni stan z migawki.",
642 - "rollback_files": "Wycofano {} plików.",
643 - "no_history": "Brak historii transakcji.",
644 - "pinned_list": "Przypięte pakiety ({}):",
645 - "no_pinned": "Brak przypiętych pakietów.",
646 - "pinned_to": "przypięty do",
647 - "unpinned": "odpięty.",
648 - "not_pinned": "nie był przypięty.",
649 - "repo_added": "Dodano repozytorium: {}",
650 - "repo_exists": "Repozytorium już istnieje: {}",
651 - "updated_done": "Odświeżanie zakończone. {} pakietów w cache.",
652 - "indexes_refreshed": "Indeksy odświeżone.",
653 - "updates_available": "⚠ jest {} pakietów do zaktualizowania – wpisz: pag update",
654 - "upgrading": "Aktualizacje: {} pakietów",
655 - "all_up_to_date": "Wszystkie pakiety są aktualne.",
656 - "removing": "Usuwanie",
657 - "orphans_found": "Osierocone zależności ({}): {}",
658 - "flatpak_missing": "Flatpak nie jest zainstalowany.",
659 - "flatpak_adding": "Dodaję zdalne repozytorium Flathub...",
660 - "flatpak_searching": "Szukam '{}' we Flathub...",
661 - "flatpak_found": "Znaleziono {} wyników:",
662 - "flatpak_not_found": "nie znaleziono we Flathub",
663 - "flatpak_install_prompt": "Zainstalować {}? [T/n] ",
664 - "flatpak_installing": "Instalowanie {}...",
665 - "flatpak_installed": "Flatpak {} zainstalowany.",
666 - "flatpak_removed": "Flatpak {} usunięty.",
667 - "flatpak_not_installed": "Flatpak {} nie jest zainstalowany.",
668 - "flatpak_info_id": "ID",
669 - "flatpak_info_version": "Wersja",
670 - "flatpak_info_branch": "Gałąź",
671 - "flatpak_info_origin": "Źródło",
672 - "flatpak_info_size": "Rozmiar",
673 - "flatpak_info_desc": "Opis",
674 - "flatpak_updated": "Flapaki zaktualizowane.",
675 - "flatpak_usage": "Użycie: pag flatpak <search|install|remove|list|update|info> [args]",
676 - "flatpak_scope": "Instalacja",
677 - "flatpak_menu_hint": "Zainstalowano i zweryfikowano, ale sesja może jej nie pokazać w menu: brak eksportów Flatpaka w XDG_DATA_DIRS.",
678 - "flatpak_menu_fix": "Dodaj /var/lib/flatpak/exports/share do XDG_DATA_DIRS (a .../exports/bin do PATH) w sesji i zaloguj się ponownie – PaganDE robi to w session/pagande-session.",
679 - "key_imported": "Klucz zaimportowany pomyślnie.",
680 - "key_removed": "Klucz usunięty: {}",
681 - "no_keys": "Brak zaufanych kluczy GPG.",
682 - "gpg_missing": "BRAK GNUPG – zainstaluj gnupg i spróbuj ponownie",
683 - "ssl_broken": "Python bez działającego modułu ssl (HTTPS niemożliwe) – napraw pakiety python/openssl (np. sudo pag install -f python).",
684 - "key_add_failed": "Import klucza nie powiódł się (błąd gpg) – klucz NIE został dodany.",
685 - "verify_ok": "Wszystkie {} plików sprawne.",
686 - "verify_errors": "Znaleziono {} problemów:",
687 - "cache_cleared": "{} plików ({:.2f} MB) usuniętych z cache.",
688 - "deployments_list": "Deploymenty ({}):",
689 - "no_deployments": "Brak deploymentów.",
690 - "active_deployment": "AKTYWNY",
691 - "deploy_rollback_ok": "Przełączono na deployment: {}",
692 - "deploy_rollback_fail": "Brak poprzedniego deploymentu.",
693 - "deploy_cleanup_ok": "Usunięto {} starych deploymentów.",
694 - "deploy_cleanup_none": "Nie ma deploymentów do wyczyszczenia (minimum {}).",
695 - "why_explicit": "zainstalowany jawnie",
696 - "why_dependency": "zależność od",
697 - "why_not_installed": "niezainstalowany",
698 - "autoremove_ok": "Usunięto {} osieroconych pakietów.",
699 - "autoremove_none": "Brak osieroconych pakietów.",
700 - "downloaded": "Pobrano {} do cache ({:.2f} MB).",
701 - "sec_downgrade": "Downgrade blocked: {pkg} {new} < {old}",
702 - "sec_suid": "SUID stripped from {path}",
703 - "sec_https": "HTTPS required for repos",
704 - "sec_badname": "Invalid package name: {name}",
705 - "sec_toobig": "Package too large: {size_mb}MB > {max_mb}MB",
706 - "sec_conflict": "File conflict: {path} owned by {owner}",
707 - "sec_audit": "{pkg} installed by {user}",
708 - "sec_locked": "Another pag process is running",
709 - "sec_downgrade_pl": "Blokada downgrade: {pkg} {new} < {old}",
710 - "sec_suid_pl": "SUID usuniety z {path}",
711 - "sec_https_pl": "Repozytorium wymaga HTTPS",
712 - "sec_badname_pl": "Nieprawidlowa nazwa pakietu: {name}",
713 - "sec_toobig_pl": "Paczka za duza: {size_mb}MB > {max_mb}MB",
714 - "sec_conflict_pl": "Konflikt plikow: {path} nalezy do {owner}",
715 - "sec_audit_pl": "{pkg} zainstalowany przez {user}",
716 - "sec_locked_pl": "Inny proces pag juz dziala",
717 -
718 - "provides_mapped": "{} → {} (provides)",
719 - "stats_title": "Statystyki PAG",
720 - "stats_packages": "Zainstalowane pakiety",
721 - "stats_files": "Śledzone pliki",
722 - "stats_size": "Całkowity rozmiar",
723 - "stats_cache": "Rozmiar cache",
724 - "stats_history": "Transakcje",
725 - "stats_last_update": "Ostatnia aktualizacja",
726 - "conf_pacnew": "Zmieniony plik konfiguracyjny zachowany; nowa wersja: {path}",
727 - "conf_pacsave": "Zmieniony plik konfiguracyjny zachowany jako {path}",
728 - "provides_conflict": "Wielu dostawców dla '{name}' ({providers}) – używam '{chosen}'",
729 -
730 - # Baza wypalona w obrazie ISO (pag base / base adopt)
731 - "base_title": "Baza z obrazu ISO",
732 - "base_no_manifest": "Ten system nie ma manifestu bazy (/usr/share/pag/base.json) – nie ma czego adoptować.",
733 - "base_iso_version": "Wersja obrazu",
734 - "base_total": "Pakiety bazy (z obrazu)",
735 - "base_tracked": "Zarządzane przez pag",
736 - "base_adoptable": "Do adoptowania z repo",
737 - "base_unmatched": "Bez odpowiednika w repo",
738 - "base_adopt_hint": "Adoptuj (pliki z obrazu zostaną zastąpione pakietami z repo): sudo pag base adopt",
739 - "base_unmatched_hint": "Te zostaną w wersji z obrazu (brak takiego pakietu w repo):",
740 - "base_more": "więcej",
741 - "base_nothing_selected": "Żadna z podanych nazw nie jest na liście do adoptowania.",
742 - "base_all_managed": "Wszystkie pakiety bazy są już zarządzane przez pag.",
743 - "base_adopt_plan": "Adoptowanie {} pakietów bazy z repo (~{:.0f} MB):",
744 - "base_dry_run": "Próba na sucho – nic nie zainstalowano.",
745 - "base_unmanaged_hint": "{} pakietów z obrazu ISO nie jest jeszcze zarządzanych przez pag – 'sudo pag base adopt' zamieni je na pakiety z repo (dopiero wtedy 'pag upgrade' je aktualizuje).",
746 - "base_overwrite": "{} pochodzi z obrazu ISO – pliki zostaną zastąpione (kopia zapasowa dla 'pag rollback').",
747 - "base_reboot_hint": "Baza zaadoptowana z repo – zrestartuj system, zanim zaczniesz używać nowych bibliotek/narzędzi.",
748 - "stats_base": "Baza (obraz) zarządzana",
749 - },
750 -}
751 -
752 -# ── Tłumaczenia z PLIKÓW (nadpisują/rozszerzają wbudowane PL/EN) ─────────────
753 -# Kolejność: PAG_LANG_DIR (env) → /etc/pag/lang → /usr/share/pag/lang →
754 -# ./pag-lang obok binarki (dev). Brak plików NIE jest błędem – zostaje
755 -# wbudowany słownik T (fallback), więc pag zawsze działa.
756 -# Przykład pliku (pag-lang/pl.json): {"app_title": "...", "usage": "..."}.
757 -def _load_lang_files() -> None:
758 - # PAG_LANG_NO_FILES=1 → pomiń pliki (używane przy eksporcie --lang-extract,
759 - # żeby wyeksportować CZYSTE wbudowane słowniki, bez starych nadpisań).
760 - if os.environ.get("PAG_LANG_NO_FILES") == "1":
761 - return
762 - dirs = []
763 - _env = os.environ.get("PAG_LANG_DIR")
764 - if _env:
765 - dirs.append(_env)
766 - # __file__ bywa niedostępne, gdy moduł jest exec/frozen (np. harness
767 - # instalacyjny) – liczymy wtedy od ścieżki programu, zamiast wywalać
768 - # NameError przy samym imporcie.
769 - _self = globals().get("__file__") or sys.argv[0] or "pag"
770 - dirs += ["/etc/pag/lang", "/usr/share/pag/lang",
771 - os.path.join(os.path.dirname(os.path.abspath(_self)), "pag-lang")]
772 - for _d in dirs:
773 - for _code in list(T.keys()) + ["pl", "en", "de"]:
774 - _p = os.path.join(_d, f"{_code}.json")
775 - try:
776 - with open(_p, "r", encoding="utf-8") as _fh:
777 - _data = json.load(_fh)
778 - if isinstance(_data, dict):
779 - # Merge (nie replace): klucze nieobecne w pliku zachowują
780 - # wbudowane tłumaczenie. Puste wartości pomijamy, żeby
781 - # niekompletny/uszkodzony plik nie wyczyścił komunikatu.
782 - _clean = {str(k): str(v) for k, v in _data.items()
783 - if str(v).strip()}
784 - T.setdefault(_code, {}).update(_clean)
785 - except (OSError, ValueError):
786 - continue
787 -
788 -
789 -_load_lang_files()
790 -
791 -def _(key: str, *args, **kwargs) -> str:
792 - """Tłumaczy klucz i formatuje argumenty.
793 -
794 - Dla LANG=pl preferuje wariant „<key>_pl” (np. komunikaty bezpieczeństwa
795 - mają krótkie wersje PL obok bazy EN), potem zwykły klucz, potem EN/klicz.
796 - """
797 - if LANG == "pl":
798 - _pl = T.get("pl", {})
799 - msg = _pl.get(key + "_pl") or _pl.get(key) or T["en"].get(key, key)
800 - else:
801 - msg = T.get(LANG, T["en"]).get(key, T["en"].get(key, key))
802 - if args or kwargs:
803 - return msg.format(*args, **kwargs)
804 - return msg
805 -
806 -
807 -def _ask_confirm() -> bool:
808 - """Pytanie potwierdzające (T/n). PAG_YES=1 → zawsze tak.
809 -
810 - EOF/brak terminala (stdin zamknięty, np. ssh bez TTY, cron, subprocess
811 - panelu webowego) → NIE – anuluj, nie wykonuj operacji bez potwierdzenia
812 - (inaczej input() rzuca EOFError i pag pada tracebackiem).
813 - Enter → tak (domyślne Y/n).
814 - """
815 - if os.environ.get("PAG_YES", "") == "1":
816 - print(_("continue_q") + " t (--yes)")
817 - return True
818 - try:
819 - ans = input(_("continue_q")).strip().lower()
820 - except (EOFError, KeyboardInterrupt):
821 - print(f"\n ⚠ {_('no_tty')}")
822 - return False
823 - return not ans or ans in ("t", "y")
824 -
825 -
826 -# =============================================================================
827 -# ŚCIEŻKI
828 -# =============================================================================
829 -PAG_ROOT = os.environ.get("PAG_ROOT", "/")
830 -PAG_DB = "/var/lib/pag"
831 -PAG_CACHE = "/var/cache/pag"
832 -PAG_CONF = "/etc/pag"
833 -REPO_CACHE = "/var/cache/pag/repos"
834 -REPOS_CONF = "/etc/pag/repos.conf"
835 -REPOS_DIR = PAG_CONF + "/repos" # drop-in: /etc/pag/repos/<nazwa>.conf
836 -INSTALLED_DB = "/var/lib/pag/installed.json"
837 -FILES_DB_SQL = "/var/lib/pag/files.db" # SQLite!
838 -WORLD_FILE = "/var/lib/pag/world"
839 -PINNED_FILE = "/var/lib/pag/pinned.json"
840 -HISTORY_FILE = "/var/lib/pag/history.json"
841 -LOCK_FILE = "/var/lib/pag/pag.lock"
842 -STAGING_DIR = "/.pag_staging" # na tej samej partycji co / (unikamy EXDEV)
843 -PKG_EXT = ".pag"
844 -REPO_CACHE_TTL = 3600
845 -MAX_PKG_SIZE = 2 * 1024 * 1024 * 1024 # 2 GB – maksymalny rozmiar paczki
846 -BASE_MANIFEST = "/usr/share/pag/base.json" # baza z obrazu ISO (pag base/adopt)
847 -
848 -# ── UPRZYWILEJOWANE PLIKI ────────────────────────────────────────────────────
849 -# Domyślnie pag zdejmuje bit SUID i wymusza właściciela root:root. Niektóre
850 -# programy MUSZĄ jednak zachować setuid/setgid albo grupę inną niż root
851 -# (/usr/bin/sudo, /usr/bin/passwd, /usr/bin/unix_chkpwd,
852 -# /usr/lib/dbus-daemon-launch-helper). Bez tego tracą możliwość działania
853 -# po aktualizacji przez pag (np. użytkownik nie zmieni hasła).
854 -#
855 -# Bezpieczeństwo: zawartość pakietu jest uwierzytelniona (podpis GPG repo +
856 -# przypięty fingerprint + SHA256 całego pakietu), więc metadane w nim są
857 -# zaufane tak samo jak same pliki. Zachowujemy uprawnienia WYŁĄCZNIE dla
858 -# ścieżek z tej listy (albo z pola `privileged:` receptury, które pagbuild
859 -# zapisuje w metadata.json).
860 -PRIVILEGED_PATHS = frozenset({
861 - "/usr/bin/cdda2wav", "/usr/bin/cdrecord",
862 - "/usr/bin/chage", "/usr/bin/expiry",
863 - "/usr/bin/fcrondyn", "/usr/bin/fcronsighup", "/usr/bin/fcrontab",
864 - "/usr/bin/firejail", "/usr/bin/fping",
865 - "/usr/bin/fusermount", "/usr/bin/fusermount3",
866 - "/usr/bin/gpasswd", "/usr/bin/ksu", "/usr/bin/lockfile",
867 - "/usr/bin/mount", "/usr/bin/mount.nfs",
868 - "/usr/bin/newgidmap", "/usr/bin/newuidmap",
869 - "/usr/bin/passwd", "/usr/bin/ping", "/usr/bin/ping6",
870 - "/usr/bin/procmail", "/usr/bin/readcd", "/usr/bin/rscsi",
871 - "/usr/bin/screen", "/usr/bin/screen-5.0.2",
872 - "/usr/bin/sg", "/usr/bin/su", "/usr/bin/sudo", "/usr/bin/traceroute",
873 - "/usr/bin/umount", "/usr/bin/unix_chkpwd", "/usr/bin/wall",
874 - "/usr/lib/dbus-daemon-launch-helper",
875 - "/usr/lib/httpd/suexec",
876 - "/usr/lib/utempter/utempter",
877 - "/usr/lib/xscreensaver/xscreensaver-auth",
878 - "/usr/libexec/libgtop_server2",
879 - "/usr/libexec/qemu-bridge-helper",
880 - "/usr/libexec/ssh-keysign",
881 - "/usr/libexec/xf86-video-intel-backlight-helper",
882 - "/opt/google/chrome/chrome-sandbox",
883 - "/opt/gitkraken/chrome-sandbox",
884 - "/opt/VirtualBox/VBoxHeadless", "/opt/VirtualBox/VBoxNetAdpCtl",
885 - "/opt/VirtualBox/VBoxNetDHCP", "/opt/VirtualBox/VBoxVolInfo",
886 - "/opt/VirtualBox/VirtualBoxVM",
887 -})
888 -ALLOWED_PKG_RE = re.compile(r'^[a-zA-Z0-9][a-zA-Z0-9._+@-]*$')
889 -
890 -# Bezpieczeństwo / audyt
891 -AUDIT_LOG = "/var/log/pag/audit.log" # dziennik operacji krytycznych (hooki, self-update)
892 -TRUST_DB = "/etc/pag/trusted.json" # mapa repo_url → fingerprint klucza podpisującego
893 -HOOK_API_VERSION = "1" # wersjonowane API hooków (env PKG_HOOK_API)
894 -
895 -# =============================================================================
896 -# IMMUTABLE OS – DEPLOYMENTY
897 -# =============================================================================
898 -# Model: zamiast mutować /, każda operacja tworzy NOWY deployment.
899 -# /var, /etc, /home są współdzielone między deploymentami.
900 -#
901 -# STRUKTURA:
902 -# /.deployments/
903 -# active → 20260723T120000 (symlink do aktywnego)
904 -# 20260723T120000/
905 -# usr/ bin/ lib/ lib64/ ... (pełny system)
906 -# var → /var (symlink do współdzielonego)
907 -# etc → /etc
908 -# home → /home
909 -# ...
910 -#
911 -# Jak to działa:
912 -# 1. pag install → kopiuje active → nowy deployment + nakłada zmiany → switch symlinka
913 -# 2. pag remove → kopiuje active → nowy deployment - usuwa pliki → switch symlinka
914 -# 3. pag deploy-rollback → przełącza active symlink na poprzedni deployment
915 -# 4. Przy starcie systemu: initrd montuje /.deployments/active jako /
916 -# =============================================================================
917 -
918 -DEPLOYMENTS_DIR = "/.deployments"
919 -ACTIVE_LINK = "/.deployments/active"
920 -DEPLOYMENTS_DB = "/var/lib/pag/deployments.json"
921 -
922 -# Ścieżki współdzielone – NIE wchodzą do deploymentu (są symlinkami do /...)
923 -SHARED_PATHS = {
924 - "/var", "/etc", "/home", "/root", "/tmp", "/run",
925 - "/dev", "/proc", "/sys", "/mnt", "/media", "/srv",
926 - # /boot współdzielone: jądro + initramfs są wspólne dla wszystkich
927 - # deploymentów (inaczej każdy trzyma własną ~50-100 MB kopię). GRUB
928 - # wskazuje na /.deployments/<id>/boot → symlink do /boot.
929 - "/boot",
930 - "/.deployments", "/.pag_staging",
931 -}
932 -
933 -def _is_shared_path(rel: str) -> bool:
934 - """Sprawdza czy ścieżka należy do katalogów współdzielonych (poza deploymentem)."""
935 - for sp in SHARED_PATHS:
936 - if rel == sp or rel.startswith(sp + "/"):
937 - return True
938 - return False
939 -
940 -def _is_config_path(rel: str) -> bool:
941 - """Czy ścieżka to plik konfiguracyjny (/etc/...)?
942 -
943 - Dla takich plików stosujemy .pacnew/.pacsave (zachowanie zmian użytkownika)
944 - zamiast bezwarunkowego nadpisania/usunięcia."""
945 - p = rel.lstrip("/")
946 - return p == "etc" or p.startswith("etc/")
947 -
948 -# Wrażliwa konfiguracja auth/systemowa – NIGDY nie nadpisujemy jej po cichu.
949 -# Nadpisanie /etc/pam.d/system-* przez pakiet (np. shadow) potrafi zablokować
950 -# logowanie/sudo („account validation failure”); dla tych ścieżek zawsze robimy
951 -# .pacnew, gdy treść na dysku różni się od tej z pakietu.
952 -_SENSITIVE_CONFIG_RE = re.compile(
953 - r'^(pam\.d/|security/|sudoers$|sudoers\.d/|shadow$|gshadow$|passwd$|group$|'
954 - r'login\.defs$|nsswitch\.conf$|default/useradd$)')
955 -
956 -def _is_sensitive_config(rel: str) -> bool:
957 - """Czy rel to wrażliwy plik /etc (PAM, sudoers, shadow, login.defs…)?"""
958 - p = rel.lstrip("/")
959 - if not p.startswith("etc/"):
960 - return False
961 - return bool(_SENSITIVE_CONFIG_RE.match(p[4:]))
962 -
963 -def _get_deployment_root() -> str:
964 - """Zwraca ścieżkę do aktywnego deploymentu, lub PAG_ROOT jeśli tryb niemutowalny wyłączony."""
965 - if os.environ.get("PAG_IMMUTABLE", "") in ("0", "no", "false", ""):
966 - return PAG_ROOT
967 - if os.path.islink(ACTIVE_LINK):
968 - return os.readlink(ACTIVE_LINK)
969 - if os.path.isdir(ACTIVE_LINK):
970 - return ACTIVE_LINK
971 - # Brak deploymentów – użyj /
972 - return PAG_ROOT
973 -
974 -def _load_deployments() -> List[dict]:
975 - """Wczytuje historię deploymentów."""
976 - if not os.path.exists(DEPLOYMENTS_DB):
977 - return []
978 - try:
979 - return json.load(open(DEPLOYMENTS_DB))
980 - except Exception:
981 - return []
982 -
983 -def _save_deployments(deployments: List[dict]):
984 - os.makedirs(os.path.dirname(DEPLOYMENTS_DB), exist_ok=True)
985 - json.dump(deployments, open(DEPLOYMENTS_DB, "w"), indent=2)
986 -
987 -def _create_deployment(pkg_names: List[str], action: str) -> Tuple[str, str]:
988 - """
989 - Tworzy nowy deployment przez skopiowanie aktywnego (CoW) i zwraca jego ścieżkę.
990 - Zwraca (deployment_dir, deployment_id).
991 - """
992 - deploy_id = datetime.now().strftime("%Y%m%dT%H%M%S")
993 - deploy_dir = os.path.join(DEPLOYMENTS_DIR, deploy_id)
994 - os.makedirs(DEPLOYMENTS_DIR, exist_ok=True)
995 -
996 - active = _get_deployment_root()
997 -
998 - if os.path.isdir(active) and active != PAG_ROOT:
999 - # Trójstopniowa strategia kopiowania deploymentu:
1000 - # 1. reflink (CoW – btrfs, xfs) → 0 MB kopiowane
1001 - # 2. hardlink (linki twarde) → 0 MB kopiowane, tylko inody
1002 - # 3. zwykłe cp (ostateczność) → pełna kopia
1003 - print(f" ⚡ Kopiowanie aktywnego deploymentu...")
1004 - copied = False
1005 - for method, cmd, label in [
1006 - ("reflink", ["cp", "--reflink=auto", "-a", active + "/.", deploy_dir + "/"], "CoW (reflink)"),
1007 - ("hardlink", ["cp", "-al", active + "/.", deploy_dir + "/"], "hardlinki"),
1008 - ("copy", ["cp", "-a", active + "/.", deploy_dir + "/"], "pełna kopia"),
1009 - ]:
1010 - try:
1011 - subprocess.run(cmd, check=True, timeout=600, capture_output=True)
1012 - print(f" ✅ Deployment: {deploy_id} ({label})")
1013 - copied = True
1014 - break
1015 - except subprocess.CalledProcessError:
1016 - if method == "copy":
1017 - raise # ostatnia deska – niech leci wyjątek
1018 - continue
1019 - if not copied:
1020 - raise RuntimeError("Nie udało się skopiować deploymentu żadną metodą")
1021 - else:
1022 - # Pierwszy deployment – tylko katalogi szkieletowe
1023 - # /boot celowo POMINIĘTE – jest współdzielone (SHARED_PATHS); poniższa
1024 - # pętla utworzy w deploymencie symlink boot → /boot.
1025 - for d in ["/usr", "/lib", "/lib64", "/bin", "/sbin", "/opt"]:
1026 - if os.path.isdir(d):
1027 - dest = os.path.join(deploy_dir, d.lstrip("/"))
1028 - os.makedirs(dest, exist_ok=True)
1029 - print(f" ✅ Pierwszy deployment: {deploy_id}")
1030 -
1031 - # Utwórz symlinki do współdzielonych katalogów
1032 - for sp in SHARED_PATHS:
1033 - link_dst = os.path.join(deploy_dir, sp.lstrip("/"))
1034 - if not os.path.lexists(link_dst) and os.path.isdir(sp):
1035 - os.symlink(sp, link_dst)
1036 -
1037 - # Zapisz w bazie deploymentów
1038 - deployments = _load_deployments()
1039 - deployments.append({
1040 - "id": deploy_id,
1041 - "action": action,
1042 - "packages": pkg_names,
1043 - "timestamp": datetime.now().isoformat(),
1044 - "active": True,
1045 - })
1046 - # Oznacz poprzednie jako nieaktywne
1047 - for d in deployments[:-1]:
1048 - d["active"] = False
1049 - _save_deployments(deployments)
1050 -
1051 - return deploy_dir, deploy_id
1052 -
1053 -def _switch_deployment(deploy_dir: str) -> bool:
1054 - """Atomowo przełącza aktywny deployment przez podmianę symlinka."""
1055 - tmp_link = ACTIVE_LINK + ".new"
1056 - if os.path.lexists(tmp_link):
1057 - os.remove(tmp_link)
1058 - os.symlink(deploy_dir, tmp_link)
1059 - os.rename(tmp_link, ACTIVE_LINK) # atomowe na tym samym FS
1060 - return True
1061 -
1062 -DEFAULT_REPOS = [
1063 - "https://repo.paganlinux.eu/stable/",
1064 -]
1065 -
1066 -# =============================================================================
1067 -# INICJALIZACJA
1068 -# =============================================================================
1069 -
1070 -def ensure_dirs():
1071 - for d in [PAG_DB, PAG_CACHE, PAG_CONF, REPO_CACHE, REPOS_DIR, STAGING_DIR, DEPLOYMENTS_DIR]:
1072 - os.makedirs(d, exist_ok=True)
1073 - for f, default in [
1074 - (REPOS_CONF, "\n".join(DEFAULT_REPOS) + "\n"),
1075 - (INSTALLED_DB, "{}"),
1076 - (PINNED_FILE, "{}"),
1077 - (HISTORY_FILE, "[]"),
1078 - ]:
1079 - if not os.path.exists(f):
1080 - with open(f, "w") as fh: fh.write(default)
1081 - if not os.path.exists(WORLD_FILE):
1082 - Path(WORLD_FILE).touch()
1083 - if not os.path.exists(GPG_HOME):
1084 - os.makedirs(GPG_HOME, exist_ok=True)
1085 - os.chmod(GPG_HOME, 0o700)
1086 - _gpg_run("--list-keys", capture_output=True)
1087 - # Inicjalizuj SQLite
1088 - _db_init()
1089 - # Wyczyść staging po poprzednim przerwanym buildzie/instalacji
1090 - if os.path.isdir(STAGING_DIR):
1091 - for entry in os.listdir(STAGING_DIR):
1092 - if entry == "backups":
1093 - continue # backupy starych wersji – potrzebne do `pag rollback`
1094 - path = os.path.join(STAGING_DIR, entry)
1095 - try:
1096 - if os.path.isfile(path) or os.path.islink(path):
1097 - os.unlink(path)
1098 - elif os.path.isdir(path):
1099 - shutil.rmtree(path, ignore_errors=True)
1100 - except OSError:
1101 - pass
1102 -
1103 -# =============================================================================
1104 -# SQLITE – BAZA PLIKÓW (poprawne zarządzanie połączeniami)
1105 -# =============================================================================
1106 -
1107 -from contextlib import contextmanager
1108 -
1109 -@contextmanager
1110 -def _db_session(readonly: Optional[bool] = None):
1111 - """Context manager – gwarantuje zamknięcie połączenia.
1112 -
1113 - Gdy katalog bazy nie jest zapisywalny (np. komenda read-only uruchomiona
1114 - jako zwykły user), otwieramy połączenie w trybie read-only. Inaczej
1115 - `PRAGMA journal_mode=WAL` próbuje pisać i kończy się błędem
1116 - „attempt to write a readonly database” zamiast zwrócić wynik.
1117 - """
1118 - if readonly is None:
1119 - readonly = not os.access(os.path.dirname(FILES_DB_SQL) or ".", os.W_OK)
1120 - if readonly:
1121 - # Katalog bazy nie jest zapisywalny (np. komenda read-only uruchomiona
1122 - # jako zwykły user). Baza jest w trybie WAL, więc SQLite przy `mode=ro`
1123 - # próbuje utworzyć plik `-shm` w katalogu – bez prawa zapisu kończy się
1124 - # to błędem „attempt to write a readonly database” nawet przy SELECT.
1125 - # Dlatego próbujemy zwykłego `mode=ro`, a gdy zawiedzie, otwieramy z
1126 - # `immutable=1` (SQLite pomija wtedy WAL/SHM i czyta ostatni
1127 - # checkpoint). Przy równoległym zapisie roota odczyt może być chwilowo
1128 - # nieaktualny – dla komend diagnostycznych (files/list/verify) to OK.
1129 - conn = sqlite3.connect(f"file:{FILES_DB_SQL}?mode=ro", uri=True, timeout=15)
1130 - try:
1131 - conn.execute("SELECT 1 FROM sqlite_master LIMIT 1")
1132 - except sqlite3.OperationalError:
1133 - conn.close()
1134 - conn = sqlite3.connect(
1135 - f"file:{FILES_DB_SQL}?mode=ro&immutable=1", uri=True, timeout=15)
1136 - else:
1137 - conn = sqlite3.connect(FILES_DB_SQL, timeout=15)
1138 - conn.execute("PRAGMA journal_mode=WAL")
1139 - conn.execute("PRAGMA synchronous=NORMAL")
1140 - conn.execute("PRAGMA foreign_keys=ON")
1141 - conn.execute("PRAGMA busy_timeout=15000")
1142 - conn.row_factory = sqlite3.Row
1143 - try:
1144 - yield conn
1145 - if not readonly:
1146 - conn.commit()
1147 - except Exception:
1148 - if not readonly:
1149 - conn.rollback()
1150 - raise
1151 - finally:
1152 - conn.close()
1153 -
1154 -
1155 -def _db_init():
1156 - """Tworzy tabele SQLite jeśli nie istnieją."""
1157 - with _db_session() as db:
1158 - db.execute("""
1159 - CREATE TABLE IF NOT EXISTS files (
1160 - id INTEGER PRIMARY KEY AUTOINCREMENT,
1161 - path TEXT NOT NULL,
1162 - package TEXT NOT NULL,
1163 - sha256 TEXT,
1164 - size INTEGER,
1165 - is_symlink INTEGER DEFAULT 0,
1166 - symlink_target TEXT,
1167 - UNIQUE(path, package)
1168 - )
1169 - """)
1170 - db.execute("CREATE INDEX IF NOT EXISTS idx_files_path ON files(path)")
1171 - db.execute("CREATE INDEX IF NOT EXISTS idx_files_pkg ON files(package)")
1172 - db.execute("""
1173 - CREATE TABLE IF NOT EXISTS file_checksums (
1174 - path TEXT PRIMARY KEY,
1175 - sha256 TEXT NOT NULL,
1176 - installed_at TEXT
1177 - )
1178 - """)
1179 - db.commit()
1180 -
1181 -def _db_record_files(pkg_name: str, files: List[dict]):
1182 - """Zapisuje pliki do SQLite (obsługuje symlinki)."""
1183 - with _db_session() as db:
1184 - # Jawna transakcja – atomowość obu zapisów i szybsze wykrycie blokady
1185 - try:
1186 - db.execute("BEGIN IMMEDIATE")
1187 - except sqlite3.OperationalError:
1188 - pass # transakcja już otwarta (implicit)
1189 - db.executemany(
1190 - "INSERT OR REPLACE INTO files (path, package, sha256, size, is_symlink, symlink_target) "
1191 - "VALUES (?,?,?,?,?,?)",
1192 - [(f["path"], pkg_name, f.get("sha256",""), f.get("size",0),
1193 - f.get("is_symlink", 0), f.get("symlink_target", ""))
1194 - for f in files]
1195 - )
1196 - db.executemany(
1197 - "INSERT OR REPLACE INTO file_checksums (path, sha256, installed_at) VALUES (?,?,?)",
1198 - [(f["path"], f.get("sha256",""), datetime.now().isoformat())
1199 - for f in files if f.get("sha256")]
1200 - )
1201 -
1202 -def _db_get_package_files(pkg_name: str) -> List[str]:
1203 - with _db_session() as db:
1204 - return [r["path"] for r in db.execute(
1205 - "SELECT DISTINCT path FROM files WHERE package=?", (pkg_name,)
1206 - )]
1207 -
1208 -def _db_get_file_owners(filepath: str) -> List[str]:
1209 - """Zwraca listę pakietów będących właścicielami pliku."""
1210 - with _db_session() as db:
1211 - return [r["package"] for r in db.execute(
1212 - "SELECT package FROM files WHERE path=?", (filepath,)
1213 - )]
1214 -
1215 -def _db_remove_package_files(pkg_name: str):
1216 - with _db_session() as db:
1217 - db.execute("DELETE FROM files WHERE package=?", (pkg_name,))
1218 - db.commit()
1219 -
1220 -def _db_get_all_file_checksums() -> Dict[str, str]:
1221 - with _db_session() as db:
1222 - return {r["path"]: r["sha256"] for r in db.execute("SELECT path, sha256 FROM file_checksums")}
1223 -
1224 -def _db_get_package_checksums(pkg_name: str) -> Dict[str, str]:
1225 - """Sumy SHA256 zapisane dla plików należących do pakietu.
1226 -
1227 - Używane do wykrycia, czy użytkownik zmodyfikował plik konfiguracyjny
1228 - (porównanie z sumą z chwili instalacji) – serce mechanizmu .pacnew/.pacsave.
1229 - """
1230 - with _db_session() as db:
1231 - return {r["path"]: r["sha256"] for r in db.execute(
1232 - "SELECT fc.path AS path, fc.sha256 AS sha256 FROM file_checksums fc "
1233 - "JOIN files f ON f.path = fc.path WHERE f.package=?", (pkg_name,))}
1234 -
1235 -
1236 -def _db_count_files() -> int:
1237 - with _db_session() as db:
1238 - return db.execute("SELECT COUNT(*) FROM files").fetchone()[0]
1239 -
1240 -# =============================================================================
1241 -# BLOKADA
1242 -# =============================================================================
1243 -
1244 -class DatabaseLock:
1245 - """Blokada plikowa (flock) – jądro zwalnia ją AUTOMATYCZNIE, gdy proces
1246 - ginie (kill -9, twardy reset). Stary PID-file miał race condition: po
1247 - śmierci pag PID mógł zostać przydzielony obcemu procesowi (PID reuse)
1248 - i pag odmawiał działania na zawsze („baza zablokowana”).
1249 - """
1250 - def __init__(self):
1251 - self._f = None
1252 - def __enter__(self):
1253 - os.makedirs(os.path.dirname(LOCK_FILE), exist_ok=True)
1254 - self._f = open(LOCK_FILE, "w")
1255 - try:
1256 - # LOCK_NB: rzuca wyjątek zamiast czekać w nieskończoność
1257 - fcntl.flock(self._f, fcntl.LOCK_EX | fcntl.LOCK_NB)
1258 - except BlockingIOError:
1259 - print(f"❌ {_('db_locked')}", file=sys.stderr)
1260 - print(f" {_('db_lock_hint', LOCK_FILE)}", file=sys.stderr)
1261 - sys.exit(1)
1262 - self._f.write(str(os.getpid()))
1263 - self._f.flush()
1264 - return self
1265 - def __exit__(self, *args):
1266 - if self._f:
1267 - try:
1268 - fcntl.flock(self._f, fcntl.LOCK_UN)
1269 - except OSError:
1270 - pass
1271 - self._f.close()
1272 - self._f = None
1273 - # Uwaga: NIE usuwamy pliku blokady. Stały plik + flock na inode to jedyny
1274 - # bezpieczny wzorzec – os.remove(), gdy inny proces trzyma blokadę na starym
1275 - # inode, otwiera wyścig (nowy proces blokowałby nowo utworzony inode).
1276 -
1277 -
1278 -class SelfUpdateLock:
1279 - """Blokada podmiany binarki pag podczas self-update.
1280 -
1281 - Niezależna od DatabaseLock (inny plik) – cmd_self_update może zostać
1282 - wywołane poza globalną blokadą (np. z zewnętrznego skryptu), a dwie
1283 - równoległe aktualizacje pisałyby do tego samego `dst.new`; `os.replace`
1284 - mógłby wtedy podmienić plik w trakcie wykonywania (uszkodzony pag).
1285 - """
1286 - def __init__(self):
1287 - self._f = None
1288 -
1289 - def __enter__(self):
1290 - lock_path = LOCK_FILE + ".self-update"
1291 - os.makedirs(os.path.dirname(lock_path), exist_ok=True)
1292 - self._f = open(lock_path, "w")
1293 - try:
1294 - fcntl.flock(self._f, fcntl.LOCK_EX | fcntl.LOCK_NB)
1295 - except BlockingIOError:
1296 - self._f.close()
1297 - self._f = None
1298 - print("❌ Inna aktualizacja pag jest w toku – spróbuj ponownie później.",
1299 - file=sys.stderr)
1300 - sys.exit(1)
1301 - self._f.write(str(os.getpid()))
1302 - self._f.flush()
1303 - return self
1304 -
1305 - def __exit__(self, *args):
1306 - if self._f:
1307 - try:
1308 - fcntl.flock(self._f, fcntl.LOCK_UN)
1309 - except OSError:
1310 - pass
1311 - self._f.close()
1312 - self._f = None
1313 -
1314 -# =============================================================================
1315 -# POMOCNICZE
1316 -# =============================================================================
1317 -
1318 -
1319 -_ALLOWED_PREFIXES = ("/usr/", "/etc/", "/var/", "/opt/",
1320 - "/boot/", "/lib/", # kernel: vmlinuz/System.map + moduły (usrmerge: lib→usr/lib)
1321 - # Pliki wewnętrzne paczki .pkg.tar.xz
1322 - "metadata.json", "data.tar.xz", "hooks/",
1323 - "sums.json")
1324 -
1325 -def _check_path_safety(name: str) -> bool:
1326 - # Normalizuj – usuń leading ./
1327 - if name.startswith("./"):
1328 - name = name[2:]
1329 - if name in (".", ""):
1330 - return True
1331 - # Porównuj z prefiksami BEZ wiodącego '/', by zarówno "/usr/bin/ls", jak i
1332 - # wewnętrzne pliki pakietu ("hooks/pre-install", "data.tar.xz") przechodziły.
1333 - norm = name.lstrip("/")
1334 - for prefix in _ALLOWED_PREFIXES:
1335 - p = prefix.lstrip("/").rstrip("/")
1336 - if norm == p or norm.startswith(p + "/"):
1337 - return True
1338 - return False
1339 -
1340 -
1341 -def _validate_pkg_name(name):
1342 - return bool(ALLOWED_PKG_RE.match(name))
1343 -
1344 -
1345 -
1346 -def _audit(msg):
1347 - from datetime import datetime, timezone
1348 - os.makedirs(os.path.dirname(AUDIT_LOG), exist_ok=True)
1349 - with open(AUDIT_LOG, "a") as f:
1350 - f.write(datetime.now(timezone.utc).isoformat() + " " + msg + "\n")
1351 -
1352 -def _strip_suid(path):
1353 - try:
1354 - st = os.stat(path)
1355 - if st.st_mode & 0o4000:
1356 - os.chmod(path, st.st_mode & ~0o4000)
1357 - print(f" {_("sec_suid", path=path)}")
1358 - except OSError:
1359 - pass
1360 -
1361 -def _check_downgrade(pkg_name, new_ver, installed_db):
1362 - if pkg_name in installed_db:
1363 - old = installed_db[pkg_name].get("version", "0")
1364 - if new_ver < old:
1365 - print(f" {_("sec_downgrade", pkg=pkg_name, new=new_ver, old=old)}")
1366 - return False
1367 - return True
1368 -
1369 -def _safe_extractall(tar: tarfile.TarFile, dest: str, *, preserve_perms: bool = True,
1370 - privileged=frozenset()):
1371 - """
1372 - Bezpieczne rozpakowanie archiwum tar z ochroną przed Directory Traversal.
1373 -
1374 - Działa na Python < 3.12 (gdzie parametr 'filter' w extractall nie istnieje)
1375 - oraz na Python 3.12+. W przeciwieństwie do filtra 'data' z Pythona 3.12,
1376 - zachowuje bity uprawnień POSIX (SUID, SGID, sticky) – preserve_perms=True.
1377 -
1378 - Ochrona oparta jest na FINALNEJ ścieżce (os.path.realpath), nie tylko na
1379 - prostym sprawdzaniu stringa:
1380 - - Blokuje ścieżki absolutne i z '..' (path traversal)
1381 - - Blokuje symlinki/hardlinki, których cel wychodzi poza dest
1382 - - Blokuje zapis "przez" złośliwy symlink, który został wcześniej
1383 - rozpakowany (np. katalog → /etc, potem zapis katalog/plik)
1384 - - Zachowuje oryginalne uprawnienia plików
1385 - """
1386 - dest_real = os.path.realpath(dest)
1387 - os.makedirs(dest_real, exist_ok=True)
1388 -
1389 - def _target_within(path: str) -> bool:
1390 - try:
1391 - return os.path.commonpath([dest_real, os.path.realpath(path)]) == dest_real
1392 - except ValueError:
1393 - # różne napędy / ścieżki nie da się wspólnie porównać → odrzuć
1394 - return False
1395 -
1396 - for member in tar.getmembers():
1397 - name = member.name
1398 -
1399 - # --- Ochrona przed Directory Traversal (szybkie string-checki) ---
1400 - if name.startswith('/'):
1401 - continue
1402 - if '..' in name.split('/'):
1403 - continue
1404 - # Zablokuj bajt NUL i backslash (bugi/obejścia tarfile na niektórych platformach)
1405 - if '\x00' in name or '\\' in name:
1406 - continue
1407 - if not _check_path_safety(name):
1408 - print(f" BLOCKED: {name}")
1409 - continue
1410 -
1411 - target = os.path.join(dest, name)
1412 -
1413 - # --- Ochrona na podstawie finalnej ścieżki ---
1414 - # Jeśli którykolwiek komponent nadrzędny jest (złośliwym) symlinkiem
1415 - # wskazującym poza dest, realpath to wykryje – zablokuj zapis.
1416 - if not _target_within(target):
1417 - print(f" BLOCKED (escape): {name}")
1418 - continue
1419 -
1420 - # --- Ochrona dla symlinków i hardlinków ---
1421 - if member.issym() or member.islnk():
1422 - link = member.linkname
1423 - # Szybkie odrzucenie linków absolutnych / z '..'
1424 - if link.startswith('/') or '..' in link.split('/'):
1425 - continue
1426 - # Sprawdź, gdzie realnie prowadzi cel linku (względem katalogu linku)
1427 - link_target = os.path.join(os.path.dirname(target), link)
1428 - if not _target_within(link_target):
1429 - print(f" BLOCKED (link escape): {name} -> {link}")
1430 - continue
1431 -
1432 - # Rozpakuj z zachowaniem metadanych. Python 3.12+ wymaga jawnego
1433 - # `filter=` (inaczej DeprecationWarning, a w 3.14+ błąd).
1434 - # UWAGA: 'fully_trusted' CELOWO pomija wbudowane filtry bezpieczeństwa
1435 - # Pythona – to nie przeoczenie. Nasza walidacja powyżej (path traversal,
1436 - # NUL/backslash, escape przez symlink, linki wychodzące poza dest) jest
1437 - # równoważna lub ostrzejsza, a 'fully_trusted' pozwala zachować bity
1438 - # SUID/SGID/sticky, które filtr 'data' by usunął (np. /usr/bin/sudo).
1439 - # SUID jest i tak zdejmowany przez _strip_suid() tuż po rozpakowaniu.
1440 - try:
1441 - if hasattr(tarfile, 'data_filter'):
1442 - # Python 3.12+
1443 - tar.extract(member, dest, set_attrs=preserve_perms, numeric_owner=False,
1444 - filter='fully_trusted')
1445 - else:
1446 - tar.extract(member, dest, set_attrs=preserve_perms, numeric_owner=False)
1447 - except Exception as e:
1448 - print(f" ⚠ Nie rozpakowano {name}: {e}")
1449 - continue
1450 - # Pliki z listy uprzywilejowanej zachowują SUID/SGID; reszta jest
1451 - # czyszczona (ochrona przed SUID niespodziewanym w pakiecie).
1452 - if "/" + os.path.relpath(target, dest_real) not in privileged:
1453 - _strip_suid(target)
1454 -
1455 -
1456 -def _sha256_file(path: str) -> str:
1457 - """SHA256 pliku. Na Python ≥3.11 używa hashlib.file_digest (pętla w C);
1458 - starsze wersje mają fallback z pętlą chunków."""
1459 - with open(path, "rb") as f:
1460 - if hasattr(hashlib, "file_digest"):
1461 - return hashlib.file_digest(f, "sha256").hexdigest()
1462 - h = hashlib.sha256()
1463 - for chunk in iter(lambda: f.read(65536), b""):
1464 - h.update(chunk)
1465 - return h.hexdigest()
1466 -
1467 -def _split_version(v: str):
1468 - """Rozdziela wersję na (release_parts, prerelease_parts).
1469 -
1470 - Przykład: '1.2.0-rc1' → ([1,2,0], ['rc','1']).
1471 - """
1472 - v = v.strip().lower().lstrip("v")
1473 - # build metadata po '+' jest ignorowane przy porównywaniu (semver)
1474 - v = v.split("+", 1)[0]
1475 - # prerelease po '-' lub '_' (np. 1.2.0-rc1, 1.2.0_rc1)
1476 - if "-" in v:
1477 - rel, pre = v.split("-", 1)
1478 - elif "_" in v:
1479 - rel, pre = v.split("_", 1)
1480 - else:
1481 - rel, pre = v, ""
1482 - nums = []
1483 - for part in rel.split("."):
1484 - m = re.match(r"(\d+)", part)
1485 - nums.append(int(m.group(1)) if m else 0)
1486 - pre_parts = [p for p in pre.split(".") if p]
1487 - return nums, pre_parts
1488 -
1489 -
1490 -def _cmp_pre(a, b):
1491 - """Porównuje ciągi identyfikatorów prerelease (reguły semver)."""
1492 - for i in range(max(len(a), len(b))):
1493 - if i >= len(a):
1494 - return -1 # krótszy prerelease jest niższy
1495 - if i >= len(b):
1496 - return 1
1497 - ia, ib = a[i], b[i]
1498 - if ia == ib:
1499 - continue
1500 - na, nb = ia.isdigit(), ib.isdigit()
1501 - if na and nb:
1502 - return 1 if int(ia) > int(ib) else -1
1503 - if na != nb:
1504 - return -1 if na else 1 # identyfikator liczbowy < alfanumeryczny
1505 - return 1 if ia > ib else -1
1506 - return 0
1507 -
1508 -
1509 -def _cmp_version(a: str, b: str) -> int:
1510 - """Porównuje dwie wersje; zwraca -1/0/1. Obsługuje prerelease (rc1, beta...)."""
1511 - a_rel, a_pre = _split_version(a)
1512 - b_rel, b_pre = _split_version(b)
1513 - # Porównaj część release (brakujące komponenty traktuj jako 0)
1514 - for i in range(max(len(a_rel), len(b_rel))):
1515 - xa = a_rel[i] if i < len(a_rel) else 0
1516 - xb = b_rel[i] if i < len(b_rel) else 0
1517 - if xa != xb:
1518 - return 1 if xa > xb else -1
1519 - # Część release równa → decyduje prerelease.
1520 - # Wersja finalna (bez prerelease) jest ZAWSZE nowsza od prerelease.
1521 - if not a_pre and not b_pre:
1522 - return 0
1523 - if not a_pre:
1524 - return 1
1525 - if not b_pre:
1526 - return -1
1527 - return _cmp_pre(a_pre, b_pre)
1528 -
1529 -
1530 -def _version_newer(a: str, b: str) -> bool:
1531 - """True gdy wersja a jest nowsza od b (z poprawną obsługą prerelease)."""
1532 - try:
1533 - return _cmp_version(a, b) > 0
1534 - except Exception:
1535 - return a != b
1536 -
1537 -def load_json(path):
1538 - try:
1539 - with open(path) as f:
1540 - return json.load(f)
1541 - except (FileNotFoundError, json.JSONDecodeError):
1542 - return {}
1543 -
1544 -def save_json(path, data):
1545 - with open(path, "w") as f:
1546 - json.dump(data, f, indent=2)
1547 -
1548 -class PackageInfo:
1549 - __slots__ = ("name","version","release","description","dependencies",
1550 - "size_bytes","sha256","gpg_fp","repo_url","filename","provides","license",
1551 - "provides_so","requires_so","privileged")
1552 - def __init__(self, d, repo=""):
1553 - self.name = d.get("name","?")
1554 - self.version = d.get("version","0")
1555 - self.release = d.get("release", 1)
1556 - self.description = d.get("description","")
1557 - self.dependencies = d.get("dependencies", d.get("depends", []))
1558 - self.size_bytes = d.get("size",0)
1559 - self.sha256 = d.get("sha256","")
1560 - self.gpg_fp = d.get("gpg_fingerprint","")
1561 - self.repo_url = repo
1562 - self.filename = d.get("filename", f"{self.name}-{self.version}{PKG_EXT}")
1563 - self.provides = d.get("provides", []) or []
1564 - self.license = d.get("license", []) or []
1565 - self.provides_so = d.get("provides_so", []) or []
1566 - self.requires_so = d.get("requires_so", []) or []
1567 - # Ścieżki, którym wolno zachować setuid/setgid i grupę (z receptury).
1568 - self.privileged = d.get("privileged", []) or []
1569 -
1570 -# =============================================================================
1571 -# REPOZYTORIA (cache, ETag, GPG)
1572 -# =============================================================================
1573 -
1574 -def _parse_repos_config():
1575 - """Parsuje repozytoria z /etc/pag/repos.conf oraz /etc/pag/repos/*.conf.
1576 -
1577 - Format linii: <url> [fingerprint]
1578 - Opcjonalny `fingerprint` (40 znaków hex) pozwala przypiąć klucz
1579 - podpisujący repo do konkretnego adresu – wtedy TOFU (auto-zaufanie przy
1580 - pierwszym użyciu) nie jest potrzebne, a zmiana klucza = błąd bezpieczeństwa.
1581 -
1582 - Drop-iny (np. stable.conf) są czytane alfabetycznie – pozwalają na
1583 - wygodne dodawanie repo bez dotykania głównego repos.conf
1584 - (np. `echo 'https://repo.paganlinux.eu/stable' > /etc/pag/repos/stable.conf`).
1585 - """
1586 - entries = []
1587 -
1588 - def _read_lines(path):
1589 - if not os.path.exists(path):
1590 - return
1591 - for line in open(path):
1592 - line = line.strip()
1593 - if not line or line.startswith("#"):
1594 - continue
1595 - parts = line.split()
1596 - url = parts[0].rstrip("/")
1597 - fp = parts[1].lower() if len(parts) > 1 else ""
1598 - entries.append({"url": url, "fingerprint": fp or None})
1599 -
1600 - # 1) Legacy: pojedynczy plik /etc/pag/repos.conf
1601 - _read_lines(REPOS_CONF)
1602 - # 2) Drop-in: /etc/pag/repos/<nazwa>.conf (sortowane, stabilna kolejność)
1603 - if os.path.isdir(REPOS_DIR):
1604 - for drop in sorted(os.listdir(REPOS_DIR)):
1605 - if drop.endswith(".conf"):
1606 - _read_lines(os.path.join(REPOS_DIR, drop))
1607 -
1608 - # Dedupe po URL (zachowaj pierwszy wpis – może mieć fingerprint)
1609 - seen, unique = set(), []
1610 - for e in entries:
1611 - if e["url"] not in seen:
1612 - seen.add(e["url"])
1613 - unique.append(e)
1614 -
1615 - if not unique:
1616 - for url in DEFAULT_REPOS:
1617 - # rstrip: get_repos()/_repo_pinned_fp() kluczują URL-e bez ukośnika
1618 - unique.append({"url": url.rstrip("/"), "fingerprint": None})
1619 - return unique
1620 -
1621 -
1622 -def get_repos():
1623 - return [e["url"] for e in _parse_repos_config()]
1624 -
1625 -
1626 -def _repo_pinned_fp(repo_url):
1627 - """Zwraca przypięty fingerprint klucza dla repo (z konfiguracji lub trust DB)."""
1628 - # Normalizacja ukośnika: _parse_repos_config() i trust DB kluczują URL-e BEZ
1629 - # końcowego „/”, a wywołujący podają często DEFAULT_REPOS[0] Z ukośnikiem.
1630 - # Bez tego przypięty klucz nie był znajdowany i lokalny .pag dostawał
1631 - # fałszywe „Brak przypiętego klucza repo” mimo poprawnego wpisu w trusted.json.
1632 - repo_url = repo_url.rstrip("/")
1633 - by_url = {e["url"]: e["fingerprint"] for e in _parse_repos_config()}
1634 - if by_url.get(repo_url):
1635 - return by_url[repo_url]
1636 - db = _load_trust_db()
1637 - fp = db.get(repo_url)
1638 - return fp.lower() if fp else None
1639 -
1640 -def _repo_cache_path(url):
1641 - return os.path.join(REPO_CACHE, url.replace("://","_").replace("/","_").replace(".","_") + ".json")
1642 -
1643 -def _repo_etag_path(url): return _repo_cache_path(url) + ".etag"
1644 -def _repo_ts_path(url): return _repo_cache_path(url) + ".ts"
1645 -
1646 -# Informacja (raz na uruchomienie), gdy cache repozytoriów jest tylko-do-odczytu –
1647 -# np. komendy read-only (`pag info`, `pag search`…) jako zwykły user: nie ma sensu
1648 -# ani prawa odświeżać /var/cache/pag/repos, więc używamy lokalnej kopii indeksu.
1649 -_cache_ro_notice_done = False
1650 -
1651 -def _cache_ro_notice():
1652 - global _cache_ro_notice_done
1653 - if _cache_ro_notice_done:
1654 - return
1655 - _cache_ro_notice_done = True
1656 - print(f" ⚠ {_('cache_ro', cache=REPO_CACHE)}", file=sys.stderr)
1657 -
1658 -def _load_repo_cache(cp: str) -> Optional[list]:
1659 - """Wczytuje cache indeksu repo; zwraca None gdy brak albo uszkodzony.
1660 -
1661 - Partial write (crash w trakcie zapisu) mógł zostawić obcięty JSON. Zamiast
1662 - zwracać pustą listę pakietów (użytkownik myśli, że repo jest puste)
1663 - sygnalizujemy None – wywołujący ponowi pobranie albo pokaże ostrzeżenie."""
1664 - if not os.path.exists(cp):
1665 - return None
1666 - try:
1667 - with open(cp, "r", encoding="utf-8") as fh:
1668 - data = json.load(fh)
1669 - pkgs = data.get("packages")
1670 - if not isinstance(pkgs, list):
1671 - raise ValueError("brak listy 'packages'")
1672 - return pkgs
1673 - except (OSError, ValueError) as e:
1674 - print(f" ⚠ Uszkodzony cache indeksu {cp}: {e}", file=sys.stderr)
1675 - return None
1676 -
1677 -
1678 -def fetch_repo_index(repo_url, force=False):
1679 - cp = _repo_cache_path(repo_url)
1680 - ep = _repo_etag_path(repo_url)
1681 - tp = _repo_ts_path(repo_url)
1682 -
1683 - if not force and os.path.exists(cp) and os.path.exists(tp):
1684 - try:
1685 - if time.time() - float(open(tp).read().strip()) < REPO_CACHE_TTL:
1686 - cached = _load_repo_cache(cp)
1687 - if cached is not None:
1688 - return cached
1689 - # uszkodzony cache – spróbuj odświeżyć z sieci
1690 - except (OSError, ValueError):
1691 - pass
1692 -
1693 - # --- Cache tylko-do-odczytu (np. `pag info` jako zwykły user) ---
1694 - # /var/cache/pag/repos należy do roota. Nie próbuj odświeżać ani pisać –
1695 - # zwykły user i tak nie zapisze indeksu; użyj lokalnej kopii (może być
1696 - # nieaktualna). Pełne odświeżenie indeksu: sudo pag sync
1697 - if not (os.path.isdir(REPO_CACHE) and os.access(REPO_CACHE, os.W_OK)):
1698 - if force:
1699 - print(f" ❌ {repo_url}: nie można odświeżyć indeksu – {REPO_CACHE} jest tylko-do-odczytu",
1700 - file=sys.stderr)
1701 - return None
1702 - _cache_ro_notice()
1703 - cached = _load_repo_cache(cp)
1704 - if cached is not None:
1705 - return cached
1706 - return None
1707 -
1708 - headers = {"User-Agent": "pag/3.0"}
1709 - if os.path.exists(tp) and not force:
1710 - try:
1711 - lm = datetime.fromtimestamp(float(open(tp).read().strip()), tz=timezone.utc)
1712 - # Wymuś lokalizację C/POSIX dla nagłówków HTTP, aby unikać problemów z nazwami dni/miesięcy
1713 - try:
1714 - old_locale = locale.setlocale(locale.LC_TIME)
1715 - locale.setlocale(locale.LC_TIME, 'C')
1716 - headers["If-Modified-Since"] = lm.strftime("%a, %d %b %Y %H:%M:%S GMT")
1717 - locale.setlocale(locale.LC_TIME, old_locale)
1718 - except (locale.Error, ValueError):
1719 - # Jeśli ustawienie lokalizacji się nie powiedzie, użyj domyślnej
1720 - headers["If-Modified-Since"] = lm.strftime("%a, %d %b %Y %H:%M:%S GMT")
1721 - except: pass
1722 - if os.path.exists(ep) and not force:
1723 - try: headers["If-None-Match"] = open(ep).read().strip()
1724 - except: pass
1725 -
1726 - # --- Pobranie indeksu (błędy SIECI nie są błędami zapisu cache) ---
1727 - try:
1728 - req = Request(f"{repo_url}/repo.json", headers=headers)
1729 - with urlopen(req, timeout=30) as resp:
1730 - etag = resp.headers.get("ETag","")
1731 - raw = resp.read()
1732 - data = json.loads(raw.decode())
1733 - except HTTPError as e:
1734 - if e.code == 304:
1735 - # Serwer: indeks bez zmian – odśwież tylko znacznik czasu (best-effort)
1736 - try:
1737 - open(tp,"w").write(str(time.time()))
1738 - except OSError:
1739 - pass
1740 - cached = _load_repo_cache(cp)
1741 - if cached is not None:
1742 - return cached
1743 - # uszkodzona kopia – potraktuj jak brak (ostrzeżenie niżej)
1744 - print(f" ⚠ HTTP {e.code} dla {repo_url}", file=sys.stderr)
1745 - return None
1746 - except Exception as e:
1747 - print(f" ⚠ Błąd pobierania indeksu {repo_url}: {e}", file=sys.stderr)
1748 - return _load_repo_cache(cp)
1749 -
1750 - # Indeks pobrany – zapisz SUROWE bajty (nie re-serializuj! podpis GPG jest
1751 - # nad oryginalnymi bajtami repo.json z serwera) i zweryfikuj podpis.
1752 - # Najpierw zapis tymczasowy + weryfikacja GPG, dopiero potem podmiana cp:
1753 - # błąd zapisu (np. pełny dysk) nie niszczy starej, zweryfikowanej kopii
1754 - # i NIGDY nie zwracamy danych, które nie przeszły weryfikacji.
1755 - tmp_path = cp + ".tmp"
1756 - try:
1757 - with open(tmp_path, "wb") as f:
1758 - f.write(raw)
1759 - if not _verify_repo_sig(repo_url, tmp_path):
1760 - return None # weryfikacja nie powiodła się – stary cache zostaje
1761 - os.replace(tmp_path, cp)
1762 - # przenieś podpis obok docelowego pliku (marker „repo ma podpis")
1763 - for _ext in (".asc", ".sig"):
1764 - if os.path.exists(tmp_path + _ext):
1765 - try:
1766 - os.replace(tmp_path + _ext, cp + _ext)
1767 - except OSError:
1768 - pass
1769 - break
1770 - if etag:
1771 - try:
1772 - open(ep,"w").write(etag)
1773 - except OSError:
1774 - pass
1775 - try:
1776 - open(tp,"w").write(str(time.time()))
1777 - except OSError:
1778 - pass
1779 - return data.get("packages",[])
1780 - except OSError as e:
1781 - print(f" ⚠ Indeks pobrany, ale nie udało się zapisać cache ({REPO_CACHE}): {e}",
1782 - file=sys.stderr)
1783 - # cp nie został podmieniony (podmiana jest po weryfikacji) – lokalna kopia
1784 - # to wciąż stare, zweryfikowane dane
1785 - return _load_repo_cache(cp)
1786 - finally:
1787 - for _p in (tmp_path, tmp_path + ".asc", tmp_path + ".sig"):
1788 - try:
1789 - os.unlink(_p)
1790 - except OSError:
1791 - pass
1792 -
1793 -def _verify_repo_sig(repo_url, cache_path) -> bool:
1794 - """Weryfikuje podpis GPG indeksu repozytorium i przypina fingerprint.
1795 -
1796 - FAIL-CLOSED: brak/nieprawidłowy podpis = False (chyba że PAG_INSECURE=1).
1797 - Zwraca True jeśli indeks jest zaufany, False jeśli należy go odrzucić.
1798 -
1799 - Model zaufania (TOFU + pinning):
1800 - - Pierwszy raz (brak przypiętego fingerprintu) → klucz jest importowany,
1801 - a fingerprint zapisywany w /etc/pag/trusted.json z JAWNYM ostrzeżeniem.
1802 - To świadomy kompromis wygody i bezpieczeństwa.
1803 - - Kolejne uruchomienia: fingerprint jest porównywany z przypiętym.
1804 - Zmiana klucza = ❌ SECURITY ERROR (fail-closed), wymagane ręczne:
1805 - pag key-trust <repo_url> (po weryfikacji nowego klucza)
1806 - """
1807 - insecure = os.environ.get("PAG_INSECURE", "") == "1"
1808 -
1809 - if not os.path.exists(GPG_HOME):
1810 - if insecure:
1811 - return True # brak GPG home – tryb insecure, akceptuj
1812 - print(f" ❌ {repo_url}: brak kluczy GPG – weryfikacja niemożliwa!")
1813 - print(f" Ustaw PAG_INSECURE=1 aby pominąć (niezalecane)")
1814 - os.remove(cache_path)
1815 - return False
1816 -
1817 - sig_path = cache_path + ".sig"
1818 - # Podpisy generowane jako .asc (armored) – próbuj .asc, potem .sig
1819 - sig_data = None
1820 - sig_ext = ""
1821 - for ext in (".asc", ".sig"):
1822 - try:
1823 - req = Request(f"{repo_url}/repo.json{ext}", headers={"User-Agent":"pag/3.0"})
1824 - with urlopen(req, timeout=15) as resp:
1825 - sig_data = resp.read()
1826 - sig_ext = ext
1827 - break
1828 - except Exception:
1829 - continue
1830 - if not sig_data:
1831 - if insecure:
1832 - return True # tryb insecure – akceptuj bez podpisu
1833 - print(f" ❌ {repo_url}: NIE MOŻNA POBRAĆ PODPISU repo.json.asc/.sig!")
1834 - print(f" Ustaw PAG_INSECURE=1 aby pominąć (niezalecane)")
1835 - os.remove(cache_path)
1836 - return False
1837 - sig_path = cache_path + sig_ext
1838 - with open(sig_path, "wb") as f:
1839 - f.write(sig_data)
1840 -
1841 - ok, fingerprint = _gpg_verify_fp(sig_path, cache_path)
1842 - if not ok:
1843 - # Automatyczny import klucza repo przy pierwszym uruchomieniu (TOFU,
1844 - # jak apt) – gdy w keyringu brakuje klucza (No public key).
1845 - res = _gpg_run("--verify", sig_path, cache_path,
1846 - capture_output=True, text=True, timeout=30)
1847 - _stderr = res.stderr.decode(errors="replace") if isinstance(res.stderr, bytes) else (res.stderr or "")
1848 - if "public key" in _stderr.lower() and "no public key" in _stderr.lower():
1849 - try:
1850 - with urlopen(Request(f"{repo_url}/paganos.asc", headers={"User-Agent": "pag/3.0"}), timeout=20) as r:
1851 - keydata = r.read()
1852 - with tempfile.NamedTemporaryFile(delete=False, suffix=".asc") as tmp:
1853 - tmp.write(keydata)
1854 - tmp.flush()
1855 - _gpg_run("--import", tmp.name, capture_output=True, timeout=30)
1856 - os.unlink(tmp.name)
1857 - print(f" 🔑 Importowano klucz repo z {repo_url}/paganos.asc")
1858 - ok, fingerprint = _gpg_verify_fp(sig_path, cache_path)
1859 - except Exception:
1860 - pass
1861 - if not ok:
1862 - if insecure:
1863 - print(f" ⚠ {repo_url}: nieprawidłowy podpis GPG (PAG_INSECURE – ignoruję)")
1864 - return True
1865 - os.remove(cache_path)
1866 - if not shutil.which(GPG_BINARY):
1867 - print(f" ❌ {repo_url}: GPG nie jest zainstalowane – nie można zweryfikować podpisu!")
1868 - print(f" Zainstaluj gnupg lub ustaw PAG_INSECURE=1 (niezalecane)")
1869 - else:
1870 - print(f" ❌ {repo_url}: NIEPRAWIDŁOWY PODPIS GPG indeksu repozytorium!")
1871 - return False
1872 -
1873 - # --- Wymuś przypięty fingerprint (TOFU + pinning) ---
1874 - pinned = _repo_pinned_fp(repo_url)
1875 - if pinned:
1876 - if not fingerprint:
1877 - if insecure:
1878 - print(f" ⚠ {repo_url}: nie można odczytać fingerprintu (PAG_INSECURE – ignoruję)")
1879 - return True
1880 - os.remove(cache_path)
1881 - print(f" ❌ [SECURITY ERROR] {repo_url}: nie można odczytać fingerprintu podpisu!")
1882 - print(f" Przypięty klucz: {pinned} – odrzucam indeks.")
1883 - return False
1884 - if fingerprint != pinned.upper():
1885 - if insecure:
1886 - print(f" ⚠ {repo_url}: ZMIENIONY KLUCZ PODPISU (PAG_INSECURE – ignoruję)")
1887 - return True
1888 - os.remove(cache_path)
1889 - print(f" ❌ [SECURITY ERROR] {repo_url}: Klucz podpisujący repo uległ zmianie!")
1890 - print(f" Oczekiwany: {pinned}")
1891 - print(f" Otrzymany: {fingerprint}")
1892 - print(f" Jeśli to celowa rotacja klucza: pag key-trust {repo_url}")
1893 - return False
1894 - return True
1895 -
1896 - if fingerprint:
1897 - # Brak przypiętego fingerprintu → TOFU: zapisz go w bazie zaufania.
1898 - db = _load_trust_db()
1899 - if db.get(repo_url) != fingerprint:
1900 - _save_trust_db({**db, repo_url: fingerprint})
1901 - print(f" 🔐 Przypięto fingerprint repo {repo_url}: {fingerprint}")
1902 - print(f" (TOFU – pierwsze zaufanie. Gdy klucz się zmieni, pag odmówi aktualizacji.)")
1903 - print(f" Aby uniknąć TOFU, dopisz fingerprint w /etc/pag/repos.conf.")
1904 - return True
1905 -
1906 -def fetch_all_packages(force=False):
1907 - all_pkgs = {}
1908 - for repo_url in get_repos():
1909 - pkgs = fetch_repo_index(repo_url, force)
1910 - if pkgs:
1911 - for pdata in pkgs:
1912 - name = pdata.get("name", pdata.get("filename","?").split("-")[0])
1913 - pkg = PackageInfo(pdata, repo_url)
1914 - if name not in all_pkgs or _version_newer(pkg.version, all_pkgs[name].version):
1915 - all_pkgs[name] = pkg
1916 - return all_pkgs
1917 -
1918 -# =============================================================================
1919 -# GPG
1920 -# =============================================================================
1921 -
1922 -def _verify_pkg_gpg(pkg_path, repo_url=None):
1923 - """Weryfikuje podpis GPG pakietu i (jeśli znamy repo) przypięty fingerprint.
1924 -
1925 - FAIL-CLOSED: brak podpisu = odrzucenie (chyba że PAG_INSECURE=1).
1926 - Zwraca (passed: bool, message: str).
1927 - """
1928 - insecure = os.environ.get("PAG_INSECURE", "") == "1"
1929 - # Brak gnupg = weryfikacja niemożliwa. Bez tej gałęzi użytkownik dostawał
1930 - # mylące „NIEPRAWIDŁOWY PODPIS GPG”, mimo że paczka i podpis są w porządku.
1931 - if not shutil.which(GPG_BINARY):
1932 - if insecure:
1933 - return True, "(gpg missing – PAG_INSECURE)"
1934 - return False, _("gpg_missing")
1935 - sig_path = pkg_path + ".sig"
1936 - if not os.path.exists(sig_path) and os.path.exists(pkg_path + ".asc"):
1937 - sig_path = pkg_path + ".asc"
1938 -
1939 - if not os.path.exists(sig_path):
1940 - if insecure:
1941 - return True, "(no signature – PAG_INSECURE)"
1942 - return False, "BRAK PODPISU – pakiet odrzucony (ustaw PAG_INSECURE=1 aby pominąć)"
1943 -
1944 - ok, fp = _gpg_verify_fp(sig_path, pkg_path)
1945 - if not ok:
1946 - if insecure:
1947 - return True, "(invalid signature – PAG_INSECURE)"
1948 - return False, "NIEPRAWIDŁOWY PODPIS GPG"
1949 -
1950 - # Opcjonalnie: sprawdź, czy podpis pochodzi od klucza przypiętego dla repo.
1951 - if repo_url:
1952 - pinned = _repo_pinned_fp(repo_url)
1953 - if pinned and fp and fp != pinned.upper():
1954 - if insecure:
1955 - return True, "(pkg signer mismatch – PAG_INSECURE)"
1956 - return False, f"PAKIET PODPISANY INNYM KLUCZEM niż repo (oczekiwano {pinned})"
1957 -
1958 - return True, "GPG verified"
1959 -
1960 -def cmd_key_add(source):
1961 - ensure_dirs()
1962 - if not shutil.which(GPG_BINARY):
1963 - print(f"❌ {_('gpg_missing')}"); return 1
1964 - if source.startswith("http"):
1965 - try:
1966 - with urlopen(Request(source, headers={"User-Agent":"pag/3.0"}), timeout=30) as resp:
1967 - keydata = resp.read()
1968 - with tempfile.NamedTemporaryFile(delete=False, suffix=".gpg") as tmp:
1969 - tmp.write(keydata); tmp.flush()
1970 - res = _gpg_run("--import", tmp.name, capture_output=True, timeout=30)
1971 - os.unlink(tmp.name)
1972 - if res.returncode != 0:
1973 - print(f"❌ {_('key_add_failed')}"); return 1
1974 - except Exception as e:
1975 - print(f"❌ Download error: {e}"); return 1
1976 - else:
1977 - res = _gpg_run("--import", source, capture_output=True, timeout=30)
1978 - if res.returncode != 0:
1979 - print(f"❌ {_('key_add_failed')}"); return 1
1980 - print(f"✅ {_('key_imported')}")
1981 -
1982 -def cmd_key_list():
1983 - if not shutil.which(GPG_BINARY):
1984 - print(f"❌ {_('gpg_missing')}"); return
1985 - if not os.path.exists(GPG_HOME):
1986 - print(_("no_keys")); return
1987 - result = _gpg_run("--list-keys", "--keyid-format", "LONG",
1988 - capture_output=True, text=True, timeout=30)
1989 - if result.returncode != 0:
1990 - print(f"❌ {_('gpg_missing')}"); return
1991 - print(result.stdout or _("no_keys"))
1992 -
1993 -def cmd_key_remove(key_id):
1994 - _gpg_run("--batch", "--yes", "--delete-key", key_id,
1995 - capture_output=True, timeout=30)
1996 - print(f"✅ {_('key_removed', key_id)}")
1997 -
1998 -def _repo_signer_fp(repo_url):
1999 - """Pobiera repo.json + podpis i zwraca fingerprint podpisującego (bez pinningu)."""
2000 - repo_url = repo_url.rstrip("/")
2001 - try:
2002 - with urlopen(Request(f"{repo_url}/repo.json", headers={"User-Agent":"pag/3.0"}), timeout=30) as r:
2003 - data = r.read()
2004 - except Exception:
2005 - return None
2006 - sig = None
2007 - sig_ext = ".asc"
2008 - for ext in (".asc", ".sig"):
2009 - try:
2010 - with urlopen(Request(f"{repo_url}/repo.json{ext}", headers={"User-Agent":"pag/3.0"}), timeout=20) as r:
2011 - sig = r.read()
2012 - sig_ext = ext
2013 - break
2014 - except Exception:
2015 - continue
2016 - if not sig:
2017 - return None
2018 - with tempfile.NamedTemporaryFile(delete=False, suffix=".json") as tf:
2019 - tf.write(data); tf.flush()
2020 - data_path = tf.name
2021 - sig_path = data_path + sig_ext
2022 - try:
2023 - with open(sig_path, "wb") as f:
2024 - f.write(sig)
2025 - ok, fp = _gpg_verify_fp(sig_path, data_path)
2026 - finally:
2027 - for p in (data_path, sig_path):
2028 - try: os.unlink(p)
2029 - except OSError: pass
2030 - return fp if ok else None
2031 -
2032 -
2033 -def cmd_key_trust(repo_url):
2034 - """Przypina fingerprint klucza podpisującego repo (koniec z TOFU dla tego repo)."""
2035 - repo_url = repo_url.rstrip("/")
2036 - print(f"🔐 Przypinam klucz repo {repo_url}...")
2037 - fp = _repo_signer_fp(repo_url)
2038 - if not fp:
2039 - print(" ❌ Nie można odczytać fingerprintu podpisu (brak/nieudany).")
2040 - print(" Upewnij się, że klucz repo jest w keyringu (pag key-add <url|file>).")
2041 - return 1
2042 - db = _load_trust_db()
2043 - _save_trust_db({**db, repo_url: fp})
2044 - print(f" ✅ Przypięto {fp} dla {repo_url}")
2045 - print(" Od teraz zmiana klucza zostanie zgłoszona jako SECURITY ERROR.")
2046 - return 0
2047 -
2048 -
2049 -def cmd_key_untrust(repo_url):
2050 - """Usuwa przypięcie fingerprintu dla repo (wraca do TOFU)."""
2051 - repo_url = repo_url.rstrip("/")
2052 - db = _load_trust_db()
2053 - if repo_url not in db:
2054 - print(f" ℹ {repo_url} nie ma przypiętego fingerprintu.")
2055 - return 0
2056 - del db[repo_url]
2057 - _save_trust_db(db)
2058 - print(f" ✅ Usunięto przypięcie dla {repo_url}.")
2059 - return 0
2060 -
2061 -
2062 -def cmd_key_trusted():
2063 - """Listuje przypięte fingerprinty repozytoriów."""
2064 - db = _load_trust_db()
2065 - if not db:
2066 - print(_("no_keys"))
2067 - return
2068 - for url, fp in sorted(db.items()):
2069 - print(f" {url}\n {fp}")
2070 -
2071 -# =============================================================================
2072 -# ATOMOWA INSTALACJA (STAGING)
2073 -# =============================================================================
2074 -
2075 -def _safe_rename(src: str, dst: str) -> bool:
2076 - """
2077 - Atomowe przeniesienie pliku. Jeśli src i dst są na różnych
2078 - systemach plików (EXDEV), kopiuje + usuwa źródło.
2079 - """
2080 - try:
2081 - os.rename(src, dst)
2082 - return True
2083 - except OSError as e:
2084 - if e.errno == 18: # EXDEV – cross-device link
2085 - shutil.copy2(src, dst)
2086 - os.remove(src)
2087 - return True
2088 - raise
2089 -
2090 -
2091 -def _install_file(src: str, rel: str, data_staging: str, sums: dict,
2092 - staging: str, journal: list, installed_files: list,
2093 - deploy_dir: str = "", backup_dir: str = "",
2094 - backup_journal: Optional[list] = None,
2095 - old_checksums: Optional[dict] = None,
2096 - privileged=frozenset()) -> bool:
2097 - """
2098 - Instaluje pojedynczy plik (zwykły lub symlink).
2099 - Obsługuje: cross-device rename, symlinki, weryfikację SHA256.
2100 -
2101 - Jeśli deploy_dir jest podany (tryb immutable), pliki systemowe trafiają
2102 - do deploymentu, a współdzielone (/var, /etc, ...) bezpośrednio do /.
2103 -
2104 - Jeśli backup_dir jest podany, a pod dst istnieje już plik (upgrade/reinstall),
2105 - stara wersja jest przenoszona do backup_dir, by rollback mógł ją przywrócić.
2106 -
2107 - old_checksums: {ścieżka: sha256 z chwili instalacji}. Gdy podane i plik /etc
2108 - został zmodyfikowany przez użytkownika, nowa wersja ląduje jako .pacnew
2109 - (stary plik NIE jest ruszany) – wzorzec jak w pacmanie.
2110 - """
2111 - # W trybie immutable: pliki współdzielone idą do /, reszta do deploymentu
2112 - if deploy_dir and _is_shared_path("/" + rel):
2113 - dst_root = PAG_ROOT
2114 - elif deploy_dir:
2115 - dst_root = deploy_dir
2116 - else:
2117 - dst_root = PAG_ROOT
2118 -
2119 - dst = os.path.join(dst_root, rel)
2120 -
2121 - # --- SYMLINK ---
2122 - if os.path.islink(src):
2123 - link_target = os.readlink(src)
2124 - # Weryfikuj sums.json dla symlinka (hash ścieżki docelowej)
2125 - expected = sums.get("/" + rel, "")
2126 - if expected:
2127 - link_hash = hashlib.sha256(link_target.encode()).hexdigest()
2128 - if expected and link_hash != expected:
2129 - return False
2130 -
2131 - os.makedirs(os.path.dirname(dst), exist_ok=True)
2132 - # Backup istniejącego symlinka (upgrade) – dla poprawnego rollbacku
2133 - if backup_dir and backup_journal is not None and os.path.lexists(dst):
2134 - try:
2135 - backup_path = os.path.join(backup_dir, rel)
2136 - os.makedirs(os.path.dirname(backup_path), exist_ok=True)
2137 - os.replace(dst, backup_path)
2138 - backup_journal.append((backup_path, "/" + rel))
2139 - journal.append(("backup", backup_path, dst))
2140 - except OSError:
2141 - pass
2142 - # Jeśli docelowy symlink już istnieje, usuń go
2143 - if os.path.islink(dst) or os.path.exists(dst):
2144 - os.remove(dst)
2145 - os.symlink(link_target, dst)
2146 - journal.append(("symlink", "", dst))
2147 - installed_files.append({
2148 - "path": "/" + rel,
2149 - "sha256": hashlib.sha256(link_target.encode()).hexdigest(),
2150 - "size": len(link_target),
2151 - "is_symlink": True,
2152 - "symlink_target": link_target,
2153 - })
2154 - return True
2155 -
2156 - # --- ZWYKŁY PLIK ---
2157 - # Oblicz SHA256
2158 - try:
2159 - file_sha = _sha256_file(src)
2160 - except Exception:
2161 - file_sha = ""
2162 -
2163 - # Weryfikuj sums.json
2164 - expected = sums.get("/" + rel, "")
2165 - if expected and file_sha and file_sha != expected:
2166 - return False
2167 -
2168 - # --- .pacnew: NIE nadpisuj pliku konfiguracyjnego, którego nie wolno zgubić ---
2169 - # Robimy `<plik>.pacnew`, gdy:
2170 - # a) plik jest śledzony i użytkownik go zmodyfikował (hash != zapisanej sumy),
2171 - # b) to wrażliwa konfiguracja (/etc/pam.d, /etc/security, sudoers, shadow…),
2172 - # a treść na dysku różni się od tej z pakietu – chroni auth przed
2173 - # cichym nadpisaniem przez `install`/`upgrade` (np. przez shadow).
2174 - # NIE robimy .pacnew, jeśli plik na dysku jest identyczny z nowym albo był
2175 - # niezmieniony od instalacji (wtedy nadpisanie jest bezpieczne).
2176 - old_sha = (old_checksums or {}).get("/" + rel, "")
2177 - if file_sha and _is_config_path(rel) and os.path.isfile(dst) and not os.path.islink(dst):
2178 - tracked_modified = bool(old_sha) and file_sha != old_sha
2179 - if tracked_modified or _is_sensitive_config(rel):
2180 - try:
2181 - cur_sha = _sha256_file(dst)
2182 - except OSError:
2183 - cur_sha = ""
2184 - if cur_sha and cur_sha != file_sha and not (old_sha and cur_sha == old_sha):
2185 - pacnew = dst + ".pacnew"
2186 - try:
2187 - _safe_rename(src, pacnew)
2188 - try:
2189 - os.chown(pacnew, 0, 0)
2190 - except (OSError, PermissionError):
2191 - pass
2192 - # Journal (do cofnięcia przy nieudanej transakcji) – ale NIE
2193 - # zapisujemy .pacnew w bazie plików: to artefakt użytkownika.
2194 - journal.append(("file", src, pacnew))
2195 - print(f" ⚠ {_('conf_pacnew', path=pacnew)}")
2196 - return True
2197 - except OSError:
2198 - pass # nie udało się – kontynuuj normalną instalację
2199 -
2200 - # Utwórz katalog docelowy
2201 - os.makedirs(os.path.dirname(dst), exist_ok=True)
2202 -
2203 - # Backup istniejącego pliku (upgrade) – dla poprawnego rollbacku
2204 - if backup_dir and backup_journal is not None and os.path.lexists(dst):
2205 - try:
2206 - backup_path = os.path.join(backup_dir, rel)
2207 - os.makedirs(os.path.dirname(backup_path), exist_ok=True)
2208 - os.replace(dst, backup_path)
2209 - backup_journal.append((backup_path, "/" + rel))
2210 - journal.append(("backup", backup_path, dst))
2211 - except OSError:
2212 - pass
2213 -
2214 - # Atomowe przeniesienie (z fallbackiem dla cross-device).
2215 - # Zachowuje bity uprawnień (SUID/SGID/sticky) – NIE używamy filter='data'.
2216 - _safe_rename(src, dst)
2217 -
2218 - if "/" + rel in privileged:
2219 - # Plik uprzywilejowany: zostaw właściciela, grupę i bity z pakietu
2220 - # (np. sudo 4755 root:root, qemu-bridge-helper 4750 root:kvm).
2221 - try:
2222 - st = os.stat(dst)
2223 - if st.st_mode & 0o6000:
2224 - _audit(f"privileged {dst} mode={oct(st.st_mode & 0o7777)} "
2225 - f"uid={st.st_uid} gid={st.st_gid}")
2226 - except OSError:
2227 - pass
2228 - else:
2229 - # Wymuś właściciela root:root. UWAGA: os.chown() NIE czyści bitów SUID/SGID.
2230 - try:
2231 - os.chown(dst, 0, 0)
2232 - except (OSError, PermissionError):
2233 - # Na niektórych systemach plików (tmpfs, fat) chown może się nie powieść
2234 - pass
2235 -
2236 - journal.append(("file", src, dst))
2237 - installed_files.append({
2238 - "path": "/" + rel,
2239 - "sha256": file_sha,
2240 - "size": os.path.getsize(dst),
2241 - "is_symlink": False,
2242 - })
2243 - return True
2244 -
2245 -
2246 -def _atomic_install(pkg_path: str, pkg: PackageInfo, deploy_dir: str = "",
2247 - backup_dir: str = "",
2248 - old_checksums: Optional[dict] = None) -> Tuple[bool, List[dict], List[Tuple[str, str]]]:
2249 - """
2250 - Rozpakowuje do staging area, potem atomowo przenosi pliki.
2251 - Jeśli deploy_dir podany – instaluje do deploymentu (tryb immutable).
2252 - Zwraca (success, [lista plików z SHA256], [(backup_path, dst), ...]).
2253 - """
2254 - staging = tempfile.mkdtemp(dir=STAGING_DIR, prefix=f".staging-{pkg.name}-")
2255 - # Wbudowana lista + ścieżki zadeklarowane przez recepturę (metadata.json).
2256 - priv = PRIVILEGED_PATHS | frozenset(pkg.privileged or ())
2257 - journal = []
2258 - installed_files = []
2259 - backup_journal: List[Tuple[str, str]] = []
2260 -
2261 - try:
2262 - # Rozpakuj .pkg.tar.xz → staging (bezpieczne – ochrona Directory Traversal)
2263 - with tarfile.open(pkg_path, "r:xz") as tf:
2264 - _safe_extractall(tf, staging)
2265 -
2266 - data_tar = os.path.join(staging, "data.tar.xz")
2267 - if not os.path.exists(data_tar):
2268 - shutil.rmtree(staging, ignore_errors=True)
2269 - return False, [], backup_journal
2270 -
2271 - # Rozpakuj data.tar.xz → staging/data (bezpieczne – ochrona Directory Traversal)
2272 - data_staging = os.path.join(staging, "data")
2273 - os.makedirs(data_staging, exist_ok=True)
2274 - with tarfile.open(data_tar, "r:xz") as tf:
2275 - _safe_extractall(tf, data_staging, privileged=priv)
2276 -
2277 - # Wczytaj sums.json
2278 - sums_path = os.path.join(data_staging, "sums.json")
2279 - sums = json.load(open(sums_path)) if os.path.exists(sums_path) else {}
2280 -
2281 - # Hook pre-install (przed przeniesieniem plików do systemu)
2282 - _run_hook(os.path.join(staging, "hooks"), "pre-install", pkg)
2283 -
2284 - # Przenieś pliki: staging/data/* → /
2285 - for root, dirs, files in os.walk(data_staging):
2286 - # Odtwórz katalogi z pakietu – w tym PUSTE (np. /etc/pulse/default.pa.d).
2287 - # Pętla plików tworzy tylko rodziców instalowanych plików, przez co
2288 - # puste katalogi z data.tar.xz ginęły przy instalacji.
2289 - for d in dirs:
2290 - src_dir = os.path.join(root, d)
2291 - rel_dir = os.path.relpath(src_dir, data_staging)
2292 - if deploy_dir and _is_shared_path("/" + rel_dir):
2293 - dst_root = PAG_ROOT
2294 - elif deploy_dir:
2295 - dst_root = deploy_dir
2296 - else:
2297 - dst_root = PAG_ROOT
2298 - dst_dir = os.path.join(dst_root, rel_dir)
2299 - if not os.path.isdir(dst_dir):
2300 - try:
2301 - os.makedirs(dst_dir, exist_ok=True)
2302 - except OSError:
2303 - pass
2304 - for fname in files:
2305 - if fname == "sums.json":
2306 - continue
2307 - src = os.path.join(root, fname)
2308 - rel = os.path.relpath(src, data_staging)
2309 -
2310 - ok = _install_file(src, rel, data_staging, sums,
2311 - staging, journal, installed_files, deploy_dir,
2312 - backup_dir, backup_journal,
2313 - old_checksums=old_checksums,
2314 - privileged=priv)
2315 - if not ok:
2316 - # Cofnij wszystkie operacje
2317 - _rollback_journal(journal, staging)
2318 - return False, [], backup_journal
2319 -
2320 - # Odbuduj cache ikon GTK dla motywów dotkniętych instalacją.
2321 - # Bez icon-theme.cache aplikacje GTK nie widzą ikon mimo obecności
2322 - # motywu (np. /usr/share/icons/Papirus). Pomijamy, gdy narzędzie
2323 - # nie jest zainstalowane.
2324 - _icon_dirs = set()
2325 - for f in installed_files:
2326 - fp = f.get("path", "") or ""
2327 - if fp.startswith("/usr/share/icons/"):
2328 - _rest = fp[len("/usr/share/icons/"):]
2329 - _theme = _rest.split("/", 1)[0]
2330 - if _theme:
2331 - _icon_dirs.add(os.path.join(PAG_ROOT, "usr/share/icons", _theme))
2332 - if _icon_dirs:
2333 - try:
2334 - subprocess.run(["gtk-update-icon-cache", "--version"],
2335 - capture_output=True, timeout=10)
2336 - for _d in sorted(_icon_dirs):
2337 - if os.path.isdir(_d):
2338 - subprocess.run(["gtk-update-icon-cache", "-f", "-q", _d],
2339 - capture_output=True, timeout=300)
2340 - except Exception:
2341 - pass
2342 -
2343 - # Uruchom hooki post-install
2344 - hooks_dir = os.path.join(staging, "hooks")
2345 - _run_hook(hooks_dir, "post-install", pkg)
2346 -
2347 - # Zachowaj hooki na wypadek usunięcia pakietu (pre/post-remove)
2348 - try:
2349 - if os.path.isdir(hooks_dir):
2350 - persisted = os.path.join(PAG_DB, "hooks", pkg.name)
2351 - shutil.rmtree(persisted, ignore_errors=True)
2352 - shutil.copytree(hooks_dir, persisted)
2353 - except Exception:
2354 - pass
2355 -
2356 - # Zapisz do SQLite
2357 - _db_record_files(pkg.name, installed_files)
2358 -
2359 - shutil.rmtree(staging, ignore_errors=True)
2360 - return True, installed_files, backup_journal
2361 -
2362 - except Exception as e:
2363 - _rollback_journal(journal, staging)
2364 - return False, [], backup_journal
2365 -
2366 -
2367 -def _refresh_dynamic_linker_cache(deploy_dir: str = "") -> bool:
2368 - """Odświeża cache ld.so po udanej instalacji pakietów."""
2369 - ldconfig = shutil.which("ldconfig")
2370 - if not ldconfig:
2371 - print(" ⚠ Nie znaleziono ldconfig — cache linkera nie został odświeżony.",
2372 - file=sys.stderr)
2373 - return False
2374 -
2375 - target_root = deploy_dir or PAG_ROOT
2376 - command = [ldconfig]
2377 - if target_root != "/":
2378 - command.extend(["-r", target_root])
2379 -
2380 - try:
2381 - subprocess.run(command, check=True, timeout=60,
2382 - stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
2383 - text=True)
2384 - return True
2385 - except (OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc:
2386 - detail = getattr(exc, "stderr", None) or str(exc)
2387 - print(f" ⚠ Nie udało się odświeżyć cache'a ld.so: {detail.strip()}",
2388 - file=sys.stderr)
2389 - return False
2390 -
2391 -
2392 -def _rollback_journal(journal: list, staging_path: str):
2393 - """Cofa wszystkie operacje z journala (odwrotna kolejność)."""
2394 - for entry in reversed(journal):
2395 - op = entry[0]
2396 - if op == "file":
2397 - _, src, dst = entry
2398 - try:
2399 - if os.path.exists(dst) or os.path.islink(dst):
2400 - _safe_rename(dst, src)
2401 - except Exception:
2402 - pass
2403 - elif op == "symlink":
2404 - _, _, dst = entry
2405 - try:
2406 - if os.path.islink(dst) or os.path.exists(dst):
2407 - os.remove(dst)
2408 - except Exception:
2409 - pass
2410 - elif op == "backup":
2411 - # Przywróć starą wersję pliku z backupu (upgrade)
2412 - _, bpath, dst = entry
2413 - try:
2414 - if os.path.lexists(bpath):
2415 - os.replace(bpath, dst)
2416 - except Exception:
2417 - pass
2418 - shutil.rmtree(staging_path, ignore_errors=True)
2419 -
2420 -# =============================================================================
2421 -# BEZPIECZNE USUWANIE
2422 -# =============================================================================
2423 -
2424 -def _safe_remove_files(pkg_name: str, installed_db: dict) -> Tuple[int, List[str]]:
2425 - """
2426 - Usuwa pliki pakietu, ale tylko jeśli NIE są współdzielone z innym pakietem.
2427 - Zwraca (liczba usuniętych, [lista usuniętych ścieżek]).
2428 - """
2429 - pkg_files = _db_get_package_files(pkg_name)
2430 - recorded = _db_get_package_checksums(pkg_name)
2431 - removed = []
2432 - skipped_shared = []
2433 - skipped_sensitive = []
2434 -
2435 - for fpath in pkg_files:
2436 - owners = _db_get_file_owners(fpath)
2437 - # Sprawdź czy inny ZAINSTALOWANY pakiet też jest właścicielem
2438 - other_owners = [o for o in owners if o != pkg_name and o in installed_db]
2439 -
2440 - if other_owners:
2441 - # Plik współdzielony – tylko usuń wpis w DB, nie kasuj pliku
2442 - skipped_shared.append(fpath)
2443 - continue
2444 -
2445 - full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
2446 - if os.path.isfile(full) or os.path.islink(full):
2447 - # Wrażliwej konfiguracji systemowej (/etc/pam.d, sudoers, shadow…)
2448 - # NIE kasujemy przy `remove` – jej brak potrafi zablokować logowanie
2449 - # i sudo (np. usunięcie system-auth/system-account). Zostaje wpis w bazie.
2450 - if _is_sensitive_config(fpath):
2451 - skipped_sensitive.append(fpath)
2452 - continue
2453 - # .pacsave: zachowaj ZMIENIONY plik konfiguracyjny zamiast kasować
2454 - # (porównanie z sumą z chwili instalacji), wzorzec jak w pacmanie.
2455 - if not os.path.islink(full) and _is_config_path(fpath):
2456 - old_sha = recorded.get(fpath, "")
2457 - if old_sha:
2458 - try:
2459 - cur_sha = _sha256_file(full)
2460 - except OSError:
2461 - cur_sha = ""
2462 - if cur_sha and cur_sha != old_sha:
2463 - pacsave = full + ".pacsave"
2464 - try:
2465 - os.replace(full, pacsave)
2466 - print(f" ⚠ {_('conf_pacsave', path=pacsave)}")
2467 - removed.append(fpath)
2468 - continue
2469 - except OSError:
2470 - pass
2471 - os.remove(full)
2472 - removed.append(fpath)
2473 -
2474 - # Usuń puste katalogi (od najgłębszych)
2475 - dirs = set()
2476 - for fpath in removed + skipped_shared:
2477 - parent = os.path.dirname(fpath)
2478 - while parent and parent != "/":
2479 - dirs.add(parent)
2480 - parent = os.path.dirname(parent)
2481 -
2482 - for d in sorted(dirs, key=len, reverse=True):
2483 - full_d = os.path.join(PAG_ROOT, d.lstrip("/"))
2484 - if os.path.isdir(full_d):
2485 - try:
2486 - os.rmdir(full_d)
2487 - except OSError:
2488 - pass # nie jest pusty – OK
2489 -
2490 - # Usuń z SQLite
2491 - _db_remove_package_files(pkg_name)
2492 -
2493 - if skipped_shared:
2494 - print(f" ⚠ {len(skipped_shared)} plików współdzielonych zachowanych")
2495 - if skipped_sensitive:
2496 - print(f" ⚠ {len(skipped_sensitive)} wrażliwych plików systemowych zachowanych")
2497 -
2498 - return len(removed) + len(skipped_shared) + len(skipped_sensitive), removed
2499 -
2500 -
2501 -def _remove_stale_files(pkg_name: str, old_files: List[str], new_paths: List[str],
2502 - installed_db: dict, deploy_dir: str = "",
2503 - backup_dir: str = "", backup_journal: Optional[list] = None) -> Tuple[int, List[str]]:
2504 - """
2505 - Po upgrade usuwa pliki starej wersji, których nie ma w nowej.
2506 -
2507 - - Pliki współdzielone z innym zainstalowanym pakietem są ZACHOWYWANE
2508 - (usuwany jest tylko wpis z bazy `files` dla tego pakietu).
2509 - - Sprząta puste katalogi i wpisy SQLite starej wersji.
2510 - Zwraca (liczba usuniętych, [usunięte ścieżki]).
2511 - """
2512 - new_set = set(new_paths)
2513 - stale = [f for f in old_files if f not in new_set]
2514 - if not stale:
2515 - return 0, []
2516 -
2517 - root = deploy_dir or PAG_ROOT
2518 - removed = []
2519 - skipped = 0
2520 - for fpath in stale:
2521 - owners = _db_get_file_owners(fpath)
2522 - other_owners = [o for o in owners if o != pkg_name and o in installed_db]
2523 - if other_owners:
2524 - # Współdzielony z innym pakietem – tylko usuń wpis z DB dla tego pakietu
2525 - skipped += 1
2526 - else:
2527 - # Wrażliwych plików systemowych NIE kasujemy, gdy nowy pakiet ich już
2528 - # nie dostarcza (np. shadow przestaje pakować system-*). Ich brak
2529 - # blokuje login/sudo; usuwamy więc tylko wpis w bazie.
2530 - if _is_sensitive_config(fpath):
2531 - skipped += 1
2532 - else:
2533 - # Gdy nowa wersja pliku /etc trafiła do .pacnew, plik użytkownika
2534 - # MUSI zostać – nie jest „przestarzały”. Zachowujemy też wpis w bazie
2535 - # (stara suma), by kolejny upgrade dalej wykrywał zmiany użytkownika.
2536 - if _is_config_path(fpath):
2537 - _cfg_full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
2538 - if os.path.lexists(_cfg_full + ".pacnew"):
2539 - skipped += 1
2540 - continue
2541 - full = os.path.join(root, fpath.lstrip("/"))
2542 - if os.path.isfile(full) or os.path.islink(full):
2543 - try:
2544 - if backup_dir and backup_journal is not None:
2545 - backup_path = os.path.join(backup_dir, fpath.lstrip("/"))
2546 - os.makedirs(os.path.dirname(backup_path), exist_ok=True)
2547 - os.replace(full, backup_path) # przenieś do backupu (rollback)
2548 - backup_journal.append((backup_path, fpath))
2549 - else:
2550 - os.remove(full)
2551 - removed.append(fpath)
2552 - except OSError:
2553 - pass
2554 - # Usuń wpis `files` dla tego pakietu (stara wersja już go nie zawiera)
2555 - with _db_session() as db:
2556 - db.execute("DELETE FROM files WHERE package=? AND path=?", (pkg_name, fpath))
2557 -
2558 - # Usuń puste katalogi (od najgłębszych)
2559 - dirs = set()
2560 - for fpath in removed:
2561 - parent = os.path.dirname(fpath)
2562 - while parent and parent != "/":
2563 - dirs.add(parent)
2564 - parent = os.path.dirname(parent)
2565 - for d in sorted(dirs, key=len, reverse=True):
2566 - full_d = os.path.join(root, d.lstrip("/"))
2567 - if os.path.isdir(full_d):
2568 - try:
2569 - os.rmdir(full_d)
2570 - except OSError:
2571 - pass # nie jest pusty – OK
2572 -
2573 - if removed:
2574 - print(f" 🧹 Usunięto {len(removed)} nieaktualnych plików ({pkg_name})")
2575 - if skipped:
2576 - print(f" ⚠ {skipped} plików współdzielonych zachowanych")
2577 -
2578 - return len(removed), removed
2579 -
2580 -
2581 -def _new_transaction_backup_root() -> str:
2582 - """Katalog na backupy NADPISYWANYCH plików dla bieżącej transakcji.
2583 -
2584 - Tworzony dla KAŻDEJ transakcji, nie tylko upgrade: „świeża” instalacja
2585 - pakietu też potrafi nadpisać pliki spoza bazy pag (baza rootfs/ISO).
2586 - Gdy transakcja padnie, rollback MUSI mieć co przywrócić – inaczej kasuje
2587 - te pliki (tak zniknął m.in. libpam.so.0 i przestał działać sudo)."""
2588 - txn = datetime.now().strftime("%Y%m%dT%H%M%S") + "-" + str(os.getpid())
2589 - root = os.path.join(STAGING_DIR, "backups", txn)
2590 - os.makedirs(root, exist_ok=True)
2591 - return root
2592 -
2593 -
2594 -def _purge_old_backups(keep_root: str = ""):
2595 - """Usuwa backupy starszych transakcji (zostawia bieżący – dla `pag rollback`)."""
2596 - base = os.path.join(STAGING_DIR, "backups")
2597 - if not os.path.isdir(base):
2598 - return
2599 - for entry in os.listdir(base):
2600 - p = os.path.join(base, entry)
2601 - if p != keep_root and os.path.isdir(p):
2602 - shutil.rmtree(p, ignore_errors=True)
2603 -
2604 -# =============================================================================
2605 -# HOOKI
2606 -# =============================================================================
2607 -# Hooki uruchamiają dowolny plik z pakietu jako root — to naturalna cecha
2608 -# menedżera pakietów (apt/pacman też tak mają), dlatego MUSISZ ufać repozytorium.
2609 -# Aby ograniczyć ryzyko:
2610 -# - hook dostaje minimalne, "czyste" środowisko (bez LD_PRELOAD, BASH_ENV itp.)
2611 -# - hooki można wyłączyć (PAG_NO_HOOKS=1) i ustawić timeout (PAG_HOOK_TIMEOUT)
2612 -# - każde uruchomienie jest logowane do /var/log/pag/audit.log
2613 -# - hook ma wersjonowane API (PKG_HOOK_API)
2614 -# =============================================================================
2615 -
2616 -# Lista wykonanych hooków — trafia do wpisu transakcji (informacja w rejestrze).
2617 -_HOOKS_RUN: List[str] = []
2618 -
2619 -
2620 -def _hook_env(pkg: PackageInfo, hook_name: str) -> dict:
2621 - """Buduje minimalne środowisko dla hooka (bez niebezpiecznych zmiennych)."""
2622 - return {
2623 - "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
2624 - "HOME": "/root",
2625 - "LANG": "C.UTF-8",
2626 - "LC_ALL": "C.UTF-8",
2627 - "PKG_NAME": pkg.name,
2628 - "PKG_VERSION": pkg.version,
2629 - "PKG_ACTION": hook_name,
2630 - "PKG_HOOK_API": HOOK_API_VERSION,
2631 - }
2632 -
2633 -
2634 -def _hook_timeout() -> int:
2635 - try:
2636 - return max(1, int(os.environ.get("PAG_HOOK_TIMEOUT", "60")))
2637 - except Exception:
2638 - return 60
2639 -
2640 -
2641 -def _run_hook(hooks_dir: str, hook_name: str, pkg: PackageInfo) -> bool:
2642 - """Uruchamia skrypt hooka jeśli istnieje.
2643 -
2644 - Zwraca True jeśli hook został WYKONANY (istniał i uruchomiono go), False w
2645 - pozostałych przypadkach (brak pliku, wyłączone hooki, błąd). Obsługuje
2646 - ograniczone środowisko, timeout, logowanie do audytu i rejestr w transakcji.
2647 - """
2648 - hook_path = os.path.join(hooks_dir, hook_name)
2649 - if not os.path.exists(hook_path):
2650 - return False
2651 -
2652 - if os.environ.get("PAG_NO_HOOKS", "") == "1":
2653 - print(f" ⚠ Hook pominięty (PAG_NO_HOOKS=1): {hook_name} dla {pkg.name}")
2654 - _audit(f"hook SKIP {hook_name} {pkg.name}-{pkg.version} (PAG_NO_HOOKS=1)")
2655 - return False
2656 -
2657 - os.chmod(hook_path, 0o755)
2658 - env = _hook_env(pkg, hook_name)
2659 - tag = f"{hook_name} {pkg.name}-{pkg.version}"
2660 - try:
2661 - result = subprocess.run([hook_path], env=env, timeout=_hook_timeout(),
2662 - check=False, capture_output=True, text=True,
2663 - cwd="/")
2664 - _HOOKS_RUN.append(tag)
2665 - if result.returncode != 0:
2666 - print(f" ⚠ Hook {hook_name} dla {pkg.name} zakończony z kodem {result.returncode}")
2667 - if result.stderr:
2668 - print(f" {result.stderr.strip()[-200:]}")
2669 - _audit(f"hook FAIL {tag} rc={result.returncode}")
2670 - else:
2671 - _audit(f"hook OK {tag}")
2672 - return True
2673 - except subprocess.TimeoutExpired:
2674 - print(f" ⚠ Hook {hook_name} dla {pkg.name} przekroczył timeout ({_hook_timeout()}s)")
2675 - _audit(f"hook TIMEOUT {tag}")
2676 - return False
2677 - except Exception as e:
2678 - print(f" ⚠ Hook {hook_name} dla {pkg.name}: {e}")
2679 - _audit(f"hook ERROR {tag}: {e}")
2680 - return False
2681 -
2682 -# =============================================================================
2683 -# TRANSAKCJE I ROLLBACK
2684 -# =============================================================================
2685 -
2686 -def _record_transaction(action, packages, success, snapshot, file_journal=None, hooks=None,
2687 - upgrade_backups=None, upgrade_backup_root=""):
2688 - history = load_json(HISTORY_FILE) if os.path.exists(HISTORY_FILE) else []
2689 - # Rejestr wykonanych hooków – informacja o tym, że uruchomiono kod pakietu
2690 - # jako root. Trafia do historii, by dało się później sprawdzić, co się działo.
2691 - executed_hooks = list(_HOOKS_RUN) if hooks is None else hooks
2692 - _HOOKS_RUN.clear()
2693 - entry = {
2694 - "action": action, "packages": packages, "success": success,
2695 - "timestamp": datetime.now().isoformat(),
2696 - "snapshot": snapshot,
2697 - "file_journal": file_journal, # lista plików do wycofania
2698 - "hooks": executed_hooks, # wykonane hooki (pre/post-install/remove)
2699 - }
2700 - if upgrade_backups:
2701 - entry["upgrade_backups"] = upgrade_backups # {dst: backup_path}
2702 - entry["upgrade_backup_root"] = upgrade_backup_root
2703 - history.append(entry)
2704 - if len(history) > 50:
2705 - history = history[-50:]
2706 - save_json(HISTORY_FILE, history)
2707 -
2708 -def cmd_history():
2709 - if not os.path.exists(HISTORY_FILE):
2710 - print(_("no_history")); return
2711 - history = load_json(HISTORY_FILE)
2712 - if not history:
2713 - print(_("no_history")); return
2714 - print(f"Ostatnie transakcje ({len(history)}):")
2715 - for i, e in enumerate(reversed(history), 1):
2716 - icon = "✅" if e["success"] else "❌"
2717 - pkgs = ", ".join(e["packages"][:5])
2718 - if len(e["packages"]) > 5: pkgs += f" (+{len(e['packages'])-5})"
2719 - print(f" {i}. {icon} {e['action']}: {pkgs}")
2720 - print(f" {e['timestamp']}")
2721 -
2722 -def cmd_rollback():
2723 - if not os.path.exists(HISTORY_FILE):
2724 - print(_("no_history")); return 1
2725 - history = load_json(HISTORY_FILE)
2726 - if not history:
2727 - print(_("no_history")); return 1
2728 -
2729 - last = None
2730 - for e in reversed(history):
2731 - if e["success"] and e.get("snapshot"):
2732 - last = e; break
2733 -
2734 - if not last:
2735 - print("❌ No snapshot to restore."); return 1
2736 -
2737 - print(f"⏪ Rolling back: {last['action']} ({last['timestamp']})")
2738 - print(f" Packages: {', '.join(last['packages'][:10])}")
2739 -
2740 - if not _ask_confirm():
2741 - return 0
2742 -
2743 - # Przywróć installed.json
2744 - save_json(INSTALLED_DB, last["snapshot"])
2745 -
2746 - # Wycofaj fizyczne pliki (jeśli zapisano journal)
2747 - # Deduplikacja: pakiet może zgłosić ten sam plik więcej niż raz (np. przez
2748 - # `provides` lub wspólną ścieżkę), a journal z historii mógł zostać zapisany
2749 - # przed dodaniem deduplikacji.
2750 - file_journal = list(dict.fromkeys(last.get("file_journal", [])))
2751 - upgrade_backups = last.get("upgrade_backups", {}) or {}
2752 - backup_root = last.get("upgrade_backup_root", "")
2753 -
2754 - # Przywróć stare wersje z backupów (upgrade) – nadpisane i usunięte stale pliki
2755 - for dst, bpath in upgrade_backups.items():
2756 - full = os.path.join(PAG_ROOT, dst.lstrip("/"))
2757 - if bpath and os.path.lexists(bpath):
2758 - try:
2759 - os.makedirs(os.path.dirname(full), exist_ok=True)
2760 - os.replace(bpath, full)
2761 - except OSError:
2762 - pass
2763 -
2764 - # Usuń nowe pliki (które nie miały poprzedniej wersji)
2765 - backed = set(upgrade_backups)
2766 - if file_journal:
2767 - for fpath in reversed(file_journal):
2768 - if fpath in backed:
2769 - continue
2770 - full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
2771 - if os.path.exists(full) or os.path.islink(full):
2772 - os.remove(full)
2773 - print(f" {_('rollback_files', len(file_journal))}")
2774 -
2775 - # Sprzątanie pustych katalogów + katalogu backupów
2776 - dirs = set()
2777 - for fpath in file_journal:
2778 - parent = os.path.dirname(fpath)
2779 - while parent and parent != "/":
2780 - dirs.add(parent)
2781 - parent = os.path.dirname(parent)
2782 - for d in sorted(dirs, key=len, reverse=True):
2783 - full_d = os.path.join(PAG_ROOT, d.lstrip("/"))
2784 - if os.path.isdir(full_d):
2785 - try:
2786 - os.rmdir(full_d)
2787 - except OSError:
2788 - pass
2789 - if backup_root:
2790 - shutil.rmtree(backup_root, ignore_errors=True)
2791 -
2792 - print(f"✅ {_('rollback_restored')}")
2793 - _record_transaction("rollback", last["packages"], True, None)
2794 - return 0
2795 -
2796 -# =============================================================================
2797 -# INSTALACJA
2798 -# =============================================================================
2799 -
2800 -def _install_local_pkg_files(paths, install_succeeded):
2801 - """Instaluje lokalne pliki .pkg.tar.xz (bez repozytorium).
2802 - Zgodnie z _atomic_install każdy plik jest instalowany atomowo.
2803 - Zwraca (failed_count, installed_files)."""
2804 - failed = 0
2805 - all_files = []
2806 - for p in paths:
2807 - p = os.path.abspath(p)
2808 - if not os.path.isfile(p):
2809 - print(f" ❌ Nie znaleziono pakietu: {p}")
2810 - failed += 1
2811 - continue
2812 - if not _verify_local_pkg_signature(p):
2813 - failed += 1
2814 - continue
2815 - try:
2816 - with tarfile.open(p, "r:xz") as tf:
2817 - meta = tf.extractfile("metadata.json")
2818 - if meta is None:
2819 - print(f" ❌ {p}: brak metadata.json")
2820 - failed += 1
2821 - continue
2822 - data = json.loads(meta.read())
2823 - except Exception as e:
2824 - print(f" ❌ {p}: nie udało się odczytać pakietu ({e})")
2825 - failed += 1
2826 - continue
2827 - pkg = PackageInfo(data, repo="local")
2828 - print(f" ↓ {pkg.name}-{pkg.version} (lokalny) ... ", end="", flush=True)
2829 - ok, files, _ = _atomic_install(p, pkg)
2830 - if ok:
2831 - install_succeeded(pkg, files)
2832 - all_files.extend(f["path"] for f in files)
2833 - print("✅")
2834 - else:
2835 - print("❌")
2836 - failed += 1
2837 - return failed, all_files
2838 -
2839 -
2840 -def _preflight_disk(total_bytes: int) -> bool:
2841 - """Pre-flight przed transakcją: wolne miejsce + mount read-only.
2842 -
2843 - Zwraca False (przerywa instalację) gdy na partycji docelowej brakuje
2844 - miejsca na pakiety albo katalog stagingu jest zamontowany read-only
2845 - (inaczej instalacja rwałaby się w połowie, zostawiając uszkodzony system).
2846 - """
2847 - target = PAG_ROOT or "/"
2848 - try:
2849 - st = os.statvfs(target)
2850 - free = st.f_bavail * st.f_frsize
2851 - except OSError:
2852 - return True # nie da się sprawdzić – nie blokuj
2853 - need_mb = total_bytes // 1048576
2854 - free_mb = free // 1048576
2855 - if free < total_bytes:
2856 - print(f" ❌ Za mało miejsca na dysku: potrzeba ~{need_mb} MB, "
2857 - f"wolne {free_mb} MB ({target})")
2858 - return False
2859 - if free < total_bytes * 3:
2860 - print(f" ⚠ Mało miejsca na dysku: wolne {free_mb} MB, "
2861 - f"pakiety ~{need_mb} MB (rozpakowane zajmą więcej)")
2862 - # Wykryj mount read-only (test zapisu w stagingu)
2863 - try:
2864 - probe = os.path.join(STAGING_DIR, ".pag-probe")
2865 - with open(probe, "w") as f:
2866 - f.write("x")
2867 - os.remove(probe)
2868 - except OSError:
2869 - print(f" ❌ {target} jest zamontowane tylko-do-odczytu – nie można instalować.")
2870 - return False
2871 - return True
2872 -
2873 -
2874 -def cmd_install(package_names, as_dep=False, upgrade=False):
2875 - ensure_dirs()
2876 - installed_db = load_json(INSTALLED_DB)
2877 - world = load_world()
2878 - pinned = load_json(PINNED_FILE)
2879 -
2880 - # Obsługa lokalnych plików .pkg.tar.xz (zbudowanych przez pagbuild) –
2881 - # nie wymaga repozytorium ani GPG.
2882 - local_files = [p for p in package_names if p.endswith(PKG_EXT) or
2883 - (os.sep in p and os.path.isfile(os.path.abspath(p)))]
2884 - if local_files:
2885 - _local_need = sum(
2886 - os.path.getsize(os.path.abspath(p))
2887 - for p in local_files if os.path.isfile(os.path.abspath(p))
2888 - )
2889 - if not _preflight_disk(_local_need):
2890 - return 1
2891 -
2892 - def _ok(pkg, files):
2893 - installed_db[pkg.name] = {
2894 - "version": pkg.version, "release": pkg.release, "description": pkg.description,
2895 - "dependencies": pkg.dependencies, "size_bytes": pkg.size_bytes,
2896 - "sha256": pkg.sha256, "installed_at": datetime.now().isoformat(),
2897 - "repo": "local",
2898 - "provides": getattr(pkg, "provides", None) or [],
2899 - "provides_so": getattr(pkg, "provides_so", None) or [],
2900 - "requires_so": getattr(pkg, "requires_so", None) or [],
2901 - }
2902 - world.add(pkg.name)
2903 - failed_local, _fl = _install_local_pkg_files(local_files, _ok)
2904 - save_json(INSTALLED_DB, installed_db)
2905 - save_world(world)
2906 - if failed_local:
2907 - return 1
2908 - _refresh_dynamic_linker_cache()
2909 - package_names = [n for n in package_names if n not in
2910 - [os.path.abspath(x) for x in local_files] and
2911 - n not in local_files]
2912 - to_install = []
2913 - if not package_names:
2914 - return 0
2915 - # pozostałe argumenty to nazwy pakietów z repo – kontynuuj
2916 -
2917 - repo_pkgs = fetch_all_packages()
2918 -
2919 - if not repo_pkgs:
2920 - print(f"❌ {_('no_index')}"); return 1
2921 -
2922 - for name in list(package_names):
2923 - if name in pinned:
2924 - print(f"⚠ {name} {_('pinned_to')} {pinned[name]} – skipping")
2925 - package_names.remove(name)
2926 -
2927 - to_install, missing_deps = _resolve_deps(package_names, repo_pkgs, installed_db)
2928 -
2929 - # ── Pakiety, których NIE MA w repo ani nie są zainstalowane ──
2930 - # Zgłoś od razu zamiast mylącego „Do zainstalowania: N (0.00 MB)”
2931 - # i prośby o potwierdzenie (np. `pag install steam` gdy steam nie istnieje).
2932 - not_found = []
2933 - for n in package_names:
2934 - real = _resolve_provides(n, repo_pkgs, installed_db)
2935 - if real not in repo_pkgs and real not in installed_db \
2936 - and not os.path.exists(os.path.abspath(n)):
2937 - not_found.append(n)
2938 - if not_found:
2939 - print(f"\n ❌ {_('pkg_not_found', ', '.join(not_found))}")
2940 - print(f" {_('not_found_hint')}")
2941 - return 1
2942 -
2943 - # --- Tryb upgrade: pakiety już zainstalowane MUSZĄ zostać ponownie
2944 - # zainstalowane z nowszej wersji (zastąpienie w tej samej transakcji).
2945 - if upgrade:
2946 - # `pag update` przekazuje tu tylko pakiety z NOWSZĄ wersją (już
2947 - # przefiltrowane w _pending_updates), a `pag install -f` wymusza
2948 - # reinstalację nawet tej SAMEJ wersji – dlatego nie filtrujemy po
2949 - # _version_newer.
2950 - upgrade_targets = [
2951 - name for name in package_names
2952 - if name in repo_pkgs
2953 - and name in installed_db
2954 - and name not in pinned
2955 - ]
2956 - for name in upgrade_targets:
2957 - if name not in to_install:
2958 - to_install.append(name)
2959 -
2960 - if not to_install and not missing_deps:
2961 - print(f"✅ {_('all_installed')}"); return 0
2962 -
2963 - # ── WERYFIKACJA ZALEŻNOŚCI ──────────────────────────────────────────
2964 - fatal_missing = _verify_dependencies(to_install, repo_pkgs, installed_db)
2965 -
2966 - if fatal_missing > 0:
2967 - print(f"❌ Nie można kontynuować – {fatal_missing} brakujących zależności.")
2968 - print(f" Zainstaluj brakujące pakiety lub dodaj repozytoria.")
2969 - return 1
2970 -
2971 - so_missing = _verify_so_deps(to_install, repo_pkgs, installed_db)
2972 - if so_missing > 0:
2973 - print(" Zainstaluj dostawcę biblioteki lub zaktualizuj repozytorium.")
2974 - return 1
2975 -
2976 - if not to_install:
2977 - print(f"✅ {_('all_installed')}"); return 0
2978 -
2979 - MAX_MB = MAX_PKG_SIZE // 1048576
2980 - for n in to_install:
2981 - if not _validate_pkg_name(n):
2982 - print(f" {_("sec_badname", name=n)}")
2983 - return 1
2984 - sz = repo_pkgs[n].size_bytes if n in repo_pkgs else 0
2985 - if sz > MAX_PKG_SIZE:
2986 - mb = sz // 1048576
2987 - print(f" {_("sec_toobig", size_mb=mb, max_mb=MAX_MB)}")
2988 - return 1
2989 - total_size = sum(repo_pkgs[n].size_bytes for n in to_install if n in repo_pkgs)
2990 - if not _preflight_disk(total_size):
2991 - return 1
2992 - print(f"\n📦 {_('to_install', len(to_install), total_size/1048576)}")
2993 - for name in to_install:
2994 - p = repo_pkgs.get(name)
2995 - if p:
2996 - if name in installed_db:
2997 - marker = " [upgrade]" if upgrade else ""
2998 - else:
2999 - marker = f" [{_('new')}]"
3000 - print(f" {name}-{p.version}{marker}")
3001 -
3002 - # Pakiet z bazy obrazu ISO (nie w installed.json) → ostrzeż, że pliki z ISO
3003 - # zostaną zastąpione pakietem z repo (kopia do `pag rollback`).
3004 - _base_warn_overwrite(to_install)
3005 -
3006 - if not as_dep and not upgrade:
3007 - if not _ask_confirm():
3008 - print(_("cancelled")); return 0
3009 -
3010 - snapshot = copy.deepcopy(installed_db)
3011 - all_installed_files = []
3012 - failed = []
3013 - # Pary (pkg, stare_pliki, nowe_pliki) do usunięcia martwych plików po upgrade
3014 - stale_candidates = []
3015 - # Katalog backupów nadpisywanych plików – dla poprawnego rollbacku.
3016 - # Dla KAŻDEJ transakcji: instalacja „nowego” pakietu także nadpisuje pliki
3017 - # spoza bazy pag (baza rootfs/ISO), a rollback bez backupu by je skasował.
3018 - backup_root = ""
3019 - all_backups: List[Tuple[str, str]] = [] # (backup_path, dst)
3020 - if to_install:
3021 - backup_root = _new_transaction_backup_root()
3022 -
3023 - # --- Dziennik transakcji (dla pełnej atomowości) ---
3024 - # Jeśli którykolwiek pakiet zawiedzie, cofamy WSZYSTKIE zainstalowane
3025 - # w tej transakcji przez _rollback_transaction().
3026 - transaction_journal: List[Tuple[str, str, str]] = [] # (op, src, dst)
3027 -
3028 - # --- Tryb immutable: utwórz nowy deployment ---
3029 - immutable = os.environ.get("PAG_IMMUTABLE", "") == "1"
3030 - deploy_dir = ""
3031 - deploy_id = ""
3032 - if immutable:
3033 - print(f"\n 🏗️ Tworzenie nowego deploymentu...")
3034 - deploy_dir, deploy_id = _create_deployment(to_install, "upgrade" if upgrade else "install")
3035 - target_root = deploy_dir
3036 - else:
3037 - target_root = ""
3038 -
3039 - # --- Faza 1: Równoległe pobieranie wszystkich pakietów ---
3040 - to_download = [repo_pkgs[name] for name in to_install if name in repo_pkgs]
3041 - if len(to_download) > 1:
3042 - print(f"\n ⏬ Pobieranie {len(to_download)} pakietów równolegle...")
3043 - downloaded = _download_packages_parallel(to_download)
3044 - else:
3045 - downloaded = {}
3046 -
3047 - # --- Faza 1b: WERYFIKACJA WSZYSTKICH paczek PRZED instalacją ---
3048 - # KLUCZOWE: GPG i SHA256 sprawdzamy dla WSZYSTKICH paczek, ZANIM
3049 - # zainstalujemy choćby jedną. Inaczej instalowany pakiet może podmienić
3050 - # bibliotekę używaną przez sam gpg (np. libassuan 3.0.1 zmienił namespace
3051 - # symboli LIBASSUAN_1.0 -> LIBASSUAN_2.0) i wtedy weryfikacja kolejnych
3052 - # paczek w tej samej transakcji pada, dając fałszywe
3053 - # „NIEPRAWIDŁOWY PODPIS GPG".
3054 - verified = {}
3055 - _vfail = []
3056 - for _name in to_install:
3057 - _pkg = repo_pkgs.get(_name)
3058 - if not _pkg:
3059 - _vfail.append((_name, _('not_found')))
3060 - continue
3061 - _pp = downloaded.get(_name)
3062 - if not _pp:
3063 - _pp = _download_pkg(_pkg)
3064 - if not _pp:
3065 - _vfail.append((_name, _('download_fail')))
3066 - continue
3067 - _gok, _gmsg = _verify_pkg_gpg(_pp, repo_url=_pkg.repo_url)
3068 - if not _gok:
3069 - _vfail.append((_name, f"{_('gpg_fail')}: {_gmsg[:60]}"))
3070 - continue
3071 - if _pkg.sha256 and _sha256_file(_pp) != _pkg.sha256:
3072 - _vfail.append((_name, _('sha256_mismatch')))
3073 - continue
3074 - verified[_name] = _pp
3075 - if _vfail:
3076 - for _n, _m in _vfail:
3077 - print(f" ❌ {_n}: {_m}")
3078 - print(" ↩ Przerwano PRZED instalacją – żadna paczka nie została zmieniona.")
3079 - return 1
3080 -
3081 - # --- Faza 2: Instalacja – JEDNA nadpisywana linia postępu (jak przy
3082 - # pobieraniu), bez ściany tekstu na każdy pakiet. W trybie
3083 - # nieinteraktywnym (logi, netinstall instalatora) wypisujemy linię na
3084 - # pakiet – tam to pożądane do logu.
3085 - t0 = time.time()
3086 - stdout_tty = sys.stdout.isatty()
3087 -
3088 - # Animowany pasek postępu („drakkar”) – jedna nadpisywana linia; morze
3089 - # faluje nawet wtedy, gdy pojedynczy pakiet instaluje się długo.
3090 - _pbar = _StepBar(len(to_install), icon="📦 ", width=25)
3091 -
3092 - def _bar_draw(idx: int, name: str) -> None:
3093 - _pbar.step(idx, name)
3094 -
3095 - def _bar_end() -> None:
3096 - _pbar.end()
3097 -
3098 - _pkg_i = 0
3099 - for name in to_install:
3100 - pkg = repo_pkgs.get(name)
3101 - if not pkg:
3102 - _bar_end()
3103 - print(f" ❌ {name}: {_('not_found')}")
3104 - failed.append(name)
3105 - break
3106 -
3107 - _pkg_i += 1
3108 - _bar_draw(_pkg_i, f"{name}-{pkg.version}")
3109 -
3110 - # Ścieżka pobrana i ZWERYFIKOWANA w fazie 1b – PRZED jakąkolwiek
3111 - # instalacją (patrz komentarz przy fazie 1b). Dzięki temu podmiana
3112 - # biblioteki używanej przez gpg nie psuje weryfikacji pozostałych.
3113 - pkg_path = verified.get(name)
3114 - if not pkg_path:
3115 - _bar_end()
3116 - print(f" ❌ {name}: {_('download_fail')}")
3117 - failed.append(name)
3118 - break # przerwij transakcję
3119 -
3120 - # Przed instalacją zapamiętaj pliki starej wersji (potrzebne w upgrade)
3121 - old_files = _db_get_package_files(name) if name in installed_db else []
3122 - # Stare sumy SHA256 – do wykrycia zmian użytkownika w plikach /etc (.pacnew)
3123 - old_checksums = _db_get_package_checksums(name) if name in installed_db else None
3124 -
3125 - # Atomowa instalacja (w upgrade backupuje nadpisywane pliki)
3126 - ok, files, backup_j = _atomic_install(pkg_path, pkg, deploy_dir,
3127 - backup_dir=backup_root,
3128 - old_checksums=old_checksums)
3129 - if ok:
3130 - installed_db[name] = {
3131 - "version": pkg.version, "release": pkg.release, "description": pkg.description,
3132 - "dependencies": pkg.dependencies, "size_bytes": pkg.size_bytes,
3133 - "sha256": pkg.sha256, "installed_at": datetime.now().isoformat(),
3134 - "repo": pkg.repo_url,
3135 - "provides": getattr(pkg, "provides", None) or [],
3136 - "provides_so": getattr(pkg, "provides_so", None) or [],
3137 - "requires_so": getattr(pkg, "requires_so", None) or [],
3138 - }
3139 - if not as_dep and name in package_names:
3140 - world.add(name)
3141 - if not stdout_tty:
3142 - print(f" ✓ {name}-{pkg.version}", flush=True)
3143 - all_installed_files.extend(f["path"] for f in files)
3144 - all_backups.extend(backup_j)
3145 -
3146 - # Upgrade: zapamiętaj stare pliki, by po sukcesie usunąć te,
3147 - # których nie ma już w nowej wersji.
3148 - if upgrade and old_files:
3149 - stale_candidates.append((name, old_files, [f["path"] for f in files]))
3150 -
3151 - # Po instalacji kernela – przebuduj initramfs
3152 - if _is_kernel_package(name):
3153 - _rebuild_initramfs(deploy_dir)
3154 - else:
3155 - _bar_end()
3156 - print(f" ❌ {name}: {_('install_failed')}")
3157 - failed.append(name)
3158 - break # PRZERWIJ – błąd instalacji
3159 -
3160 - # Deduplikacja journalu – ten sam plik może trafić tu dwukrotnie (np. przez
3161 - # `provides`); rollback i historia nie potrzebują duplikatów.
3162 - all_installed_files = list(dict.fromkeys(all_installed_files))
3163 -
3164 - # --- Rollback całej transakcji jeśli cokolwiek zawiodło ---
3165 - if failed:
3166 - _bar_end()
3167 - print(f"\n ↩ Cofanie transakcji ({len(failed)} błędów)...")
3168 - _rollback_transaction(installed_db, snapshot, all_installed_files,
3169 - deploy_dir, immutable, backups=all_backups)
3170 - if backup_root:
3171 - shutil.rmtree(backup_root, ignore_errors=True)
3172 - _record_transaction("upgrade" if upgrade else "install", to_install, False, snapshot)
3173 - return 1
3174 -
3175 - # --- Po sukcesie transakcji: usuń nieaktualne pliki starych wersji (upgrade).
3176 - # Usunięte pliki trafiają do backupu, aby `pag rollback` mógł je przywrócić.
3177 - for pkg_name, old_files, new_paths in stale_candidates:
3178 - _remove_stale_files(pkg_name, old_files, new_paths, installed_db, deploy_dir,
3179 - backup_root, all_backups)
3180 -
3181 - save_json(INSTALLED_DB, installed_db)
3182 - save_world(world)
3183 - _record_transaction("upgrade" if upgrade else "install", to_install, True, snapshot,
3184 - file_journal=all_installed_files,
3185 - upgrade_backups={dst: bp for bp, dst in all_backups} if all_backups else None,
3186 - upgrade_backup_root=backup_root)
3187 -
3188 - # Zachowaj backupy bieżącej transakcji (dla `pag rollback`), usuń starsze.
3189 - if backup_root:
3190 - _purge_old_backups(keep_root=backup_root)
3191 -
3192 - _bar_end()
3193 -
3194 - # --- Tryb immutable: przełącz na nowy deployment ---
3195 - if immutable and not failed:
3196 - _refresh_dynamic_linker_cache(deploy_dir)
3197 - print(f"\n 🔄 Przełączanie na deployment {deploy_id}...")
3198 - _switch_deployment(deploy_dir)
3199 - print(f" ✅ Aktywny deployment: {deploy_id}")
3200 - _update_grub_config()
3201 - cmd_deploy_cleanup(keep=5) # Zostawia 5 najnowszych deploymentów
3202 - print(f" 💡 Restart wymagany do przeładowania systemu.")
3203 - else:
3204 - _refresh_dynamic_linker_cache()
3205 - # Hooki zbiorcze – raz na transakcję (fc-cache itp.), tylko gdy pliki
3206 - # trafiły do realnego systemu (nie do deploymentu).
3207 - _process_triggers(all_installed_files)
3208 -
3209 - print(f"\n✅ {_('installed', len(to_install))} ({(time.time()-t0):.0f}s)")
3210 - return 0
3211 -
3212 -
3213 -def _rollback_transaction(installed_db: dict, snapshot: dict,
3214 - installed_files: List[str],
3215 - deploy_dir: str, is_immutable: bool,
3216 - backups: Optional[List[Tuple[str, str]]] = None):
3217 - """
3218 - Cofa WSZYSTKIE pakiety zainstalowane w bieżącej transakcji.
3219 - Przywraca installed_db do stanu sprzed transakcji.
3220 - Usuwa fizyczne pliki z systemu (lub deploymentu w trybie immutable).
3221 - Jeśli podano `backups` (upgrade) – przywraca stare wersje nadpisanych plików.
3222 - """
3223 - # Przywróć installed_db
3224 - installed_db.clear()
3225 - installed_db.update(snapshot)
3226 -
3227 - root = deploy_dir if is_immutable else PAG_ROOT
3228 - backup_map = {dst: src for src, dst in (backups or [])}
3229 -
3230 - # Przywróć stare wersje z backupów (upgrade)
3231 - for dst, bpath in backup_map.items():
3232 - full = os.path.join(root, dst.lstrip("/"))
3233 - if os.path.lexists(bpath):
3234 - try:
3235 - os.makedirs(os.path.dirname(full), exist_ok=True)
3236 - os.replace(bpath, full)
3237 - except OSError:
3238 - pass
3239 -
3240 - # Usuń nowe pliki (które nie miały poprzedniej wersji)
3241 - for fpath in reversed(installed_files):
3242 - if fpath in backup_map:
3243 - continue
3244 - full = os.path.join(root, fpath.lstrip("/"))
3245 - if os.path.isfile(full) or os.path.islink(full):
3246 - try:
3247 - os.remove(full)
3248 - except OSError:
3249 - pass
3250 -
3251 - # Wyczyść puste katalogi
3252 - dirs_to_check = set()
3253 - for fpath in installed_files:
3254 - parent = os.path.dirname(fpath)
3255 - while parent and parent != "/":
3256 - dirs_to_check.add(parent)
3257 - parent = os.path.dirname(parent)
3258 - for d in sorted(dirs_to_check, key=len, reverse=True):
3259 - full_d = os.path.join(root, d.lstrip("/"))
3260 - if os.path.isdir(full_d):
3261 - try:
3262 - os.rmdir(full_d)
3263 - except OSError:
3264 - pass
3265 -
3266 - # W trybie immutable: usuń nieudany deployment
3267 - if is_immutable and deploy_dir:
3268 - shutil.rmtree(deploy_dir, ignore_errors=True)
3269 -
3270 - save_json(INSTALLED_DB, snapshot)
3271 -
3272 -
3273 -# =============================================================================
3274 -# USUWANIE
3275 -# =============================================================================
3276 -
3277 -def cmd_remove(package_names):
3278 - installed_db = load_json(INSTALLED_DB)
3279 - world = load_world()
3280 - snapshot = copy.deepcopy(installed_db)
3281 - removed = []
3282 - removed_files = []
3283 -
3284 - total = len(package_names)
3285 - for i, name in enumerate(package_names, 1):
3286 - if name not in installed_db:
3287 - print(f" ⚠ {name}: not installed"); continue
3288 -
3289 - # Pasek postępu (animowany „drakkar” na TTY)
3290 - pct = (i - 1) / total * 100
3291 - bar = _pagan_bar(pct, 25, time.time(), animated=sys.stderr.isatty())
3292 - print(f" 🗑 [{bar}] {i}/{total} ({pct:.0f}%) ", end="\r", file=sys.stderr, flush=True)
3293 -
3294 - print(f"🗑 {name}-{installed_db[name]['version']} ...", end=" ", flush=True)
3295 -
3296 - # Pre-remove hook (jeśli dostępny w staging)
3297 - _run_hook_for_installed(name, "pre-remove")
3298 -
3299 - count, rm_files = _safe_remove_files(name, installed_db)
3300 - del installed_db[name]
3301 - world.discard(name)
3302 - removed.append(name)
3303 - removed_files.extend(rm_files)
3304 - print(f"✅ ({count} files)")
3305 -
3306 - # Post-remove hook + sprzątanie zapisanych hooków
3307 - _run_hook_for_installed(name, "post-remove")
3308 - shutil.rmtree(os.path.join(PAG_DB, "hooks", name), ignore_errors=True)
3309 -
3310 - save_json(INSTALLED_DB, installed_db)
3311 - save_world(world)
3312 - _record_transaction("remove", removed, True, snapshot)
3313 -
3314 - print(file=sys.stderr) # wyczyść linię paska postępu
3315 -
3316 - if not removed: return 0
3317 - print(f"\n✅ Removed {len(removed)}.")
3318 - _process_triggers(removed_files)
3319 -
3320 - orphans = _find_orphans(installed_db, world)
3321 - if orphans:
3322 - print(f"\n💡 {_('orphans_found', len(orphans), ', '.join(sorted(orphans)[:10]))}")
3323 - print(" 'pag remove-orphans' to clean up.")
3324 - return 0
3325 -
3326 -def _run_hook_for_installed(pkg_name, hook_name):
3327 - """Próbuje uruchomić hook z katalogu pakietu (jeśli został zapisany)."""
3328 - hook_dir = os.path.join(PAG_DB, "hooks", pkg_name)
3329 - if os.path.isdir(hook_dir):
3330 - ver = load_json(INSTALLED_DB).get(pkg_name, {}).get("version", "")
3331 - _run_hook(hook_dir, hook_name, PackageInfo({"name": pkg_name, "version": ver}))
3332 -
3333 -
3334 -# =============================================================================
3335 -# TRIGGERS – hooki zbiorcze (raz na transakcję, nie per pakiet)
3336 -# =============================================================================
3337 -# Wzorem pacman/dpkg: pakiet/administrator deklaruje zainteresowanie ścieżkami,
3338 -# a pasujący trigger uruchamia się DOKŁADNIE RAZ na końcu transakcji
3339 -# (np. fc-cache, glib-compile-schemas, update-desktop-database) zamiast po
3340 -# każdym pakiecie z osobna.
3341 -
3342 -TRIGGERS_DIR = PAG_CONF + "/triggers"
3343 -
3344 -DEFAULT_TRIGGERS = [
3345 - {"name": "font-cache", "paths": ["/usr/share/fonts/", "/usr/local/share/fonts/"],
3346 - "run": "fc-cache -fs"},
3347 - {"name": "glib-schemas", "paths": ["/usr/share/glib-2.0/schemas/"],
3348 - "run": "glib-compile-schemas /usr/share/glib-2.0/schemas"},
3349 - {"name": "desktop-database", "paths": ["/usr/share/applications/"],
3350 - "run": "update-desktop-database -q /usr/share/applications"},
3351 - {"name": "mime-database", "paths": ["/usr/share/mime/"],
3352 - "run": "update-mime-database /usr/share/mime"},
3353 -]
3354 -
3355 -def _load_triggers() -> List[dict]:
3356 - """Ładuje triggery: domyślne (tylko gdy binarka istnieje) + /etc/pag/triggers/*.json."""
3357 - out = []
3358 - for t in DEFAULT_TRIGGERS:
3359 - bin_name = t["run"].split()[0]
3360 - if shutil.which(bin_name):
3361 - out.append(dict(t))
3362 - if os.path.isdir(TRIGGERS_DIR):
3363 - for fn in sorted(os.listdir(TRIGGERS_DIR)):
3364 - if not fn.endswith(".json"):
3365 - continue
3366 - try:
3367 - with open(os.path.join(TRIGGERS_DIR, fn)) as f:
3368 - data = json.load(f)
3369 - except (OSError, json.JSONDecodeError):
3370 - continue
3371 - if isinstance(data, dict):
3372 - data = [data]
3373 - for t in data:
3374 - if isinstance(t, dict) and t.get("name") and t.get("paths") and t.get("run"):
3375 - out.append(t)
3376 - return out
3377 -
3378 -def _process_triggers(touched_paths: List[str]):
3379 - """Uruchamia pasujące triggery RAZ na końcu transakcji (best-effort)."""
3380 - if not touched_paths:
3381 - return
3382 - if os.environ.get("PAG_NO_HOOKS", "") == "1":
3383 - return
3384 - import shlex as _shlex
3385 - matched = []
3386 - for trig in _load_triggers():
3387 - if any(path.startswith(p) for p in trig["paths"] for path in touched_paths):
3388 - matched.append(trig)
3389 - for trig in matched:
3390 - run = trig["run"]
3391 - print(f" ⚡ Trigger: {trig['name']} ({run})")
3392 - try:
3393 - r = subprocess.run(_shlex.split(run), capture_output=True, text=True, timeout=120)
3394 - _audit(f"TRIGGER {trig['name']}: {run} rc={r.returncode}")
3395 - if r.returncode != 0:
3396 - print(f" ⚠ rc={r.returncode}: {(r.stderr or r.stdout or '').strip()[:160]}")
3397 - except subprocess.TimeoutExpired:
3398 - print(f" ⚠ trigger {trig['name']} przekroczył limit czasu (120 s)")
3399 - _audit(f"TRIGGER {trig['name']} TIMEOUT")
3400 - except Exception as e:
3401 - print(f" ⚠ trigger {trig['name']}: {e}")
3402 -
3403 -# =============================================================================
3404 -# UPDATE / UPGRADE / LIST / SEARCH / INFO / VERIFY
3405 -# =============================================================================
3406 -
3407 -def _cleanup_tmp_files(*paths):
3408 - """Usuwa tymczasowe pliki (np. .pag.new) po nieudanej operacji."""
3409 - for p in paths:
3410 - try:
3411 - if os.path.isfile(p):
3412 - os.remove(p)
3413 - except OSError:
3414 - pass
3415 -
3416 -
3417 -def cmd_self_update():
3418 - """Aktualizuje samego klienta pag z repo (podpisany /stable/pag).
3419 -
3420 - Kolejność: pobierz → weryfikacja GPG (+ fingerprint repo) → SHA256 →
3421 - kontrola składni (compile) → backup → atomowe os.replace.
3422 -
3423 - Podmieniamy plik, z którego pag ZOSTAŁ URUCHOMIONY (a nie hardkodowane
3424 - /usr/local/bin/pag): gdy pakiet instaluje /usr/bin/pag, a self-update
3425 - pisał do /usr/local/bin/pag, powstawały DWIE kopie o różnych wersjach
3426 - i zależnie od PATH `pag --version` pokazywał raz jedną, raz drugą."""
3427 - # Dedykowana blokada – patrz SelfUpdateLock. Chroni zapis dst.new oraz
3428 - # os.replace przed równoległą aktualizacją (np. cron + ręcznie).
3429 - with SelfUpdateLock():
3430 - return _self_update_impl()
3431 -
3432 -
3433 -def _self_update_impl():
3434 - repos = get_repos()
3435 - if not repos:
3436 - print("❌ Brak repozytoriów w konfiguracji.")
3437 - return 1
3438 - # Aktualizuj bieżący plik (Python ≥3.9 ustawia __file__ jako ścieżkę
3439 - # bezwzględną). Poza /usr|/usr/local (np. uruchomienie z checkoutu)
3440 - # nie nadpisujemy niczego – wracamy do domyślnej lokalizacji instalacji.
3441 - dst = "/usr/local/bin/pag"
3442 - try:
3443 - cand = os.path.realpath(__file__)
3444 - if cand.startswith(("/usr/", "/usr/local/")):
3445 - dst = cand
3446 - except Exception:
3447 - pass
3448 - base = repos[0]
3449 - dst_new = dst + ".new"
3450 - dst_bak = dst + ".bak"
3451 - print(f"🔄 Sprawdzam aktualizację pag z {base}...")
3452 - try:
3453 - with urlopen(Request(f"{base}/pag", headers={"User-Agent": "pag/3.0"}), timeout=20) as r:
3454 - data = r.read()
3455 - with urlopen(Request(f"{base}/pag.asc", headers={"User-Agent": "pag/3.0"}), timeout=20) as r:
3456 - sig = r.read()
3457 - except Exception as e:
3458 - print(f" ❌ Nie można pobrać pag: {e}")
3459 - return 1
3460 -
3461 - # Zapisz nową wersję w katalogu docelowym (ta sama partycja → atomowy rename)
3462 - with open(dst_new, "wb") as f:
3463 - f.write(data)
3464 - with open(dst_new + ".asc", "wb") as f:
3465 - f.write(sig)
3466 -
3467 - # --- 1. Weryfikacja podpisu GPG – bez tego nie instalujemy ---
3468 - insecure = os.environ.get("PAG_INSECURE", "") == "1"
3469 - ok, fp = _gpg_verify_fp(dst_new + ".asc", dst_new)
3470 - if not ok:
3471 - # Automatyczny import klucza (TOFU) – jak w _verify_repo_sig
3472 - res = _gpg_run("--verify", dst_new + ".asc", dst_new,
3473 - capture_output=True, text=True)
3474 - _stderr = res.stderr.decode(errors="replace") if isinstance(res.stderr, bytes) else (res.stderr or "")
3475 - if "public key" in _stderr.lower() and "no public key" in _stderr.lower():
3476 - try:
3477 - with urlopen(Request(f"{base}/paganos.asc", headers={"User-Agent": "pag/3.0"}), timeout=20) as r:
3478 - keydata = r.read()
3479 - with tempfile.NamedTemporaryFile(delete=False, suffix=".asc") as tmp:
3480 - tmp.write(keydata); tmp.flush()
3481 - _gpg_run("--import", tmp.name, capture_output=True, timeout=30)
3482 - os.unlink(tmp.name)
3483 - print(f" 🔑 Importowano klucz repo z {base}/paganos.asc")
3484 - ok, fp = _gpg_verify_fp(dst_new + ".asc", dst_new)
3485 - except Exception:
3486 - pass
3487 - if not ok:
3488 - if insecure:
3489 - print(" ⚠ Nieprawidłowy podpis aktualizacji (PAG_INSECURE – ignoruję)")
3490 - else:
3491 - print(" ❌ Nieprawidłowy podpis aktualizacji – nie aktualizuję.")
3492 - _cleanup_tmp_files(dst_new, dst_new + ".asc")
3493 - return 1
3494 - # Sprawdź fingerprint względem przypiętego klucza repo
3495 - pinned = _repo_pinned_fp(base)
3496 - if pinned:
3497 - if not fp:
3498 - print(" ❌ Nie można potwierdzić fingerprintu podpisu aktualizacji.")
3499 - _cleanup_tmp_files(dst_new, dst_new + ".asc")
3500 - return 1
3501 - if fp != pinned.upper():
3502 - if insecure:
3503 - print(" ⚠ Podpis aktualizacji innym kluczem (PAG_INSECURE – ignoruję)")
3504 - else:
3505 - print(" ❌ [SECURITY ERROR] Podpis aktualizacji innym kluczem niż repo!")
3506 - print(f" Oczekiwany: {pinned}, Otrzymany: {fp}")
3507 - _cleanup_tmp_files(dst_new, dst_new + ".asc")
3508 - return 1
3509 -
3510 - # --- 2. Weryfikacja SHA256 (jeśli repo publikuje pag.sha256) ---
3511 - try:
3512 - with urlopen(Request(f"{base}/pag.sha256", headers={"User-Agent": "pag/3.0"}), timeout=15) as r:
3513 - sha = r.read().decode().strip().split()[0]
3514 - if sha:
3515 - actual = hashlib.sha256(data).hexdigest()
3516 - if actual.lower() != sha.lower():
3517 - print(f" ❌ SHA256 niezgodny! Oczekiwano {sha}, jest {actual}")
3518 - _cleanup_tmp_files(dst_new, dst_new + ".asc")
3519 - return 1
3520 - print(" ✅ SHA256 zgodny")
3521 - except Exception:
3522 - # Brak pag.sha256 w repo – opcjonalne; nie blokuj aktualizacji.
3523 - pass
3524 -
3525 - # --- 3. Kontrola składni (nie uruchamiaj uszkodzonego/poddanego edycji pliku) ---
3526 - try:
3527 - compile(data, "pag", "exec")
3528 - except SyntaxError as e:
3529 - print(f" ❌ Błąd składni w nowym pag: {e}")
3530 - _cleanup_tmp_files(dst_new, dst_new + ".asc")
3531 - return 1
3532 -
3533 - m = (re.search(rb'PAG_VERSION\s*=\s*"(\d+\.\d+\.\d+[a-z]?)"', data[:3000])
3534 - or re.search(rb"v(\d+\.\d+\.\d+[a-z]?)", data[:3000]))
3535 - new_ver = m.group(1).decode() if m else "?"
3536 - print(f" ✅ Pobrano pag {new_ver} (obecny {PAG_VERSION}), podpis zweryfikowany")
3537 -
3538 - # --- 4. Backup + atomowa podmiana ---
3539 - if os.path.exists(dst):
3540 - shutil.copy2(dst, dst_bak)
3541 - os.chmod(dst_new, 0o755)
3542 - os.replace(dst_new, dst) # atomowe na tym samym FS
3543 - try:
3544 - if os.path.exists(dst_new + ".asc"):
3545 - os.remove(dst_new + ".asc")
3546 - except OSError:
3547 - pass
3548 - print(f" ✅ Zainstalowano nowy pag. Stary zachowany jako {dst_bak}")
3549 - # Ostrzeż, gdy w PATH pierwsza jest INNA kopia `pag` – inaczej
3550 - # `pag --version` dalej pokaże starą wersję i wygląda to jak brak update.
3551 - other = shutil.which("pag")
3552 - if other and os.path.realpath(other) != os.path.realpath(dst):
3553 - print(f" ⚠ W PATH pierwszy jest inny pag: {other} (zaktualizowano {dst})")
3554 - print(f" Usuń starą kopię: sudo rm {other}")
3555 - print(" Uruchom ponownie pag, aby użyć nowej wersji.")
3556 - return 0
3557 -
3558 -
3559 -def _candidate_newer(rp, inst):
3560 - """Czy pakiet z repo jest nowszy od zainstalowanego.
3561 - Porównuje (version, release): sam bump pkgrel (np. auto-rebuild modułów
3562 - po aktualizacji jądra: nvidia-kernel-618 610.57.04-1 -> -2) też musi być
3563 - widziany przez `pag update`. Stare rekordy instalacji (bez pola release)
3564 - traktujemy jak release=1 – nie generują churnu, dopóki nie wrócą do
3565 - reinstalacji/zmiany wersji."""
3566 - rv = getattr(rp, "version", "0")
3567 - iv = inst.get("version", "0")
3568 - if _version_newer(rv, iv):
3569 - return True
3570 - if rv != iv:
3571 - return False
3572 - rr = int(getattr(rp, "release", 1) or 1)
3573 - ir = int(inst.get("release", 1) or 1)
3574 - return rr > ir
3575 -
3576 -
3577 -def _pending_updates() -> List[str]:
3578 - """Zainstalowane pakiety z nowszą wersją/release w repo (bez przypiętych)."""
3579 - installed = load_json(INSTALLED_DB)
3580 - pinned = load_json(PINNED_FILE)
3581 - repo = fetch_all_packages()
3582 - if not repo:
3583 - return []
3584 - return [n for n, i in installed.items()
3585 - if n not in pinned and (rp := repo.get(n)) and _candidate_newer(rp, i)]
3586 -
3587 -# =============================================================================
3588 -# BAZA Z OBRAZU ISO → REPO (`pag base`) – pełny rolling
3589 -# =============================================================================
3590 -# ISO jest zbudowane ZE ŹRÓDEŁ (glibc, gcc, gtk, XFCE, …) – pag tych pakietów
3591 -# nie instalował, więc nie ma ich w installed.json/files.db. Skutki:
3592 -# • `pag upgrade` ich NIE dotyka (nie ma o nich pojęcia),
3593 -# • mimo to `pag install <nazwa>` je NADPISZE – pag robi kopię plików spoza
3594 -# swojej bazy (patrz _new_transaction_backup_root), więc nie są nietykalne.
3595 -#
3596 -# /usr/share/pag/base.json (wypalany przez build-pagan.sh) mówi, co jest w bazie
3597 -# obrazu i w jakiej wersji. `pag base` pokazuje stan, a `pag base adopt` dogrywa
3598 -# te pakiety z repo – po tym zabiegu pag zarządza nimi normalnie, więc
3599 -# `pag upgrade` aktualizuje CAŁY system (rolling), a nie tylko to, co sam
3600 -# wcześniej zainstalował.
3601 -#
3602 -# Nazwy z buildera różnią się od nazw pakietów w repo (builder buduje „libX11”,
3603 -# repo ma pakiet „xorg-libx11”), stąd aliasy poniżej. Nazwy bez odpowiednika
3604 -# w repo zostają w wersji z obrazu – raport mówi o tym wprost, zamiast udawać,
3605 -# że są aktualne.
3606 -BASE_NAME_ALIASES = {
3607 - "atk": "at-spi2-core",
3608 - "dejavu-fonts": "dejavu-ttf",
3609 - "fontconfig": "xorg-fontconfig",
3610 - "gtk": "gtk3",
3611 - "iceauth": "xorg-iceauth",
3612 - "libX11": "xorg-libx11",
3613 - "libXau": "xorg-libxau",
3614 - "libXdmcp": "xorg-libxdmcp",
3615 - "libXext": "xorg-libxext",
3616 - "libXft": "xorg-libxft",
3617 - "libdrm": "xorg-libdrm",
3618 - "libnspr": "nspr",
3619 - "libxkbfile": "xorg-libxkbfile",
3620 - "libxklavier": "xorg-libxklavier",
3621 - "linux-pam": "pam",
3622 - "pixman": "xorg-pixman",
3623 - "sdl2": "sdl",
3624 - "setxkbmap": "xorg-setxkbmap",
3625 - "xauth": "xorg-xauth",
3626 - "xf86-input-libinput": "xorg-xf86-input-libinput",
3627 - "xf86-video-fbdev": "xorg-xf86-video-fbdev",
3628 - "xinit": "xorg-xinit",
3629 - "xkbcomp": "xorg-xkbcomp",
3630 - "xkeyboard-config": "xorg-xkeyboard-config",
3631 - # Builder buduje wpa_supplicant (z podkreślnikiem), a repo ma wpa-supplicant
3632 - # (z myślnikiem) – bez tego aliasu pakiet nie dostawał aktualizacji z repo,
3633 - # mimo że repo.json zna DOKŁADNIE tę samą wersję.
3634 - "wpa_supplicant": "wpa-supplicant",
3635 -}
3636 -
3637 -
3638 -def _base_manifest() -> dict:
3639 - """Manifest bazy z obrazu ({} gdy obraz go nie dostarcza)."""
3640 - _d = load_json(os.path.join(PAG_ROOT, BASE_MANIFEST.lstrip("/")))
3641 - return _d if isinstance(_d, dict) else {}
3642 -
3643 -
3644 -def _base_entries() -> list:
3645 - """[(nazwa_z_buildera, wersja_z_obrazu), ...] z manifestu."""
3646 - _out = []
3647 - for _e in (_base_manifest().get("packages") or []):
3648 - if isinstance(_e, str):
3649 - if _e:
3650 - _out.append((_e, "?"))
3651 - elif isinstance(_e, dict) and _e.get("name"):
3652 - _out.append((str(_e["name"]), str(_e.get("version") or "?")))
3653 - return _out
3654 -
3655 -
3656 -def _base_repo_name(name: str, repo: dict, installed: dict) -> str:
3657 - """Nazwa pakietu w repo dla nazwy z buildera (alias → provides → brak)."""
3658 - if name in repo:
3659 - return name
3660 - _alias = BASE_NAME_ALIASES.get(name)
3661 - if _alias and _alias in repo:
3662 - return _alias
3663 - _real = _resolve_provides(name, repo, installed)
3664 - return _real if _real in repo else ""
3665 -
3666 -
3667 -def _base_summary(repo: Optional[dict] = None) -> dict:
3668 - """Klasyfikacja pakietów bazy z obrazu wobec repo.
3669 -
3670 - repo=None → pobiera indeks repo (potrzebny do listy „do adoptowania”).
3671 - repo={} → bez sieci: rozpoznaje tylko to, czym pag już zarządza.
3672 - """
3673 - _entries = _base_entries()
3674 - if not _entries:
3675 - return {"total": 0, "tracked": 0, "adoptable": [], "unmatched": []}
3676 - if repo is None:
3677 - repo = fetch_all_packages()
3678 - installed = load_json(INSTALLED_DB)
3679 - tracked, adoptable, unmatched = 0, [], []
3680 - for _n, _v in _entries:
3681 - _real = _base_repo_name(_n, repo, installed)
3682 - if _n in installed or (_real and _real in installed):
3683 - tracked += 1
3684 - elif _real:
3685 - adoptable.append((_n, _real, _v))
3686 - else:
3687 - unmatched.append(_n)
3688 - return {"total": len(_entries), "tracked": tracked,
3689 - "adoptable": adoptable, "unmatched": unmatched}
3690 -
3691 -
3692 -def _base_hint_unmanaged() -> None:
3693 - """Jednozdaniowa informacja dla `pag sync/update/upgrade`."""
3694 - try:
3695 - _s = _base_summary()
3696 - except Exception:
3697 - return
3698 - if _s["adoptable"]:
3699 - print(f"\n ℹ {_('base_unmanaged_hint', len(_s['adoptable']))}")
3700 -
3701 -
3702 -def _base_warn_overwrite(names) -> None:
3703 - """Ostrzeżenie w `pag install`, gdy pakiet pochodzi z bazy obrazu ISO."""
3704 - _entries = _base_entries()
3705 - if not _entries:
3706 - return
3707 - _known = set()
3708 - for _n, _v in _entries:
3709 - _known.add(_n)
3710 - _al = BASE_NAME_ALIASES.get(_n)
3711 - if _al:
3712 - _known.add(_al)
3713 - _hit = [n for n in names if n in _known]
3714 - if _hit:
3715 - _listed = ", ".join(_hit[:5]) + (" …" if len(_hit) > 5 else "")
3716 - print(f" ℹ {_('base_overwrite', _listed)}")
3717 -
3718 -
3719 -def cmd_base_status():
3720 - """`pag base` / `pag base status` – co w systemie pochodzi z obrazu,
3721 - czym pag już zarządza i co da się zaadoptować z repo."""
3722 - _man = _base_manifest()
3723 - if not _man:
3724 - print(f" ℹ {_('base_no_manifest')}")
3725 - return 0
3726 - _s = _base_summary()
3727 - print(f"\n {_c('bold', _('base_title'))}")
3728 - print(f" {'─' * 46}")
3729 - _de = _man.get("de") or ""
3730 - print(f" {_('base_iso_version'):<34} {_man.get('iso_version', '?')}" + (f" ({_de})" if _de else ""))
3731 - print(f" {_('base_total'):<34} {_s['total']}")
3732 - print(f" {_('base_tracked'):<34} {_s['tracked']}")
3733 - print(f" {_('base_adoptable'):<34} {len(_s['adoptable'])}")
3734 - print(f" {_('base_unmatched'):<34} {len(_s['unmatched'])}")
3735 - if _s["adoptable"]:
3736 - print(f"\n {_('base_adopt_hint')}")
3737 - for _iso_n, _real, _v in _s["adoptable"][:10]:
3738 - _m = "" if _iso_n == _real else f" ({_iso_n})"
3739 - print(f" {_real}-{_v}{_m}")
3740 - if len(_s["adoptable"]) > 10:
3741 - print(f" … {len(_s['adoptable']) - 10} {_('base_more')}")
3742 - if _s["unmatched"]:
3743 - print(f"\n {_('base_unmatched_hint')}")
3744 - print(" " + ", ".join(_s["unmatched"][:12])
3745 - + (f" … +{len(_s['unmatched']) - 12}" if len(_s["unmatched"]) > 12 else ""))
3746 - return 0
3747 -
3748 -
3749 -def cmd_base_adopt(args):
3750 - """`pag base adopt [pkg...] [--dry-run]` – dograj bazę z obrazu z repo.
3751 -
3752 - Pakiety bazy nie ma w installed.json, więc pag traktuje je jak NOWĄ
3753 - instalację: pliki z obrazu trafiają do kopii transakcji (działa
3754 - `pag rollback`), a po sukcesie pag zarządza nimi jak każdym innym pakietem.
3755 - """
3756 - if not _base_manifest():
3757 - print(f" ℹ {_('base_no_manifest')}")
3758 - return 1
3759 - repo = fetch_all_packages()
3760 - if not repo:
3761 - print(f"❌ {_('no_index')}")
3762 - return 1
3763 - _want = [a for a in args if not a.startswith("-") and a != "adopt"]
3764 - _s = _base_summary(repo)
3765 - plan = _s["adoptable"]
3766 - if _want:
3767 - _sel = set(_want)
3768 - plan = [p for p in plan if p[0] in _sel or p[1] in _sel]
3769 - if not plan:
3770 - print(f" ℹ {_('base_nothing_selected')}")
3771 - return 0
3772 - if not plan:
3773 - print(f"✅ {_('base_all_managed')}")
3774 - return 0
3775 - _size = sum(repo[r].size_bytes for _i, r, _v in plan if r in repo)
3776 - print(f"\n {_('base_adopt_plan', len(plan), _size / 1048576)}")
3777 - for _iso_n, _real, _v in plan[:20]:
3778 - _rv = repo[_real].version if _real in repo else "?"
3779 - _m = "" if _iso_n == _real else f" ({_iso_n} → {_real})"
3780 - print(f" {_real}: {_v} → {_rv}{_m}")
3781 - if len(plan) > 20:
3782 - print(f" … {len(plan) - 20} {_('base_more')}")
3783 - if "-n" in args or "--dry-run" in args:
3784 - print(f" {_('base_dry_run')}")
3785 - return 0
3786 - _rc = cmd_install([r for _i, r, _v in plan])
3787 - if _rc == 0:
3788 - # Wymienione biblioteki/narzędzia (glibc, gcc, GTK…) są już nowe na dysku,
3789 - # ale działające procesy wciąż mają stare w pamięci – restart domyka.
3790 - print(f"\n ℹ {_('base_reboot_hint')}")
3791 - return _rc
3792 -
3793 -
3794 -def _base_cached_index() -> dict:
3795 - """Indeks repo TYLKO z lokalnego cache (zero sieci) – do mapowania nazw.
3796 -
3797 - Potrzebne dla `pag base register`: rejestracja bazy obrazu nie może zależeć
3798 - od sieci (odpala się w buildzie, w chroocie, bez DNS). Cache indeksu powstaje
3799 - przy okazji `pag sync`/`pag install` i po nim wystarcza.
3800 - """
3801 - _out = {}
3802 - try:
3803 - for _r in get_repos():
3804 - _cp = _repo_cache_path(_r)
3805 - if not os.path.exists(_cp):
3806 - continue
3807 - for _pdata in (_load_repo_cache(_cp) or []):
3808 - _n = _pdata.get("name") or _pdata.get("filename", "?").split("-")[0]
3809 - _pkg = PackageInfo(_pdata, _r)
3810 - if _n not in _out or _version_newer(_pkg.version, _out[_n].version):
3811 - _out[_n] = _pkg
3812 - except Exception:
3813 - return _out
3814 - return _out
3815 -
3816 -
3817 -def cmd_base_register(args):
3818 - """`pag base register [--force] [--dry-run]` – wpisz bazę obrazu do installed.json.
3819 -
3820 - PO CO: pakietów zbudowanych przez builder (glibc, gcc, GTK, XFCE…) nie ma
3821 - w installed.json, więc `pag upgrade` ich NIE widzi i system nie da się
3822 - prowadzić w trybie rolling – trzeba by najpierw `pag base adopt`, czyli
3823 - ponownie ŚCIĄGNĄĆ całą bazę z repo. Rejestracja zamiast tego zapisuje je
3824 - jako zainstalowane **z wersją z obrazu** (to ona leży na dysku), więc
3825 - `pag upgrade` porówna ją z repo i podniesie tylko to, co nowsze.
3826 -
3827 - Offline: nic nie pobiera. Cache indeksu repo (jeśli jest) służy WYŁĄCZNIE do
3828 - mapowania nazw builder → repo (BASE_NAME_ALIASES/provides) i metadanych
3829 - (release/opis/zależności). Nazwy bez odpowiednika w repo zostają jak są.
3830 -
3831 - OGRANICZENIE: rejestracja nie zna listy plików pakietu (files.db), więc
3832 - dopóki pakiet nie zostanie zaktualizowany z repo, `pag verify`/`pag remove`
3833 - go nie obejmą (`pag base adopt` nadal jest drogą do pełnego przejęcia).
3834 - """
3835 - _force = "-f" in args or "--force" in args
3836 - _dry = "-n" in args or "--dry-run" in args
3837 -
3838 - _entries = _base_entries()
3839 - if not _entries:
3840 - print(f" ℹ {_('base_no_manifest')}")
3841 - return 1
3842 -
3843 - _repo = _base_cached_index()
3844 - installed = load_json(INSTALLED_DB)
3845 - world = load_world()
3846 - _now = datetime.now().isoformat()
3847 -
3848 - added, skipped, renamed = [], 0, 0
3849 - for _n, _v in _entries:
3850 - _real = _base_repo_name(_n, _repo, installed) if _repo else ""
3851 - _key = _real or _n
3852 - if _real and _real != _n:
3853 - renamed += 1
3854 - if _key in installed and not _force:
3855 - skipped += 1
3856 - continue
3857 - _pkg = _repo.get(_key)
3858 - installed[_key] = {
3859 - "version": _v or (getattr(_pkg, "version", "") or "?"),
3860 - "release": getattr(_pkg, "release", "") or "1",
3861 - "description": (getattr(_pkg, "description", "") or "")
3862 - or "Pagan Linux – pakiet bazy obrazu",
3863 - "dependencies": list(getattr(_pkg, "dependencies", []) or []),
3864 - "size_bytes": getattr(_pkg, "size_bytes", 0) or 0,
3865 - "sha256": "",
3866 - "installed_at": _now,
3867 - "repo": "base",
3868 - "provides": list(getattr(_pkg, "provides", []) or []),
3869 - "provides_so": list(getattr(_pkg, "provides_so", []) or []),
3870 - "requires_so": list(getattr(_pkg, "requires_so", []) or []),
3871 - }
3872 - world.add(_key)
3873 - added.append(_key)
3874 -
3875 - if _dry:
3876 - print(f" ℹ {_('base_register_plan', len(added))}")
3877 - return 0
3878 - if added:
3879 - save_json(INSTALLED_DB, installed)
3880 - save_world(world)
3881 - print(f" ✅ {_('base_register_ok', len(added), skipped)}")
3882 - if renamed:
3883 - print(f" ℹ {_('base_register_renamed', renamed)}")
3884 - if not _repo:
3885 - print(f" ℹ {_('base_register_nocache')}")
3886 - return 0
3887 -
3888 -
3889 -def cmd_update(do_upgrade: bool = False):
3890 - """`pag sync` / `pag update` – odświeżenie indeksów + raport aktualizacji.
3891 -
3892 - sync → tylko odświeżenie indeksów + info: „jest X pakietów do
3893 - zaktualizowania – wpisz: pag update".
3894 - update → odświeżenie indeksów + AKTUALIZACJA PAKIETÓW (pakiety, nie system).
3895 - Pomijamy cache TTL (inaczej nowe pakiety/aktualizacje są niewidoczne nawet
3896 - przez godzinę). Pełne pobranie + weryfikacja GPG przy każdym odświeżeniu.
3897 - """
3898 - force = True
3899 - print("🔄 Refreshing indexes...")
3900 - for repo_url in get_repos():
3901 - pkgs = fetch_repo_index(repo_url, force=force)
3902 - cp = _repo_cache_path(repo_url)
3903 - has_sig = os.path.exists(cp + ".sig")
3904 - print(f" {'✅' if pkgs is not None else '❌'} {repo_url}: {len(pkgs or [])} pkgs {'🔐' if has_sig else '⚠'}")
3905 - print(f"✅ {_('indexes_refreshed')}")
3906 -
3907 - # Powiadomienie o nowszej wersji pag (repo.json["pag_version"])
3908 - try:
3909 - for r in get_repos():
3910 - cp = _repo_cache_path(r)
3911 - if os.path.exists(cp):
3912 - d = json.load(open(cp))
3913 - rv = d.get("pag_version", "")
3914 - if rv and rv != PAG_VERSION:
3915 - print(f" ⚠ Nowa wersja pag {rv} dostępna – uruchom: pag self-update")
3916 - except Exception:
3917 - pass
3918 -
3919 - # Raport: pakiety do aktualizacji
3920 - pending = _pending_updates()
3921 - if not pending:
3922 - print(f"✅ {_('all_up_to_date')}")
3923 - _base_hint_unmanaged()
3924 - return 0
3925 - print(f"{_('updates_available', len(pending))}")
3926 - installed = load_json(INSTALLED_DB)
3927 - repo = fetch_all_packages()
3928 - for n in pending:
3929 - print(f" {n}: {installed.get(n, {}).get('version', '?')} → {repo[n].version}")
3930 - if not do_upgrade:
3931 - _base_hint_unmanaged()
3932 - return 0 # sync: tylko informacja
3933 - if not _ask_confirm():
3934 - return 0
3935 - _rc = cmd_install(pending, upgrade=True)
3936 - _base_hint_unmanaged()
3937 - return _rc
3938 -
3939 -def _initramfs_stale() -> bool:
3940 - """Czy initramfs jest starszy niż najnowsze jądro (wymaga przebudowy)."""
3941 - try:
3942 - kernels = [k for k in os.listdir("/boot") if k.startswith("vmlinuz-")] if os.path.isdir("/boot") else []
3943 - if not kernels:
3944 - return False
3945 - newest = max(os.path.getmtime(os.path.join("/boot", k)) for k in kernels)
3946 - initrd = "/boot/initramfs.img"
3947 - return (not os.path.exists(initrd)) or os.path.getmtime(initrd) < newest
3948 - except Exception:
3949 - return False
3950 -
3951 -def cmd_upgrade():
3952 - """`pag upgrade` – aktualizacja SYSTEMU: pakiety + kernel/initramfs/GRUB."""
3953 - rc = cmd_update(do_upgrade=True)
3954 - if rc != 0:
3955 - return rc
3956 - # System: dopilnuj initramfs (gdyby kernel był nowszy) + GRUB (immutable)
3957 - if _initramfs_stale():
3958 - print(" 🐧 Przebudowa initramfs (nowsze jądro)...")
3959 - _rebuild_initramfs()
3960 - try:
3961 - if _load_deployments():
3962 - _update_grub_config()
3963 - except Exception:
3964 - pass
3965 - return 0
3966 -
3967 -def cmd_list(installed_only=False):
3968 - if installed_only:
3969 - db = load_json(INSTALLED_DB)
3970 - pinned = load_json(PINNED_FILE)
3971 - if not db: print("No packages installed."); return
3972 - print(f"Installed ({len(db)}):")
3973 - for n, i in sorted(db.items()):
3974 - pin = " 📌" if n in pinned else ""
3975 - print(f" {n}-{i['version']}{pin} – {i.get('description','')}")
3976 - else:
3977 - pkgs = fetch_all_packages()
3978 - installed = load_json(INSTALLED_DB)
3979 - pinned = load_json(PINNED_FILE)
3980 - print(f"Available ({len(pkgs)}):")
3981 - for n, p in sorted(pkgs.items()):
3982 - m = "✓" if n in installed else " "
3983 - extra = f" [installed: {installed[n]['version']}]" if n in installed else ""
3984 - if n in pinned: extra += " 📌"
3985 - print(f" [{m}] {n}-{p.version} – {p.description}{extra}")
3986 -
3987 -def cmd_search(query):
3988 - pkgs = fetch_all_packages()
3989 - results = [(n,p) for n,p in pkgs.items() if query.lower() in n.lower() or query.lower() in p.description.lower()]
3990 - if not results: print(f"❌ No results for: {query}"); return
3991 - installed = load_json(INSTALLED_DB)
3992 - print(f"Results for '{query}' ({len(results)}):")
3993 - for n,p in sorted(results):
3994 - print(f" [{'✓' if n in installed else ' '}] {n}-{p.version}")
3995 - print(f" {p.description}")
3996 -
3997 -
3998 -def _smart_search(query: str) -> int:
3999 - """
4000 - Inteligentne wyszukiwanie: repo PaganOS + Flathub.
4001 - Uruchamiane gdy użytkownik wpisze `pag <nazwa>` zamiast `pag install <nazwa>`.
4002 - Pokazuje dostępne źródła i sugeruje komendy instalacji.
4003 - """
4004 - # 1. Repo PaganOS
4005 - try:
4006 - pkgs = fetch_all_packages()
4007 - except Exception:
4008 - pkgs = {}
4009 - repo_lower = [(n, p) for n, p in pkgs.items()
4010 - if query.lower() in n.lower() or query.lower() in p.description.lower()]
4011 -
4012 - # 2. Flathub (jeśli dostępny)
4013 - flat = _flatpak_search_raw(query) if _check_flatpak(quiet=True) else []
4014 -
4015 - if not repo_lower and not flat:
4016 - print(f"\n ❌ '{query}' — nie znaleziono.")
4017 - print(f" Repo PaganOS: pag search {query}")
4018 - if _check_flatpak(quiet=True):
4019 - print(f" Flathub: pag flatpak search {query}")
4020 - print(f" Dodaj repo: pag repo-add <url>")
4021 - return 1
4022 -
4023 - installed = load_json(INSTALLED_DB)
4024 -
4025 - # ── Repo PaganOS ──
4026 - if repo_lower:
4027 - exact = [(n, p) for n, p in repo_lower if n.lower() == query.lower()]
4028 - show = (exact or repo_lower)[:6]
4029 - print(f"\n 📦 PaganOS — '{query}':")
4030 - for n, p in sorted(show):
4031 - mark = "✓" if n in installed else " "
4032 - desc = p.description[:70] if len(p.description) > 75 else p.description
4033 - print(f" [{mark}] {n}-{p.version}")
4034 - if desc:
4035 - print(f" {desc}")
4036 - if len(repo_lower) > 6:
4037 - print(f" ... i {len(repo_lower) - 6} więcej (pag search {query})")
4038 -
4039 - # ── Flathub ──
4040 - if flat:
4041 - print(f"\n 📦 Flathub — '{query}':")
4042 - for r in flat[:5]:
4043 - mark = "✓" if r.get("installed") else " "
4044 - name = r.get("name") or r.get("application", "?")
4045 - desc = (r.get("description") or "")[:65]
4046 - print(f" [{mark}] {name}")
4047 - if desc:
4048 - print(f" {desc}")
4049 - if len(flat) > 5:
4050 - print(f" ... i {len(flat) - 5} więcej (pag flatpak search {query})")
4051 -
4052 - # ── Sugestie instalacji ──
4053 - print()
4054 - if repo_lower:
4055 - best = sorted(repo_lower, key=lambda x: (x[0].lower() != query.lower(), -len(x[1].name if hasattr(x[1], 'name') else 0)))[0][0]
4056 - if best in installed:
4057 - print(f" ✓ {best} jest już zainstalowany ({installed[best]['version']})")
4058 - else:
4059 - print(f" 💡 sudo pag install {best}")
4060 - if flat:
4061 - best_fp = flat[0].get("application") or flat[0].get("name", query)
4062 - print(f" 💡 pag flatpak install {best_fp}")
4063 -
4064 - return 0
4065 -
4066 -def cmd_info(name):
4067 - pkgs = fetch_all_packages()
4068 - p = pkgs.get(name)
4069 - info = load_json(INSTALLED_DB).get(name)
4070 - if not p and not info: print(f"❌ '{name}' not found."); return 1
4071 - print(f"📦 {name}")
4072 - if p:
4073 - print(f" Version (repo): {p.version}")
4074 - print(f" Description: {p.description}")
4075 - print(f" Size: {p.size_bytes/1048576:.1f} MB")
4076 - print(f" SHA256: {p.sha256[:32]}...")
4077 - print(f" GPG: {p.gpg_fp or 'none'}")
4078 - print(f" Dependencies: {', '.join(p.dependencies) if p.dependencies else '(none)'}")
4079 - if info:
4080 - print(f" Installed: {info['version']} ({info.get('installed_at','?')})")
4081 -
4082 -def cmd_files(name):
4083 - if name not in load_json(INSTALLED_DB):
4084 - print(f"❌ '{name}' not installed."); return 1
4085 - files = _db_get_package_files(name)
4086 - print(f"Files in {name} ({len(files)}):")
4087 - for f in sorted(files): print(f" {f}")
4088 -
4089 -def cmd_verify(deep=False):
4090 - installed = load_json(INSTALLED_DB)
4091 - if not installed: print("Nothing to verify."); return
4092 - errors = []
4093 -
4094 - # Wczytaj WSZYSTKIE sumy RAZ (nie w pętli!) – przy 50k plików wywołanie
4095 - # _db_get_all_file_checksums() per-plik dawało O(n²) i godziny zamiast sekund.
4096 - all_checksums = _db_get_all_file_checksums() if deep else {}
4097 - for name in installed:
4098 - for fpath in _db_get_package_files(name):
4099 - full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
4100 - if not (os.path.exists(full) or os.path.islink(full)):
4101 - errors.append(f" ❌ {name}: missing {fpath}")
4102 - elif deep:
4103 - expected = all_checksums.get(fpath, "")
4104 - if expected:
4105 - actual = _sha256_file(full)
4106 - if actual != expected:
4107 - errors.append(f" ❌ {name}: SHA256 mismatch {fpath}")
4108 -
4109 - if errors:
4110 - print(f"❌ {_('verify_errors', len(errors))}")
4111 - for e in errors[:50]: print(e)
4112 - return 1
4113 - total = _db_count_files()
4114 - print(f"✅ {_('verify_ok', total)}")
4115 -
4116 -# =============================================================================
4117 -# PINNING / CLEAN / ORPHANS / REPO / FLATPAK
4118 -# =============================================================================
4119 -
4120 -def cmd_pin(name, version=""):
4121 - pinned = load_json(PINNED_FILE)
4122 - if version:
4123 - pinned[name] = version
4124 - else:
4125 - info = load_json(INSTALLED_DB).get(name, {})
4126 - pinned[name] = info.get("version", "?")
4127 - save_json(PINNED_FILE, pinned)
4128 - print(f"📌 {name} {_('pinned_to')} {pinned[name]}")
4129 -
4130 -def cmd_unpin(name):
4131 - pinned = load_json(PINNED_FILE)
4132 - if name in pinned:
4133 - del pinned[name]; save_json(PINNED_FILE, pinned)
4134 - print(f"🔓 {name} {_('unpinned')}")
4135 - else:
4136 - print(f"⚠ {name} {_('not_pinned')}")
4137 -
4138 -def cmd_pinned():
4139 - pinned = load_json(PINNED_FILE)
4140 - if not pinned: print(_("no_pinned")); return
4141 - print(_("pinned_list", len(pinned)))
4142 - for n,v in sorted(pinned.items()): print(f" 📌 {n} = {v}")
4143 -
4144 -def cmd_clean():
4145 - if os.path.isdir(PAG_CACHE):
4146 - count = size = 0
4147 - for f in os.listdir(PAG_CACHE):
4148 - fp = os.path.join(PAG_CACHE, f)
4149 - if os.path.isfile(fp):
4150 - size += os.path.getsize(fp); os.remove(fp); count += 1
4151 - print(f"✅ {_('cache_cleared', count, size/1048576)}")
4152 -
4153 -def cmd_remove_orphans():
4154 - installed = load_json(INSTALLED_DB)
4155 - world = load_world()
4156 - orphans = _find_orphans(installed, world)
4157 - if not orphans: print("✅ No orphans."); return
4158 - print(f"Orphans ({len(orphans)}):")
4159 - for n in sorted(orphans): print(f" {n}-{installed[n]['version']}")
4160 - if not _ask_confirm():
4161 - return
4162 - cmd_remove(list(orphans))
4163 -
4164 -
4165 -# =============================================================================
4166 -# PROVIDES – PAKIETY WIRTUALNE
4167 -# =============================================================================
4168 -
4169 -PROVIDES_MAP = {
4170 - "pkgconfig(glib-2.0)": "glib",
4171 - "pkgconfig(gobject-introspection-1.0)": "gobject-introspection",
4172 - "pkgconfig(gtk+-3.0)": "gtk",
4173 - "pkgconfig(gtk4)": "gtk",
4174 - "pkgconfig(zlib)": "zlib",
4175 - "pkgconfig(libffi)": "libffi",
4176 - "pkgconfig(expat)": "expat",
4177 - "pkgconfig(libsystemd)": "systemd",
4178 - "pkgconfig(dbus-1)": "dbus",
4179 - "pkgconfig(mount)": "util-linux",
4180 - "pkgconfig(blkid)": "util-linux",
4181 - "pkgconfig(libcap)": "libcap",
4182 - "pkgconfig(liblzma)": "xz",
4183 - "pkgconfig(libzstd)": "zstd",
4184 - "pkgconfig(bzip2)": "bzip2",
4185 - "pkgconfig(libcurl)": "curl",
4186 - "pkgconfig(openssl)": "openssl",
4187 - "pkgconfig(libpcre2-8)": "pcre2",
4188 - "pkgconfig(libxml-2.0)": "libxml2",
4189 - "pkgconfig(libxslt)": "libxslt",
4190 - "pkgconfig(freetype2)": "freetype",
4191 - "pkgconfig(fontconfig)": "fontconfig",
4192 - "pkgconfig(harfbuzz)": "harfbuzz",
4193 - "pkgconfig(cairo)": "cairo",
4194 - "pkgconfig(pango)": "pango",
4195 - "pkgconfig(xt)": "xorg-libxt",
4196 - "pkgconfig(xmu)": "xorg-libxmu",
4197 - "pkgconfig(ice)": "xorg-libice",
4198 - "pkgconfig(sm)": "xorg-libsm",
4199 - "pkgconfig(x11)": "xorg-libx11",
4200 - "pkgconfig(xext)": "xorg-libxext",
4201 - "pkgconfig(xrandr)": "xorg-libxrandr",
4202 - "pkgconfig(xfixes)": "xorg-libxfixes",
4203 - "pkgconfig(xcursor)": "xorg-libxcursor",
4204 - "pkgconfig(xinerama)": "xorg-libxinerama",
4205 - "pkgconfig(xrender)": "xorg-libxrender",
4206 - "pkgconfig(xau)": "xorg-libxau",
4207 - "pkgconfig(xcb)": "xorg-libxcb",
4208 - "pkgconfig(xdamage)": "xorg-libxdamage",
4209 - "pkgconfig(xcomposite)": "xorg-libxcomposite",
4210 - "pkgconfig(xft)": "xorg-libxft",
4211 - "pkgconfig(xss)": "xorg-libxss",
4212 - "pkgconfig(libsoup-3.0)": "libsoup3",
4213 - "pkgconfig(libsoup-2.4)": "libsoup2",
4214 - "pkgconfig(gdk-pixbuf-2.0)": "gdk-pixbuf2",
4215 - "pkgconfig(libpng)": "libpng",
4216 - "pkgconfig(libjpeg)": "libjpeg-turbo",
4217 - "pkgconfig(libtiff-4)": "libtiff",
4218 - "pkgconfig(ffi)": "libffi",
4219 - # ── system / baza ──
4220 - "pkgconfig(libcrypto)": "openssl",
4221 - "pkgconfig(libssl)": "openssl",
4222 - "pkgconfig(libudev)": "systemd",
4223 - "pkgconfig(libmount)": "util-linux",
4224 - "pkgconfig(libblkid)": "util-linux",
4225 - "pkgconfig(uuid)": "util-linux",
4226 - "pkgconfig(libexpat)": "expat",
4227 - "pkgconfig(libpcre)": "pcre",
4228 - "pkgconfig(ncursesw)": "ncurses",
4229 - "pkgconfig(tinfo)": "ncurses",
4230 - "pkgconfig(panel)": "ncurses",
4231 - "pkgconfig(readline)": "readline",
4232 - "pkgconfig(libseccomp)": "libseccomp",
4233 - "pkgconfig(pam)": "linux-pam",
4234 - "pkgconfig(libxcrypt)": "libxcrypt",
4235 - "pkgconfig(libcrypt)": "libxcrypt",
4236 - "pkgconfig(libnsl)": "libnsl",
4237 - "pkgconfig(liblz4)": "lz4",
4238 - "pkgconfig(libevent)": "libevent",
4239 - "pkgconfig(libarchive)": "libarchive",
4240 - "pkgconfig(sqlite3)": "sqlite",
4241 - "pkgconfig(libpq)": "postgresql",
4242 - "pkgconfig(mysqlclient)": "mariadb",
4243 - "pkgconfig(json-c)": "json-c",
4244 - "pkgconfig(json-glib-1.0)": "json-glib",
4245 - "pkgconfig(libunistring)": "libunistring",
4246 - "pkgconfig(libidn2)": "libidn2",
4247 - "pkgconfig(libpsl)": "libpsl",
4248 - "pkgconfig(icu-uc)": "icu",
4249 - "pkgconfig(icu-i18n)": "icu",
4250 - "pkgconfig(icu-io)": "icu",
4251 - "pkgconfig(gnutls)": "gnutls",
4252 - "pkgconfig(nettle)": "nettle",
4253 - "pkgconfig(hogweed)": "nettle",
4254 - "pkgconfig(libgcrypt)": "libgcrypt",
4255 - "pkgconfig(libgpg-error)": "libgpg-error",
4256 - "pkgconfig(libassuan)": "libassuan",
4257 - "pkgconfig(libusb-1.0)": "libusb",
4258 - "pkgconfig(libusb)": "libusb",
4259 - "pkgconfig(libgudev-1.0)": "libgudev",
4260 - "pkgconfig(gudev-1.0)": "libgudev",
4261 - "pkgconfig(polkit-gobject-1)": "polkit",
4262 - "pkgconfig(polkit-agent-1)": "polkit",
4263 - "pkgconfig(libpciaccess)": "libpciaccess",
4264 - "pkgconfig(pixman-1)": "pixman",
4265 - "pkgconfig(libdrm)": "libdrm",
4266 - "pkgconfig(libva)": "libva",
4267 - "pkgconfig(libva-drm)": "libva",
4268 - "pkgconfig(libva-x11)": "libva",
4269 - "pkgconfig(libva-wayland)": "libva",
4270 - "pkgconfig(vdpau)": "libvdpau",
4271 - "pkgconfig(libvdpau)": "libvdpau",
4272 - "pkgconfig(libinput)": "libinput",
4273 - "pkgconfig(libevdev)": "libevdev",
4274 - "pkgconfig(mtdev)": "mtdev",
4275 - # ── grafika / GL / multimedia ──
4276 - "pkgconfig(gbm)": "mesa",
4277 - "pkgconfig(gl)": "libglvnd",
4278 - "pkgconfig(egl)": "libglvnd",
4279 - "pkgconfig(glesv2)": "libglvnd",
4280 - "pkgconfig(glx)": "libglvnd",
4281 - "pkgconfig(vulkan)": "vulkan-loader",
4282 - "pkgconfig(libxkbcommon)": "libxkbcommon",
4283 - "pkgconfig(xkbcommon)": "libxkbcommon",
4284 - "pkgconfig(xkbcommon-x11)": "libxkbcommon",
4285 - "pkgconfig(xcb)": "xorg-libxcb",
4286 - "pkgconfig(xcb-util)": "xcb-util",
4287 - "pkgconfig(xcb-keysyms)": "xcb-util-keysyms",
4288 - "pkgconfig(xcb-icccm)": "xcb-util-wm",
4289 - "pkgconfig(xcb-cursor)": "xcb-util-cursor",
4290 - "pkgconfig(xcb-renderutil)": "xcb-util-renderutil",
4291 - "pkgconfig(xcb-image)": "xcb-util-image",
4292 - "pkgconfig(xcb-errors)": "xcb-util-errors",
4293 - "pkgconfig(wayland-client)": "wayland",
4294 - "pkgconfig(wayland-server)": "wayland",
4295 - "pkgconfig(wayland-cursor)": "wayland",
4296 - "pkgconfig(wayland-egl)": "wayland",
4297 - "pkgconfig(wayland-protocols)": "wayland-protocols",
4298 - "pkgconfig(gstreamer-1.0)": "gstreamer",
4299 - "pkgconfig(gstreamer-base-1.0)": "gstreamer",
4300 - "pkgconfig(gstreamer-check-1.0)": "gstreamer",
4301 - "pkgconfig(gstreamer-controller-1.0)": "gstreamer",
4302 - "pkgconfig(gstreamer-app-1.0)": "gst-plugins-base",
4303 - "pkgconfig(gstreamer-video-1.0)": "gst-plugins-base",
4304 - "pkgconfig(gstreamer-audio-1.0)": "gst-plugins-base",
4305 - "pkgconfig(gstreamer-pbutils-1.0)": "gst-plugins-base",
4306 - "pkgconfig(gstreamer-fft-1.0)": "gst-plugins-base",
4307 - "pkgconfig(gstreamer-riff-1.0)": "gst-plugins-base",
4308 - "pkgconfig(gstreamer-rtp-1.0)": "gst-plugins-base",
4309 - "pkgconfig(gstreamer-rtsp-1.0)": "gst-plugins-base",
4310 - "pkgconfig(gstreamer-sdp-1.0)": "gst-plugins-base",
4311 - "pkgconfig(gstreamer-net-1.0)": "gst-plugins-base",
4312 - "pkgconfig(gstreamer-gl-1.0)": "gst-plugins-base",
4313 - "pkgconfig(libpulse)": "libpulse",
4314 - "pkgconfig(libpulse-simple)": "libpulse",
4315 - "pkgconfig(libpulse-mainloop-glib)": "libpulse",
4316 - "pkgconfig(alsa)": "alsa-lib",
4317 - "pkgconfig(jack)": "jack2",
4318 - "pkgconfig(libsamplerate)": "libsamplerate",
4319 - "pkgconfig(sndfile)": "libsndfile",
4320 - "pkgconfig(libavcodec)": "ffmpeg",
4321 - "pkgconfig(libavformat)": "ffmpeg",
4322 - "pkgconfig(libavutil)": "ffmpeg",
4323 - "pkgconfig(libavfilter)": "ffmpeg",
4324 - "pkgconfig(libswscale)": "ffmpeg",
4325 - "pkgconfig(libswresample)": "ffmpeg",
4326 - "pkgconfig(libpostproc)": "ffmpeg",
4327 - "pkgconfig(SDL2)": "sdl2",
4328 - "pkgconfig(SDL)": "sdl",
4329 - "pkgconfig(SDL2_image)": "sdl2-image",
4330 - "pkgconfig(SDL2_ttf)": "sdl2-ttf",
4331 - "pkgconfig(SDL2_mixer)": "sdl2-mixer",
4332 - "pkgconfig(SDL2_net)": "sdl2-net",
4333 - "pkgconfig(libpng16)": "libpng",
4334 - "pkgconfig(libwebp)": "libwebp",
4335 - "pkgconfig(libwebpmux)": "libwebp",
4336 - "pkgconfig(libwebpdemux)": "libwebp",
4337 - "pkgconfig(libopenjp2)": "openjpeg2",
4338 - "pkgconfig(lcms2)": "lcms2",
4339 - "pkgconfig(libheif)": "libheif",
4340 - "pkgconfig(libde265)": "libde265",
4341 - "pkgconfig(x264)": "x264",
4342 - "pkgconfig(x265)": "x265",
4343 - # ── glib / gio ──
4344 - "pkgconfig(gio-unix-2.0)": "glib",
4345 - "pkgconfig(gmodule-2.0)": "glib",
4346 - "pkgconfig(gthread-2.0)": "glib",
4347 - "pkgconfig(girepository-2.0)": "gobject-introspection",
4348 - "pkgconfig(girepository-1.0)": "gobject-introspection",
4349 - "pkgconfig(libglib-2.0)": "glib",
4350 - "pkgconfig(libgobject-2.0)": "glib",
4351 -}
4352 -
4353 -# Ostrzeżenia o wielu dostawcach tej samej wirtualnej nazwy – raz na proces.
4354 -_PROVIDES_WARNED = set()
4355 -# Cache indeksu provides dla danego obiektu repo: (repo_obj, {virtual: [pkg,...]}).
4356 -# Trzymamy referencję do repo, by uniknąć pomyłki przy ponownym użyciu id().
4357 -_provides_cache = (None, {})
4358 -
4359 -def _provides_index(repo: dict) -> dict:
4360 - """Buduje (i cache’uje) mapę wirtualna nazwa → lista dostawców w repo.
4361 -
4362 - Pozwala wybrać dostawcę DETERMINISTYCZNIE (posortowanego) zamiast zależeć
4363 - od kolejności wstawiania w repo.json, oraz ostrzec o konflikcie provides."""
4364 - global _provides_cache
4365 - cached_repo, idx = _provides_cache
4366 - if cached_repo is repo:
4367 - return idx
4368 - idx = {}
4369 - for _pn, _p in repo.items():
4370 - for _prov in (getattr(_p, "provides", None) or []):
4371 - idx.setdefault(_prov, []).append(_pn)
4372 - for _prov, _pns in idx.items():
4373 - if len(_pns) > 1 and _prov not in _PROVIDES_WARNED:
4374 - _PROVIDES_WARNED.add(_prov)
4375 - _sorted = sorted(_pns)
4376 - print(f" ⚠ {_('provides_conflict', name=_prov, providers=', '.join(_sorted), chosen=_sorted[0])}",
4377 - file=sys.stderr)
4378 - _provides_cache = (repo, idx)
4379 - return idx
4380 -
4381 -
4382 -def _resolve_provides(name: str, repo: dict, installed: Optional[dict] = None) -> str:
4383 - """Rozwija wirtualną nazwę pakietu do rzeczywistej nazwy.
4384 -
4385 - Kolejność: repo → PROVIDES_MAP → wzorce → provides z repo.json →
4386 - provides ZAINSTALOWANYCH pakietów (lokalnie zbudowane poza repo też
4387 - dostarczają wirtualne zależności) → fallback pkgconfig (czyszczenie nazwy).
4388 - """
4389 - if name in repo:
4390 - return name
4391 - if name in PROVIDES_MAP:
4392 - real = PROVIDES_MAP[name]
4393 - if real in repo:
4394 - return real
4395 - # Wzorce: moduły Qt (Qt5Core/Qt6Widgets) i GStreamer (gstreamer-video-1.0)
4396 - if name.startswith("pkgconfig(Qt5"):
4397 - real = "qt5"
4398 - if real in repo:
4399 - return real
4400 - if name.startswith("pkgconfig(Qt6"):
4401 - real = "qt6"
4402 - if real in repo:
4403 - return real
4404 - if name.startswith("pkgconfig(gstreamer-") and name.endswith("-1.0)"):
4405 - real = "gstreamer"
4406 - if real in repo:
4407 - return real
4408 - if name.startswith("pkgconfig(gst-"):
4409 - real = "gst-plugins-base"
4410 - if real in repo:
4411 - return real
4412 - # Dynamiczne provides z repo.json (sekcja provides: w PAGBUILD.yaml)
4413 - # Determinizm: przy wielu dostawcach wybieramy posortowanego pierwszego
4414 - # (i ostrzegamy raz), zamiast zależeć od kolejności w repo.json.
4415 - _idx = _provides_index(repo)
4416 - if name in _idx:
4417 - return min(_idx[name])
4418 - # provides ZAINSTALOWANYCH pakietów – lokalnie zbudowane (pagbuild, poza
4419 - # repo) też dostarczają wirtualne zależności i muszą być rozpoznawane.
4420 - if installed:
4421 - _inst_cands = [pn for pn, meta in installed.items()
4422 - if isinstance(meta, dict) and name in (meta.get("provides") or [])]
4423 - if _inst_cands:
4424 - return min(_inst_cands)
4425 - clean = name
4426 - if name.startswith("pkgconfig(") and ")" in name:
4427 - clean = name.split("(", 1)[1].rstrip(")")
4428 - elif name.startswith("pkgconfig32(") and ")" in name:
4429 - clean = name.split("(", 1)[1].rstrip(")")
4430 - if clean != name and clean in repo:
4431 - return clean
4432 - return name
4433 -
4434 -
4435 -def cmd_why(pkg_name: str):
4436 - """Pokazuje dlaczego pakiet jest zainstalowany."""
4437 - installed = load_json(INSTALLED_DB)
4438 - world = load_world()
4439 - if pkg_name not in installed:
4440 - print(f" {pkg_name}: {_('why_not_installed')}"); return 1
4441 - if pkg_name in world:
4442 - print(f" {pkg_name}-{installed[pkg_name]['version']}: {_('why_explicit')}")
4443 - return 0
4444 - parents = set()
4445 - for w in world:
4446 - _find_dep_path(w, pkg_name, installed, set(), [], parents)
4447 - if parents:
4448 - for pp in sorted(parents):
4449 - print(f" {pkg_name}: {_('why_dependency')} {' → '.join(pp)}")
4450 - else:
4451 - print(f" {pkg_name}: {_('why_dependency')} (unknown/orphan)")
4452 - return 0
4453 -
4454 -
4455 -def _find_dep_path(cur, target, installed, visited, path, results):
4456 - if cur in visited: return
4457 - visited.add(cur); path.append(cur)
4458 - if cur == target:
4459 - results.add(tuple(path))
4460 - else:
4461 - for dep in installed.get(cur, {}).get("dependencies", []):
4462 - _find_dep_path(dep, target, installed, visited, path, results)
4463 - path.pop(); visited.discard(cur)
4464 -
4465 -
4466 -def cmd_autoremove():
4467 - """Automatycznie usuwa osierocone zależności bez pytania."""
4468 - installed = load_json(INSTALLED_DB)
4469 - world = load_world()
4470 - orphans = _find_orphans(installed, world)
4471 - if not orphans: print(f"✅ {_('autoremove_none')}"); return 0
4472 - print(f"🗑 {_('orphans_found', len(orphans), ', '.join(sorted(orphans)[:10]))}")
4473 - return cmd_remove(list(orphans))
4474 -
4475 -
4476 -def cmd_download(package_names):
4477 - """Pobiera pakiety do cache bez instalowania."""
4478 - ensure_dirs()
4479 - repo = fetch_all_packages()
4480 - if not repo: print(f"❌ {_('no_index')}"); return 1
4481 - total_size = 0; downloaded = []
4482 - for name in package_names:
4483 - pkg = repo.get(name)
4484 - if not pkg:
4485 - print(f" ❌ {name}: {_('not_found')}"); continue
4486 - print(f" ↓ {name}-{pkg.version} ...", end=" ", flush=True)
4487 - path = _download_pkg(pkg)
4488 - if path:
4489 - total_size += os.path.getsize(path)
4490 - downloaded.append(name)
4491 - print(_c("green", "✓"))
4492 - else:
4493 - print(_c("red", "✗"))
4494 - if downloaded:
4495 - print(f"\n✅ {_('downloaded', len(downloaded), total_size/1048576)}")
4496 - return 0 if len(downloaded) == len(package_names) else 1
4497 -
4498 -
4499 -def cmd_stats():
4500 - """Wyświetla statystyki PAG."""
4501 - installed = load_json(INSTALLED_DB)
4502 - history = load_json(HISTORY_FILE) if os.path.exists(HISTORY_FILE) else []
4503 - total_size = sum(i.get("size_bytes", 0) for i in installed.values())
4504 - total_files = _db_count_files()
4505 - cache_size = sum(
4506 - os.path.getsize(os.path.join(PAG_CACHE, f))
4507 - for f in os.listdir(PAG_CACHE)
4508 - if os.path.isfile(os.path.join(PAG_CACHE, f))
4509 - ) if os.path.isdir(PAG_CACHE) else 0
4510 - last_update = "never"
4511 - for e in reversed(history):
4512 - if e.get("action") in ("install", "upgrade") and e.get("success"):
4513 - last_update = e.get("timestamp", "?")[:19]; break
4514 - print(f"\n {_c('bold', _('stats_title'))}")
4515 - print(f" {'─' * 40}")
4516 - print(f" {_('stats_packages'):<30} {len(installed)}")
4517 - print(f" {_('stats_files'):<30} {total_files}")
4518 - print(f" {_('stats_size'):<30} {total_size/1048576:.1f} MB")
4519 - print(f" {_('stats_cache'):<30} {cache_size/1048576:.1f} MB")
4520 - print(f" {_('stats_history'):<30} {len(history)}")
4521 - print(f" {_('stats_last_update'):<30} {last_update}")
4522 - _bs = _base_summary(repo={}) # bez sieci – tylko stan zarządzania bazą
4523 - if _bs["total"]:
4524 - _bt = f"{_bs['tracked']}/{_bs['total']}"
4525 - if _bs["tracked"] < _bs["total"]:
4526 - _bt += " (sudo pag base adopt)"
4527 - print(f" {_('stats_base'):<30} {_bt}")
4528 - by_size = sorted(installed.items(), key=lambda x: x[1].get("size_bytes", 0), reverse=True)[:5]
4529 - if by_size:
4530 - print(f"\n {_c('dim', 'Top 5:')}")
4531 - for n, i in by_size:
4532 - print(f" {n}-{i['version']} {i.get('size_bytes',0)/1048576:.1f} MB")
4533 - return 0
4534 -
4535 -
4536 -def cmd_repo_add(url, name=None):
4537 - if not url.startswith("https://") and not os.environ.get("PAG_INSECURE"):
4538 - print(f" {_('sec_https')}"); return 1
4539 - ensure_dirs()
4540 - url = url.rstrip("/")
4541 - repos = get_repos()
4542 - if url in repos: print(f"⚠ {_('repo_exists', url)}"); return
4543 - if name:
4544 - # Drop-in: /etc/pag/repos/<nazwa>.conf (jak `echo url > .../stable.conf`)
4545 - os.makedirs(REPOS_DIR, exist_ok=True)
4546 - target = os.path.join(REPOS_DIR, name.rstrip("/").replace("/", "_") + ".conf")
4547 - with open(target, "w") as f: f.write(f"{url}\n")
4548 - print(f"✅ {_('repo_added', url)} → {target}")
4549 - return
4550 - with open(REPOS_CONF, "a") as f: f.write(f"{url}\n")
4551 - print(f"✅ {_('repo_added', url)}")
4552 -
4553 -def cmd_repo_list():
4554 - for i, url in enumerate(get_repos(), 1): print(f" {i}. {url}")
4555 -
4556 -FLATPAK_REMOTE_URL = "https://flathub.org/repo/flathub.flatpakrepo"
4557 -
4558 -def _check_flatpak(quiet: bool = False):
4559 - if not shutil.which("flatpak"):
4560 - if not quiet:
4561 - print(f"❌ {_('flatpak_missing')}")
4562 - return False
4563 - r = subprocess.run(["flatpak", "remotes"], capture_output=True, text=True)
4564 - if "flathub" not in r.stdout:
4565 - print(f"⚠ {_('flatpak_adding')}")
4566 - # Jako root dodajemy remote systemowy; bez roota – w instalacji użytkownika,
4567 - # żeby remote i miejsce instalacji były spójne (patrz _flatpak_do_install).
4568 - add = ["flatpak", "remote-add", "--if-not-exists"]
4569 - if os.geteuid() != 0:
4570 - add.append("--user")
4571 - subprocess.run(add + ["flathub", FLATPAK_REMOTE_URL], check=False)
4572 - return True
4573 -
4574 -def _spinner(msg: str):
4575 - """Prosty spinner „myślenia” w osobnym wątku. Zwraca funkcję stop()."""
4576 - stop = threading.Event()
4577 - def _spin():
4578 - for c in itertools.cycle("|/-\\"):
4579 - if stop.is_set():
4580 - break
4581 - sys.stdout.write(f"\r {msg} {c}")
4582 - sys.stdout.flush()
4583 - time.sleep(0.1)
4584 - t = threading.Thread(target=_spin, daemon=True)
4585 - t.start()
4586 - def _stop():
4587 - stop.set()
4588 - t.join(timeout=0.3)
4589 - sys.stdout.write("\r" + " " * (len(msg) + 4) + "\r")
4590 - sys.stdout.flush()
4591 - return _stop
4592 -
4593 -
4594 -def _flatpak_search_raw(query: str) -> List[dict]:
4595 - """Szuka we Flathub i zwraca listę wyników jako słowniki."""
4596 - if not _check_flatpak():
4597 - return []
4598 - stop = _spinner("Szukam we Flathub...")
4599 - try:
4600 - try:
4601 - r = subprocess.run(
4602 - ["flatpak", "search", "--columns=name,description,application,version,branch,remotes", query],
4603 - capture_output=True, text=True, timeout=120
4604 - )
4605 - finally:
4606 - stop()
4607 - if r.returncode != 0 and "No matches found" not in r.stdout and not r.stdout.strip():
4608 - print(f" ⚠ flatpak search: {r.stderr.strip()[:150]}")
4609 - results = []
4610 - for line in r.stdout.strip().split("\n"):
4611 - parts = line.split("\t")
4612 - if len(parts) >= 3:
4613 - results.append({
4614 - "name": parts[0].strip(),
4615 - "description": parts[1].strip() if len(parts) > 1 else "",
4616 - "app_id": parts[2].strip() if len(parts) > 2 else "",
4617 - "version": parts[3].strip() if len(parts) > 3 else "",
4618 - "branch": parts[4].strip() if len(parts) > 4 else "stable",
4619 - "origin": parts[5].strip() if len(parts) > 5 else "flathub",
4620 - })
4621 - return results
4622 - except Exception as e:
4623 - print(f" ⚠ Błąd wyszukiwania: {e}", file=sys.stderr)
4624 - return []
4625 -
4626 -def _flatpak_find_best(query: str) -> Optional[dict]:
4627 - """
4628 - Szuka we Flathub i próbuje znaleźć najlepsze dopasowanie.
4629 - - Jeśli query dokładnie pasuje do app_id → zwraca od razu
4630 - - Jeśli query pasuje do nazwy → zwraca pierwsze
4631 - - Jeśli wiele wyników → wyświetla listę i pyta użytkownika
4632 - - Jeśli brak → zwraca None
4633 - """
4634 - results = _flatpak_search_raw(query)
4635 - if not results:
4636 - return None
4637 -
4638 - # Dokładne dopasowanie app_id
4639 - exact = [r for r in results if r["app_id"].lower() == query.lower()]
4640 - if exact:
4641 - return exact[0]
4642 -
4643 - # Dokładne dopasowanie nazwy
4644 - exact_name = [r for r in results if r["name"].lower() == query.lower()]
4645 - if exact_name:
4646 - return exact_name[0]
4647 -
4648 - # Jednoznaczne dopasowanie (tylko 1 wynik)
4649 - if len(results) == 1:
4650 - return results[0]
4651 -
4652 - # Wiele wyników – pokaż użytkownikowi
4653 - print(f"\n {_('flatpak_found', len(results))}")
4654 - for i, r in enumerate(results):
4655 - print(f" {i+1}. {_c('bold', r['name'])} ({r['app_id']})")
4656 - if r["version"]:
4657 - print(f" {_('flatpak_info_version')}: {r['version']}")
4658 - if r["description"]:
4659 - desc = r["description"][:80] + ("..." if len(r["description"]) > 80 else "")
4660 - print(f" {desc}")
4661 -
4662 - try:
4663 - choice = input(f"\n Wybierz numer (1-{len(results)}) lub Enter aby anulować: ").strip()
4664 - if not choice:
4665 - return None
4666 - idx = int(choice) - 1
4667 - if 0 <= idx < len(results):
4668 - return results[idx]
4669 - except (EOFError, ValueError, IndexError):
4670 - pass
4671 - return None
4672 -
4673 -def _flatpak_get_installed_info(app_id: str) -> Optional[dict]:
4674 - """Zwraca info o zainstalowanym flatpaku lub None."""
4675 - try:
4676 - r = subprocess.run(
4677 - ["flatpak", "info", "--columns=name,version,branch,origin,installed-size,description", app_id],
4678 - capture_output=True, text=True, timeout=10
4679 - )
4680 - if r.returncode != 0:
4681 - return None
4682 - parts = r.stdout.strip().split("\t")
4683 - if len(parts) < 3:
4684 - return None
4685 - return {
4686 - "name": parts[0].strip(),
4687 - "version": parts[1].strip() if len(parts) > 1 else "",
4688 - "branch": parts[2].strip() if len(parts) > 2 else "",
4689 - "origin": parts[3].strip() if len(parts) > 3 else "",
4690 - "size": parts[4].strip() if len(parts) > 4 else "",
4691 - "description": parts[5].strip() if len(parts) > 5 else "",
4692 - }
4693 - except Exception:
4694 - return None
4695 -
4696 -def _flatpak_is_installed(app_id: str) -> bool:
4697 - """Sprawdza czy flatpak o danym ID jest zainstalowany."""
4698 - try:
4699 - r = subprocess.run(
4700 - ["flatpak", "info", app_id],
4701 - capture_output=True, text=True, timeout=10
4702 - )
4703 - return r.returncode == 0
4704 - except Exception:
4705 - return False
4706 -
4707 -# =============================================================================
4708 -# FLATPAK – KOMENDY GŁÓWNE (zunifikowany interfejs)
4709 -# =============================================================================
4710 -# pag flatpak <query> → szuka i proponuje instalację (jeśli nie zainstalowany)
4711 -# pag flatpak search <query> → tylko szuka
4712 -# pag flatpak install <query> → instaluje
4713 -# pag flatpak remove <id> → usuwa
4714 -# pag flatpak list → lista zainstalowanych
4715 -# pag flatpak update → aktualizuje wszystkie
4716 -# pag flatpak info <id> → szczegóły flatpaka
4717 -
4718 -def cmd_flatpak(args: list):
4719 - """
4720 - Główna komenda flatpak – inteligentnie rozpoznaje intencję:
4721 - pag flatpak firefox → szuka i instaluje (jeśli nieznaleziony → szuka)
4722 - pag flatpak search firefox → tylko wyszukiwanie
4723 - pag flatpak install ... → bezpośrednia instalacja
4724 - pag flatpak remove ... → odinstalowanie
4725 - pag flatpak list → lista
4726 - pag flatpak update → aktualizacja
4727 - pag flatpak info ... → szczegóły
4728 - """
4729 - if not _check_flatpak():
4730 - return 1
4731 -
4732 - if not args:
4733 - # Bez argumentów – domyślnie lista
4734 - return cmd_flatpak_list()
4735 -
4736 - subcmd = args[0].lower()
4737 - rest = args[1:]
4738 -
4739 - # ── Podkomendy jawne ────────────────────────────────────────────────
4740 - if subcmd == "search":
4741 - if not rest:
4742 - print(_("flatpak_usage")); return 1
4743 - return cmd_flatpak_search(" ".join(rest))
4744 -
4745 - elif subcmd == "install":
4746 - if not rest:
4747 - print(_("flatpak_usage")); return 1
4748 - return _flatpak_smart_install(rest)
4749 -
4750 - elif subcmd == "remove" or subcmd == "uninstall":
4751 - if not rest:
4752 - print(_("flatpak_usage")); return 1
4753 - return _flatpak_smart_remove(rest)
4754 -
4755 - elif subcmd == "list":
4756 - return cmd_flatpak_list()
4757 -
4758 - elif subcmd == "update":
4759 - return cmd_flatpak_update()
4760 -
4761 - elif subcmd == "info":
4762 - if not rest:
4763 - print(_("flatpak_usage")); return 1
4764 - return cmd_flatpak_info(rest[0])
4765 -
4766 - else:
4767 - # ── Inteligentne wykrywanie: pag flatpak <nazwa> ────────────────
4768 - # Sprawdź czy to zainstalowany flatpak → pokaż info
4769 - # Jeśli nie → szukaj i zaproponuj instalację
4770 - query = " ".join(args)
4771 -
4772 - # Najpierw sprawdź czy już zainstalowany
4773 - if _flatpak_is_installed(query):
4774 - print(f" 📦 {_c('green', query)} – already installed (use 'pag flatpak info {query}' for details)")
4775 - return cmd_flatpak_info(query)
4776 -
4777 - # Szukaj we Flathub
4778 - print(f" {_('flatpak_searching', query)}")
4779 - best = _flatpak_find_best(query)
4780 - if not best:
4781 - print(f" ❌ '{query}' – {_('flatpak_not_found')}")
4782 - return 1
4783 -
4784 - print(f"\n {_c('cyan', best['name'])} ({best['app_id']})")
4785 - if best["version"]:
4786 - print(f" {_('flatpak_info_version')}: {best['version']}")
4787 - if best["description"]:
4788 - print(f" {best['description']}")
4789 -
4790 - try:
4791 - ans = input(f"\n {_('flatpak_install_prompt', best['name'])}").strip().lower()
4792 - except (EOFError, KeyboardInterrupt):
4793 - print(f"\n ⚠ {_('no_tty')}")
4794 - return 0
4795 - if ans and ans not in ("t", "y"):
4796 - print(_("cancelled"))
4797 - return 0
4798 -
4799 - return _flatpak_do_install(best["app_id"])
4800 -
4801 -def _flatpak_smart_install(names: list) -> int:
4802 - """Instaluje flatpaki – obsługuje nazwy częściowe (wyszukuje przed instalacją)."""
4803 - failed = 0
4804 - for name in names:
4805 - if "." in name and "/" not in name:
4806 - # Wygląda na pełne app_id (np. org.mozilla.firefox)
4807 - app_id = name
4808 - else:
4809 - # Szukaj najlepszego dopasowania
4810 - best = _flatpak_find_best(name)
4811 - if not best:
4812 - print(f" ❌ '{name}' – {_('flatpak_not_found')}")
4813 - failed += 1
4814 - continue
4815 - app_id = best["app_id"]
4816 - print(f" → {best['name']} ({app_id})")
4817 -
4818 - if _flatpak_do_install(app_id) != 0:
4819 - failed += 1
4820 - return 1 if failed else 0
4821 -
4822 -def _flatpak_export_dirs() -> List[str]:
4823 - """Katalogi eksportów Flatpaka (system + użytkownika) obecne na dysku.
4824 -
4825 - Instalacja użytkownika roota (/root/.local/share/flatpak) jest świadomie
4826 - POMIJANA – to wewnętrzny artefakt roota, którego sesja użytkownika nigdy
4827 - nie zobaczy (patrz _flatpak_do_install)."""
4828 - dirs = ["/var/lib/flatpak/exports"]
4829 - home = os.path.expanduser("~")
4830 - if home and home not in ("/root", "/"):
4831 - dirs.append(os.path.join(home, ".local", "share", "flatpak", "exports"))
4832 - return [d for d in dirs if os.path.isdir(d)]
4833 -
4834 -
4835 -def _flatpak_refresh_caches() -> None:
4836 - """Odświeża cache pulpitu i ikon po zmianie w Flatpaku (best-effort).
4837 -
4838 - Flatpak robi to sam, ale tylko gdy `update-desktop-database` jest w PATH.
4839 - Bez tego nowo zainstalowana aplikacja bywa nieobecna w menu."""
4840 - for exports in _flatpak_export_dirs():
4841 - apps = os.path.join(exports, "share", "applications")
4842 - if os.path.isdir(apps) and shutil.which("update-desktop-database"):
4843 - subprocess.run(["update-desktop-database", apps],
4844 - capture_output=True, check=False, timeout=60)
4845 - icons = os.path.join(exports, "share", "icons", "hicolor")
4846 - if os.path.isdir(icons) and shutil.which("gtk-update-icon-cache"):
4847 - subprocess.run(["gtk-update-icon-cache", "-q", "-t", "-f", icons],
4848 - capture_output=True, check=False, timeout=120)
4849 -
4850 -
4851 -def _flatpak_session_sees_exports() -> bool:
4852 - """Czy bieżąca sesja ma eksporty Flatpaka w XDG_DATA_DIRS."""
4853 - raw = os.environ.get("XDG_DATA_DIRS", "")
4854 - dirs = {d for d in raw.split(":") if d} or {"/usr/local/share", "/usr/share"}
4855 - return any(os.path.join(e, "share") in dirs for e in _flatpak_export_dirs())
4856 -
4857 -
4858 -def _flatpak_warn_if_invisible() -> None:
4859 - """Ostrzega, gdy sesja nie widzi eksportów – inaczej wygląda to jak
4860 - „zainstalowało się, ale nie ma go w menu / na PC”."""
4861 - if not _flatpak_session_sees_exports():
4862 - print(f" ⚠ {_('flatpak_menu_hint')}")
4863 - print(f" {_('flatpak_menu_fix')}")
4864 -
4865 -
4866 -def _flatpak_do_install(app_id: str) -> int:
4867 - """Wykonuje właściwą instalację flatpaka.
4868 -
4869 - Jako root wymuszamy instalację SYSTEMOWĄ (--system). Bez tego `flatpak`
4870 - uruchomiony jako root potrafi zainstalować aplikację w instalacji
4871 - użytkownika roota (/root/.local/share/flatpak) – widocznej dla roota, ale
4872 - nie dla zalogowanego użytkownika. To dokładnie efekt „instaluje, ale nie
4873 - mam tego na PC”. Bez roota próbujemy instalacji systemowej (polkit),
4874 - a w razie niepowodzenia cofamy się do instalacji użytkownika (--user).
4875 -
4876 - Zakres (scope) ma znaczenie: instalacja SYSTEMOWA (--system) jest widoczna
4877 - dla wszystkich użytkowników, a --user tylko dla bieżącego (dla roota:
4878 - /root/.local/... → niewidoczna dla sesji). `flatpak list` bez flag pokazuje
4879 - oba zakresy, więc systemowa instalacja roota jest widoczna też dla
4880 - zwykłego użytkownika."""
4881 - print(f" {_('flatpak_installing', app_id)}")
4882 - if os.geteuid() == 0:
4883 - result = subprocess.run(
4884 - ["flatpak", "install", "-y", "--system", "flathub", app_id],
4885 - check=False, timeout=600)
4886 - else:
4887 - result = subprocess.run(
4888 - ["flatpak", "install", "-y", "flathub", app_id],
4889 - check=False, timeout=600)
4890 - if result.returncode != 0:
4891 - # Flathub tylko dla użytkownika / brak agenta polkit – instalacja
4892 - # lokalna użytkownika jest lepsza niż twardy błąd.
4893 - subprocess.run(
4894 - ["flatpak", "remote-add", "--if-not-exists", "--user",
4895 - "flathub", FLATPAK_REMOTE_URL], check=False, timeout=60)
4896 - result = subprocess.run(
4897 - ["flatpak", "install", "-y", "--user", "flathub", app_id],
4898 - check=False, timeout=600)
4899 - if result.returncode != 0:
4900 - print(f" ❌ {_('download_fail')}: {app_id}")
4901 - return 1
4902 - _flatpak_refresh_caches()
4903 - print(f" ✅ {_('flatpak_installed', app_id)}")
4904 - _flatpak_warn_if_invisible()
4905 - return 0
4906 -
4907 -def _flatpak_smart_remove(names: list) -> int:
4908 - """Usuwa flatpaki – obsługuje nazwy częściowe."""
4909 - # Pobierz listę zainstalowanych
4910 - try:
4911 - r = subprocess.run(
4912 - ["flatpak", "list", "--columns=application,name"],
4913 - capture_output=True, text=True, timeout=10
4914 - )
4915 - installed = {}
4916 - for line in r.stdout.strip().split("\n"):
4917 - parts = line.split("\t")
4918 - if len(parts) >= 2:
4919 - installed[parts[0].strip()] = parts[1].strip()
4920 - except Exception:
4921 - installed = {}
4922 -
4923 - failed = 0
4924 - for name in names:
4925 - app_id = name
4926 -
4927 - # Jeśli nie podano pełnego ID – spróbuj dopasować
4928 - if name not in installed:
4929 - matches = {aid: aname for aid, aname in installed.items()
4930 - if name.lower() in aid.lower() or name.lower() in aname.lower()}
4931 - if len(matches) == 0:
4932 - print(f" ❌ '{name}' – {_('flatpak_not_installed', name)}")
4933 - failed += 1
4934 - continue
4935 - elif len(matches) == 1:
4936 - app_id = list(matches.keys())[0]
4937 - print(f" → {matches[app_id]} ({app_id})")
4938 - else:
4939 - print(f"\n Wiele dopasowań dla '{name}':")
4940 - for i, (aid, aname) in enumerate(sorted(matches.items()), 1):
4941 - print(f" {i}. {aname} ({aid})")
4942 - try:
4943 - choice = input(f"\n Wybierz numer (1-{len(matches)}) lub Enter: ").strip()
4944 - if not choice:
4945 - failed += 1
4946 - continue
4947 - aid_list = sorted(matches.keys())
4948 - app_id = aid_list[int(choice) - 1]
4949 - except (EOFError, ValueError, IndexError):
4950 - failed += 1
4951 - continue
4952 -
4953 - print(f" 🗑 {app_id} ...", end=" ", flush=True)
4954 - result = subprocess.run(
4955 - ["flatpak", "uninstall", "-y", app_id],
4956 - capture_output=True, text=True, timeout=120
4957 - )
4958 - if result.returncode == 0:
4959 - print("✅")
4960 - print(f" {_('flatpak_removed', app_id)}")
4961 - else:
4962 - print("❌")
4963 - failed += 1
4964 - if not failed:
4965 - _flatpak_refresh_caches()
4966 - return 1 if failed else 0
4967 -
4968 -def cmd_flatpak_search(q: str):
4969 - """Wyszukuje we Flathub i wyświetla wyniki (z możliwością wyboru do instalacji)."""
4970 - if not _check_flatpak():
4971 - return 1
4972 - results = _flatpak_search_raw(q)
4973 - if not results:
4974 - print(f" ❌ '{q}' – {_('flatpak_not_found')}")
4975 - return 1
4976 - print(f"\n {_('flatpak_found', len(results))}")
4977 - shown = results[:30] # max 30 wyników
4978 - for i, r in enumerate(shown, 1):
4979 - installed = "📦 " if _flatpak_is_installed(r["app_id"]) else " "
4980 - print(f" {i:>2}. {installed}{_c('bold', r['name'])} ({r['app_id']})")
4981 - if r["version"]:
4982 - print(f" {_('flatpak_info_version')}: {r['version']} | {_('flatpak_info_branch')}: {r['branch']}")
4983 - if r["description"]:
4984 - desc = r["description"][:100] + ("..." if len(r["description"]) > 100 else "")
4985 - print(f" {_c('dim', desc)}")
4986 - if len(results) > 30:
4987 - print(f" ... i {len(results) - 30} więcej. Doprecyzuj zapytanie.")
4988 -
4989 - # Interaktywny wybór – wpisz numer, aby zainstalować (Enter = anuluj)
4990 - try:
4991 - ans = input(f"\n Wybierz numer do zainstalowania (1-{len(shown)}) lub Enter aby anulować: ").strip()
4992 - except (EOFError, KeyboardInterrupt):
4993 - return 0
4994 - if ans:
4995 - try:
4996 - idx = int(ans) - 1
4997 - if 0 <= idx < len(shown):
4998 - return _flatpak_do_install(shown[idx]["app_id"])
4999 - print(_("cancelled"))
5000 - except (ValueError, IndexError):
5001 - print(_("cancelled"))
5002 - return 0
5003 -
5004 -def cmd_flatpak_list():
5005 - """Wyświetla zainstalowane flatpaki."""
5006 - if not _check_flatpak():
5007 - return 1
5008 - r = subprocess.run(
5009 - ["flatpak", "list", "--columns=application,name,version,origin,installation,installed-size"],
5010 - capture_output=True, text=True, timeout=10
5011 - )
5012 - lines = [l for l in r.stdout.strip().split("\n") if l.strip()]
5013 - if not lines:
5014 - print(" (brak zainstalowanych flatpaków)")
5015 - return 0
5016 - print(f" Zainstalowane flatpaki ({len(lines)}):")
5017 - for line in lines:
5018 - parts = line.split("\t")
5019 - if len(parts) >= 3:
5020 - app_id, name, version = parts[0], parts[1], parts[2]
5021 - scope = parts[4] if len(parts) > 4 else ""
5022 - size = parts[5] if len(parts) > 5 else ""
5023 - size_str = f" ({size})" if size else ""
5024 - scope_str = f" [{scope}]" if scope else ""
5025 - print(f" 📦 {_c('bold', name)} {version}{scope_str}{size_str}")
5026 - print(f" {_c('dim', app_id)}")
5027 - return 0
5028 -
5029 -def cmd_flatpak_update():
5030 - """Aktualizuje wszystkie flatpaki."""
5031 - if not _check_flatpak():
5032 - return 1
5033 - print(" 🔄 Aktualizacja flatpaków...")
5034 - result = subprocess.run(["flatpak", "update", "-y"], check=False, timeout=600)
5035 - if result.returncode == 0:
5036 - _flatpak_refresh_caches()
5037 - print(f" ✅ {_('flatpak_updated')}")
5038 - return result.returncode
5039 -
5040 -def cmd_flatpak_info(app_id: str):
5041 - """Wyświetla szczegóły flatpaka (zainstalowanego lub z Flathub)."""
5042 - if not _check_flatpak():
5043 - return 1
5044 -
5045 - # Najpierw sprawdź zainstalowany
5046 - info = _flatpak_get_installed_info(app_id)
5047 - if info:
5048 - print(f"\n 📦 {_c('bold', info['name'])} {_c('green', '[zainstalowany]')}")
5049 - print(f" {'─' * 45}")
5050 - print(f" {_('flatpak_info_id'):<16} {app_id}")
5051 - print(f" {_('flatpak_info_version'):<16} {info['version']}")
5052 - print(f" {_('flatpak_info_branch'):<16} {info['branch']}")
5053 - print(f" {_('flatpak_info_origin'):<16} {info['origin']}")
5054 - if info["size"]:
5055 - print(f" {_('flatpak_info_size'):<16} {info['size']}")
5056 - if info["description"]:
5057 - print(f" {_('flatpak_info_desc'):<16} {info['description']}")
5058 - return 0
5059 -
5060 - # Szukaj we Flathub
5061 - results = _flatpak_search_raw(app_id)
5062 - exact = [r for r in results if r["app_id"].lower() == app_id.lower()]
5063 - if not exact:
5064 - # Spróbuj częściowego dopasowania
5065 - if results:
5066 - exact = [results[0]]
5067 - else:
5068 - print(f" ❌ '{app_id}' – {_('flatpak_not_found')}")
5069 - return 1
5070 -
5071 - r = exact[0]
5072 - print(f"\n 📦 {_c('bold', r['name'])} (Flathub)")
5073 - print(f" {'─' * 45}")
5074 - print(f" {_('flatpak_info_id'):<16} {r['app_id']}")
5075 - print(f" {_('flatpak_info_version'):<16} {r['version']}")
5076 - if r["description"]:
5077 - print(f" {_('flatpak_info_desc'):<16} {r['description']}")
5078 - print(f"\n 💡 Aby zainstalować: pag flatpak install {r['app_id']}")
5079 - return 0
5080 -
5081 -# =============================================================================
5082 -# IMMUTABLE OS – KOMENDY DEPLOYMENTOWE
5083 -# =============================================================================
5084 -
5085 -# Pakiety jądra – po ich instalacji trzeba przebudować initramfs
5086 -KERNEL_PACKAGE_PATTERNS = ["linux", "kernel", "linux-kernel", "linux-lts"]
5087 -
5088 -def _is_kernel_package(name: str) -> bool:
5089 - """Sprawdza czy pakiet to jądro (wymaga przebudowy initramfs)."""
5090 - name_lower = name.lower()
5091 - return any(pattern in name_lower for pattern in KERNEL_PACKAGE_PATTERNS)
5092 -
5093 -def _rebuild_initramfs(deploy_dir: str = "") -> bool:
5094 - """
5095 - Przebudowuje initramfs dla aktywnego (lub podanego) deploymentu.
5096 - Używa skryptu pag-initramfs lub ręcznego cpio.
5097 - """
5098 - if deploy_dir:
5099 - root = deploy_dir
5100 - else:
5101 - root = _get_deployment_root()
5102 -
5103 - if root == PAG_ROOT:
5104 - # Zwykły system – użyj dracut jeśli dostępny
5105 - if shutil.which("dracut"):
5106 - print(" 🔧 Przebudowa initramfs (dracut)...")
5107 - result = subprocess.run(
5108 - ["dracut", "--force", "/boot/initramfs.img"],
5109 - capture_output=True, text=True, timeout=120
5110 - )
5111 - return result.returncode == 0
5112 - elif shutil.which("mkinitcpio"):
5113 - print(" 🔧 Przebudowa initramfs (mkinitcpio)...")
5114 - result = subprocess.run(
5115 - ["mkinitcpio", "-g", "/boot/initramfs.img"],
5116 - capture_output=True, text=True, timeout=120
5117 - )
5118 - return result.returncode == 0
5119 - else:
5120 - print(" ⚠ Brak dracut/mkinitcpio – initramfs nie został przebudowany")
5121 - return False
5122 -
5123 - # Tryb immutable – budujemy initramfs dla deploymentu
5124 - print(" 🔧 Budowanie initramfs dla deploymentu...")
5125 -
5126 - # Sprawdź czy mamy nasz skrypt init
5127 - pag_init_script = "/usr/share/pag/initramfs-init"
5128 - if not os.path.exists(pag_init_script):
5129 - # Szukaj w źródłach (developerski fallback)
5130 - alt_paths = [
5131 - os.path.join(os.path.dirname(os.path.abspath(__file__)), "scripts", "initramfs-init"),
5132 - "/usr/share/pag/init",
5133 - ]
5134 - for p in alt_paths:
5135 - if os.path.exists(p):
5136 - pag_init_script = p
5137 - break
5138 -
5139 - if not os.path.exists(pag_init_script):
5140 - print(" ⚠ Nie znaleziono pag-initramfs-init – pomijam budowę initramfs")
5141 - return False
5142 -
5143 - boot_dir = os.path.join(root, "boot")
5144 - os.makedirs(boot_dir, exist_ok=True)
5145 -
5146 - # Znajdź jądro (vmlinuz-*)
5147 - kernels = sorted(
5148 - [f for f in os.listdir(boot_dir) if f.startswith("vmlinuz-")],
5149 - reverse=True
5150 - ) if os.path.exists(boot_dir) else []
5151 - if not kernels:
5152 - print(" ⚠ Nie znaleziono vmlinuz-* w /boot deploymentu")
5153 - return False
5154 -
5155 - kernel_ver = kernels[0].replace("vmlinuz-", "")
5156 - print(f" 🐧 Jądro: {kernel_ver}")
5157 -
5158 - # Buduj initramfs ręcznie (cpio)
5159 - tmpdir = tempfile.mkdtemp(prefix="pag-initramfs-")
5160 - try:
5161 - # Podstawowa struktura
5162 - for d in ["bin", "sbin", "dev", "proc", "sys", "run", "new_root",
5163 - "usr/bin", "usr/sbin", "lib", "lib64", "etc"]:
5164 - os.makedirs(os.path.join(tmpdir, d), exist_ok=True)
5165 -
5166 - # Skopiuj init
5167 - shutil.copy2(pag_init_script, os.path.join(tmpdir, "init"))
5168 - os.chmod(os.path.join(tmpdir, "init"), 0o755)
5169 -
5170 - # Skopiuj niezbędne binaria (busybox lub podstawowe narzędzia)
5171 - busybox_paths = [
5172 - os.path.join(root, "usr/bin/busybox"),
5173 - os.path.join(root, "bin/busybox"),
5174 - "/usr/bin/busybox",
5175 - "/bin/busybox",
5176 - ]
5177 - busybox = None
5178 - for bp in busybox_paths:
5179 - if os.path.exists(bp):
5180 - busybox = bp
5181 - break
5182 -
5183 - if busybox:
5184 - shutil.copy2(busybox, os.path.join(tmpdir, "bin/busybox"))
5185 - # Utwórz symlinki dla podstawowych komend
5186 - for cmd in ["sh", "mount", "umount", "ls", "cat", "echo", "sleep",
5187 - "readlink", "mkdir", "switch_root", "cp", "rm"]:
5188 - link = os.path.join(tmpdir, "bin", cmd)
5189 - if not os.path.exists(link):
5190 - os.symlink("busybox", link)
5191 - # /bin/sh → busybox
5192 - if not os.path.exists(os.path.join(tmpdir, "bin/sh")):
5193 - os.symlink("busybox", os.path.join(tmpdir, "bin/sh"))
5194 - else:
5195 - # Bez busybox – kopiuj podstawowe narzędzia z deploymentu
5196 - for tool in ["bash", "mount", "umount", "readlink", "mkdir", "cat", "sleep", "cp", "rm"]:
5197 - src = os.path.join(root, "usr/bin", tool)
5198 - if not os.path.exists(src):
5199 - src = os.path.join(root, "bin", tool)
5200 - if os.path.exists(src):
5201 - dest = os.path.join(tmpdir, "bin", os.path.basename(tool))
5202 - shutil.copy2(src, dest)
5203 - # Kopiuj zależności .so
5204 - _copy_libs_for_binary(src, tmpdir, root)
5205 -
5206 - # Dodaj moduły jądra (opcjonalnie – dla sterowników dyskowych)
5207 - modules_src = os.path.join(root, "lib/modules", kernel_ver)
5208 - if os.path.isdir(modules_src):
5209 - modules_dst = os.path.join(tmpdir, "lib/modules", kernel_ver)
5210 - # Kopiuj tylko niezbędne (fs, block, drivers/ata, drivers/nvme)
5211 - for sub in ["kernel/fs", "kernel/drivers/ata", "kernel/drivers/nvme",
5212 - "kernel/drivers/scsi", "kernel/drivers/virtio",
5213 - "modules.order", "modules.builtin"]:
5214 - src_sub = os.path.join(modules_src, sub)
5215 - if os.path.exists(src_sub):
5216 - dst_sub = os.path.join(modules_dst, sub)
5217 - os.makedirs(os.path.dirname(dst_sub), exist_ok=True)
5218 - if os.path.isdir(src_sub):
5219 - try:
5220 - shutil.copytree(src_sub, dst_sub, dirs_exist_ok=True, symlinks=True,
5221 - ignore_dangling_symlinks=True)
5222 - except (FileNotFoundError, PermissionError):
5223 - print(f" ⚠ Pomijam niedostępne pliki: {sub}")
5224 - else:
5225 - try:
5226 - shutil.copy2(src_sub, dst_sub)
5227 - except (FileNotFoundError, PermissionError):
5228 - print(f" ⚠ Pomijam niedostępny plik: {sub}")
5229 -
5230 - # Pakuj do initramfs.img
5231 - initramfs_path = os.path.join(boot_dir, "initramfs.img")
5232 - old_cwd = os.getcwd()
5233 - os.chdir(tmpdir)
5234 - try:
5235 - with open(initramfs_path + ".tmp", "wb") as out:
5236 - _run_cpio_pipeline(tmpdir, out)
5237 - os.rename(initramfs_path + ".tmp", initramfs_path)
5238 - finally:
5239 - os.chdir(old_cwd)
5240 -
5241 - size_mb = os.path.getsize(initramfs_path) / 1048576
5242 - print(f" ✅ initramfs.img ({size_mb:.1f} MB) → {initramfs_path}")
5243 - return True
5244 -
5245 - except Exception as e:
5246 - print(f" ❌ Błąd budowy initramfs: {e}")
5247 - return False
5248 - finally:
5249 - shutil.rmtree(tmpdir, ignore_errors=True)
5250 -
5251 -
5252 -def _run_cpio_pipeline(tmpdir: str, out):
5253 - """find . -print0 | cpio --null -oH newc | gzip — bez shell=True.
5254 -
5255 - Buduje pipeline przez subprocess.Popen, unikając pośrednika powłoki
5256 - (brak ryzyka injection i niepotrzebnego procesu sh). Wykonuje się w cwd=tmpdir.
5257 - Separatory NUL (\0): plik/katalog ze znakiem nowej linii w nazwie nie
5258 - rozjeżdża cpio (inaczej uszkodzone archiwum → kernel panic przy rozruchu).
5259 - """
5260 - find = subprocess.Popen(["find", ".", "-print0"], cwd=tmpdir, stdout=subprocess.PIPE)
5261 - cpio = subprocess.Popen(["cpio", "--null", "-oH", "newc"], cwd=tmpdir,
5262 - stdin=find.stdout, stdout=subprocess.PIPE)
5263 - find.stdout.close() # zwolnij uchwyt – cpio dostanie SIGPIPE po zakończeniu find
5264 - gzip = subprocess.Popen(["gzip"], stdin=cpio.stdout, stdout=out)
5265 - cpio.stdout.close()
5266 - try:
5267 - gzip.wait(timeout=120)
5268 - if gzip.returncode != 0:
5269 - raise subprocess.CalledProcessError(gzip.returncode, ["gzip"])
5270 - cpio.wait(timeout=30)
5271 - find.wait(timeout=30)
5272 - except subprocess.TimeoutExpired:
5273 - for p in (gzip, cpio, find):
5274 - p.kill()
5275 - raise
5276 - finally:
5277 - for p in (find, cpio, gzip):
5278 - if p.poll() is None:
5279 - p.kill()
5280 - # Skontroluj też kody procesów pośrednich (cpio/find mogą zawieść, a gzip zwrócić 0)
5281 - if cpio.returncode != 0:
5282 - raise subprocess.CalledProcessError(cpio.returncode, ["cpio"])
5283 - if find.returncode != 0:
5284 - raise subprocess.CalledProcessError(find.returncode, ["find"])
5285 -
5286 -
5287 -def _copy_libs_for_binary(binary: str, dest_dir: str, root: str):
5288 - """Kopiuje zależności .so dla binarki do initramfs (uproszczone ldd)."""
5289 - try:
5290 - result = subprocess.run(
5291 - ["ldd", binary], capture_output=True, text=True, timeout=10
5292 - )
5293 - for line in result.stdout.split("\n"):
5294 - m = re.search(r'=>\s+(/\S+)', line)
5295 - if m:
5296 - lib_path = m.group(1)
5297 - lib_rel = lib_path.lstrip("/")
5298 - lib_dest = os.path.join(dest_dir, lib_rel)
5299 - if not os.path.exists(lib_dest):
5300 - os.makedirs(os.path.dirname(lib_dest), exist_ok=True)
5301 - # Szukaj w deployment root lub systemie
5302 - if os.path.exists(lib_path):
5303 - shutil.copy2(lib_path, lib_dest)
5304 - else:
5305 - alt = os.path.join(root, lib_rel)
5306 - if os.path.exists(alt):
5307 - shutil.copy2(alt, lib_dest)
5308 - except Exception:
5309 - pass
5310 -
5311 -
5312 -def cmd_initramfs_update():
5313 - """Ręcznie przebudowuje initramfs dla bieżącego deploymentu."""
5314 - ensure_dirs()
5315 - deploy_dir = _get_deployment_root()
5316 - if deploy_dir != PAG_ROOT:
5317 - print(f"🏗️ Deployment: {os.path.basename(deploy_dir)}")
5318 - ok = _rebuild_initramfs(deploy_dir)
5319 - if ok:
5320 - print("✅ Initramfs zaktualizowany.")
5321 - # Po initramfs – zaktualizuj też GRUB
5322 - _update_grub_config()
5323 - else:
5324 - print("❌ Błąd aktualizacji initramfs.")
5325 - return 0 if ok else 1
5326 -
5327 -
5328 -def _update_grub_config():
5329 - """
5330 - Generuje wpisy GRUB dla wszystkich deploymentów.
5331 - Każdy deployment dostaje własny wpis – rollback możliwy z bootloadera.
5332 - """
5333 - grub_cfg = "/boot/grub/grub.cfg"
5334 - if not os.path.exists(os.path.dirname(grub_cfg)):
5335 - return # brak GRUB
5336 -
5337 - deployments = _load_deployments()
5338 - root_dev = _detect_root_device()
5339 - if not root_dev:
5340 - print(" ⚠ Nie udało się wykryć partycji root – wpisy GRUB nie dostaną root=.",
5341 - file=sys.stderr)
5342 - print(" Ustaw PAG_ROOT_DEVICE=/dev/... (lub PAG_GRUB_ROOT) i powtórz.",
5343 - file=sys.stderr)
5344 - root_arg = f" root={root_dev}" if root_dev else ""
5345 -
5346 - lines = [
5347 - "# =====================================================================",
5348 - "# Pagan Linux – GRUB config (wygenerowane przez pag grub-update)",
5349 - f"# Data: {datetime.now().isoformat()}",
5350 - "# =====================================================================",
5351 - "",
5352 - ]
5353 -
5354 - # Domyślny – ostatni (najnowszy) deployment
5355 - if deployments:
5356 - latest = deployments[-1]["id"]
5357 - lines.append(f"set default=0")
5358 - lines.append(f"set timeout=5")
5359 - else:
5360 - lines.append("set default=0")
5361 - lines.append("set timeout=5")
5362 - lines.append("")
5363 -
5364 - # Wpisy dla każdego deploymentu (od najnowszego)
5365 - entry_num = 0
5366 - for d in reversed(deployments):
5367 - deploy_dir = os.path.join(DEPLOYMENTS_DIR, d["id"])
5368 - boot_dir = os.path.join(deploy_dir, "boot")
5369 - kernels = sorted(
5370 - [f for f in os.listdir(boot_dir) if f.startswith("vmlinuz-")],
5371 - reverse=True
5372 - ) if os.path.isdir(boot_dir) else []
5373 -
5374 - kernel_path = f"/.deployments/{d['id']}/boot/{kernels[0]}" if kernels else ""
5375 - initrd_path = f"/.deployments/{d['id']}/boot/initramfs.img"
5376 - initrd_line = f"initrd {initrd_path}" if os.path.exists(os.path.join(boot_dir, "initramfs.img")) else ""
5377 -
5378 - active_mark = " [AKTYWNY]" if d.get("active") else ""
5379 - pkg_list = ", ".join(d.get("packages", [])[:3])
5380 - label = f"Pagan Linux – {d['id']}{active_mark}"
5381 -
5382 - lines.append(f"menuentry '{label}' {{")
5383 - if kernel_path:
5384 - lines.append(f" linux {kernel_path}{root_arg} rw quiet")
5385 - else:
5386 - lines.append(f" # Brak jądra w tym deploymencie")
5387 - if initrd_line:
5388 - lines.append(f" {initrd_line}")
5389 - lines.append("}")
5390 - lines.append("")
5391 - entry_num += 1
5392 -
5393 - # Wpis fallback: zwykły root (gdyby wszystko padło).
5394 - # Uwaga: GRUB NIE rozwija globów – trzeba podać KONKRETNY plik jądra
5395 - # (wcześniejsze `linux /boot/vmlinuz-*` było niepoprawne).
5396 - fallback_kernels = sorted(
5397 - [f for f in os.listdir("/boot") if f.startswith("vmlinuz-")],
5398 - reverse=True
5399 - ) if os.path.isdir("/boot") else []
5400 - lines.append("menuentry 'Pagan Linux – fallback (zwykły root)' {")
5401 - if fallback_kernels:
5402 - lines.append(f" linux /boot/{fallback_kernels[0]}{root_arg} rw quiet")
5403 - else:
5404 - lines.append(" # Brak jądra w /boot")
5405 - lines.append(f" initrd /boot/initramfs.img")
5406 - lines.append("}")
5407 - lines.append("")
5408 -
5409 - # Zapisz
5410 - os.makedirs(os.path.dirname(grub_cfg), exist_ok=True)
5411 - with open(grub_cfg, "w") as f:
5412 - f.write("\n".join(lines))
5413 -
5414 - print(" 📋 GRUB config zaktualizowany – wpisy dla każdego deploymentu")
5415 -
5416 -
5417 -def _root_device_from_fstab(path: str = "/etc/fstab") -> str:
5418 - """Zwraca DEVICE z wpisu dla '/' w fstab (pomija komentarze)."""
5419 - try:
5420 - with open(path, "r", encoding="utf-8", errors="replace") as fh:
5421 - for line in fh:
5422 - line = line.split("#", 1)[0].strip()
5423 - if not line:
5424 - continue
5425 - parts = line.split()
5426 - if len(parts) >= 2 and parts[1] == "/":
5427 - return parts[0]
5428 - except OSError:
5429 - pass
5430 - return ""
5431 -
5432 -
5433 -def _in_chroot() -> bool:
5434 - """Heurystyka: czy działamy w chrocie (build ISO/IMG)?
5435 -
5436 - W chrocie /proc/1/root to root HOSTA – inny system plików niż nasz '/'.
5437 - Na zwykłym systemie PID 1 ma root równy '/'. PAGAN_ROOT ustawiają skrypty
5438 - budujące i jest dziedziczony przez chroot (dodatkowa wskazówka).
5439 - """
5440 - if os.environ.get("PAG_IN_CHROOT") == "1":
5441 - return True
5442 - if os.environ.get("PAGAN_ROOT"):
5443 - return True
5444 - try:
5445 - return os.stat("/").st_dev != os.stat("/proc/1/root").st_dev
5446 - except OSError:
5447 - return False
5448 -
5449 -
5450 -def _detect_root_device() -> str:
5451 - """Wykrywa urządzenie/identyfikator partycji root dla GRUB (root=...).
5452 -
5453 - Kolejność (od najbardziej wiarygodnego w danym kontekście):
5454 - 1) PAG_ROOT_DEVICE / PAG_GRUB_ROOT – jawny override (build ISO/IMG,
5455 - instalator); najpewniejszy, bo nie zgadujemy.
5456 - 2) /etc/fstab TARGETU – w chrocie findmnt '/' zwraca partycję HOSTA,
5457 - a fstab opisuje target (np. root=/dev/sda2 dla obrazu IMG).
5458 - 3) findmnt '/' – na żywym systemie (obsługuje UUID/LUKS/subvol).
5459 - Zwraca "" gdy nie da się ustalić – wtedy GRUB nie dostaje błędnego root=.
5460 - """
5461 - explicit = (os.environ.get("PAG_ROOT_DEVICE")
5462 - or os.environ.get("PAG_GRUB_ROOT") or "").strip()
5463 - if explicit:
5464 - return explicit
5465 -
5466 - fstab_dev = _root_device_from_fstab()
5467 - if _in_chroot() and fstab_dev:
5468 - return fstab_dev
5469 -
5470 - try:
5471 - result = subprocess.run(
5472 - ["findmnt", "-n", "-o", "SOURCE", "/"],
5473 - capture_output=True, text=True, timeout=5
5474 - )
5475 - if result.returncode == 0 and result.stdout.strip():
5476 - return result.stdout.strip()
5477 - except Exception:
5478 - pass
5479 -
5480 - # Ostatnia deska: fstab targetu (lepsze niż hardkodowane /dev/sda1,
5481 - # które na sprzęcie z NVMe dawało niebootowalny system).
5482 - return fstab_dev
5483 -
5484 -
5485 -def cmd_grub_update():
5486 - """Ręcznie regeneruje konfigurację GRUB (wpisy dla deploymentów)."""
5487 - ensure_dirs()
5488 - print("📋 Aktualizacja konfiguracji GRUB...")
5489 - _update_grub_config()
5490 - print("✅ GRUB zaktualizowany.")
5491 - return 0
5492 -
5493 -def cmd_deploy_list():
5494 - """Wyświetla listę wszystkich deploymentów."""
5495 - deployments = _load_deployments()
5496 - if not deployments:
5497 - print(_("no_deployments")); return
5498 -
5499 - print(_("deployments_list", len(deployments)))
5500 - active = os.readlink(ACTIVE_LINK) if os.path.islink(ACTIVE_LINK) else ""
5501 -
5502 - for d in reversed(deployments):
5503 - marker = f" ◀ {_('active_deployment')}" if d.get("active") or d["id"] == os.path.basename(active) else ""
5504 - print(f" {d['id']}{marker}")
5505 - print(f" {d['action']}: {', '.join(d['packages'][:5])}")
5506 - if len(d.get('packages', [])) > 5:
5507 - print(f" +{len(d['packages']) - 5} więcej...")
5508 - print(f" {d['timestamp']}")
5509 -
5510 -
5511 -def cmd_deploy_rollback():
5512 - """Przełącza na poprzedni deployment."""
5513 - deployments = _load_deployments()
5514 - active_indices = [i for i, d in enumerate(deployments) if d.get("active")]
5515 -
5516 - if len(deployments) < 2:
5517 - print(f"❌ {_('deploy_rollback_fail')}"); return 1
5518 -
5519 - current_idx = active_indices[0] if active_indices else len(deployments) - 1
5520 - prev_idx = current_idx - 1 if current_idx > 0 else -1
5521 -
5522 - if prev_idx < 0:
5523 - print(f"❌ {_('deploy_rollback_fail')}"); return 1
5524 -
5525 - prev = deployments[prev_idx]
5526 - prev_dir = os.path.join(DEPLOYMENTS_DIR, prev["id"])
5527 -
5528 - if not os.path.isdir(prev_dir):
5529 - print(f"❌ Deployment {prev['id']} nie istnieje na dysku"); return 1
5530 -
5531 - print(f"⏪ Przywracanie deploymentu: {prev['id']}")
5532 - print(f" {prev['action']}: {', '.join(prev['packages'][:5])}")
5533 -
5534 - if not _ask_confirm():
5535 - return 0
5536 -
5537 - _switch_deployment(prev_dir)
5538 -
5539 - for d in deployments:
5540 - d["active"] = (d["id"] == prev["id"])
5541 - _save_deployments(deployments)
5542 -
5543 - _update_grub_config()
5544 - print(f"✅ {_('deploy_rollback_ok', prev['id'])}")
5545 - print(" 💡 Restart wymagany do przeładowania systemu.")
5546 - return 0
5547 -
5548 -
5549 -def cmd_deploy_cleanup(keep: int = 3):
5550 - """Usuwa stare deploymenty, zachowując ostatnie `keep`."""
5551 - deployments = _load_deployments()
5552 -
5553 - if len(deployments) <= keep:
5554 - print(f"✅ {_('deploy_cleanup_none', keep)}"); return 0
5555 -
5556 - to_remove = deployments[:-keep]
5557 - removed = 0
5558 -
5559 - for d in to_remove:
5560 - deploy_dir = os.path.join(DEPLOYMENTS_DIR, d["id"])
5561 - if os.path.isdir(deploy_dir):
5562 - shutil.rmtree(deploy_dir, ignore_errors=True)
5563 - removed += 1
5564 -
5565 - remaining = deployments[-keep:]
5566 - _save_deployments(remaining)
5567 -
5568 - print(f"✅ {_('deploy_cleanup_ok', removed)}")
5569 - return 0
5570 -
5571 -
5572 -# =============================================================================
5573 -# POMOCNICZE
5574 -# =============================================================================
5575 -
5576 -# Pakiety dostarczane przez bazowy system (zawsze "zainstalowane"). Wchodzą do
5577 -# rootfs z ISO przez data.tar.xz, więc NIE ma ich w repo.json ani w bazie pag –
5578 -# każda zależność od nich (glibc, bash, python3…) wyglądałaby na "brakującą".
5579 -# Współdzielone przez rozwijanie i weryfikację zależności.
5580 -SYSTEM_BASE = {
5581 - "glibc", "libc", "gcc", "g++", "make", "binutils", "coreutils", "bash",
5582 - "linux-api-headers", "kernel-headers", "zlib", "pkg-config", "pkgconf",
5583 - "tar", "gzip", "xz", "bzip2", "findutils", "grep", "sed", "gawk", "awk",
5584 - "diffutils", "patch", "file", "m4", "perl", "python3", "sh",
5585 -}
5586 -
5587 -
5588 -def _resolve_deps(names, repo, installed):
5589 - resolved, visited = [], set()
5590 - missing = [] # zależności których nie ma ani w repo ani zainstalowane
5591 -
5592 - def _is_base(dep):
5593 - """True, gdy zależność dostarcza bazowy system (także przez provides)."""
5594 - return dep in SYSTEM_BASE \
5595 - or _resolve_provides(dep, repo, installed) in SYSTEM_BASE
5596 -
5597 - def visit(name, explicit=False):
5598 - if name in visited: return
5599 -
5600 - # Rozwijanie wirtualnych zależności przez provides
5601 - target = _resolve_provides(name, repo, installed)
5602 -
5603 - # Zależność dostarczana przez bazowy system – nie ma jej w repo ani w
5604 - # bazie pag, więc nie "brakuje" jej i nie próbujemy jej instalować.
5605 - # Wyjątek: nazwa podana wprost przez użytkownika (explicit=True).
5606 - if not explicit and target in SYSTEM_BASE:
5607 - return
5608 -
5609 - if target in visited: return
5610 - visited.add(target)
5611 - if target in repo:
5612 - for dep in repo[target].dependencies:
5613 - real_dep = _resolve_provides(dep, repo, installed)
5614 - real_target = real_dep if real_dep in repo else dep
5615 -
5616 - if _is_base(dep):
5617 - continue
5618 -
5619 - # Sprawdź czy zależność jest dostępna
5620 - if real_target not in installed and real_target not in repo:
5621 - if dep not in missing:
5622 - missing.append(dep)
5623 -
5624 - if dep not in installed:
5625 - visit(real_target)
5626 - elif target not in installed:
5627 - # Pakiet nie istnieje ani w repo ani zainstalowany
5628 - if target not in missing:
5629 - missing.append(target)
5630 -
5631 - if target not in installed and target not in resolved:
5632 - resolved.append(target)
5633 -
5634 - for name in names:
5635 - visit(name, explicit=True)
5636 -
5637 - # Zwróć brakujące (do sprawdzenia przez wywołującego)
5638 - return resolved, missing
5639 -
5640 -def _verify_dependencies(to_install: list, repo: dict, installed: dict) -> int:
5641 - """
5642 - Sprawdza czy wszystkie zależności pakietów do instalacji są spełnione.
5643 - Zwraca liczbę brakujących zależności.
5644 - """
5645 - all_missing = []
5646 - all_warnings = []
5647 -
5648 - for pkg_name in to_install:
5649 - pkg = repo.get(pkg_name)
5650 - if not pkg:
5651 - continue
5652 -
5653 - for dep in pkg.dependencies:
5654 - if dep in SYSTEM_BASE:
5655 - continue # bazowy system dostarcza tę zależność
5656 - real_dep = _resolve_provides(dep, repo, installed)
5657 - # Sprawdź czy zależność jest dostępna (w repo lub już zainstalowana)
5658 - in_repo = real_dep in repo
5659 - in_installed = real_dep in installed
5660 - will_be_installed = real_dep in to_install
5661 -
5662 - if not in_repo and not in_installed and not will_be_installed:
5663 - if dep not in all_missing:
5664 - all_missing.append((pkg_name, dep))
5665 - elif in_repo and not in_installed and not will_be_installed:
5666 - if dep not in [w[1] for w in all_warnings]:
5667 - all_warnings.append((pkg_name, dep, real_dep))
5668 -
5669 - if all_missing:
5670 - print(f"\n❌ {_c('red', 'BRAKUJĄCE ZALEŻNOŚCI')} – nie można zainstalować:")
5671 - for pkg, dep in all_missing:
5672 - print(f" {pkg} → potrzebuje {_c('red', dep)} (brak w repozytoriach)")
5673 - print()
5674 -
5675 - if all_warnings:
5676 - print(f"\n⚠ {_c('yellow', 'NIESPEŁNIONE ZALEŻNOŚCI')} – zostaną doinstalowane:")
5677 - for pkg, dep, real in all_warnings:
5678 - print(f" {pkg} → {dep} ({_c('green', real)} – będzie pobrane)")
5679 - print()
5680 -
5681 - return len(all_missing)
5682 -
5683 -# Biblioteki bazowe (glibc/gcc runtime) – zawsze dostępne, nie wymagają pakietu
5684 -BASE_SO = {
5685 - "libc.so.6", "libm.so.6", "libpthread.so.0", "libdl.so.2", "librt.so.1",
5686 - "libutil.so.1", "libresolv.so.2", "libnsl.so.1", "libcrypt.so.1",
5687 - "ld-linux.so.2", "ld-linux-x86-64.so.2", "ld-linux-aarch64.so.1",
5688 - "libgcc_s.so.1", "linux-vdso.so.1",
5689 -}
5690 -
5691 -def _verify_so_deps(to_install: list, repo: dict, installed: dict) -> int:
5692 - """Sprawdza wymagania ABI (provides_so / requires_so z metadata.json).
5693 -
5694 - Fail-closed TYLKO gdy metadata jawnie deklaruje requires_so, a żaden pakiet
5695 - (bazowy, zainstalowany lub instalowany w tej transakcji) nie dostarcza
5696 - wymaganej wersji biblioteki. Stare pakiety bez tych pól są pomijane.
5697 - """
5698 - provided = set(BASE_SO)
5699 - for n in to_install:
5700 - p = repo.get(n)
5701 - if p:
5702 - provided.update(p.provides_so or [])
5703 - for n, info in installed.items():
5704 - provided.update(info.get("provides_so", []) or [])
5705 -
5706 - missing = []
5707 - for n in sorted(to_install):
5708 - p = repo.get(n)
5709 - if not p:
5710 - continue
5711 - for so in (p.requires_so or []):
5712 - if so not in provided:
5713 - missing.append((n, so))
5714 -
5715 - if missing:
5716 - print(f"\n❌ {_c('red', 'BRAK WYMAGANYCH BIBLIOTEK (ABI so-name)')}:")
5717 - for n, so in missing:
5718 - print(f" {n} → wymaga {_c('red', so)} – żaden pakiet nie dostarcza tej wersji")
5719 - print()
5720 - return len(missing)
5721 -
5722 -def _download_pkg(pkg, attempts: int = 3, progress: bool = True):
5723 - """Pobiera pakiet do cache. `progress=False` wycisza pasek (np. gdy
5724 - równoległy pobierający pokazuje własny pasek zbiorczy)."""
5725 - url = f"{pkg.repo_url}/{pkg.filename}"
5726 - dest = os.path.join(PAG_CACHE, pkg.filename)
5727 - if os.path.exists(dest) and (not pkg.sha256 or _sha256_file(dest) == pkg.sha256):
5728 - _download_pkg_sig(pkg, dest) # upewnij się, że sygnatura jest w cache
5729 - return dest
5730 - last_err = None
5731 - for attempt in range(1, attempts + 1):
5732 - try:
5733 - req = Request(url, headers={"User-Agent":"pag/3.0"})
5734 - with urlopen(req, timeout=600) as resp:
5735 - total = int(resp.headers.get("Content-Length", 0))
5736 - bar = DownloadBar(pkg.filename, total) if progress else None
5737 - with open(dest, "wb") as f:
5738 - while True:
5739 - chunk = resp.read(65536)
5740 - if not chunk:
5741 - break
5742 - f.write(chunk)
5743 - if bar is not None:
5744 - bar.update(len(chunk))
5745 - if bar is not None:
5746 - bar.close()
5747 - if pkg.sha256 and _sha256_file(dest) != pkg.sha256:
5748 - last_err = "SHA256 mismatch"
5749 - try:
5750 - os.remove(dest)
5751 - except OSError:
5752 - pass
5753 - if attempt < attempts:
5754 - print(f" ↻ Ponawiam pobieranie {pkg.filename} "
5755 - f"({attempt}/{attempts - 1})...", file=sys.stderr)
5756 - time.sleep(attempt)
5757 - continue
5758 - return None
5759 - _download_pkg_sig(pkg, dest)
5760 - return dest
5761 - except Exception as e:
5762 - last_err = e
5763 - # Usuń częściowy plik – bez tego mógłby zostać użyty jako „cache”
5764 - # (gdy pakiet nie ma sha256) albo mylić kolejną próbę.
5765 - try:
5766 - if os.path.exists(dest):
5767 - os.remove(dest)
5768 - except OSError:
5769 - pass
5770 - if attempt < attempts:
5771 - print(f" ↻ Ponawiam pobieranie {pkg.filename} "
5772 - f"({attempt}/{attempts - 1})...", file=sys.stderr)
5773 - time.sleep(attempt)
5774 - continue
5775 - print(f" ⚠ Błąd pobierania {pkg.filename}: {last_err}", file=sys.stderr)
5776 - return None
5777 -
5778 -def _download_pkg_sig(pkg, dest):
5779 - """Zapewnia AKTUALNY podpis pakietu (.asc, fallback .sig) w cache.
5780 -
5781 - Istniejący podpis jest używany tylko wtedy, gdy faktycznie weryfikuje TĘ
5782 - paczkę. Inaczej po przebudowie tej samej wersji (ten sam plik, nowy sha256)
5783 - stary podpis zostawał obok nowej paczki i weryfikacja dawała fałszywe
5784 - „NIEPRAWIDŁOWY PODPIS GPG”.
5785 - """
5786 - for ext in (".asc", ".sig"):
5787 - sig_dest = dest + ext
5788 - if os.path.exists(sig_dest):
5789 - ok, _fp = _gpg_verify_fp(sig_dest, dest)
5790 - if ok:
5791 - return
5792 - for ext in (".asc", ".sig"):
5793 - sig_dest = dest + ext
5794 - try:
5795 - req = Request(f"{pkg.repo_url}/{pkg.filename}{ext}", headers={"User-Agent":"pag/3.0"})
5796 - with urlopen(req, timeout=30) as resp:
5797 - data = resp.read()
5798 - except Exception:
5799 - continue
5800 - # nie mieszaj rozszerzeń – zostaje tylko ten wariant podpisu
5801 - for other in (".asc", ".sig"):
5802 - if other != ext:
5803 - try:
5804 - os.remove(dest + other)
5805 - except OSError:
5806 - pass
5807 - with open(sig_dest, "wb") as f:
5808 - f.write(data)
5809 - return
5810 - # Nie udało się pobrać podpisu – usuń nieaktualny z cache, żeby weryfikacja
5811 - # nie porównywała paczki z podpisem od innej wersji (czytelny „BRAK PODPISU”).
5812 - for other in (".asc", ".sig"):
5813 - try:
5814 - os.remove(dest + other)
5815 - except OSError:
5816 - pass
5817 -
5818 -def _download_packages_parallel(pkgs: List[PackageInfo], max_workers: int = 4) -> Dict[str, Optional[str]]:
5819 - """
5820 - Równoległe pobieranie wielu pakietów przez ThreadPoolExecutor.
5821 - Znacząco przyspiesza przy dużych aktualizacjach (50+ pakietów).
5822 - Zwraca słownik {nazwa_pakietu: ścieżka_lub_None}.
5823 - """
5824 - results = {}
5825 - total = len(pkgs)
5826 - completed = 0
5827 - with ThreadPoolExecutor(max_workers=max_workers) as executor:
5828 - future_to_pkg = {executor.submit(_download_pkg, pkg, progress=False): pkg for pkg in pkgs}
5829 - for future in as_completed(future_to_pkg):
5830 - pkg = future_to_pkg[future]
5831 - try:
5832 - results[pkg.name] = future.result()
5833 - except Exception:
5834 - results[pkg.name] = None
5835 - completed += 1
5836 - # Pasek postępu (animowany „drakkar” na TTY)
5837 - pct = completed / total * 100
5838 - bar = _pagan_bar(pct, 20, time.time(), animated=sys.stderr.isatty())
5839 - print(f"\r ⏬ [{bar}] {completed}/{total} ({pct:.0f}%)", end="", file=sys.stderr, flush=True)
5840 - print(file=sys.stderr) # nowa linia po zakończeniu
5841 - return results
5842 -
5843 -def load_world():
5844 - if not os.path.exists(WORLD_FILE): return set()
5845 - return {l.strip() for l in open(WORLD_FILE) if l.strip()}
5846 -
5847 -def save_world(w):
5848 - with open(WORLD_FILE,"w") as f:
5849 - for n in sorted(w): f.write(f"{n}\n")
5850 -
5851 -def _find_orphans(installed, world):
5852 - needed = set(world)
5853 - changed = True
5854 - while changed:
5855 - changed = False
5856 - for n in list(needed):
5857 - for dep in installed.get(n,{}).get("dependencies",[]):
5858 - if dep not in needed and dep in installed:
5859 - needed.add(dep); changed = True
5860 - return {n for n in installed if n not in needed}
5861 -
5862 -# =============================================================================
5863 -# MAIN
5864 -# =============================================================================
5865 -
5866 -def cmd_sbom(argv):
5867 - """pag sbom export [spdx|cyclonedx] – manifest SBOM zainstalowanych pakietów.
5868 -
5869 - Wypisuje na stdout JSON (SPDX 2.3 lub CycloneDX 1.5) z listą
5870 - zainstalowanych pakietów, wersji, licencji i sum SHA256.
5871 - """
5872 - fmt = (argv[0] if argv else "spdx").lower()
5873 - if fmt not in ("spdx", "cyclonedx"):
5874 - print("❌ Format: spdx | cyclonedx")
5875 - return 1
5876 - installed = load_json(INSTALLED_DB)
5877 - if not installed:
5878 - print("{}") if fmt == "cyclonedx" else print("{\"packages\": []}")
5879 - return 0
5880 - # metadata repo (licencje) – best-effort
5881 - try:
5882 - repo = fetch_all_packages()
5883 - except Exception:
5884 - repo = {}
5885 - names = sorted(installed)
5886 - created = datetime.now().astimezone().isoformat(timespec="seconds")
5887 -
5888 - def _license_of(name):
5889 - p = repo.get(name)
5890 - lic = getattr(p, "license", None) or []
5891 - if isinstance(lic, list):
5892 - lic = ", ".join(x for x in lic if x)
5893 - return lic or "NOASSERTION"
5894 -
5895 - if fmt == "spdx":
5896 - doc = {
5897 - "spdxVersion": "SPDX-2.3",
5898 - "dataLicense": "CC0-1.0",
5899 - "SPDXID": "SPDXRef-DOCUMENT",
5900 - "name": "PaganOS-installed",
5901 - "documentNamespace": f"https://repo.paganlinux.eu/sbom/installed-{int(time.time())}",
5902 - "creationInfo": {
5903 - "created": created,
5904 - "creators": [f"Tool: pag-{PAG_VERSION}"],
5905 - },
5906 - "packages": [],
5907 - }
5908 - for i, n in enumerate(names):
5909 - info = installed[n]
5910 - doc["packages"].append({
5911 - "SPDXID": f"SPDXRef-Package-{i+1}",
5912 - "name": n,
5913 - "versionInfo": info.get("version", ""),
5914 - "downloadLocation": info.get("repo", "NOASSERTION"),
5915 - "filesAnalyzed": False,
5916 - "licenseConcluded": _license_of(n),
5917 - "checksums": [{"algorithm": "SHA256", "checksumValue": info.get("sha256", "")}],
5918 - })
5919 - else: # cyclonedx
5920 - doc = {
5921 - "bomFormat": "CycloneDX",
5922 - "specVersion": "1.5",
5923 - "serialNumber": f"urn:uuid:{str(uuid.uuid4())}",
5924 - "version": 1,
5925 - "metadata": {
5926 - "timestamp": created,
5927 - "tools": [{"vendor": "PaganOS", "name": "pag", "version": PAG_VERSION}],
5928 - },
5929 - "components": [],
5930 - }
5931 - for n in names:
5932 - info = installed[n]
5933 - lic = _license_of(n)
5934 - comp = {
5935 - "type": "library",
5936 - "name": n,
5937 - "version": info.get("version", ""),
5938 - "hashes": [{"alg": "SHA-256", "content": info.get("sha256", "")}],
5939 - }
5940 - if lic != "NOASSERTION":
5941 - comp["licenses"] = [{"license": {"id": lic}}]
5942 - doc["components"].append(comp)
5943 - print(json.dumps(doc, indent=2, ensure_ascii=False))
5944 - return 0
5945 -
5946 -
5947 -USAGE_EN = """pag v3 – Pagan Linux Package Manager
5948 -
5949 -BASIC:
5950 - pag install <pkg>... Install packages
5951 - pag remove <pkg>... Remove packages
5952 - pag update Update PACKAGES (refreshes indexes first)
5953 - pag sync Refresh indexes + show pending package updates
5954 - pag upgrade Update SYSTEM (packages + kernel/initramfs/GRUB)
5955 - pag list [--installed] List available / installed
5956 - pag search <query> Search packages
5957 - pag info <pkg> Package details
5958 - pag files <pkg> List package files
5959 - pag verify [--deep] Verify integrity (--deep = SHA256 per file)
5960 - pag clean Clear download cache
5961 - pag stats System statistics
5962 - pag download <pkg>... Download packages to cache (offline prep)
5963 -
5964 -ROLLING (base baked into the image):
5965 - pag base [status] Image packages vs. repo (what pag manages)
5966 - pag base adopt [pkg...] Adopt base packages from the repo (--dry-run = preview)
5967 -
5968 -SECURITY:
5969 - pag key-add <url|file> Import GPG key
5970 - pag key-list List trusted keys
5971 - pag key-remove <id> Remove key
5972 - pag key-trust <repo> Pin repo signing key fingerprint (no TOFU)
5973 - pag key-untrust <repo> Forget repo fingerprint (back to TOFU)
5974 - pag key-trusted List pinned repo fingerprints
5975 -
5976 -ADVANCED:
5977 - pag why <pkg> Show why a package is installed
5978 - pag autoremove Auto-remove orphaned dependencies
5979 - pag pin <pkg> [ver] Pin package version
5980 - pag unpin <pkg> Unpin
5981 - pag pinned List pinned
5982 - pag history Transaction history
5983 - pag rollback Rollback last transaction
5984 - pag remove-orphans Remove orphaned deps
5985 - pag repo-add <url> [name] Add repository (drop-in /etc/pag/repos/)
5986 - pag repo-list List repositories
5987 - pag sbom export [fmt] SBOM manifest (spdx|cyclonedx)
5988 -
5989 -FLATPAK:
5990 - pag flatpak [<query>] Search & install (smart)
5991 - pag flatpak search <q> Search Flathub
5992 - pag flatpak install <id> Install flatpak
5993 - pag flatpak remove <id> Remove flatpak
5994 - pag flatpak list List installed flatpaks
5995 - pag flatpak update Update all flatpaks
5996 - pag flatpak info <id> Show flatpak details
5997 -
5998 -IMMUTABLE OS (PAG_IMMUTABLE=1):
5999 - pag deploy-list List all deployments
6000 - pag deploy-rollback Switch to previous deployment
6001 - pag deploy-cleanup [N] Remove old deployments (keep last N, default 3)
6002 - pag initramfs-update Rebuild initramfs for current kernel/deployment
6003 - pag grub-update Regenerate GRUB entries for all deployments
6004 -"""
6005 -
6006 -USAGE_PL = """pag v3 – Pagan Linux Package Manager
6007 -
6008 -PODSTAWOWE:
6009 - pag install <pkg>... Instalacja pakietów
6010 - pag remove <pkg>... Usuwanie pakietów
6011 - pag update Aktualizacja PAKIETÓW (odświeża indeksy)
6012 - pag sync Odśwież indeksy + info o aktualizacjach
6013 - pag upgrade Aktualizacja SYSTEMU (pakiety + kernel/initramfs/GRUB)
6014 - pag list [--installed] Lista dostępnych / zainstalowanych
6015 - pag search <query> Szukaj pakietów
6016 - pag info <pkg> Szczegóły pakietu
6017 - pag files <pkg> Lista plików pakietu
6018 - pag verify [--deep] Weryfikacja integralności
6019 - pag clean Wyczyść cache pobierania
6020 - pag stats Statystyki systemu
6021 - pag download <pkg>... Pobierz do cache (offline)
6022 -
6023 -ROLLING (baza wypalona w obrazie):
6024 - pag base [status] Pakiety z obrazu vs repo (czym pag zarządza)
6025 - pag base adopt [pkg...] Adoptuj pakiety bazy z repo (--dry-run = podgląd)
6026 -
6027 -BEZPIECZEŃSTWO:
6028 - pag key-add <url|file> Importuj klucz GPG
6029 - pag key-list Lista zaufanych kluczy
6030 - pag key-remove <id> Usuń klucz
6031 - pag key-trust <repo> Przypnij fingerprint klucza repo (bez TOFU)
6032 - pag key-untrust <repo> Zapomnij fingerprint repo (powrót do TOFU)
6033 - pag key-trusted Lista przypiętych fingerprintów repo
6034 -
6035 -ZAAWANSOWANE:
6036 - pag why <pkg> Dlaczego pakiet jest zainstalowany
6037 - pag autoremove Usuń osierocone zależności
6038 - pag pin <pkg> [ver] Przypnij wersję pakietu
6039 - pag unpin <pkg> Odepnij
6040 - pag pinned Lista przypiętych
6041 - pag history Historia transakcji
6042 - pag rollback Cofnij ostatnią transakcję
6043 - pag remove-orphans Usuń osierocone zależności
6044 - pag repo-add <url> [nazwa] Dodaj repozytorium (drop-in w /etc/pag/repos/)
6045 - pag repo-list Lista repozytoriów
6046 - pag sbom export [fmt] Manifest SBOM (spdx|cyclonedx)
6047 -
6048 -FLATPAK:
6049 - pag flatpak [<query>] Szukaj i instaluj
6050 - pag flatpak search <q> Szukaj na Flathub
6051 - pag flatpak install <id> Zainstaluj flatpak
6052 - pag flatpak remove <id> Usuń flatpak
6053 - pag flatpak list Lista zainstalowanych
6054 - pag flatpak update Aktualizuj wszystkie
6055 - pag flatpak info <id> Szczegóły flatpaka
6056 -
6057 -IMMUTABLE OS (PAG_IMMUTABLE=1):
6058 - pag deploy-list Lista wdrożeń
6059 - pag deploy-rollback Przełącz na poprzednie wdrożenie
6060 - pag deploy-cleanup [N] Usuń stare wdrożenia (zachowaj N, domyślnie 3)
6061 - pag initramfs-update Przebuduj initramfs
6062 - pag grub-update Regeneruj wpisy GRUB"""
6063 -
6064 -def _get_usage():
6065 - # Plik językowy może dostarczyć klucz "usage" – wtedy wygrywa z wbudowanym.
6066 - _u = T.get(LANG, {}).get("usage")
6067 - if _u:
6068 - return _u
6069 - if LANG == "pl":
6070 - return USAGE_PL
6071 - return USAGE_EN
6072 -
6073 -
6074 -def _extract_lang(outdir: str) -> int:
6075 - """Eksport wbudowanych tłumaczeń do outdir/{pl,en}.json (+ klucz "usage").
6076 -
6077 - Używane przez recepturę pakietu (pag.pag), żeby tłumaczenia jechały RAZEM
6078 - z wersją paga – po `pag install/upgrade pag` i self-update są zawsze zgodne.
6079 - """
6080 - os.makedirs(outdir, exist_ok=True)
6081 - for _code in ("pl", "en"):
6082 - _d = dict(T.get(_code, {}))
6083 - _u = globals().get(f"USAGE_{_code.upper()}", "")
6084 - if _u:
6085 - _d["usage"] = _u
6086 - _p = os.path.join(outdir, f"{_code}.json")
6087 - with open(_p, "w", encoding="utf-8") as _fh:
6088 - json.dump(_d, _fh, ensure_ascii=False, indent=2, sort_keys=True)
6089 - print(f" ✓ {_p} ({len(_d)} kluczy)")
6090 - return 0
6091 -
6092 -
6093 -def main():
6094 - # Ukryte (używane przy budowie pakietu): eksport tłumaczeń do plików
6095 - if len(sys.argv) >= 3 and sys.argv[1] == "--lang-extract":
6096 - sys.exit(_extract_lang(sys.argv[2]))
6097 - if len(sys.argv) >= 2 and sys.argv[1] in ("--version", "-V", "version"):
6098 - print(f"pag {PAG_VERSION}")
6099 - sys.exit(0)
6100 - if len(sys.argv) == 2 and sys.argv[1] in ("--help", "-h", "help"):
6101 - print(_get_usage()); sys.exit(0)
6102 - if len(sys.argv) < 2:
6103 - print(_get_usage()); sys.exit(0)
6104 -
6105 - cmd = sys.argv[1]
6106 - args = sys.argv[2:]
6107 -
6108 - # Python bez modułu ssl = brak HTTPS w urllib. Powiedz to wprost, zamiast
6109 - # pokazywać mylące „unknown url type: https” przy każdej operacji sieciowej.
6110 - if not _ssl_ok():
6111 - print(f" ⚠ {_('ssl_broken')}", file=sys.stderr)
6112 -
6113 - # --- Komendy TYLKO DO ODCZYTU (nie wymagają roota) ---
6114 - READ_ONLY = {
6115 - "list": lambda: cmd_list("--installed" in args),
6116 - "search": lambda: cmd_search(args[0]) if args else print("Usage: pag search <query>"),
6117 - "info": lambda: cmd_info(args[0]) if args else print("Usage: pag info <pkg>"),
6118 - "files": lambda: cmd_files(args[0]) if args else print("Usage: pag files <pkg>"),
6119 - "verify": lambda: cmd_verify("--deep" in args),
6120 - "why": lambda: cmd_why(args[0]) if args else print("Usage: pag why <pkg>"),
6121 - "stats": cmd_stats,
6122 - "pinned": cmd_pinned,
6123 - "history": cmd_history,
6124 - "repo-list": cmd_repo_list,
6125 - "key-list": cmd_key_list,
6126 - "key-trusted": cmd_key_trusted,
6127 - "flatpak": lambda: cmd_flatpak(args),
6128 - "flatpak-search": lambda: cmd_flatpak_search(args[0]) if args else print("Usage: pag flatpak-search <query>"),
6129 - "flatpak-list": cmd_flatpak_list,
6130 - "flatpak-info": lambda: cmd_flatpak_info(args[0]) if args else print("Usage: pag flatpak-info <id>"),
6131 - "deploy-list": cmd_deploy_list,
6132 - "deploy": cmd_deploy_list,
6133 - "sbom": lambda: cmd_sbom(args),
6134 - }
6135 -
6136 - if cmd in READ_ONLY:
6137 - sys.exit(READ_ONLY[cmd]() or 0)
6138 -
6139 - # --- `pag base` / `pag base status`: tylko odczyt (bez roota i bez locka) ---
6140 - # `pag base adopt` NIE wpada tutaj – idzie ścieżką komend zapisu (roota + lock
6141 - # pilnuje wspólna obsługa niżej), żeby transakcja była bezpieczna.
6142 - if cmd in ("base", "base-status") and not (args and args[0] in ("adopt", "register")):
6143 - sys.exit(cmd_base_status() or 0)
6144 -
6145 - # --- Smart search: `pag <nazwa-pakietu>` → repo + Flathub + sugestie ---
6146 - WRITE_CMDS = {
6147 - "install", "remove", "update", "sync", "upgrade", "clean", "download",
6148 - "autoremove", "remove-orphans", "pin", "unpin", "rollback",
6149 - "repo-add", "key-add", "key-remove", "key-trust", "key-untrust",
6150 - "self-update",
6151 - "flatpak", "flatpak-install", "flatpak-remove", "flatpak-update",
6152 - "deploy-rollback", "deploy-cleanup", "initramfs-update", "grub-update",
6153 - "base", "base-adopt", "base-register",
6154 - }
6155 - if cmd not in WRITE_CMDS:
6156 - # Literówka komendy? (np. `pag instal steam` zamiast `pag install`) –
6157 - # zasugeruj poprawną komendę ZAMIAST wpadać w smart search (który
6158 - # potrafi wisieć na `flatpak search` aż do Ctrl-C).
6159 - _known = set(READ_ONLY) | set(WRITE_CMDS)
6160 - _close = difflib.get_close_matches(cmd, _known, n=1, cutoff=0.75)
6161 - if _close:
6162 - print(f"❌ Nieznana komenda: '{cmd}'. Czy chodziło o '{_close[0]}'?")
6163 - print(f" Uruchom 'pag' bez argumentów, aby zobaczyć listę komend.")
6164 - sys.exit(1)
6165 - sys.exit(_smart_search(" ".join([cmd] + args)) or 0)
6166 -
6167 - # Obsługa flag globalnych (-y/--yes)
6168 - global_args = []
6169 - for a in args:
6170 - if a in ("-y", "--yes"):
6171 - os.environ["PAG_YES"] = "1"
6172 - else:
6173 - global_args.append(a)
6174 - args = global_args
6175 -
6176 - # --- Komendy ZAPISU (wymagają roota) ---
6177 - if os.geteuid() != 0:
6178 - print(f"❌ {_('root_required')}", file=sys.stderr); sys.exit(1)
6179 -
6180 - ensure_dirs()
6181 -
6182 - with DatabaseLock():
6183 - WRITE_COMMANDS = {
6184 - "install": lambda: cmd_install(
6185 - [a for a in args if a not in ("-f", "--force", "--")],
6186 - upgrade=("-f" in args or "--force" in args)),
6187 - "remove": lambda: cmd_remove(args),
6188 - "update": lambda: cmd_update(do_upgrade=True),
6189 - "sync": lambda: cmd_update(do_upgrade=False),
6190 - "upgrade": cmd_upgrade,
6191 - "clean": cmd_clean,
6192 - "download": lambda: cmd_download(args),
6193 - "autoremove": cmd_autoremove,
6194 - "remove-orphans": cmd_remove_orphans,
6195 - "pin": lambda: cmd_pin(args[0], args[1] if len(args)>1 else ""),
6196 - "unpin": lambda: cmd_unpin(args[0]) if args else print("Usage: pag unpin <pkg>"),
6197 - "rollback": cmd_rollback,
6198 - "repo-add": lambda: cmd_repo_add(args[0], args[1] if len(args) > 1 else "") if args else print("Usage: pag repo-add <url> [name]"),
6199 - "key-add": lambda: cmd_key_add(args[0]) if args else print("Usage: pag key-add <url|file>"),
6200 - "key-remove": lambda: cmd_key_remove(args[0]) if args else print("Usage: pag key-remove <id>"),
6201 - "key-trust": lambda: cmd_key_trust(args[0]) if args else print("Usage: pag key-trust <repo_url>"),
6202 - "key-untrust": lambda: cmd_key_untrust(args[0]) if args else print("Usage: pag key-untrust <repo_url>"),
6203 - "self-update": cmd_self_update,
6204 - "flatpak": lambda: cmd_flatpak(args),
6205 - "flatpak-install": lambda: _flatpak_smart_install(args) if args else print("Usage: pag flatpak-install <app>"),
6206 - "flatpak-remove": lambda: _flatpak_smart_remove(args) if args else print("Usage: pag flatpak-remove <app>"),
6207 - "flatpak-update": cmd_flatpak_update,
6208 - "deploy-rollback": cmd_deploy_rollback,
6209 - "deploy-cleanup": lambda: cmd_deploy_cleanup(int(args[0]) if args else 3),
6210 - "initramfs-update": cmd_initramfs_update,
6211 - "grub-update": cmd_grub_update,
6212 - "base": lambda: cmd_base_register(args) if (args and args[0] == "register") else cmd_base_adopt(args),
6213 - "base-adopt": lambda: cmd_base_adopt(args),
6214 - "base-register": lambda: cmd_base_register(args),
6215 - }
6216 -
6217 - fn = WRITE_COMMANDS.get(cmd)
6218 - if fn:
6219 - sys.exit(fn() or 0)
6220 - # Should never reach here – _smart_search handles unknowns
6221 - sys.exit(_smart_search(" ".join([cmd] + args)) or 0)
6222 -
6223 -if __name__ == "__main__":
6224 - try:
6225 - main()
6226 - except KeyboardInterrupt:
6227 - # Ctrl-C (np. podczas flatpak search / pobierania) – bez tracebacka
6228 - print("\n ⚠ Przerwano (Ctrl-C).")
1 +#!/usr/bin/env python3
2 +"""
3 +╔══════════════════════════════════════════════════════════════════════════════╗
4 +║ PAG - Pagan Linux Package Manager v4.0.2 ║
5 +║ Produkcyjny menedżer pakietów – atomowy, bezpieczny, i18n ║
6 +╚══════════════════════════════════════════════════════════════════════════════╝
7 +
8 +KLUCZOWE CECHY:
9 + - Atomowa instalacja przez staging (tmpdir → rename) – brak pół-instalacji
10 + - Bezpieczne usuwanie – sprawdza czy plik nie jest współdzielony
11 + - SQLite dla bazy plików – miliony plików bez problemu
12 + - GPG: weryfikacja repo.json + podpisy pakietów + pinning fingerprintu
13 + - Hooki: pre/post-install, pre/post-remove (piaskownica env, timeout, audit)
14 + - Głęboka weryfikacja SHA256 per-plik
15 + - Pełny rollback – cofa fizyczne pliki
16 + - Blokada flock – tylko jedna instancja
17 + - Transakcje z migawkami + rejestr wykonanych hooków
18 + - Cache HTTP (ETag/If-Modified-Since)
19 + - Wielojęzyczność (i18n) – PL, EN
20 +
21 +FORMAT PAKIETU (.pag):
22 + ├── data.tar.xz – pliki + sums.json (SHA256 per plik)
23 + ├── metadata.json – nazwa, wersja, zależności
24 + └── hooks/ – pre-install, post-install, pre-remove, post-remove
25 +
26 +MODEL ZAUFANIA / BEZPIECZEŃSTWO:
27 + - Repozytorium MUSI być zaufane: podpisy GPG zweryfikowane; fingerprint
28 + klucza przypiętego do repo (TOFU przy pierwszym użyciu, potem pinning).
29 + - Hooki uruchamiają dowolny plik z pakietu jako ROOT (jak apt/pacman).
30 + Ograniczamy je (czyste env, timeout, PAG_NO_HOOKS=1, log do
31 + /var/log/pag/audit.log) i rejestrujemy w transakcji, ale ostatecznie
32 + instalujesz kod, któremu ufasz.
33 + - self-update: weryfikacja podpisu + SHA256 + składnia, atomowa podmiana.
34 +"""
35 +
36 +import os, sys, json, copy, shutil, hashlib, tarfile, tempfile, subprocess, time, fcntl, sqlite3, locale, re, difflib
37 +
38 +# Fix TLS trust inside the Pagan chroot: point Python at the CA bundle that
39 +# pag ships, otherwise urlopen() fails with "unable to get local issuer
40 +# certificate" (no default capath/cafile is resolved in the chroot).
41 +for _cafile in (
42 + "/etc/ssl/certs/ca-certificates.crt",
43 + "/etc/ssl/cert.pem",
44 +):
45 + if os.path.isfile(_cafile):
46 + os.environ["SSL_CERT_FILE"] = _cafile
47 + break
48 +
49 +from pathlib import Path
50 +from datetime import datetime, timezone
51 +from typing import Dict, List, Optional, Tuple, Set
52 +from concurrent.futures import ThreadPoolExecutor, as_completed
53 +from urllib.request import urlopen, Request
54 +import threading, itertools
55 +import uuid # serialNumber SBOM (CycloneDX)
56 +
57 +# Wersja klienta – do porównania z repo.json["pag_version"] (self-update)
58 +PAG_VERSION = "4.0.2"
59 +from urllib.error import URLError, HTTPError
60 +
61 +# =============================================================================
62 +# Pagan progress — animowany pasek „Drakkar” (własny motyw Pagan/Loki)
63 +# -----------------------------------------------------------------------------
64 +# Zamiast statycznego „█” pasek jest animowany: łódź wikingów płynie po
65 +# falującym morzu, a za nią ciągnie się smuga z wędrującym refleksem. Animacja
66 +# jest funkcją czasu, więc „płynie” nawet gdy postęp stoi w miejscu (długa
67 +# instalacja jednego pakietu, przerwa między fragmentami pobierania).
68 +#
69 +# Konfiguracja (zmienne środowiskowe):
70 +# PAG_NO_ANIM=1 – wyłącz animację (zostaje klasyczny statyczny pasek)
71 +# PAG_BAR_STYLE=<styl> – drakkar (domyślnie) | snake | classic
72 +# Poza TTY animacja jest automatycznie wyłączona (czyste logi w plikach).
73 +# =============================================================================
74 +
75 +_PAGAN_ANIM = os.environ.get("PAG_NO_ANIM", "") not in ("1", "true", "yes", "on")
76 +_PAGAN_STYLE = os.environ.get("PAG_BAR_STYLE", "drakkar").strip().lower()
77 +_DRAW_LOCK = threading.Lock() # serializacja zapisów wielu pasków
78 +
79 +# Dwie fazy fali – przesuwane w czasie dają wrażenie ruchu morza.
80 +_WAVE_PHASES = ("~_", "_~")
81 +
82 +
83 +def _classic_bar(pct: float, width: int) -> str:
84 + """Klasyczny statyczny pasek █/░ (fallback dla logów i PAG_NO_ANIM)."""
85 + filled = int(round(width * max(0.0, min(100.0, pct)) / 100.0))
86 + return "█" * filled + "░" * (width - filled)
87 +
88 +
89 +def _drakkar_bar(pct: float, width: int, t: float, filled: int) -> str:
90 + """Drakkar (łódź wikingów) płynący po falującym morzu.
91 +
92 + - przed łodzią: falujące morze (~ _ przesuwane w czasie),
93 + - dziób łodzi: » (kolumna = bieżący postęp),
94 + - za łodzią: smuga z wędrującym refleksem światła.
95 + """
96 + done = pct >= 100.0
97 + wave = _WAVE_PHASES[int(t * 6) % len(_WAVE_PHASES)]
98 + ship = min(filled, width - 1)
99 + glow = int(t * 10) % ship if ship > 0 else -1
100 + out = []
101 + for i in range(width):
102 + if done:
103 + out.append("»" if i == width - 1 else "█") # łódź zacumowana
104 + elif i < ship:
105 + out.append("█" if i == glow else "▓")
106 + elif i == ship:
107 + out.append("»")
108 + else:
109 + out.append(wave[i & 1])
110 + return "".join(out)
111 +
112 +
113 +def _snake_bar(pct: float, width: int, t: float, filled: int) -> str:
114 + """Jörmungandr – wąż sunący przez pasek (głowa @, łuski o/~, ogon ·)."""
115 + done = pct >= 100.0
116 + head = min(filled, width - 1)
117 + out = []
118 + for i in range(width):
119 + if done:
120 + out.append("@" if i == width - 1 else "o")
121 + elif i < head:
122 + out.append("o" if (i + int(t * 6)) & 1 else "~")
123 + elif i == head:
124 + out.append("@")
125 + else:
126 + out.append("·")
127 + return "".join(out)
128 +
129 +
130 +def _pagan_bar(pct: float, width: int = 30, t: float = 0.0,
131 + style: Optional[str] = None, animated: bool = True) -> str:
132 + """Zwraca jednoliniowy pasek postępu o STAŁEJ szerokości `width`.
133 +
134 + `pct` – postęp 0..100
135 + `t` – czas (s); różne `t` → inna klatka animacji
136 + `animated` – False wymusza klasyczny statyczny pasek (np. brak TTY)
137 + """
138 + width = max(6, int(width))
139 + pct = max(0.0, min(100.0, float(pct)))
140 + style = style or _PAGAN_STYLE
141 + if not animated or not _PAGAN_ANIM or style == "classic":
142 + return _classic_bar(pct, width)
143 + filled = int(round(width * pct / 100.0))
144 + if style == "snake":
145 + return _snake_bar(pct, width, t, filled)
146 + return _drakkar_bar(pct, width, t, filled)
147 +
148 +
149 +class _Bar:
150 + """Baza animowanych pasków: rysują JEDNĄ nadpisywaną linię na `stream`.
151 +
152 + Gdy mamy TTY, wątek w tle odświeża pasek ~10×/s, dzięki czemu morze faluje
153 + także wtedy, gdy postęp chwilowo się nie zmienia.
154 + """
155 + def __init__(self, width: int, stream=None):
156 + self.width = width
157 + self.stream = stream if stream is not None else sys.stderr
158 + self.tty = self.stream.isatty()
159 + self._lock = threading.RLock()
160 + self._last_len = 0
161 + self._stop = threading.Event()
162 + self._thread = None
163 +
164 + # -- wątek animacji -------------------------------------------------------
165 + def _start_anim(self):
166 + if _PAGAN_ANIM and self.tty and self._thread is None:
167 + self._thread = threading.Thread(target=self._anim_loop, daemon=True)
168 + self._thread.start()
169 +
170 + def _anim_loop(self):
171 + while not self._stop.wait(0.1):
172 + with self._lock:
173 + if self._stop.is_set():
174 + break
175 + self._write(self._line())
176 +
177 + def _stop_anim(self):
178 + self._stop.set()
179 + if self._thread is not None:
180 + self._thread.join(timeout=0.3)
181 + self._thread = None
182 +
183 + # -- rysowanie ------------------------------------------------------------
184 + def _write(self, line: str):
185 + clear = " " * max(0, self._last_len - len(line))
186 + with _DRAW_LOCK:
187 + self.stream.write(f"\r{line}{clear}")
188 + self.stream.flush()
189 + self._last_len = len(line)
190 +
191 + def _line(self) -> str:
192 + raise NotImplementedError
193 +
194 + def _clear_line(self):
195 + if self.tty and self._last_len:
196 + with _DRAW_LOCK:
197 + self.stream.write("\r" + " " * self._last_len + "\r")
198 + self.stream.flush()
199 + self._last_len = 0
200 +
201 + def _newline(self):
202 + if self.tty and self._last_len:
203 + self.stream.write("\n")
204 + self.stream.flush()
205 + self._last_len = 0
206 +
207 +
208 +class ProgressBar(_Bar):
209 + """Pasek postępu dla N elementów — animowany („drakkar”) na TTY."""
210 + def __init__(self, total: int, desc: str = "", unit: str = "", width: int = 30):
211 + super().__init__(width)
212 + self.total = max(total, 1)
213 + self.desc = desc
214 + self.unit = unit
215 + self.n = 0
216 + self.suffix = ""
217 + self.start = time.time()
218 + self._start_anim()
219 +
220 + def _line(self) -> str:
221 + pct = self.n / self.total * 100
222 + elapsed = time.time() - self.start
223 + speed = self.n / elapsed if elapsed > 0 else 0
224 + if self.n >= self.total:
225 + eta_str = "done"
226 + elif speed > 0:
227 + eta = (self.total - self.n) / speed
228 + eta_str = f"{eta:.0f}s" if eta < 60 else f"{eta/60:.1f}m"
229 + else:
230 + eta_str = "?..."
231 + bar = _pagan_bar(pct, self.width, time.time(), animated=self.tty)
232 + return f" {self.desc} [{bar}] {self.n}/{self.total} ({pct:.0f}%) ETA {eta_str}{self.suffix}"
233 +
234 + def update(self, n: Optional[int] = None, suffix: str = ""):
235 + with self._lock:
236 + if n is not None:
237 + self.n = n
238 + else:
239 + self.n += 1
240 + self.suffix = suffix
241 + if self.tty:
242 + self._write(self._line())
243 + elif (self.n == 1 or self.n >= self.total
244 + or self.n % max(1, self.total // 10) == 0):
245 + # Bez TTY – tylko kamienie milowe (czysty log)
246 + print(self._line(), file=self.stream)
247 +
248 + def close(self):
249 + self._stop_anim()
250 + with self._lock:
251 + self._newline()
252 +
253 + def __enter__(self):
254 + return self
255 +
256 + def __exit__(self, *args):
257 + self.close()
258 +
259 +
260 +class DownloadBar(_Bar):
261 + """Animowany pasek pobierania (na podstawie Content-Length)."""
262 + def __init__(self, filename: str, total_bytes: int):
263 + super().__init__(25)
264 + self.filename = filename
265 + self.total = total_bytes
266 + self.downloaded = 0
267 + self.start = time.time()
268 + self._start_anim()
269 +
270 + def _line(self) -> str:
271 + pct = self.downloaded / self.total * 100 if self.total > 0 else 0.0
272 + elapsed = time.time() - self.start
273 + speed = self.downloaded / elapsed if elapsed > 0 else 0
274 + if self.total > 0 and speed > 0:
275 + eta = (self.total - self.downloaded) / speed
276 + eta_str = f"{eta:.0f}s" if eta < 60 else f"{eta/60:.1f}m"
277 + else:
278 + eta_str = "?..."
279 + bar = _pagan_bar(pct, self.width, time.time(), animated=self.tty)
280 + sz = self._fmt_size(self.total)
281 + spd = self._fmt_size(int(speed))
282 + return f" ↓ {self.filename} [{bar}] {pct:.0f}% {sz} {spd}/s ETA {eta_str}"
283 +
284 + def update(self, chunk_size: int):
285 + with self._lock:
286 + self.downloaded += chunk_size
287 + if self.tty and self.total > 0:
288 + self._write(self._line())
289 +
290 + def close(self):
291 + self._stop_anim()
292 + with self._lock:
293 + if self.total > 0:
294 + self._newline()
295 +
296 + @staticmethod
297 + def _fmt_size(n: int) -> str:
298 + for unit in ("B", "KB", "MB", "GB"):
299 + if n < 1024:
300 + return f"{n:.1f} {unit}"
301 + n /= 1024
302 + return f"{n:.1f} TB"
303 +
304 +
305 +class _StepBar(_Bar):
306 + """Animowany pasek dla pętli „krok po kroku” (instalacja/aktualizacja).
307 +
308 + Pasek nie skacze skokowo co pakiet – między krokami łagodnie „dopełza”
309 + w stronę kolejnego progu (jak w instalatorach), więc rośnie w sposób
310 + ciągły. Wątek animacji odświeża go ~10×/s.
311 + """
312 + def __init__(self, total: int, icon: str = "", width: int = 25,
313 + creep_tau: float = 3.0):
314 + super().__init__(width)
315 + self.total = max(total, 1)
316 + self.icon = icon
317 + self.creep_tau = creep_tau # „stała czasu” dopełzania (s)
318 + self.idx = 0
319 + self.label = ""
320 + self.t0 = time.time()
321 + self._step_t = time.time() # start bieżącego pakietu
322 + self._start_anim()
323 +
324 + def _frac(self) -> float:
325 + """Ukończona część [0..1]: kroki + wygładzone dopełzanie w bieżącym."""
326 + done = max(0, self.idx - 1)
327 + if done >= self.total:
328 + return 1.0
329 + # 0.5 ** (dt/tau): 0 → ~1 asymptotycznie; cap 0.9, by krok był widoczny
330 + creep = 1.0 - 0.5 ** ((time.time() - self._step_t) / self.creep_tau)
331 + return (done + min(creep, 0.9)) / self.total
332 +
333 + def _line(self) -> str:
334 + pct = self._frac() * 100.0
335 + eta_s = ""
336 + if self.idx > 1:
337 + avg = (time.time() - self.t0) / (self.idx - 1)
338 + rem = avg * (self.total - self.idx + 1)
339 + eta_s = f" ~{rem:.0f}s" if rem < 60 else f" ~{rem/60:.1f}m"
340 + bar = _pagan_bar(pct, self.width, time.time(), animated=self.tty)
341 + return f" {self.icon}[{bar}] {self.idx}/{self.total} ({pct:.0f}%) {self.label}{eta_s}"
342 +
343 + def step(self, idx: int, label: str):
344 + with self._lock:
345 + self.idx = idx
346 + self.label = label
347 + self._step_t = time.time()
348 + if self.tty:
349 + self._write(self._line())
350 + else:
351 + print(self._line(), file=self.stream)
352 +
353 + def end(self):
354 + self._stop_anim()
355 + with self._lock:
356 + self._clear_line()
357 +
358 +# =============================================================================
359 +# GPG – BEZPIECZNE WYWOŁYWANIE (odporne na brak binarki gpg)
360 +# =============================================================================
361 +
362 +GPG_BINARY = shutil.which("gpg2") or shutil.which("gpg") or "gpg"
363 +GPG_HOME = "/etc/pag/gpg" # izolowany keyring (działa z keyboxd GPG 2.4+)
364 +
365 +def _ssl_ok() -> bool:
366 + """Czy Python ma działający moduł ssl (HTTPS w urllib).
367 +
368 + Bez niego urllib nie zna schematu https i każda operacja sieciowa kończy
369 + się „unknown url type: https” – myląco, bo wygląda jak błąd adresu.
370 + """
371 + try:
372 + import ssl # noqa: F401
373 + return True
374 + except Exception:
375 + return False
376 +
377 +
378 +def _gpg_run(*args, timeout: int = 30, **kwargs) -> subprocess.CompletedProcess:
379 + """
380 + Bezpieczne wywołanie GPG – przechwytuje FileNotFoundError,
381 + gdyby gpg/gpg2 nie było zainstalowane w minimalnym środowisku.
382 + Wymusza LC_ALL=C aby komunikaty GPG były zawsze po angielsku
383 + (niezależnie od locale systemu) – kluczowe dla parsowania stderr.
384 + """
385 + env = kwargs.pop("env", None) or os.environ.copy()
386 + env["LC_ALL"] = "C"
387 + env["GNUPGHOME"] = GPG_HOME
388 + try:
389 + return subprocess.run([GPG_BINARY, *args], timeout=timeout, env=env, **kwargs)
390 + except FileNotFoundError:
391 + # GPG nie jest dostępne – zwróć błąd z komunikatem
392 + # (szanuj text=True – inaczej caller dostaje bytes i może wybuchnąć TypeError)
393 + _text = bool(kwargs.get("text") or kwargs.get("universal_newlines"))
394 + _msg = f"GPG binary not found ({GPG_BINARY})"
395 + return subprocess.CompletedProcess(
396 + [GPG_BINARY, *args], 127,
397 + stdout=("" if _text else b""),
398 + stderr=(_msg if _text else _msg.encode()),
399 + )
400 + except subprocess.TimeoutExpired:
401 + return subprocess.CompletedProcess(
402 + [GPG_BINARY, *args], 124,
403 + stdout=b"", stderr=b"GPG operation timed out"
404 + )
405 +
406 +def _load_trust_db() -> dict:
407 + """Mapa repo_url → fingerprint klucza podpisującego (baza zaufania)."""
408 + try:
409 + with open(TRUST_DB) as f:
410 + return json.load(f)
411 + except (FileNotFoundError, json.JSONDecodeError):
412 + return {}
413 +
414 +
415 +def _save_trust_db(db: dict):
416 + os.makedirs(os.path.dirname(TRUST_DB), exist_ok=True)
417 + with open(TRUST_DB, "w") as f:
418 + json.dump(db, f, indent=2)
419 +
420 +
421 +def _gpg_verify_fp(sig_path: str, data_path: str, timeout: int = 30):
422 + """Weryfikuje podpis i odczytuje fingerprint podpisującego.
423 +
424 + Używa --status-fd=1 i linii VALIDSIG <fingerprint>. Zwraca (ok, fingerprint).
425 +
426 + FAIL-CLOSED: OK tylko gdy GPG zwrócił 0 ORAZ w statusie maszynowym jest
427 + linia VALIDSIG. Nie zakładamy sukcesu na podstawie samego kodu wyjścia –
428 + gdyby format --status-fd się zmienił, wolimy odrzucić podpis niż przyjąć
429 + niezaufany pakiet (wywołujący traktuje fp=None jako brak potwierdzenia).
430 + """
431 + env = os.environ.copy()
432 + res = _gpg_run("--verify", "--status-fd", "1", sig_path, data_path,
433 + capture_output=True, text=True, timeout=timeout, env=env)
434 + out = res.stdout or ""
435 + m = re.search(r"\[GNUPG:\]\s+VALIDSIG\s+([0-9A-Fa-f]{16,})", out)
436 + if not m:
437 + m = re.search(r"\bVALIDSIG\s+([0-9A-Fa-f]{16,})", out)
438 + if res.returncode != 0 or not m:
439 + return False, None
440 + return True, m.group(1).upper()
441 +
442 +
443 +def _verify_local_pkg_signature(pkg_path: str) -> bool:
444 + """Weryfikuje lokalny .pag tym samym kluczem co zaufane repo."""
445 + # PAG_INSECURE=1 – spójnie z _verify_repo_sig() i _verify_pkg_signature().
446 + # Potrzebne w środowisku BUILDA: instalator buduje własne .pag (np. `kernel`)
447 + # lokalnie, nie ma dla nich pliku .asc, a klucza prywatnego repo celowo NIE ma
448 + # na maszynie budującej. Wcześniej ta funkcja jako jedyna ignorowała
449 + # PAG_INSECURE, więc obejście używane przez resztę builda tu nie działało.
450 + if os.environ.get("PAG_INSECURE", "") == "1":
451 + print(" ⚠ PAG_INSECURE=1 – pomijam weryfikację podpisu pakietu lokalnego")
452 + return True
453 + sig_path = next((pkg_path + ext for ext in (".asc", ".sig")
454 + if os.path.isfile(pkg_path + ext)), "")
455 + if not sig_path:
456 + print(f" ❌ Brak podpisu dla pakietu: {pkg_path}")
457 + print(" Wymagany jest plik .pag.asc/.pag.sig z tego samego źródła.")
458 + return False
459 + ok, fingerprint = _gpg_verify_fp(sig_path, pkg_path)
460 + if not ok or not fingerprint:
461 + print(f" ❌ Nieprawidłowy podpis pakietu: {pkg_path}")
462 + return False
463 + expected = _repo_pinned_fp(DEFAULT_REPOS[0])
464 + if not expected:
465 + print(" ❌ Brak przypiętego klucza repo dla lokalnego pakietu.")
466 + print(" Uruchom najpierw: sudo pag sync")
467 + return False
468 + if fingerprint != expected.upper():
469 + print(" ❌ [SECURITY ERROR] Pakiet podpisano innym kluczem repo.")
470 + print(f" Oczekiwany: {expected}")
471 + print(f" Otrzymany: {fingerprint}")
472 + return False
473 + print(f" 🔐 Podpis pakietu OK ({fingerprint})")
474 + return True
475 +
476 +
477 +# =============================================================================
478 +# i18n – WIELOJĘZYCZNOŚĆ
479 +# =============================================================================
480 +
481 +LANG = os.environ.get("LANG", "en_US.UTF-8")[:2] # pl, en, de...
482 +COLOR = os.environ.get("NO_COLOR", "") == "" and sys.stdout.isatty()
483 +
484 +def _c(code: str, text: str) -> str:
485 + """Dodaje kody ANSI jeśli kolor jest włączony."""
486 + if not COLOR:
487 + return text
488 + colors = {
489 + "green": "\033[32m", "red": "\033[31m", "yellow": "\033[33m",
490 + "cyan": "\033[36m", "bold": "\033[1m", "dim": "\033[2m",
491 + "reset": "\033[0m",
492 + }
493 + return f"{colors.get(code,'')}{text}{colors['reset']}"
494 +
495 +T = {
496 + "en": {
497 + "root_required": "pag requires root privileges (sudo).",
498 + "db_locked": "Another pag instance is running.",
499 + "db_lock_hint": "If no other pag process is running, wait a moment and retry.",
500 + "no_index": "Cannot fetch repository indexes. Run 'pag update'.",
501 + "cache_ro": "Repo cache is read-only ({cache}) – using local index (may be outdated).\n Refresh as root: sudo pag sync",
502 + "all_installed": "All packages are already installed.",
503 + "to_install": "To install: {} packages ({:.2f} MB)",
504 + "new": "NEW",
505 + "continue_q": "Continue? [Y/n] ",
506 + "no_tty": "No TTY / stdin closed (EOF) – cancelling.",
507 + "cancelled": "Cancelled.",
508 + "not_found": "not found in repos",
509 + "pkg_not_found": "Package not found: {} (not in any repo)",
510 + "not_found_hint": "Check the spelling or run 'pag search <query>'.",
511 + "downloading": "Downloading",
512 + "download_fail": "download failed",
513 + "gpg_fail": "GPG verification failed",
514 + "sha256_mismatch": "SHA256 mismatch",
515 + "install_failed": "installation failed",
516 + "installed": "Installed {} packages.",
517 + "rollback_restored": "Restored previous state from snapshot.",
518 + "rollback_files": "Rolled back {} files.",
519 + "no_history": "No transaction history.",
520 + "pinned_list": "Pinned packages ({}):",
521 + "no_pinned": "No pinned packages.",
522 + "pinned_to": "pinned to",
523 + "unpinned": "unpinned.",
524 + "not_pinned": "was not pinned.",
525 + "repo_added": "Added repository: {}",
526 + "repo_exists": "Repository already exists: {}",
527 + "updated_done": "Index refresh complete. {} packages cached.",
528 + "indexes_refreshed": "Indexes refreshed.",
529 + "updates_available": "⚠ {} packages have updates – run: pag update",
530 + "upgrading": "Upgrading: {} packages",
531 + "all_up_to_date": "All packages are up to date.",
532 + "removing": "Removing",
533 + "orphans_found": "Orphaned dependencies ({}): {}",
534 + "flatpak_missing": "Flatpak is not installed.",
535 + "flatpak_adding": "Adding Flathub remote...",
536 + "flatpak_searching": "Searching Flathub for '{}'...",
537 + "flatpak_found": "Found {} results:",
538 + "flatpak_not_found": "not found on Flathub",
539 + "flatpak_install_prompt": "Install {}? [Y/n] ",
540 + "flatpak_installing": "Installing {}...",
541 + "flatpak_installed": "Flatpak {} installed.",
542 + "flatpak_removed": "Flatpak {} removed.",
543 + "flatpak_not_installed": "Flatpak {} is not installed.",
544 + "flatpak_info_id": "ID",
545 + "flatpak_info_version": "Version",
546 + "flatpak_info_branch": "Branch",
547 + "flatpak_info_origin": "Origin",
548 + "flatpak_info_size": "Installed size",
549 + "flatpak_info_desc": "Description",
550 + "flatpak_updated": "Flatpaks updated.",
551 + "flatpak_usage": "Usage: pag flatpak <search|install|remove|list|update|info> [args]",
552 + "flatpak_scope": "Installation",
553 + "flatpak_menu_hint": "Installed and verified, but this session may not show it in the menu: Flatpak exports are missing from XDG_DATA_DIRS.",
554 + "flatpak_menu_fix": "Add /var/lib/flatpak/exports/share to XDG_DATA_DIRS (and .../exports/bin to PATH) in your session, then re-login – PaganDE does this in session/pagande-session.",
555 + "key_imported": "Key imported successfully.",
556 + "key_removed": "Key removed: {}",
557 + "no_keys": "No trusted GPG keys.",
558 + "gpg_missing": "GNUPG MISSING – install gnupg and retry",
559 + "ssl_broken": "Python has no working ssl module (HTTPS impossible) – fix the python/openssl packages (e.g. sudo pag install -f python).",
560 + "key_add_failed": "Key import failed (gpg error) – key was NOT added.",
561 + "verify_ok": "All {} files intact.",
562 + "verify_errors": "{} problems found:",
563 + "cache_cleared": "{} files ({:.2f} MB) cleared from cache.",
564 + "deployments_list": "Deployments ({}):",
565 + "no_deployments": "No deployments.",
566 + "active_deployment": "ACTIVE",
567 + "deploy_rollback_ok": "Switched to deployment: {}",
568 + "deploy_rollback_fail": "No previous deployment.",
569 + "deploy_cleanup_ok": "Removed {} old deployments.",
570 + "deploy_cleanup_none": "No deployments to clean (minimum {}).",
571 + "why_explicit": "explicitly installed",
572 + "why_dependency": "dependency of",
573 + "why_not_installed": "not installed",
574 + "rdepends_title": "Reverse dependencies of {} ({}):",
575 + "rdepends_none": "nothing depends on it.",
576 + "autoremove_ok": "Removed {} orphaned packages.",
577 + "autoremove_none": "No orphaned packages.",
578 + "downloaded": "Downloaded {} to cache ({:.2f} MB).",
579 + "provides_mapped": "{} → {} (provides)",
580 + "stats_title": "PAG Statistics",
581 + "stats_packages": "Installed packages",
582 + "stats_files": "Tracked files",
583 + "stats_size": "Total size",
584 + "stats_cache": "Cache size",
585 + "stats_history": "Transactions",
586 + "stats_last_update": "Last update",
587 + # Komunikaty bezpieczeństwa (baza EN; PL w tabeli "pl" jako sec_*_pl)
588 + "sec_downgrade": "Downgrade blocked: {pkg} {new} < {old}",
589 + "sec_suid": "SUID stripped from {path}",
590 + "sec_https": "HTTPS required for repos",
591 + "sec_badname": "Invalid package name: {name}",
592 + "sec_toobig": "Package too large: {size_mb}MB > {max_mb}MB",
593 + "sec_conflict": "File conflict: {path} owned by {owner}",
594 + "sec_audit": "{pkg} installed by {user}",
595 + "sec_locked": "Another pag process is running",
596 + # Konfiguracja (/etc) – zachowanie zmian użytkownika
597 + "conf_pacnew": "Modified config kept; new version saved as {path}",
598 + "conf_pacsave": "Modified config kept as {path}",
599 + # Zależności wirtualne (provides)
600 + "provides_conflict": "Multiple providers for '{name}' ({providers}) – using '{chosen}'",
601 +
602 + # Base baked into the ISO image (pag base / base adopt)
603 + "base_title": "Base from the ISO image",
604 + "base_no_manifest": "This system carries no base manifest (/usr/share/pag/base.json) – nothing to adopt.",
605 + "base_iso_version": "Image version",
606 + "base_total": "Base packages (from image)",
607 + "base_tracked": "Managed by pag",
608 + "base_adoptable": "Adoptable from repo",
609 + "base_unmatched": "No counterpart in repo",
610 + "base_adopt_hint": "Adopt them (image files get replaced by repo packages): sudo pag base adopt",
611 + "base_unmatched_hint": "These stay at the image version (no such package in repo):",
612 + "base_more": "more",
613 + "base_nothing_selected": "None of the given names is on the adopt list.",
614 + "base_all_managed": "Every base package is already managed by pag.",
615 + "base_adopt_plan": "Adopting {} base packages from the repo (~{:.0f} MB):",
616 + "base_dry_run": "Dry run – nothing was installed.",
617 + "base_unmanaged_hint": "{} packages from the ISO image are not managed by pag yet – 'sudo pag base adopt' replaces them with repo packages (only then does 'pag upgrade' update them).",
618 + "base_overwrite": "{} comes from the ISO image – its files will be replaced (backup kept for 'pag rollback').",
619 + "base_reboot_hint": "Base adopted from the repo – reboot before using the new libraries/toolchain.",
620 + "stats_base": "Base (image) managed",
621 + },
622 + "pl": {
623 + "root_required": "pag wymaga uprawnień root (sudo).",
624 + "db_locked": "Inna instancja pag jest uruchomiona.",
625 + "db_lock_hint": "Jeśli żaden inny proces pag nie działa, poczekaj chwilę i spróbuj ponownie.",
626 + "no_index": "Nie można pobrać indeksów repozytoriów. Uruchom 'pag update'.",
627 + "cache_ro": "Cache repozytoriów jest tylko-do-odczytu ({cache}) – używam lokalnego indeksu (może być nieaktualny).\n Odśwież jako root: sudo pag sync",
628 + "all_installed": "Wszystkie pakiety są już zainstalowane.",
629 + "to_install": "Do zainstalowania: {} pakietów ({:.2f} MB)",
630 + "new": "NOWY",
631 + "continue_q": "Kontynuować? [T/n] ",
632 + "no_tty": "Brak terminala (EOF) – anuluję.",
633 + "cancelled": "Anulowano.",
634 + "not_found": "brak w repozytoriach",
635 + "pkg_not_found": "Nie znaleziono pakietu: {} (brak w repozytoriach)",
636 + "not_found_hint": "Sprawdź pisownię lub uruchom 'pag search <fraza>'.",
637 + "downloading": "Pobieranie",
638 + "download_fail": "błąd pobierania",
639 + "gpg_fail": "błąd weryfikacji GPG",
640 + "sha256_mismatch": "niezgodność SHA256",
641 + "install_failed": "błąd instalacji",
642 + "installed": "Zainstalowano {} pakietów.",
643 + "rollback_restored": "Przywrócono poprzedni stan z migawki.",
644 + "rollback_files": "Wycofano {} plików.",
645 + "no_history": "Brak historii transakcji.",
646 + "pinned_list": "Przypięte pakiety ({}):",
647 + "no_pinned": "Brak przypiętych pakietów.",
648 + "pinned_to": "przypięty do",
649 + "unpinned": "odpięty.",
650 + "not_pinned": "nie był przypięty.",
651 + "repo_added": "Dodano repozytorium: {}",
652 + "repo_exists": "Repozytorium już istnieje: {}",
653 + "updated_done": "Odświeżanie zakończone. {} pakietów w cache.",
654 + "indexes_refreshed": "Indeksy odświeżone.",
655 + "updates_available": "⚠ jest {} pakietów do zaktualizowania – wpisz: pag update",
656 + "upgrading": "Aktualizacje: {} pakietów",
657 + "all_up_to_date": "Wszystkie pakiety są aktualne.",
658 + "removing": "Usuwanie",
659 + "orphans_found": "Osierocone zależności ({}): {}",
660 + "flatpak_missing": "Flatpak nie jest zainstalowany.",
661 + "flatpak_adding": "Dodaję zdalne repozytorium Flathub...",
662 + "flatpak_searching": "Szukam '{}' we Flathub...",
663 + "flatpak_found": "Znaleziono {} wyników:",
664 + "flatpak_not_found": "nie znaleziono we Flathub",
665 + "flatpak_install_prompt": "Zainstalować {}? [T/n] ",
666 + "flatpak_installing": "Instalowanie {}...",
667 + "flatpak_installed": "Flatpak {} zainstalowany.",
668 + "flatpak_removed": "Flatpak {} usunięty.",
669 + "flatpak_not_installed": "Flatpak {} nie jest zainstalowany.",
670 + "flatpak_info_id": "ID",
671 + "flatpak_info_version": "Wersja",
672 + "flatpak_info_branch": "Gałąź",
673 + "flatpak_info_origin": "Źródło",
674 + "flatpak_info_size": "Rozmiar",
675 + "flatpak_info_desc": "Opis",
676 + "flatpak_updated": "Flapaki zaktualizowane.",
677 + "flatpak_usage": "Użycie: pag flatpak <search|install|remove|list|update|info> [args]",
678 + "flatpak_scope": "Instalacja",
679 + "flatpak_menu_hint": "Zainstalowano i zweryfikowano, ale sesja może jej nie pokazać w menu: brak eksportów Flatpaka w XDG_DATA_DIRS.",
680 + "flatpak_menu_fix": "Dodaj /var/lib/flatpak/exports/share do XDG_DATA_DIRS (a .../exports/bin do PATH) w sesji i zaloguj się ponownie – PaganDE robi to w session/pagande-session.",
681 + "key_imported": "Klucz zaimportowany pomyślnie.",
682 + "key_removed": "Klucz usunięty: {}",
683 + "no_keys": "Brak zaufanych kluczy GPG.",
684 + "gpg_missing": "BRAK GNUPG – zainstaluj gnupg i spróbuj ponownie",
685 + "ssl_broken": "Python bez działającego modułu ssl (HTTPS niemożliwe) – napraw pakiety python/openssl (np. sudo pag install -f python).",
686 + "key_add_failed": "Import klucza nie powiódł się (błąd gpg) – klucz NIE został dodany.",
687 + "verify_ok": "Wszystkie {} plików sprawne.",
688 + "verify_errors": "Znaleziono {} problemów:",
689 + "cache_cleared": "{} plików ({:.2f} MB) usuniętych z cache.",
690 + "deployments_list": "Deploymenty ({}):",
691 + "no_deployments": "Brak deploymentów.",
692 + "active_deployment": "AKTYWNY",
693 + "deploy_rollback_ok": "Przełączono na deployment: {}",
694 + "deploy_rollback_fail": "Brak poprzedniego deploymentu.",
695 + "deploy_cleanup_ok": "Usunięto {} starych deploymentów.",
696 + "deploy_cleanup_none": "Nie ma deploymentów do wyczyszczenia (minimum {}).",
697 + "why_explicit": "zainstalowany jawnie",
698 + "why_dependency": "zależność od",
699 + "why_not_installed": "niezainstalowany",
700 + "rdepends_title": "Odwrotne zależności {} ({}):",
701 + "rdepends_none": "nic od niego nie zależy.",
702 + "autoremove_ok": "Usunięto {} osieroconych pakietów.",
703 + "autoremove_none": "Brak osieroconych pakietów.",
704 + "downloaded": "Pobrano {} do cache ({:.2f} MB).",
705 + "sec_downgrade": "Downgrade blocked: {pkg} {new} < {old}",
706 + "sec_suid": "SUID stripped from {path}",
707 + "sec_https": "HTTPS required for repos",
708 + "sec_badname": "Invalid package name: {name}",
709 + "sec_toobig": "Package too large: {size_mb}MB > {max_mb}MB",
710 + "sec_conflict": "File conflict: {path} owned by {owner}",
711 + "sec_audit": "{pkg} installed by {user}",
712 + "sec_locked": "Another pag process is running",
713 + "sec_downgrade_pl": "Blokada downgrade: {pkg} {new} < {old}",
714 + "sec_suid_pl": "SUID usuniety z {path}",
715 + "sec_https_pl": "Repozytorium wymaga HTTPS",
716 + "sec_badname_pl": "Nieprawidlowa nazwa pakietu: {name}",
717 + "sec_toobig_pl": "Paczka za duza: {size_mb}MB > {max_mb}MB",
718 + "sec_conflict_pl": "Konflikt plikow: {path} nalezy do {owner}",
719 + "sec_audit_pl": "{pkg} zainstalowany przez {user}",
720 + "sec_locked_pl": "Inny proces pag juz dziala",
721 +
722 + "provides_mapped": "{} → {} (provides)",
723 + "stats_title": "Statystyki PAG",
724 + "stats_packages": "Zainstalowane pakiety",
725 + "stats_files": "Śledzone pliki",
726 + "stats_size": "Całkowity rozmiar",
727 + "stats_cache": "Rozmiar cache",
728 + "stats_history": "Transakcje",
729 + "stats_last_update": "Ostatnia aktualizacja",
730 + "conf_pacnew": "Zmieniony plik konfiguracyjny zachowany; nowa wersja: {path}",
731 + "conf_pacsave": "Zmieniony plik konfiguracyjny zachowany jako {path}",
732 + "provides_conflict": "Wielu dostawców dla '{name}' ({providers}) – używam '{chosen}'",
733 +
734 + # Baza wypalona w obrazie ISO (pag base / base adopt)
735 + "base_title": "Baza z obrazu ISO",
736 + "base_no_manifest": "Ten system nie ma manifestu bazy (/usr/share/pag/base.json) – nie ma czego adoptować.",
737 + "base_iso_version": "Wersja obrazu",
738 + "base_total": "Pakiety bazy (z obrazu)",
739 + "base_tracked": "Zarządzane przez pag",
740 + "base_adoptable": "Do adoptowania z repo",
741 + "base_unmatched": "Bez odpowiednika w repo",
742 + "base_adopt_hint": "Adoptuj (pliki z obrazu zostaną zastąpione pakietami z repo): sudo pag base adopt",
743 + "base_unmatched_hint": "Te zostaną w wersji z obrazu (brak takiego pakietu w repo):",
744 + "base_more": "więcej",
745 + "base_nothing_selected": "Żadna z podanych nazw nie jest na liście do adoptowania.",
746 + "base_all_managed": "Wszystkie pakiety bazy są już zarządzane przez pag.",
747 + "base_adopt_plan": "Adoptowanie {} pakietów bazy z repo (~{:.0f} MB):",
748 + "base_dry_run": "Próba na sucho – nic nie zainstalowano.",
749 + "base_unmanaged_hint": "{} pakietów z obrazu ISO nie jest jeszcze zarządzanych przez pag – 'sudo pag base adopt' zamieni je na pakiety z repo (dopiero wtedy 'pag upgrade' je aktualizuje).",
750 + "base_overwrite": "{} pochodzi z obrazu ISO – pliki zostaną zastąpione (kopia zapasowa dla 'pag rollback').",
751 + "base_reboot_hint": "Baza zaadoptowana z repo – zrestartuj system, zanim zaczniesz używać nowych bibliotek/narzędzi.",
752 + "stats_base": "Baza (obraz) zarządzana",
753 + },
754 +}
755 +
756 +# ── Tłumaczenia z PLIKÓW (nadpisują/rozszerzają wbudowane PL/EN) ─────────────
757 +# Kolejność: PAG_LANG_DIR (env) → /etc/pag/lang → /usr/share/pag/lang →
758 +# ./pag-lang obok binarki (dev). Brak plików NIE jest błędem – zostaje
759 +# wbudowany słownik T (fallback), więc pag zawsze działa.
760 +# Przykład pliku (pag-lang/pl.json): {"app_title": "...", "usage": "..."}.
761 +def _load_lang_files() -> None:
762 + # PAG_LANG_NO_FILES=1 → pomiń pliki (używane przy eksporcie --lang-extract,
763 + # żeby wyeksportować CZYSTE wbudowane słowniki, bez starych nadpisań).
764 + if os.environ.get("PAG_LANG_NO_FILES") == "1":
765 + return
766 + dirs = []
767 + _env = os.environ.get("PAG_LANG_DIR")
768 + if _env:
769 + dirs.append(_env)
770 + # __file__ bywa niedostępne, gdy moduł jest exec/frozen (np. harness
771 + # instalacyjny) – liczymy wtedy od ścieżki programu, zamiast wywalać
772 + # NameError przy samym imporcie.
773 + _self = globals().get("__file__") or sys.argv[0] or "pag"
774 + dirs += ["/etc/pag/lang", "/usr/share/pag/lang",
775 + os.path.join(os.path.dirname(os.path.abspath(_self)), "pag-lang")]
776 + for _d in dirs:
777 + for _code in list(T.keys()) + ["pl", "en", "de"]:
778 + _p = os.path.join(_d, f"{_code}.json")
779 + try:
780 + with open(_p, "r", encoding="utf-8") as _fh:
781 + _data = json.load(_fh)
782 + if isinstance(_data, dict):
783 + # Merge (nie replace): klucze nieobecne w pliku zachowują
784 + # wbudowane tłumaczenie. Puste wartości pomijamy, żeby
785 + # niekompletny/uszkodzony plik nie wyczyścił komunikatu.
786 + _clean = {str(k): str(v) for k, v in _data.items()
787 + if str(v).strip()}
788 + T.setdefault(_code, {}).update(_clean)
789 + except (OSError, ValueError):
790 + continue
791 +
792 +
793 +_load_lang_files()
794 +
795 +def _(key: str, *args, **kwargs) -> str:
796 + """Tłumaczy klucz i formatuje argumenty.
797 +
798 + Dla LANG=pl preferuje wariant „<key>_pl” (np. komunikaty bezpieczeństwa
799 + mają krótkie wersje PL obok bazy EN), potem zwykły klucz, potem EN/klicz.
800 + """
801 + if LANG == "pl":
802 + _pl = T.get("pl", {})
803 + msg = _pl.get(key + "_pl") or _pl.get(key) or T["en"].get(key, key)
804 + else:
805 + msg = T.get(LANG, T["en"]).get(key, T["en"].get(key, key))
806 + if args or kwargs:
807 + return msg.format(*args, **kwargs)
808 + return msg
809 +
810 +
811 +def _ask_confirm() -> bool:
812 + """Pytanie potwierdzające (T/n). PAG_YES=1 → zawsze tak.
813 +
814 + EOF/brak terminala (stdin zamknięty, np. ssh bez TTY, cron, subprocess
815 + panelu webowego) → NIE – anuluj, nie wykonuj operacji bez potwierdzenia
816 + (inaczej input() rzuca EOFError i pag pada tracebackiem).
817 + Enter → tak (domyślne Y/n).
818 + """
819 + if os.environ.get("PAG_YES", "") == "1":
820 + print(_("continue_q") + " t (--yes)")
821 + return True
822 + try:
823 + ans = input(_("continue_q")).strip().lower()
824 + except (EOFError, KeyboardInterrupt):
825 + print(f"\n ⚠ {_('no_tty')}")
826 + return False
827 + return not ans or ans in ("t", "y")
828 +
829 +
830 +# =============================================================================
831 +# ŚCIEŻKI
832 +# =============================================================================
833 +PAG_ROOT = os.environ.get("PAG_ROOT", "/")
834 +PAG_DB = "/var/lib/pag"
835 +PAG_CACHE = "/var/cache/pag"
836 +PAG_CONF = "/etc/pag"
837 +REPO_CACHE = "/var/cache/pag/repos"
838 +REPOS_CONF = "/etc/pag/repos.conf"
839 +REPOS_DIR = PAG_CONF + "/repos" # drop-in: /etc/pag/repos/<nazwa>.conf
840 +INSTALLED_DB = "/var/lib/pag/installed.json"
841 +FILES_DB_SQL = "/var/lib/pag/files.db" # SQLite!
842 +WORLD_FILE = "/var/lib/pag/world"
843 +PINNED_FILE = "/var/lib/pag/pinned.json"
844 +HISTORY_FILE = "/var/lib/pag/history.json"
845 +LOCK_FILE = "/var/lib/pag/pag.lock"
846 +STAGING_DIR = "/.pag_staging" # na tej samej partycji co / (unikamy EXDEV)
847 +PKG_EXT = ".pag"
848 +REPO_CACHE_TTL = 3600
849 +MAX_PKG_SIZE = 2 * 1024 * 1024 * 1024 # 2 GB – maksymalny rozmiar paczki
850 +BASE_MANIFEST = "/usr/share/pag/base.json" # baza z obrazu ISO (pag base/adopt)
851 +
852 +# ── UPRZYWILEJOWANE PLIKI ────────────────────────────────────────────────────
853 +# Domyślnie pag zdejmuje bit SUID i wymusza właściciela root:root. Niektóre
854 +# programy MUSZĄ jednak zachować setuid/setgid albo grupę inną niż root
855 +# (/usr/bin/sudo, /usr/bin/passwd, /usr/bin/unix_chkpwd,
856 +# /usr/lib/dbus-daemon-launch-helper). Bez tego tracą możliwość działania
857 +# po aktualizacji przez pag (np. użytkownik nie zmieni hasła).
858 +#
859 +# Bezpieczeństwo: zawartość pakietu jest uwierzytelniona (podpis GPG repo +
860 +# przypięty fingerprint + SHA256 całego pakietu), więc metadane w nim są
861 +# zaufane tak samo jak same pliki. Zachowujemy uprawnienia WYŁĄCZNIE dla
862 +# ścieżek z tej listy (albo z pola `privileged:` receptury, które pagbuild
863 +# zapisuje w metadata.json).
864 +PRIVILEGED_PATHS = frozenset({
865 + "/usr/bin/cdda2wav", "/usr/bin/cdrecord",
866 + "/usr/bin/chage", "/usr/bin/expiry",
867 + "/usr/bin/fcrondyn", "/usr/bin/fcronsighup", "/usr/bin/fcrontab",
868 + "/usr/bin/firejail", "/usr/bin/fping",
869 + "/usr/bin/fusermount", "/usr/bin/fusermount3",
870 + "/usr/bin/gpasswd", "/usr/bin/ksu", "/usr/bin/lockfile",
871 + "/usr/bin/mount", "/usr/bin/mount.nfs",
872 + "/usr/bin/newgidmap", "/usr/bin/newuidmap",
873 + "/usr/bin/passwd", "/usr/bin/ping", "/usr/bin/ping6",
874 + "/usr/bin/procmail", "/usr/bin/readcd", "/usr/bin/rscsi",
875 + "/usr/bin/screen", "/usr/bin/screen-5.0.2",
876 + "/usr/bin/sg", "/usr/bin/su", "/usr/bin/sudo", "/usr/bin/traceroute",
877 + "/usr/bin/umount", "/usr/bin/unix_chkpwd", "/usr/bin/wall",
878 + "/usr/lib/dbus-daemon-launch-helper",
879 + "/usr/lib/httpd/suexec",
880 + "/usr/lib/utempter/utempter",
881 + "/usr/lib/xscreensaver/xscreensaver-auth",
882 + "/usr/libexec/libgtop_server2",
883 + "/usr/libexec/qemu-bridge-helper",
884 + "/usr/libexec/ssh-keysign",
885 + "/usr/libexec/xf86-video-intel-backlight-helper",
886 + "/opt/google/chrome/chrome-sandbox",
887 + "/opt/gitkraken/chrome-sandbox",
888 + "/opt/VirtualBox/VBoxHeadless", "/opt/VirtualBox/VBoxNetAdpCtl",
889 + "/opt/VirtualBox/VBoxNetDHCP", "/opt/VirtualBox/VBoxVolInfo",
890 + "/opt/VirtualBox/VirtualBoxVM",
891 +})
892 +ALLOWED_PKG_RE = re.compile(r'^[a-zA-Z0-9][a-zA-Z0-9._+@-]*$')
893 +
894 +# Bezpieczeństwo / audyt
895 +AUDIT_LOG = "/var/log/pag/audit.log" # dziennik operacji krytycznych (hooki, self-update)
896 +TRUST_DB = "/etc/pag/trusted.json" # mapa repo_url → fingerprint klucza podpisującego
897 +HOOK_API_VERSION = "1" # wersjonowane API hooków (env PKG_HOOK_API)
898 +
899 +# =============================================================================
900 +# IMMUTABLE OS – DEPLOYMENTY
901 +# =============================================================================
902 +# Model: zamiast mutować /, każda operacja tworzy NOWY deployment.
903 +# /var, /etc, /home są współdzielone między deploymentami.
904 +#
905 +# STRUKTURA:
906 +# /.deployments/
907 +# active → 20260723T120000 (symlink do aktywnego)
908 +# 20260723T120000/
909 +# usr/ bin/ lib/ lib64/ ... (pełny system)
910 +# var → /var (symlink do współdzielonego)
911 +# etc → /etc
912 +# home → /home
913 +# ...
914 +#
915 +# Jak to działa:
916 +# 1. pag install → kopiuje active → nowy deployment + nakłada zmiany → switch symlinka
917 +# 2. pag remove → kopiuje active → nowy deployment - usuwa pliki → switch symlinka
918 +# 3. pag deploy-rollback → przełącza active symlink na poprzedni deployment
919 +# 4. Przy starcie systemu: initrd montuje /.deployments/active jako /
920 +# =============================================================================
921 +
922 +DEPLOYMENTS_DIR = "/.deployments"
923 +ACTIVE_LINK = "/.deployments/active"
924 +DEPLOYMENTS_DB = "/var/lib/pag/deployments.json"
925 +
926 +# Ścieżki współdzielone – NIE wchodzą do deploymentu (są symlinkami do /...)
927 +SHARED_PATHS = {
928 + "/var", "/etc", "/home", "/root", "/tmp", "/run",
929 + "/dev", "/proc", "/sys", "/mnt", "/media", "/srv",
930 + # /boot współdzielone: jądro + initramfs są wspólne dla wszystkich
931 + # deploymentów (inaczej każdy trzyma własną ~50-100 MB kopię). GRUB
932 + # wskazuje na /.deployments/<id>/boot → symlink do /boot.
933 + "/boot",
934 + "/.deployments", "/.pag_staging",
935 +}
936 +
937 +def _is_shared_path(rel: str) -> bool:
938 + """Sprawdza czy ścieżka należy do katalogów współdzielonych (poza deploymentem)."""
939 + for sp in SHARED_PATHS:
940 + if rel == sp or rel.startswith(sp + "/"):
941 + return True
942 + return False
943 +
944 +def _is_config_path(rel: str) -> bool:
945 + """Czy ścieżka to plik konfiguracyjny (/etc/...)?
946 +
947 + Dla takich plików stosujemy .pacnew/.pacsave (zachowanie zmian użytkownika)
948 + zamiast bezwarunkowego nadpisania/usunięcia."""
949 + p = rel.lstrip("/")
950 + return p == "etc" or p.startswith("etc/")
951 +
952 +# Wrażliwa konfiguracja auth/systemowa – NIGDY nie nadpisujemy jej po cichu.
953 +# Nadpisanie /etc/pam.d/system-* przez pakiet (np. shadow) potrafi zablokować
954 +# logowanie/sudo („account validation failure”); dla tych ścieżek zawsze robimy
955 +# .pacnew, gdy treść na dysku różni się od tej z pakietu.
956 +_SENSITIVE_CONFIG_RE = re.compile(
957 + r'^(pam\.d/|security/|sudoers$|sudoers\.d/|shadow$|gshadow$|passwd$|group$|'
958 + r'login\.defs$|nsswitch\.conf$|default/useradd$)')
959 +
960 +def _is_sensitive_config(rel: str) -> bool:
961 + """Czy rel to wrażliwy plik /etc (PAM, sudoers, shadow, login.defs…)?"""
962 + p = rel.lstrip("/")
963 + if not p.startswith("etc/"):
964 + return False
965 + return bool(_SENSITIVE_CONFIG_RE.match(p[4:]))
966 +
967 +def _get_deployment_root() -> str:
968 + """Zwraca ścieżkę do aktywnego deploymentu, lub PAG_ROOT jeśli tryb niemutowalny wyłączony."""
969 + if os.environ.get("PAG_IMMUTABLE", "") in ("0", "no", "false", ""):
970 + return PAG_ROOT
971 + if os.path.islink(ACTIVE_LINK):
972 + return os.readlink(ACTIVE_LINK)
973 + if os.path.isdir(ACTIVE_LINK):
974 + return ACTIVE_LINK
975 + # Brak deploymentów – użyj /
976 + return PAG_ROOT
977 +
978 +def _load_deployments() -> List[dict]:
979 + """Wczytuje historię deploymentów."""
980 + if not os.path.exists(DEPLOYMENTS_DB):
981 + return []
982 + try:
983 + return json.load(open(DEPLOYMENTS_DB))
984 + except Exception:
985 + return []
986 +
987 +def _save_deployments(deployments: List[dict]):
988 + os.makedirs(os.path.dirname(DEPLOYMENTS_DB), exist_ok=True)
989 + json.dump(deployments, open(DEPLOYMENTS_DB, "w"), indent=2)
990 +
991 +def _create_deployment(pkg_names: List[str], action: str) -> Tuple[str, str]:
992 + """
993 + Tworzy nowy deployment przez skopiowanie aktywnego (CoW) i zwraca jego ścieżkę.
994 + Zwraca (deployment_dir, deployment_id).
995 + """
996 + deploy_id = datetime.now().strftime("%Y%m%dT%H%M%S")
997 + deploy_dir = os.path.join(DEPLOYMENTS_DIR, deploy_id)
998 + os.makedirs(DEPLOYMENTS_DIR, exist_ok=True)
999 +
1000 + active = _get_deployment_root()
1001 +
1002 + if os.path.isdir(active) and active != PAG_ROOT:
1003 + # Trójstopniowa strategia kopiowania deploymentu:
1004 + # 1. reflink (CoW – btrfs, xfs) → 0 MB kopiowane
1005 + # 2. hardlink (linki twarde) → 0 MB kopiowane, tylko inody
1006 + # 3. zwykłe cp (ostateczność) → pełna kopia
1007 + print(f" ⚡ Kopiowanie aktywnego deploymentu...")
1008 + copied = False
1009 + for method, cmd, label in [
1010 + ("reflink", ["cp", "--reflink=auto", "-a", active + "/.", deploy_dir + "/"], "CoW (reflink)"),
1011 + ("hardlink", ["cp", "-al", active + "/.", deploy_dir + "/"], "hardlinki"),
1012 + ("copy", ["cp", "-a", active + "/.", deploy_dir + "/"], "pełna kopia"),
1013 + ]:
1014 + try:
1015 + subprocess.run(cmd, check=True, timeout=600, capture_output=True)
1016 + print(f" ✅ Deployment: {deploy_id} ({label})")
1017 + copied = True
1018 + break
1019 + except subprocess.CalledProcessError:
1020 + if method == "copy":
1021 + raise # ostatnia deska – niech leci wyjątek
1022 + continue
1023 + if not copied:
1024 + raise RuntimeError("Nie udało się skopiować deploymentu żadną metodą")
1025 + else:
1026 + # Pierwszy deployment – tylko katalogi szkieletowe
1027 + # /boot celowo POMINIĘTE – jest współdzielone (SHARED_PATHS); poniższa
1028 + # pętla utworzy w deploymencie symlink boot → /boot.
1029 + for d in ["/usr", "/lib", "/lib64", "/bin", "/sbin", "/opt"]:
1030 + if os.path.isdir(d):
1031 + dest = os.path.join(deploy_dir, d.lstrip("/"))
1032 + os.makedirs(dest, exist_ok=True)
1033 + print(f" ✅ Pierwszy deployment: {deploy_id}")
1034 +
1035 + # Utwórz symlinki do współdzielonych katalogów
1036 + for sp in SHARED_PATHS:
1037 + link_dst = os.path.join(deploy_dir, sp.lstrip("/"))
1038 + if not os.path.lexists(link_dst) and os.path.isdir(sp):
1039 + os.symlink(sp, link_dst)
1040 +
1041 + # Zapisz w bazie deploymentów
1042 + deployments = _load_deployments()
1043 + deployments.append({
1044 + "id": deploy_id,
1045 + "action": action,
1046 + "packages": pkg_names,
1047 + "timestamp": datetime.now().isoformat(),
1048 + "active": True,
1049 + })
1050 + # Oznacz poprzednie jako nieaktywne
1051 + for d in deployments[:-1]:
1052 + d["active"] = False
1053 + _save_deployments(deployments)
1054 +
1055 + return deploy_dir, deploy_id
1056 +
1057 +def _switch_deployment(deploy_dir: str) -> bool:
1058 + """Atomowo przełącza aktywny deployment przez podmianę symlinka."""
1059 + tmp_link = ACTIVE_LINK + ".new"
1060 + if os.path.lexists(tmp_link):
1061 + os.remove(tmp_link)
1062 + os.symlink(deploy_dir, tmp_link)
1063 + os.rename(tmp_link, ACTIVE_LINK) # atomowe na tym samym FS
1064 + return True
1065 +
1066 +DEFAULT_REPOS = [
1067 + "https://repo.paganlinux.eu/stable/",
1068 +]
1069 +
1070 +# =============================================================================
1071 +# INICJALIZACJA
1072 +# =============================================================================
1073 +
1074 +def ensure_dirs():
1075 + for d in [PAG_DB, PAG_CACHE, PAG_CONF, REPO_CACHE, REPOS_DIR, STAGING_DIR, DEPLOYMENTS_DIR]:
1076 + os.makedirs(d, exist_ok=True)
1077 + for f, default in [
1078 + (REPOS_CONF, "\n".join(DEFAULT_REPOS) + "\n"),
1079 + (INSTALLED_DB, "{}"),
1080 + (PINNED_FILE, "{}"),
1081 + (HISTORY_FILE, "[]"),
1082 + ]:
1083 + if not os.path.exists(f):
1084 + with open(f, "w") as fh: fh.write(default)
1085 + if not os.path.exists(WORLD_FILE):
1086 + Path(WORLD_FILE).touch()
1087 + if not os.path.exists(GPG_HOME):
1088 + os.makedirs(GPG_HOME, exist_ok=True)
1089 + os.chmod(GPG_HOME, 0o700)
1090 + _gpg_run("--list-keys", capture_output=True)
1091 + # Inicjalizuj SQLite
1092 + _db_init()
1093 + # Wyczyść staging po poprzednim przerwanym buildzie/instalacji
1094 + if os.path.isdir(STAGING_DIR):
1095 + for entry in os.listdir(STAGING_DIR):
1096 + if entry == "backups":
1097 + continue # backupy starych wersji – potrzebne do `pag rollback`
1098 + path = os.path.join(STAGING_DIR, entry)
1099 + try:
1100 + if os.path.isfile(path) or os.path.islink(path):
1101 + os.unlink(path)
1102 + elif os.path.isdir(path):
1103 + shutil.rmtree(path, ignore_errors=True)
1104 + except OSError:
1105 + pass
1106 +
1107 +# =============================================================================
1108 +# SQLITE – BAZA PLIKÓW (poprawne zarządzanie połączeniami)
1109 +# =============================================================================
1110 +
1111 +from contextlib import contextmanager
1112 +
1113 +@contextmanager
1114 +def _db_session(readonly: Optional[bool] = None):
1115 + """Context manager – gwarantuje zamknięcie połączenia.
1116 +
1117 + Gdy katalog bazy nie jest zapisywalny (np. komenda read-only uruchomiona
1118 + jako zwykły user), otwieramy połączenie w trybie read-only. Inaczej
1119 + `PRAGMA journal_mode=WAL` próbuje pisać i kończy się błędem
1120 + „attempt to write a readonly database” zamiast zwrócić wynik.
1121 + """
1122 + if readonly is None:
1123 + readonly = not os.access(os.path.dirname(FILES_DB_SQL) or ".", os.W_OK)
1124 + if readonly:
1125 + # Katalog bazy nie jest zapisywalny (np. komenda read-only uruchomiona
1126 + # jako zwykły user). Baza jest w trybie WAL, więc SQLite przy `mode=ro`
1127 + # próbuje utworzyć plik `-shm` w katalogu – bez prawa zapisu kończy się
1128 + # to błędem „attempt to write a readonly database” nawet przy SELECT.
1129 + # Dlatego próbujemy zwykłego `mode=ro`, a gdy zawiedzie, otwieramy z
1130 + # `immutable=1` (SQLite pomija wtedy WAL/SHM i czyta ostatni
1131 + # checkpoint). Przy równoległym zapisie roota odczyt może być chwilowo
1132 + # nieaktualny – dla komend diagnostycznych (files/list/verify) to OK.
1133 + conn = sqlite3.connect(f"file:{FILES_DB_SQL}?mode=ro", uri=True, timeout=15)
1134 + try:
1135 + conn.execute("SELECT 1 FROM sqlite_master LIMIT 1")
1136 + except sqlite3.OperationalError:
1137 + conn.close()
1138 + conn = sqlite3.connect(
1139 + f"file:{FILES_DB_SQL}?mode=ro&immutable=1", uri=True, timeout=15)
1140 + else:
1141 + conn = sqlite3.connect(FILES_DB_SQL, timeout=15)
1142 + conn.execute("PRAGMA journal_mode=WAL")
1143 + conn.execute("PRAGMA synchronous=NORMAL")
1144 + conn.execute("PRAGMA foreign_keys=ON")
1145 + conn.execute("PRAGMA busy_timeout=15000")
1146 + conn.row_factory = sqlite3.Row
1147 + try:
1148 + yield conn
1149 + if not readonly:
1150 + conn.commit()
1151 + except Exception:
1152 + if not readonly:
1153 + conn.rollback()
1154 + raise
1155 + finally:
1156 + conn.close()
1157 +
1158 +
1159 +def _db_init():
1160 + """Tworzy tabele SQLite jeśli nie istnieją."""
1161 + with _db_session() as db:
1162 + db.execute("""
1163 + CREATE TABLE IF NOT EXISTS files (
1164 + id INTEGER PRIMARY KEY AUTOINCREMENT,
1165 + path TEXT NOT NULL,
1166 + package TEXT NOT NULL,
1167 + sha256 TEXT,
1168 + size INTEGER,
1169 + is_symlink INTEGER DEFAULT 0,
1170 + symlink_target TEXT,
1171 + UNIQUE(path, package)
1172 + )
1173 + """)
1174 + db.execute("CREATE INDEX IF NOT EXISTS idx_files_path ON files(path)")
1175 + db.execute("CREATE INDEX IF NOT EXISTS idx_files_pkg ON files(package)")
1176 + db.execute("""
1177 + CREATE TABLE IF NOT EXISTS file_checksums (
1178 + path TEXT PRIMARY KEY,
1179 + sha256 TEXT NOT NULL,
1180 + installed_at TEXT
1181 + )
1182 + """)
1183 + db.commit()
1184 +
1185 +def _db_record_files(pkg_name: str, files: List[dict]):
1186 + """Zapisuje pliki do SQLite (obsługuje symlinki)."""
1187 + with _db_session() as db:
1188 + # Jawna transakcja – atomowość obu zapisów i szybsze wykrycie blokady
1189 + try:
1190 + db.execute("BEGIN IMMEDIATE")
1191 + except sqlite3.OperationalError:
1192 + pass # transakcja już otwarta (implicit)
1193 + db.executemany(
1194 + "INSERT OR REPLACE INTO files (path, package, sha256, size, is_symlink, symlink_target) "
1195 + "VALUES (?,?,?,?,?,?)",
1196 + [(f["path"], pkg_name, f.get("sha256",""), f.get("size",0),
1197 + f.get("is_symlink", 0), f.get("symlink_target", ""))
1198 + for f in files]
1199 + )
1200 + db.executemany(
1201 + "INSERT OR REPLACE INTO file_checksums (path, sha256, installed_at) VALUES (?,?,?)",
1202 + [(f["path"], f.get("sha256",""), datetime.now().isoformat())
1203 + for f in files if f.get("sha256")]
1204 + )
1205 +
1206 +def _db_get_package_files(pkg_name: str) -> List[str]:
1207 + with _db_session() as db:
1208 + return [r["path"] for r in db.execute(
1209 + "SELECT DISTINCT path FROM files WHERE package=?", (pkg_name,)
1210 + )]
1211 +
1212 +def _db_get_file_owners(filepath: str) -> List[str]:
1213 + """Zwraca listę pakietów będących właścicielami pliku."""
1214 + with _db_session() as db:
1215 + return [r["package"] for r in db.execute(
1216 + "SELECT package FROM files WHERE path=?", (filepath,)
1217 + )]
1218 +
1219 +def _db_remove_package_files(pkg_name: str):
1220 + with _db_session() as db:
1221 + db.execute("DELETE FROM files WHERE package=?", (pkg_name,))
1222 + db.commit()
1223 +
1224 +def _db_get_all_file_checksums() -> Dict[str, str]:
1225 + with _db_session() as db:
1226 + return {r["path"]: r["sha256"] for r in db.execute("SELECT path, sha256 FROM file_checksums")}
1227 +
1228 +def _db_get_package_checksums(pkg_name: str) -> Dict[str, str]:
1229 + """Sumy SHA256 zapisane dla plików należących do pakietu.
1230 +
1231 + Używane do wykrycia, czy użytkownik zmodyfikował plik konfiguracyjny
1232 + (porównanie z sumą z chwili instalacji) – serce mechanizmu .pacnew/.pacsave.
1233 + """
1234 + with _db_session() as db:
1235 + return {r["path"]: r["sha256"] for r in db.execute(
1236 + "SELECT fc.path AS path, fc.sha256 AS sha256 FROM file_checksums fc "
1237 + "JOIN files f ON f.path = fc.path WHERE f.package=?", (pkg_name,))}
1238 +
1239 +
1240 +def _db_count_files() -> int:
1241 + with _db_session() as db:
1242 + return db.execute("SELECT COUNT(*) FROM files").fetchone()[0]
1243 +
1244 +# =============================================================================
1245 +# BLOKADA
1246 +# =============================================================================
1247 +
1248 +class DatabaseLock:
1249 + """Blokada plikowa (flock) – jądro zwalnia ją AUTOMATYCZNIE, gdy proces
1250 + ginie (kill -9, twardy reset). Stary PID-file miał race condition: po
1251 + śmierci pag PID mógł zostać przydzielony obcemu procesowi (PID reuse)
1252 + i pag odmawiał działania na zawsze („baza zablokowana”).
1253 + """
1254 + def __init__(self):
1255 + self._f = None
1256 + def __enter__(self):
1257 + os.makedirs(os.path.dirname(LOCK_FILE), exist_ok=True)
1258 + self._f = open(LOCK_FILE, "w")
1259 + try:
1260 + # LOCK_NB: rzuca wyjątek zamiast czekać w nieskończoność
1261 + fcntl.flock(self._f, fcntl.LOCK_EX | fcntl.LOCK_NB)
1262 + except BlockingIOError:
1263 + print(f"❌ {_('db_locked')}", file=sys.stderr)
1264 + print(f" {_('db_lock_hint', LOCK_FILE)}", file=sys.stderr)
1265 + sys.exit(1)
1266 + self._f.write(str(os.getpid()))
1267 + self._f.flush()
1268 + return self
1269 + def __exit__(self, *args):
1270 + if self._f:
1271 + try:
1272 + fcntl.flock(self._f, fcntl.LOCK_UN)
1273 + except OSError:
1274 + pass
1275 + self._f.close()
1276 + self._f = None
1277 + # Uwaga: NIE usuwamy pliku blokady. Stały plik + flock na inode to jedyny
1278 + # bezpieczny wzorzec – os.remove(), gdy inny proces trzyma blokadę na starym
1279 + # inode, otwiera wyścig (nowy proces blokowałby nowo utworzony inode).
1280 +
1281 +
1282 +class SelfUpdateLock:
1283 + """Blokada podmiany binarki pag podczas self-update.
1284 +
1285 + Niezależna od DatabaseLock (inny plik) – cmd_self_update może zostać
1286 + wywołane poza globalną blokadą (np. z zewnętrznego skryptu), a dwie
1287 + równoległe aktualizacje pisałyby do tego samego `dst.new`; `os.replace`
1288 + mógłby wtedy podmienić plik w trakcie wykonywania (uszkodzony pag).
1289 + """
1290 + def __init__(self):
1291 + self._f = None
1292 +
1293 + def __enter__(self):
1294 + lock_path = LOCK_FILE + ".self-update"
1295 + os.makedirs(os.path.dirname(lock_path), exist_ok=True)
1296 + self._f = open(lock_path, "w")
1297 + try:
1298 + fcntl.flock(self._f, fcntl.LOCK_EX | fcntl.LOCK_NB)
1299 + except BlockingIOError:
1300 + self._f.close()
1301 + self._f = None
1302 + print("❌ Inna aktualizacja pag jest w toku – spróbuj ponownie później.",
1303 + file=sys.stderr)
1304 + sys.exit(1)
1305 + self._f.write(str(os.getpid()))
1306 + self._f.flush()
1307 + return self
1308 +
1309 + def __exit__(self, *args):
1310 + if self._f:
1311 + try:
1312 + fcntl.flock(self._f, fcntl.LOCK_UN)
1313 + except OSError:
1314 + pass
1315 + self._f.close()
1316 + self._f = None
1317 +
1318 +# =============================================================================
1319 +# POMOCNICZE
1320 +# =============================================================================
1321 +
1322 +
1323 +_ALLOWED_PREFIXES = ("/usr/", "/etc/", "/var/", "/opt/",
1324 + "/boot/", "/lib/", # kernel: vmlinuz/System.map + moduły (usrmerge: lib→usr/lib)
1325 + # Pliki wewnętrzne paczki .pkg.tar.xz
1326 + "metadata.json", "data.tar.xz", "hooks/",
1327 + "sums.json")
1328 +
1329 +def _check_path_safety(name: str) -> bool:
1330 + # Normalizuj – usuń leading ./
1331 + if name.startswith("./"):
1332 + name = name[2:]
1333 + if name in (".", ""):
1334 + return True
1335 + # Porównuj z prefiksami BEZ wiodącego '/', by zarówno "/usr/bin/ls", jak i
1336 + # wewnętrzne pliki pakietu ("hooks/pre-install", "data.tar.xz") przechodziły.
1337 + norm = name.lstrip("/")
1338 + for prefix in _ALLOWED_PREFIXES:
1339 + p = prefix.lstrip("/").rstrip("/")
1340 + if norm == p or norm.startswith(p + "/"):
1341 + return True
1342 + return False
1343 +
1344 +
1345 +def _validate_pkg_name(name):
1346 + return bool(ALLOWED_PKG_RE.match(name))
1347 +
1348 +
1349 +
1350 +def _audit(msg):
1351 + from datetime import datetime, timezone
1352 + os.makedirs(os.path.dirname(AUDIT_LOG), exist_ok=True)
1353 + with open(AUDIT_LOG, "a") as f:
1354 + f.write(datetime.now(timezone.utc).isoformat() + " " + msg + "\n")
1355 +
1356 +def _strip_suid(path):
1357 + try:
1358 + st = os.stat(path)
1359 + if st.st_mode & 0o4000:
1360 + os.chmod(path, st.st_mode & ~0o4000)
1361 + print(f" {_("sec_suid", path=path)}")
1362 + except OSError:
1363 + pass
1364 +
1365 +def _check_downgrade(pkg_name, new_ver, installed_db):
1366 + if pkg_name in installed_db:
1367 + old = installed_db[pkg_name].get("version", "0")
1368 + if new_ver < old:
1369 + print(f" {_("sec_downgrade", pkg=pkg_name, new=new_ver, old=old)}")
1370 + return False
1371 + return True
1372 +
1373 +def _safe_extractall(tar: tarfile.TarFile, dest: str, *, preserve_perms: bool = True,
1374 + privileged=frozenset()):
1375 + """
1376 + Bezpieczne rozpakowanie archiwum tar z ochroną przed Directory Traversal.
1377 +
1378 + Działa na Python < 3.12 (gdzie parametr 'filter' w extractall nie istnieje)
1379 + oraz na Python 3.12+. W przeciwieństwie do filtra 'data' z Pythona 3.12,
1380 + zachowuje bity uprawnień POSIX (SUID, SGID, sticky) – preserve_perms=True.
1381 +
1382 + Ochrona oparta jest na FINALNEJ ścieżce (os.path.realpath), nie tylko na
1383 + prostym sprawdzaniu stringa:
1384 + - Blokuje ścieżki absolutne i z '..' (path traversal)
1385 + - Blokuje symlinki/hardlinki, których cel wychodzi poza dest
1386 + - Blokuje zapis "przez" złośliwy symlink, który został wcześniej
1387 + rozpakowany (np. katalog → /etc, potem zapis katalog/plik)
1388 + - Zachowuje oryginalne uprawnienia plików
1389 + """
1390 + dest_real = os.path.realpath(dest)
1391 + os.makedirs(dest_real, exist_ok=True)
1392 +
1393 + def _target_within(path: str) -> bool:
1394 + try:
1395 + return os.path.commonpath([dest_real, os.path.realpath(path)]) == dest_real
1396 + except ValueError:
1397 + # różne napędy / ścieżki nie da się wspólnie porównać → odrzuć
1398 + return False
1399 +
1400 + for member in tar.getmembers():
1401 + name = member.name
1402 +
1403 + # --- Ochrona przed Directory Traversal (szybkie string-checki) ---
1404 + if name.startswith('/'):
1405 + continue
1406 + if '..' in name.split('/'):
1407 + continue
1408 + # Zablokuj bajt NUL i backslash (bugi/obejścia tarfile na niektórych platformach)
1409 + if '\x00' in name or '\\' in name:
1410 + continue
1411 + if not _check_path_safety(name):
1412 + print(f" BLOCKED: {name}")
1413 + continue
1414 +
1415 + target = os.path.join(dest, name)
1416 +
1417 + # --- Ochrona na podstawie finalnej ścieżki ---
1418 + # Jeśli którykolwiek komponent nadrzędny jest (złośliwym) symlinkiem
1419 + # wskazującym poza dest, realpath to wykryje – zablokuj zapis.
1420 + if not _target_within(target):
1421 + print(f" BLOCKED (escape): {name}")
1422 + continue
1423 +
1424 + # --- Ochrona dla symlinków i hardlinków ---
1425 + if member.issym() or member.islnk():
1426 + link = member.linkname
1427 + # Szybkie odrzucenie linków absolutnych / z '..'
1428 + if link.startswith('/') or '..' in link.split('/'):
1429 + continue
1430 + # Sprawdź, gdzie realnie prowadzi cel linku (względem katalogu linku)
1431 + link_target = os.path.join(os.path.dirname(target), link)
1432 + if not _target_within(link_target):
1433 + print(f" BLOCKED (link escape): {name} -> {link}")
1434 + continue
1435 +
1436 + # Rozpakuj z zachowaniem metadanych. Python 3.12+ wymaga jawnego
1437 + # `filter=` (inaczej DeprecationWarning, a w 3.14+ błąd).
1438 + # UWAGA: 'fully_trusted' CELOWO pomija wbudowane filtry bezpieczeństwa
1439 + # Pythona – to nie przeoczenie. Nasza walidacja powyżej (path traversal,
1440 + # NUL/backslash, escape przez symlink, linki wychodzące poza dest) jest
1441 + # równoważna lub ostrzejsza, a 'fully_trusted' pozwala zachować bity
1442 + # SUID/SGID/sticky, które filtr 'data' by usunął (np. /usr/bin/sudo).
1443 + # SUID jest i tak zdejmowany przez _strip_suid() tuż po rozpakowaniu.
1444 + try:
1445 + if hasattr(tarfile, 'data_filter'):
1446 + # Python 3.12+
1447 + tar.extract(member, dest, set_attrs=preserve_perms, numeric_owner=False,
1448 + filter='fully_trusted')
1449 + else:
1450 + tar.extract(member, dest, set_attrs=preserve_perms, numeric_owner=False)
1451 + except Exception as e:
1452 + print(f" ⚠ Nie rozpakowano {name}: {e}")
1453 + continue
1454 + # Pliki z listy uprzywilejowanej zachowują SUID/SGID; reszta jest
1455 + # czyszczona (ochrona przed SUID niespodziewanym w pakiecie).
1456 + if "/" + os.path.relpath(target, dest_real) not in privileged:
1457 + _strip_suid(target)
1458 +
1459 +
1460 +def _sha256_file(path: str) -> str:
1461 + """SHA256 pliku. Na Python ≥3.11 używa hashlib.file_digest (pętla w C);
1462 + starsze wersje mają fallback z pętlą chunków."""
1463 + with open(path, "rb") as f:
1464 + if hasattr(hashlib, "file_digest"):
1465 + return hashlib.file_digest(f, "sha256").hexdigest()
1466 + h = hashlib.sha256()
1467 + for chunk in iter(lambda: f.read(65536), b""):
1468 + h.update(chunk)
1469 + return h.hexdigest()
1470 +
1471 +def _split_version(v: str):
1472 + """Rozdziela wersję na (release_parts, prerelease_parts).
1473 +
1474 + Przykład: '1.2.0-rc1' → ([1,2,0], ['rc','1']).
1475 + """
1476 + v = v.strip().lower().lstrip("v")
1477 + # build metadata po '+' jest ignorowane przy porównywaniu (semver)
1478 + v = v.split("+", 1)[0]
1479 + # prerelease po '-' lub '_' (np. 1.2.0-rc1, 1.2.0_rc1)
1480 + if "-" in v:
1481 + rel, pre = v.split("-", 1)
1482 + elif "_" in v:
1483 + rel, pre = v.split("_", 1)
1484 + else:
1485 + rel, pre = v, ""
1486 + nums = []
1487 + for part in rel.split("."):
1488 + m = re.match(r"(\d+)", part)
1489 + nums.append(int(m.group(1)) if m else 0)
1490 + pre_parts = [p for p in pre.split(".") if p]
1491 + return nums, pre_parts
1492 +
1493 +
1494 +def _cmp_pre(a, b):
1495 + """Porównuje ciągi identyfikatorów prerelease (reguły semver)."""
1496 + for i in range(max(len(a), len(b))):
1497 + if i >= len(a):
1498 + return -1 # krótszy prerelease jest niższy
1499 + if i >= len(b):
1500 + return 1
1501 + ia, ib = a[i], b[i]
1502 + if ia == ib:
1503 + continue
1504 + na, nb = ia.isdigit(), ib.isdigit()
1505 + if na and nb:
1506 + return 1 if int(ia) > int(ib) else -1
1507 + if na != nb:
1508 + return -1 if na else 1 # identyfikator liczbowy < alfanumeryczny
1509 + return 1 if ia > ib else -1
1510 + return 0
1511 +
1512 +
1513 +def _cmp_version(a: str, b: str) -> int:
1514 + """Porównuje dwie wersje; zwraca -1/0/1. Obsługuje prerelease (rc1, beta...)."""
1515 + a_rel, a_pre = _split_version(a)
1516 + b_rel, b_pre = _split_version(b)
1517 + # Porównaj część release (brakujące komponenty traktuj jako 0)
1518 + for i in range(max(len(a_rel), len(b_rel))):
1519 + xa = a_rel[i] if i < len(a_rel) else 0
1520 + xb = b_rel[i] if i < len(b_rel) else 0
1521 + if xa != xb:
1522 + return 1 if xa > xb else -1
1523 + # Część release równa → decyduje prerelease.
1524 + # Wersja finalna (bez prerelease) jest ZAWSZE nowsza od prerelease.
1525 + if not a_pre and not b_pre:
1526 + return 0
1527 + if not a_pre:
1528 + return 1
1529 + if not b_pre:
1530 + return -1
1531 + return _cmp_pre(a_pre, b_pre)
1532 +
1533 +
1534 +def _version_newer(a: str, b: str) -> bool:
1535 + """True gdy wersja a jest nowsza od b (z poprawną obsługą prerelease)."""
1536 + try:
1537 + return _cmp_version(a, b) > 0
1538 + except Exception:
1539 + return a != b
1540 +
1541 +def load_json(path):
1542 + try:
1543 + with open(path) as f:
1544 + return json.load(f)
1545 + except (FileNotFoundError, json.JSONDecodeError):
1546 + return {}
1547 +
1548 +def save_json(path, data):
1549 + with open(path, "w") as f:
1550 + json.dump(data, f, indent=2)
1551 +
1552 +class PackageInfo:
1553 + __slots__ = ("name","version","release","description","dependencies",
1554 + "size_bytes","sha256","gpg_fp","repo_url","filename","provides","license",
1555 + "provides_so","requires_so","privileged")
1556 + def __init__(self, d, repo=""):
1557 + self.name = d.get("name","?")
1558 + self.version = d.get("version","0")
1559 + self.release = d.get("release", 1)
1560 + self.description = d.get("description","")
1561 + self.dependencies = d.get("dependencies", d.get("depends", []))
1562 + self.size_bytes = d.get("size",0)
1563 + self.sha256 = d.get("sha256","")
1564 + self.gpg_fp = d.get("gpg_fingerprint","")
1565 + self.repo_url = repo
1566 + self.filename = d.get("filename", f"{self.name}-{self.version}{PKG_EXT}")
1567 + self.provides = d.get("provides", []) or []
1568 + self.license = d.get("license", []) or []
1569 + self.provides_so = d.get("provides_so", []) or []
1570 + self.requires_so = d.get("requires_so", []) or []
1571 + # Ścieżki, którym wolno zachować setuid/setgid i grupę (z receptury).
1572 + self.privileged = d.get("privileged", []) or []
1573 +
1574 +# =============================================================================
1575 +# REPOZYTORIA (cache, ETag, GPG)
1576 +# =============================================================================
1577 +
1578 +def _parse_repos_config():
1579 + """Parsuje repozytoria z /etc/pag/repos.conf oraz /etc/pag/repos/*.conf.
1580 +
1581 + Format linii: <url> [fingerprint]
1582 + Opcjonalny `fingerprint` (40 znaków hex) pozwala przypiąć klucz
1583 + podpisujący repo do konkretnego adresu – wtedy TOFU (auto-zaufanie przy
1584 + pierwszym użyciu) nie jest potrzebne, a zmiana klucza = błąd bezpieczeństwa.
1585 +
1586 + Drop-iny (np. stable.conf) są czytane alfabetycznie – pozwalają na
1587 + wygodne dodawanie repo bez dotykania głównego repos.conf
1588 + (np. `echo 'https://repo.paganlinux.eu/stable' > /etc/pag/repos/stable.conf`).
1589 + """
1590 + entries = []
1591 +
1592 + def _read_lines(path):
1593 + if not os.path.exists(path):
1594 + return
1595 + for line in open(path):
1596 + line = line.strip()
1597 + if not line or line.startswith("#"):
1598 + continue
1599 + parts = line.split()
1600 + url = parts[0].rstrip("/")
1601 + fp = parts[1].lower() if len(parts) > 1 else ""
1602 + entries.append({"url": url, "fingerprint": fp or None})
1603 +
1604 + # 1) Legacy: pojedynczy plik /etc/pag/repos.conf
1605 + _read_lines(REPOS_CONF)
1606 + # 2) Drop-in: /etc/pag/repos/<nazwa>.conf (sortowane, stabilna kolejność)
1607 + if os.path.isdir(REPOS_DIR):
1608 + for drop in sorted(os.listdir(REPOS_DIR)):
1609 + if drop.endswith(".conf"):
1610 + _read_lines(os.path.join(REPOS_DIR, drop))
1611 +
1612 + # Dedupe po URL (zachowaj pierwszy wpis – może mieć fingerprint)
1613 + seen, unique = set(), []
1614 + for e in entries:
1615 + if e["url"] not in seen:
1616 + seen.add(e["url"])
1617 + unique.append(e)
1618 +
1619 + if not unique:
1620 + for url in DEFAULT_REPOS:
1621 + # rstrip: get_repos()/_repo_pinned_fp() kluczują URL-e bez ukośnika
1622 + unique.append({"url": url.rstrip("/"), "fingerprint": None})
1623 + return unique
1624 +
1625 +
1626 +def get_repos():
1627 + return [e["url"] for e in _parse_repos_config()]
1628 +
1629 +
1630 +def _repo_pinned_fp(repo_url):
1631 + """Zwraca przypięty fingerprint klucza dla repo (z konfiguracji lub trust DB)."""
1632 + # Normalizacja ukośnika: _parse_repos_config() i trust DB kluczują URL-e BEZ
1633 + # końcowego „/”, a wywołujący podają często DEFAULT_REPOS[0] Z ukośnikiem.
1634 + # Bez tego przypięty klucz nie był znajdowany i lokalny .pag dostawał
1635 + # fałszywe „Brak przypiętego klucza repo” mimo poprawnego wpisu w trusted.json.
1636 + repo_url = repo_url.rstrip("/")
1637 + by_url = {e["url"]: e["fingerprint"] for e in _parse_repos_config()}
1638 + if by_url.get(repo_url):
1639 + return by_url[repo_url]
1640 + db = _load_trust_db()
1641 + fp = db.get(repo_url)
1642 + return fp.lower() if fp else None
1643 +
1644 +def _repo_cache_path(url):
1645 + return os.path.join(REPO_CACHE, url.replace("://","_").replace("/","_").replace(".","_") + ".json")
1646 +
1647 +def _repo_etag_path(url): return _repo_cache_path(url) + ".etag"
1648 +def _repo_ts_path(url): return _repo_cache_path(url) + ".ts"
1649 +
1650 +# Informacja (raz na uruchomienie), gdy cache repozytoriów jest tylko-do-odczytu –
1651 +# np. komendy read-only (`pag info`, `pag search`…) jako zwykły user: nie ma sensu
1652 +# ani prawa odświeżać /var/cache/pag/repos, więc używamy lokalnej kopii indeksu.
1653 +_cache_ro_notice_done = False
1654 +
1655 +def _cache_ro_notice():
1656 + global _cache_ro_notice_done
1657 + if _cache_ro_notice_done:
1658 + return
1659 + _cache_ro_notice_done = True
1660 + print(f" ⚠ {_('cache_ro', cache=REPO_CACHE)}", file=sys.stderr)
1661 +
1662 +def _load_repo_cache(cp: str) -> Optional[list]:
1663 + """Wczytuje cache indeksu repo; zwraca None gdy brak albo uszkodzony.
1664 +
1665 + Partial write (crash w trakcie zapisu) mógł zostawić obcięty JSON. Zamiast
1666 + zwracać pustą listę pakietów (użytkownik myśli, że repo jest puste)
1667 + sygnalizujemy None – wywołujący ponowi pobranie albo pokaże ostrzeżenie."""
1668 + if not os.path.exists(cp):
1669 + return None
1670 + try:
1671 + with open(cp, "r", encoding="utf-8") as fh:
1672 + data = json.load(fh)
1673 + pkgs = data.get("packages")
1674 + if not isinstance(pkgs, list):
1675 + raise ValueError("brak listy 'packages'")
1676 + return pkgs
1677 + except (OSError, ValueError) as e:
1678 + print(f" ⚠ Uszkodzony cache indeksu {cp}: {e}", file=sys.stderr)
1679 + return None
1680 +
1681 +
1682 +def fetch_repo_index(repo_url, force=False):
1683 + cp = _repo_cache_path(repo_url)
1684 + ep = _repo_etag_path(repo_url)
1685 + tp = _repo_ts_path(repo_url)
1686 +
1687 + if not force and os.path.exists(cp) and os.path.exists(tp):
1688 + try:
1689 + if time.time() - float(open(tp).read().strip()) < REPO_CACHE_TTL:
1690 + cached = _load_repo_cache(cp)
1691 + if cached is not None:
1692 + return cached
1693 + # uszkodzony cache – spróbuj odświeżyć z sieci
1694 + except (OSError, ValueError):
1695 + pass
1696 +
1697 + # --- Cache tylko-do-odczytu (np. `pag info` jako zwykły user) ---
1698 + # /var/cache/pag/repos należy do roota. Nie próbuj odświeżać ani pisać –
1699 + # zwykły user i tak nie zapisze indeksu; użyj lokalnej kopii (może być
1700 + # nieaktualna). Pełne odświeżenie indeksu: sudo pag sync
1701 + if not (os.path.isdir(REPO_CACHE) and os.access(REPO_CACHE, os.W_OK)):
1702 + if force:
1703 + print(f" ❌ {repo_url}: nie można odświeżyć indeksu – {REPO_CACHE} jest tylko-do-odczytu",
1704 + file=sys.stderr)
1705 + return None
1706 + _cache_ro_notice()
1707 + cached = _load_repo_cache(cp)
1708 + if cached is not None:
1709 + return cached
1710 + return None
1711 +
1712 + headers = {"User-Agent": "pag/3.0"}
1713 + if os.path.exists(tp) and not force:
1714 + try:
1715 + lm = datetime.fromtimestamp(float(open(tp).read().strip()), tz=timezone.utc)
1716 + # Wymuś lokalizację C/POSIX dla nagłówków HTTP, aby unikać problemów z nazwami dni/miesięcy
1717 + try:
1718 + old_locale = locale.setlocale(locale.LC_TIME)
1719 + locale.setlocale(locale.LC_TIME, 'C')
1720 + headers["If-Modified-Since"] = lm.strftime("%a, %d %b %Y %H:%M:%S GMT")
1721 + locale.setlocale(locale.LC_TIME, old_locale)
1722 + except (locale.Error, ValueError):
1723 + # Jeśli ustawienie lokalizacji się nie powiedzie, użyj domyślnej
1724 + headers["If-Modified-Since"] = lm.strftime("%a, %d %b %Y %H:%M:%S GMT")
1725 + except: pass
1726 + if os.path.exists(ep) and not force:
1727 + try: headers["If-None-Match"] = open(ep).read().strip()
1728 + except: pass
1729 +
1730 + # --- Pobranie indeksu (błędy SIECI nie są błędami zapisu cache) ---
1731 + try:
1732 + req = Request(f"{repo_url}/repo.json", headers=headers)
1733 + with urlopen(req, timeout=30) as resp:
1734 + etag = resp.headers.get("ETag","")
1735 + raw = resp.read()
1736 + data = json.loads(raw.decode())
1737 + except HTTPError as e:
1738 + if e.code == 304:
1739 + # Serwer: indeks bez zmian – odśwież tylko znacznik czasu (best-effort)
1740 + try:
1741 + open(tp,"w").write(str(time.time()))
1742 + except OSError:
1743 + pass
1744 + cached = _load_repo_cache(cp)
1745 + if cached is not None:
1746 + return cached
1747 + # uszkodzona kopia – potraktuj jak brak (ostrzeżenie niżej)
1748 + print(f" ⚠ HTTP {e.code} dla {repo_url}", file=sys.stderr)
1749 + return None
1750 + except Exception as e:
1751 + print(f" ⚠ Błąd pobierania indeksu {repo_url}: {e}", file=sys.stderr)
1752 + return _load_repo_cache(cp)
1753 +
1754 + # Indeks pobrany – zapisz SUROWE bajty (nie re-serializuj! podpis GPG jest
1755 + # nad oryginalnymi bajtami repo.json z serwera) i zweryfikuj podpis.
1756 + # Najpierw zapis tymczasowy + weryfikacja GPG, dopiero potem podmiana cp:
1757 + # błąd zapisu (np. pełny dysk) nie niszczy starej, zweryfikowanej kopii
1758 + # i NIGDY nie zwracamy danych, które nie przeszły weryfikacji.
1759 + tmp_path = cp + ".tmp"
1760 + try:
1761 + with open(tmp_path, "wb") as f:
1762 + f.write(raw)
1763 + if not _verify_repo_sig(repo_url, tmp_path):
1764 + return None # weryfikacja nie powiodła się – stary cache zostaje
1765 + os.replace(tmp_path, cp)
1766 + # przenieś podpis obok docelowego pliku (marker „repo ma podpis")
1767 + for _ext in (".asc", ".sig"):
1768 + if os.path.exists(tmp_path + _ext):
1769 + try:
1770 + os.replace(tmp_path + _ext, cp + _ext)
1771 + except OSError:
1772 + pass
1773 + break
1774 + if etag:
1775 + try:
1776 + open(ep,"w").write(etag)
1777 + except OSError:
1778 + pass
1779 + try:
1780 + open(tp,"w").write(str(time.time()))
1781 + except OSError:
1782 + pass
1783 + return data.get("packages",[])
1784 + except OSError as e:
1785 + print(f" ⚠ Indeks pobrany, ale nie udało się zapisać cache ({REPO_CACHE}): {e}",
1786 + file=sys.stderr)
1787 + # cp nie został podmieniony (podmiana jest po weryfikacji) – lokalna kopia
1788 + # to wciąż stare, zweryfikowane dane
1789 + return _load_repo_cache(cp)
1790 + finally:
1791 + for _p in (tmp_path, tmp_path + ".asc", tmp_path + ".sig"):
1792 + try:
1793 + os.unlink(_p)
1794 + except OSError:
1795 + pass
1796 +
1797 +def _verify_repo_sig(repo_url, cache_path) -> bool:
1798 + """Weryfikuje podpis GPG indeksu repozytorium i przypina fingerprint.
1799 +
1800 + FAIL-CLOSED: brak/nieprawidłowy podpis = False (chyba że PAG_INSECURE=1).
1801 + Zwraca True jeśli indeks jest zaufany, False jeśli należy go odrzucić.
1802 +
1803 + Model zaufania (TOFU + pinning):
1804 + - Pierwszy raz (brak przypiętego fingerprintu) → klucz jest importowany,
1805 + a fingerprint zapisywany w /etc/pag/trusted.json z JAWNYM ostrzeżeniem.
1806 + To świadomy kompromis wygody i bezpieczeństwa.
1807 + - Kolejne uruchomienia: fingerprint jest porównywany z przypiętym.
1808 + Zmiana klucza = ❌ SECURITY ERROR (fail-closed), wymagane ręczne:
1809 + pag key-trust <repo_url> (po weryfikacji nowego klucza)
1810 + """
1811 + insecure = os.environ.get("PAG_INSECURE", "") == "1"
1812 +
1813 + if not os.path.exists(GPG_HOME):
1814 + if insecure:
1815 + return True # brak GPG home – tryb insecure, akceptuj
1816 + print(f" ❌ {repo_url}: brak kluczy GPG – weryfikacja niemożliwa!")
1817 + print(f" Ustaw PAG_INSECURE=1 aby pominąć (niezalecane)")
1818 + os.remove(cache_path)
1819 + return False
1820 +
1821 + sig_path = cache_path + ".sig"
1822 + # Podpisy generowane jako .asc (armored) – próbuj .asc, potem .sig
1823 + sig_data = None
1824 + sig_ext = ""
1825 + for ext in (".asc", ".sig"):
1826 + try:
1827 + req = Request(f"{repo_url}/repo.json{ext}", headers={"User-Agent":"pag/3.0"})
1828 + with urlopen(req, timeout=15) as resp:
1829 + sig_data = resp.read()
1830 + sig_ext = ext
1831 + break
1832 + except Exception:
1833 + continue
1834 + if not sig_data:
1835 + if insecure:
1836 + return True # tryb insecure – akceptuj bez podpisu
1837 + print(f" ❌ {repo_url}: NIE MOŻNA POBRAĆ PODPISU repo.json.asc/.sig!")
1838 + print(f" Ustaw PAG_INSECURE=1 aby pominąć (niezalecane)")
1839 + os.remove(cache_path)
1840 + return False
1841 + sig_path = cache_path + sig_ext
1842 + with open(sig_path, "wb") as f:
1843 + f.write(sig_data)
1844 +
1845 + ok, fingerprint = _gpg_verify_fp(sig_path, cache_path)
1846 + if not ok:
1847 + # Automatyczny import klucza repo przy pierwszym uruchomieniu (TOFU,
1848 + # jak apt) – gdy w keyringu brakuje klucza (No public key).
1849 + res = _gpg_run("--verify", sig_path, cache_path,
1850 + capture_output=True, text=True, timeout=30)
1851 + _stderr = res.stderr.decode(errors="replace") if isinstance(res.stderr, bytes) else (res.stderr or "")
1852 + if "public key" in _stderr.lower() and "no public key" in _stderr.lower():
1853 + try:
1854 + with urlopen(Request(f"{repo_url}/paganos.asc", headers={"User-Agent": "pag/3.0"}), timeout=20) as r:
1855 + keydata = r.read()
1856 + with tempfile.NamedTemporaryFile(delete=False, suffix=".asc") as tmp:
1857 + tmp.write(keydata)
1858 + tmp.flush()
1859 + _gpg_run("--import", tmp.name, capture_output=True, timeout=30)
1860 + os.unlink(tmp.name)
1861 + print(f" 🔑 Importowano klucz repo z {repo_url}/paganos.asc")
1862 + ok, fingerprint = _gpg_verify_fp(sig_path, cache_path)
1863 + except Exception:
1864 + pass
1865 + if not ok:
1866 + if insecure:
1867 + print(f" ⚠ {repo_url}: nieprawidłowy podpis GPG (PAG_INSECURE – ignoruję)")
1868 + return True
1869 + os.remove(cache_path)
1870 + if not shutil.which(GPG_BINARY):
1871 + print(f" ❌ {repo_url}: GPG nie jest zainstalowane – nie można zweryfikować podpisu!")
1872 + print(f" Zainstaluj gnupg lub ustaw PAG_INSECURE=1 (niezalecane)")
1873 + else:
1874 + print(f" ❌ {repo_url}: NIEPRAWIDŁOWY PODPIS GPG indeksu repozytorium!")
1875 + return False
1876 +
1877 + # --- Wymuś przypięty fingerprint (TOFU + pinning) ---
1878 + pinned = _repo_pinned_fp(repo_url)
1879 + if pinned:
1880 + if not fingerprint:
1881 + if insecure:
1882 + print(f" ⚠ {repo_url}: nie można odczytać fingerprintu (PAG_INSECURE – ignoruję)")
1883 + return True
1884 + os.remove(cache_path)
1885 + print(f" ❌ [SECURITY ERROR] {repo_url}: nie można odczytać fingerprintu podpisu!")
1886 + print(f" Przypięty klucz: {pinned} – odrzucam indeks.")
1887 + return False
1888 + if fingerprint != pinned.upper():
1889 + if insecure:
1890 + print(f" ⚠ {repo_url}: ZMIENIONY KLUCZ PODPISU (PAG_INSECURE – ignoruję)")
1891 + return True
1892 + os.remove(cache_path)
1893 + print(f" ❌ [SECURITY ERROR] {repo_url}: Klucz podpisujący repo uległ zmianie!")
1894 + print(f" Oczekiwany: {pinned}")
1895 + print(f" Otrzymany: {fingerprint}")
1896 + print(f" Jeśli to celowa rotacja klucza: pag key-trust {repo_url}")
1897 + return False
1898 + return True
1899 +
1900 + if fingerprint:
1901 + # Brak przypiętego fingerprintu → TOFU: zapisz go w bazie zaufania.
1902 + db = _load_trust_db()
1903 + if db.get(repo_url) != fingerprint:
1904 + _save_trust_db({**db, repo_url: fingerprint})
1905 + print(f" 🔐 Przypięto fingerprint repo {repo_url}: {fingerprint}")
1906 + print(f" (TOFU – pierwsze zaufanie. Gdy klucz się zmieni, pag odmówi aktualizacji.)")
1907 + print(f" Aby uniknąć TOFU, dopisz fingerprint w /etc/pag/repos.conf.")
1908 + return True
1909 +
1910 +def fetch_all_packages(force=False):
1911 + all_pkgs = {}
1912 + for repo_url in get_repos():
1913 + pkgs = fetch_repo_index(repo_url, force)
1914 + if pkgs:
1915 + for pdata in pkgs:
1916 + name = pdata.get("name", pdata.get("filename","?").split("-")[0])
1917 + pkg = PackageInfo(pdata, repo_url)
1918 + if name not in all_pkgs or _version_newer(pkg.version, all_pkgs[name].version):
1919 + all_pkgs[name] = pkg
1920 + return all_pkgs
1921 +
1922 +# =============================================================================
1923 +# GPG
1924 +# =============================================================================
1925 +
1926 +def _verify_pkg_gpg(pkg_path, repo_url=None):
1927 + """Weryfikuje podpis GPG pakietu i (jeśli znamy repo) przypięty fingerprint.
1928 +
1929 + FAIL-CLOSED: brak podpisu = odrzucenie (chyba że PAG_INSECURE=1).
1930 + Zwraca (passed: bool, message: str).
1931 + """
1932 + insecure = os.environ.get("PAG_INSECURE", "") == "1"
1933 + # Brak gnupg = weryfikacja niemożliwa. Bez tej gałęzi użytkownik dostawał
1934 + # mylące „NIEPRAWIDŁOWY PODPIS GPG”, mimo że paczka i podpis są w porządku.
1935 + if not shutil.which(GPG_BINARY):
1936 + if insecure:
1937 + return True, "(gpg missing – PAG_INSECURE)"
1938 + return False, _("gpg_missing")
1939 + sig_path = pkg_path + ".sig"
1940 + if not os.path.exists(sig_path) and os.path.exists(pkg_path + ".asc"):
1941 + sig_path = pkg_path + ".asc"
1942 +
1943 + if not os.path.exists(sig_path):
1944 + if insecure:
1945 + return True, "(no signature – PAG_INSECURE)"
1946 + return False, "BRAK PODPISU – pakiet odrzucony (ustaw PAG_INSECURE=1 aby pominąć)"
1947 +
1948 + ok, fp = _gpg_verify_fp(sig_path, pkg_path)
1949 + if not ok:
1950 + if insecure:
1951 + return True, "(invalid signature – PAG_INSECURE)"
1952 + return False, "NIEPRAWIDŁOWY PODPIS GPG"
1953 +
1954 + # Opcjonalnie: sprawdź, czy podpis pochodzi od klucza przypiętego dla repo.
1955 + if repo_url:
1956 + pinned = _repo_pinned_fp(repo_url)
1957 + if pinned and fp and fp != pinned.upper():
1958 + if insecure:
1959 + return True, "(pkg signer mismatch – PAG_INSECURE)"
1960 + return False, f"PAKIET PODPISANY INNYM KLUCZEM niż repo (oczekiwano {pinned})"
1961 +
1962 + return True, "GPG verified"
1963 +
1964 +def cmd_key_add(source):
1965 + ensure_dirs()
1966 + if not shutil.which(GPG_BINARY):
1967 + print(f"❌ {_('gpg_missing')}"); return 1
1968 + if source.startswith("http"):
1969 + try:
1970 + with urlopen(Request(source, headers={"User-Agent":"pag/3.0"}), timeout=30) as resp:
1971 + keydata = resp.read()
1972 + with tempfile.NamedTemporaryFile(delete=False, suffix=".gpg") as tmp:
1973 + tmp.write(keydata); tmp.flush()
1974 + res = _gpg_run("--import", tmp.name, capture_output=True, timeout=30)
1975 + os.unlink(tmp.name)
1976 + if res.returncode != 0:
1977 + print(f"❌ {_('key_add_failed')}"); return 1
1978 + except Exception as e:
1979 + print(f"❌ Download error: {e}"); return 1
1980 + else:
1981 + res = _gpg_run("--import", source, capture_output=True, timeout=30)
1982 + if res.returncode != 0:
1983 + print(f"❌ {_('key_add_failed')}"); return 1
1984 + print(f"✅ {_('key_imported')}")
1985 +
1986 +def cmd_key_list():
1987 + if not shutil.which(GPG_BINARY):
1988 + print(f"❌ {_('gpg_missing')}"); return
1989 + if not os.path.exists(GPG_HOME):
1990 + print(_("no_keys")); return
1991 + result = _gpg_run("--list-keys", "--keyid-format", "LONG",
1992 + capture_output=True, text=True, timeout=30)
1993 + if result.returncode != 0:
1994 + print(f"❌ {_('gpg_missing')}"); return
1995 + print(result.stdout or _("no_keys"))
1996 +
1997 +def cmd_key_remove(key_id):
1998 + _gpg_run("--batch", "--yes", "--delete-key", key_id,
1999 + capture_output=True, timeout=30)
2000 + print(f"✅ {_('key_removed', key_id)}")
2001 +
2002 +def _repo_signer_fp(repo_url):
2003 + """Pobiera repo.json + podpis i zwraca fingerprint podpisującego (bez pinningu)."""
2004 + repo_url = repo_url.rstrip("/")
2005 + try:
2006 + with urlopen(Request(f"{repo_url}/repo.json", headers={"User-Agent":"pag/3.0"}), timeout=30) as r:
2007 + data = r.read()
2008 + except Exception:
2009 + return None
2010 + sig = None
2011 + sig_ext = ".asc"
2012 + for ext in (".asc", ".sig"):
2013 + try:
2014 + with urlopen(Request(f"{repo_url}/repo.json{ext}", headers={"User-Agent":"pag/3.0"}), timeout=20) as r:
2015 + sig = r.read()
2016 + sig_ext = ext
2017 + break
2018 + except Exception:
2019 + continue
2020 + if not sig:
2021 + return None
2022 + with tempfile.NamedTemporaryFile(delete=False, suffix=".json") as tf:
2023 + tf.write(data); tf.flush()
2024 + data_path = tf.name
2025 + sig_path = data_path + sig_ext
2026 + try:
2027 + with open(sig_path, "wb") as f:
2028 + f.write(sig)
2029 + ok, fp = _gpg_verify_fp(sig_path, data_path)
2030 + finally:
2031 + for p in (data_path, sig_path):
2032 + try: os.unlink(p)
2033 + except OSError: pass
2034 + return fp if ok else None
2035 +
2036 +
2037 +def cmd_key_trust(repo_url):
2038 + """Przypina fingerprint klucza podpisującego repo (koniec z TOFU dla tego repo)."""
2039 + repo_url = repo_url.rstrip("/")
2040 + print(f"🔐 Przypinam klucz repo {repo_url}...")
2041 + fp = _repo_signer_fp(repo_url)
2042 + if not fp:
2043 + print(" ❌ Nie można odczytać fingerprintu podpisu (brak/nieudany).")
2044 + print(" Upewnij się, że klucz repo jest w keyringu (pag key-add <url|file>).")
2045 + return 1
2046 + db = _load_trust_db()
2047 + _save_trust_db({**db, repo_url: fp})
2048 + print(f" ✅ Przypięto {fp} dla {repo_url}")
2049 + print(" Od teraz zmiana klucza zostanie zgłoszona jako SECURITY ERROR.")
2050 + return 0
2051 +
2052 +
2053 +def cmd_key_untrust(repo_url):
2054 + """Usuwa przypięcie fingerprintu dla repo (wraca do TOFU)."""
2055 + repo_url = repo_url.rstrip("/")
2056 + db = _load_trust_db()
2057 + if repo_url not in db:
2058 + print(f" ℹ {repo_url} nie ma przypiętego fingerprintu.")
2059 + return 0
2060 + del db[repo_url]
2061 + _save_trust_db(db)
2062 + print(f" ✅ Usunięto przypięcie dla {repo_url}.")
2063 + return 0
2064 +
2065 +
2066 +def cmd_key_trusted():
2067 + """Listuje przypięte fingerprinty repozytoriów."""
2068 + db = _load_trust_db()
2069 + if not db:
2070 + print(_("no_keys"))
2071 + return
2072 + for url, fp in sorted(db.items()):
2073 + print(f" {url}\n {fp}")
2074 +
2075 +# =============================================================================
2076 +# ATOMOWA INSTALACJA (STAGING)
2077 +# =============================================================================
2078 +
2079 +def _safe_rename(src: str, dst: str) -> bool:
2080 + """
2081 + Atomowe przeniesienie pliku. Jeśli src i dst są na różnych
2082 + systemach plików (EXDEV), kopiuje + usuwa źródło.
2083 + """
2084 + try:
2085 + os.rename(src, dst)
2086 + return True
2087 + except OSError as e:
2088 + if e.errno == 18: # EXDEV – cross-device link
2089 + shutil.copy2(src, dst)
2090 + os.remove(src)
2091 + return True
2092 + raise
2093 +
2094 +
2095 +def _install_file(src: str, rel: str, data_staging: str, sums: dict,
2096 + staging: str, journal: list, installed_files: list,
2097 + deploy_dir: str = "", backup_dir: str = "",
2098 + backup_journal: Optional[list] = None,
2099 + old_checksums: Optional[dict] = None,
2100 + privileged=frozenset()) -> bool:
2101 + """
2102 + Instaluje pojedynczy plik (zwykły lub symlink).
2103 + Obsługuje: cross-device rename, symlinki, weryfikację SHA256.
2104 +
2105 + Jeśli deploy_dir jest podany (tryb immutable), pliki systemowe trafiają
2106 + do deploymentu, a współdzielone (/var, /etc, ...) bezpośrednio do /.
2107 +
2108 + Jeśli backup_dir jest podany, a pod dst istnieje już plik (upgrade/reinstall),
2109 + stara wersja jest przenoszona do backup_dir, by rollback mógł ją przywrócić.
2110 +
2111 + old_checksums: {ścieżka: sha256 z chwili instalacji}. Gdy podane i plik /etc
2112 + został zmodyfikowany przez użytkownika, nowa wersja ląduje jako .pacnew
2113 + (stary plik NIE jest ruszany) – wzorzec jak w pacmanie.
2114 + """
2115 + # W trybie immutable: pliki współdzielone idą do /, reszta do deploymentu
2116 + if deploy_dir and _is_shared_path("/" + rel):
2117 + dst_root = PAG_ROOT
2118 + elif deploy_dir:
2119 + dst_root = deploy_dir
2120 + else:
2121 + dst_root = PAG_ROOT
2122 +
2123 + dst = os.path.join(dst_root, rel)
2124 +
2125 + # --- SYMLINK ---
2126 + if os.path.islink(src):
2127 + link_target = os.readlink(src)
2128 + # Weryfikuj sums.json dla symlinka (hash ścieżki docelowej)
2129 + expected = sums.get("/" + rel, "")
2130 + if expected:
2131 + link_hash = hashlib.sha256(link_target.encode()).hexdigest()
2132 + if expected and link_hash != expected:
2133 + return False
2134 +
2135 + os.makedirs(os.path.dirname(dst), exist_ok=True)
2136 + # Backup istniejącego symlinka (upgrade) – dla poprawnego rollbacku
2137 + if backup_dir and backup_journal is not None and os.path.lexists(dst):
2138 + try:
2139 + backup_path = os.path.join(backup_dir, rel)
2140 + os.makedirs(os.path.dirname(backup_path), exist_ok=True)
2141 + os.replace(dst, backup_path)
2142 + backup_journal.append((backup_path, "/" + rel))
2143 + journal.append(("backup", backup_path, dst))
2144 + except OSError:
2145 + pass
2146 + # Jeśli docelowy symlink już istnieje, usuń go
2147 + if os.path.islink(dst) or os.path.exists(dst):
2148 + os.remove(dst)
2149 + os.symlink(link_target, dst)
2150 + journal.append(("symlink", "", dst))
2151 + installed_files.append({
2152 + "path": "/" + rel,
2153 + "sha256": hashlib.sha256(link_target.encode()).hexdigest(),
2154 + "size": len(link_target),
2155 + "is_symlink": True,
2156 + "symlink_target": link_target,
2157 + })
2158 + return True
2159 +
2160 + # --- ZWYKŁY PLIK ---
2161 + # Oblicz SHA256
2162 + try:
2163 + file_sha = _sha256_file(src)
2164 + except Exception:
2165 + file_sha = ""
2166 +
2167 + # Weryfikuj sums.json
2168 + expected = sums.get("/" + rel, "")
2169 + if expected and file_sha and file_sha != expected:
2170 + return False
2171 +
2172 + # --- .pacnew: NIE nadpisuj pliku konfiguracyjnego, którego nie wolno zgubić ---
2173 + # Robimy `<plik>.pacnew`, gdy:
2174 + # a) plik jest śledzony i użytkownik go zmodyfikował (hash != zapisanej sumy),
2175 + # b) to wrażliwa konfiguracja (/etc/pam.d, /etc/security, sudoers, shadow…),
2176 + # a treść na dysku różni się od tej z pakietu – chroni auth przed
2177 + # cichym nadpisaniem przez `install`/`upgrade` (np. przez shadow).
2178 + # NIE robimy .pacnew, jeśli plik na dysku jest identyczny z nowym albo był
2179 + # niezmieniony od instalacji (wtedy nadpisanie jest bezpieczne).
2180 + old_sha = (old_checksums or {}).get("/" + rel, "")
2181 + if file_sha and _is_config_path(rel) and os.path.isfile(dst) and not os.path.islink(dst):
2182 + tracked_modified = bool(old_sha) and file_sha != old_sha
2183 + if tracked_modified or _is_sensitive_config(rel):
2184 + try:
2185 + cur_sha = _sha256_file(dst)
2186 + except OSError:
2187 + cur_sha = ""
2188 + if cur_sha and cur_sha != file_sha and not (old_sha and cur_sha == old_sha):
2189 + pacnew = dst + ".pacnew"
2190 + try:
2191 + _safe_rename(src, pacnew)
2192 + try:
2193 + os.chown(pacnew, 0, 0)
2194 + except (OSError, PermissionError):
2195 + pass
2196 + # Journal (do cofnięcia przy nieudanej transakcji) – ale NIE
2197 + # zapisujemy .pacnew w bazie plików: to artefakt użytkownika.
2198 + journal.append(("file", src, pacnew))
2199 + print(f" ⚠ {_('conf_pacnew', path=pacnew)}")
2200 + return True
2201 + except OSError:
2202 + pass # nie udało się – kontynuuj normalną instalację
2203 +
2204 + # Utwórz katalog docelowy
2205 + os.makedirs(os.path.dirname(dst), exist_ok=True)
2206 +
2207 + # Backup istniejącego pliku (upgrade) – dla poprawnego rollbacku
2208 + if backup_dir and backup_journal is not None and os.path.lexists(dst):
2209 + try:
2210 + backup_path = os.path.join(backup_dir, rel)
2211 + os.makedirs(os.path.dirname(backup_path), exist_ok=True)
2212 + os.replace(dst, backup_path)
2213 + backup_journal.append((backup_path, "/" + rel))
2214 + journal.append(("backup", backup_path, dst))
2215 + except OSError:
2216 + pass
2217 +
2218 + # Atomowe przeniesienie (z fallbackiem dla cross-device).
2219 + # Zachowuje bity uprawnień (SUID/SGID/sticky) – NIE używamy filter='data'.
2220 + _safe_rename(src, dst)
2221 +
2222 + if "/" + rel in privileged:
2223 + # Plik uprzywilejowany: zostaw właściciela, grupę i bity z pakietu
2224 + # (np. sudo 4755 root:root, qemu-bridge-helper 4750 root:kvm).
2225 + try:
2226 + st = os.stat(dst)
2227 + if st.st_mode & 0o6000:
2228 + _audit(f"privileged {dst} mode={oct(st.st_mode & 0o7777)} "
2229 + f"uid={st.st_uid} gid={st.st_gid}")
2230 + except OSError:
2231 + pass
2232 + else:
2233 + # Wymuś właściciela root:root. UWAGA: os.chown() NIE czyści bitów SUID/SGID.
2234 + try:
2235 + os.chown(dst, 0, 0)
2236 + except (OSError, PermissionError):
2237 + # Na niektórych systemach plików (tmpfs, fat) chown może się nie powieść
2238 + pass
2239 +
2240 + journal.append(("file", src, dst))
2241 + installed_files.append({
2242 + "path": "/" + rel,
2243 + "sha256": file_sha,
2244 + "size": os.path.getsize(dst),
2245 + "is_symlink": False,
2246 + })
2247 + return True
2248 +
2249 +
2250 +def _atomic_install(pkg_path: str, pkg: PackageInfo, deploy_dir: str = "",
2251 + backup_dir: str = "",
2252 + old_checksums: Optional[dict] = None) -> Tuple[bool, List[dict], List[Tuple[str, str]]]:
2253 + """
2254 + Rozpakowuje do staging area, potem atomowo przenosi pliki.
2255 + Jeśli deploy_dir podany – instaluje do deploymentu (tryb immutable).
2256 + Zwraca (success, [lista plików z SHA256], [(backup_path, dst), ...]).
2257 + """
2258 + staging = tempfile.mkdtemp(dir=STAGING_DIR, prefix=f".staging-{pkg.name}-")
2259 + # Wbudowana lista + ścieżki zadeklarowane przez recepturę (metadata.json).
2260 + priv = PRIVILEGED_PATHS | frozenset(pkg.privileged or ())
2261 + journal = []
2262 + installed_files = []
2263 + backup_journal: List[Tuple[str, str]] = []
2264 +
2265 + try:
2266 + # Rozpakuj .pkg.tar.xz → staging (bezpieczne – ochrona Directory Traversal)
2267 + with tarfile.open(pkg_path, "r:xz") as tf:
2268 + _safe_extractall(tf, staging)
2269 +
2270 + data_tar = os.path.join(staging, "data.tar.xz")
2271 + if not os.path.exists(data_tar):
2272 + shutil.rmtree(staging, ignore_errors=True)
2273 + return False, [], backup_journal
2274 +
2275 + # Rozpakuj data.tar.xz → staging/data (bezpieczne – ochrona Directory Traversal)
2276 + data_staging = os.path.join(staging, "data")
2277 + os.makedirs(data_staging, exist_ok=True)
2278 + with tarfile.open(data_tar, "r:xz") as tf:
2279 + _safe_extractall(tf, data_staging, privileged=priv)
2280 +
2281 + # Wczytaj sums.json
2282 + sums_path = os.path.join(data_staging, "sums.json")
2283 + sums = json.load(open(sums_path)) if os.path.exists(sums_path) else {}
2284 +
2285 + # Hook pre-install (przed przeniesieniem plików do systemu)
2286 + _run_hook(os.path.join(staging, "hooks"), "pre-install", pkg)
2287 +
2288 + # Przenieś pliki: staging/data/* → /
2289 + for root, dirs, files in os.walk(data_staging):
2290 + # Odtwórz katalogi z pakietu – w tym PUSTE (np. /etc/pulse/default.pa.d).
2291 + # Pętla plików tworzy tylko rodziców instalowanych plików, przez co
2292 + # puste katalogi z data.tar.xz ginęły przy instalacji.
2293 + for d in dirs:
2294 + src_dir = os.path.join(root, d)
2295 + rel_dir = os.path.relpath(src_dir, data_staging)
2296 + if deploy_dir and _is_shared_path("/" + rel_dir):
2297 + dst_root = PAG_ROOT
2298 + elif deploy_dir:
2299 + dst_root = deploy_dir
2300 + else:
2301 + dst_root = PAG_ROOT
2302 + dst_dir = os.path.join(dst_root, rel_dir)
2303 + if not os.path.isdir(dst_dir):
2304 + try:
2305 + os.makedirs(dst_dir, exist_ok=True)
2306 + except OSError:
2307 + pass
2308 + for fname in files:
2309 + if fname == "sums.json":
2310 + continue
2311 + src = os.path.join(root, fname)
2312 + rel = os.path.relpath(src, data_staging)
2313 +
2314 + ok = _install_file(src, rel, data_staging, sums,
2315 + staging, journal, installed_files, deploy_dir,
2316 + backup_dir, backup_journal,
2317 + old_checksums=old_checksums,
2318 + privileged=priv)
2319 + if not ok:
2320 + # Cofnij wszystkie operacje
2321 + _rollback_journal(journal, staging)
2322 + return False, [], backup_journal
2323 +
2324 + # Odbuduj cache ikon GTK dla motywów dotkniętych instalacją.
2325 + # Bez icon-theme.cache aplikacje GTK nie widzą ikon mimo obecności
2326 + # motywu (np. /usr/share/icons/Papirus). Pomijamy, gdy narzędzie
2327 + # nie jest zainstalowane.
2328 + _icon_dirs = set()
2329 + for f in installed_files:
2330 + fp = f.get("path", "") or ""
2331 + if fp.startswith("/usr/share/icons/"):
2332 + _rest = fp[len("/usr/share/icons/"):]
2333 + _theme = _rest.split("/", 1)[0]
2334 + if _theme:
2335 + _icon_dirs.add(os.path.join(PAG_ROOT, "usr/share/icons", _theme))
2336 + if _icon_dirs:
2337 + try:
2338 + subprocess.run(["gtk-update-icon-cache", "--version"],
2339 + capture_output=True, timeout=10)
2340 + for _d in sorted(_icon_dirs):
2341 + if os.path.isdir(_d):
2342 + subprocess.run(["gtk-update-icon-cache", "-f", "-q", _d],
2343 + capture_output=True, timeout=300)
2344 + except Exception:
2345 + pass
2346 +
2347 + # Uruchom hooki post-install
2348 + hooks_dir = os.path.join(staging, "hooks")
2349 + _run_hook(hooks_dir, "post-install", pkg)
2350 +
2351 + # Zachowaj hooki na wypadek usunięcia pakietu (pre/post-remove)
2352 + try:
2353 + if os.path.isdir(hooks_dir):
2354 + persisted = os.path.join(PAG_DB, "hooks", pkg.name)
2355 + shutil.rmtree(persisted, ignore_errors=True)
2356 + shutil.copytree(hooks_dir, persisted)
2357 + except Exception:
2358 + pass
2359 +
2360 + # Zapisz do SQLite
2361 + _db_record_files(pkg.name, installed_files)
2362 +
2363 + shutil.rmtree(staging, ignore_errors=True)
2364 + return True, installed_files, backup_journal
2365 +
2366 + except Exception as e:
2367 + _rollback_journal(journal, staging)
2368 + return False, [], backup_journal
2369 +
2370 +
2371 +def _refresh_dynamic_linker_cache(deploy_dir: str = "") -> bool:
2372 + """Odświeża cache ld.so po udanej instalacji pakietów."""
2373 + ldconfig = shutil.which("ldconfig")
2374 + if not ldconfig:
2375 + print(" ⚠ Nie znaleziono ldconfig — cache linkera nie został odświeżony.",
2376 + file=sys.stderr)
2377 + return False
2378 +
2379 + target_root = deploy_dir or PAG_ROOT
2380 + command = [ldconfig]
2381 + if target_root != "/":
2382 + command.extend(["-r", target_root])
2383 +
2384 + try:
2385 + subprocess.run(command, check=True, timeout=60,
2386 + stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
2387 + text=True)
2388 + return True
2389 + except (OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc:
2390 + detail = getattr(exc, "stderr", None) or str(exc)
2391 + print(f" ⚠ Nie udało się odświeżyć cache'a ld.so: {detail.strip()}",
2392 + file=sys.stderr)
2393 + return False
2394 +
2395 +
2396 +def _rollback_journal(journal: list, staging_path: str):
2397 + """Cofa wszystkie operacje z journala (odwrotna kolejność)."""
2398 + for entry in reversed(journal):
2399 + op = entry[0]
2400 + if op == "file":
2401 + _, src, dst = entry
2402 + try:
2403 + if os.path.exists(dst) or os.path.islink(dst):
2404 + _safe_rename(dst, src)
2405 + except Exception:
2406 + pass
2407 + elif op == "symlink":
2408 + _, _, dst = entry
2409 + try:
2410 + if os.path.islink(dst) or os.path.exists(dst):
2411 + os.remove(dst)
2412 + except Exception:
2413 + pass
2414 + elif op == "backup":
2415 + # Przywróć starą wersję pliku z backupu (upgrade)
2416 + _, bpath, dst = entry
2417 + try:
2418 + if os.path.lexists(bpath):
2419 + os.replace(bpath, dst)
2420 + except Exception:
2421 + pass
2422 + shutil.rmtree(staging_path, ignore_errors=True)
2423 +
2424 +# =============================================================================
2425 +# BEZPIECZNE USUWANIE
2426 +# =============================================================================
2427 +
2428 +def _safe_remove_files(pkg_name: str, installed_db: dict) -> Tuple[int, List[str]]:
2429 + """
2430 + Usuwa pliki pakietu, ale tylko jeśli NIE są współdzielone z innym pakietem.
2431 + Zwraca (liczba usuniętych, [lista usuniętych ścieżek]).
2432 + """
2433 + pkg_files = _db_get_package_files(pkg_name)
2434 + recorded = _db_get_package_checksums(pkg_name)
2435 + removed = []
2436 + skipped_shared = []
2437 + skipped_sensitive = []
2438 +
2439 + for fpath in pkg_files:
2440 + owners = _db_get_file_owners(fpath)
2441 + # Sprawdź czy inny ZAINSTALOWANY pakiet też jest właścicielem
2442 + other_owners = [o for o in owners if o != pkg_name and o in installed_db]
2443 +
2444 + if other_owners:
2445 + # Plik współdzielony – tylko usuń wpis w DB, nie kasuj pliku
2446 + skipped_shared.append(fpath)
2447 + continue
2448 +
2449 + full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
2450 + if os.path.isfile(full) or os.path.islink(full):
2451 + # Wrażliwej konfiguracji systemowej (/etc/pam.d, sudoers, shadow…)
2452 + # NIE kasujemy przy `remove` – jej brak potrafi zablokować logowanie
2453 + # i sudo (np. usunięcie system-auth/system-account). Zostaje wpis w bazie.
2454 + if _is_sensitive_config(fpath):
2455 + skipped_sensitive.append(fpath)
2456 + continue
2457 + # .pacsave: zachowaj ZMIENIONY plik konfiguracyjny zamiast kasować
2458 + # (porównanie z sumą z chwili instalacji), wzorzec jak w pacmanie.
2459 + if not os.path.islink(full) and _is_config_path(fpath):
2460 + old_sha = recorded.get(fpath, "")
2461 + if old_sha:
2462 + try:
2463 + cur_sha = _sha256_file(full)
2464 + except OSError:
2465 + cur_sha = ""
2466 + if cur_sha and cur_sha != old_sha:
2467 + pacsave = full + ".pacsave"
2468 + try:
2469 + os.replace(full, pacsave)
2470 + print(f" ⚠ {_('conf_pacsave', path=pacsave)}")
2471 + removed.append(fpath)
2472 + continue
2473 + except OSError:
2474 + pass
2475 + os.remove(full)
2476 + removed.append(fpath)
2477 +
2478 + # Usuń puste katalogi (od najgłębszych)
2479 + dirs = set()
2480 + for fpath in removed + skipped_shared:
2481 + parent = os.path.dirname(fpath)
2482 + while parent and parent != "/":
2483 + dirs.add(parent)
2484 + parent = os.path.dirname(parent)
2485 +
2486 + for d in sorted(dirs, key=len, reverse=True):
2487 + full_d = os.path.join(PAG_ROOT, d.lstrip("/"))
2488 + if os.path.isdir(full_d):
2489 + try:
2490 + os.rmdir(full_d)
2491 + except OSError:
2492 + pass # nie jest pusty – OK
2493 +
2494 + # Usuń z SQLite
2495 + _db_remove_package_files(pkg_name)
2496 +
2497 + if skipped_shared:
2498 + print(f" ⚠ {len(skipped_shared)} plików współdzielonych zachowanych")
2499 + if skipped_sensitive:
2500 + print(f" ⚠ {len(skipped_sensitive)} wrażliwych plików systemowych zachowanych")
2501 +
2502 + return len(removed) + len(skipped_shared) + len(skipped_sensitive), removed
2503 +
2504 +
2505 +def _remove_stale_files(pkg_name: str, old_files: List[str], new_paths: List[str],
2506 + installed_db: dict, deploy_dir: str = "",
2507 + backup_dir: str = "", backup_journal: Optional[list] = None) -> Tuple[int, List[str]]:
2508 + """
2509 + Po upgrade usuwa pliki starej wersji, których nie ma w nowej.
2510 +
2511 + - Pliki współdzielone z innym zainstalowanym pakietem są ZACHOWYWANE
2512 + (usuwany jest tylko wpis z bazy `files` dla tego pakietu).
2513 + - Sprząta puste katalogi i wpisy SQLite starej wersji.
2514 + Zwraca (liczba usuniętych, [usunięte ścieżki]).
2515 + """
2516 + new_set = set(new_paths)
2517 + stale = [f for f in old_files if f not in new_set]
2518 + if not stale:
2519 + return 0, []
2520 +
2521 + root = deploy_dir or PAG_ROOT
2522 + removed = []
2523 + skipped = 0
2524 + for fpath in stale:
2525 + owners = _db_get_file_owners(fpath)
2526 + other_owners = [o for o in owners if o != pkg_name and o in installed_db]
2527 + if other_owners:
2528 + # Współdzielony z innym pakietem – tylko usuń wpis z DB dla tego pakietu
2529 + skipped += 1
2530 + else:
2531 + # Wrażliwych plików systemowych NIE kasujemy, gdy nowy pakiet ich już
2532 + # nie dostarcza (np. shadow przestaje pakować system-*). Ich brak
2533 + # blokuje login/sudo; usuwamy więc tylko wpis w bazie.
2534 + if _is_sensitive_config(fpath):
2535 + skipped += 1
2536 + else:
2537 + # Gdy nowa wersja pliku /etc trafiła do .pacnew, plik użytkownika
2538 + # MUSI zostać – nie jest „przestarzały”. Zachowujemy też wpis w bazie
2539 + # (stara suma), by kolejny upgrade dalej wykrywał zmiany użytkownika.
2540 + if _is_config_path(fpath):
2541 + _cfg_full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
2542 + if os.path.lexists(_cfg_full + ".pacnew"):
2543 + skipped += 1
2544 + continue
2545 + full = os.path.join(root, fpath.lstrip("/"))
2546 + if os.path.isfile(full) or os.path.islink(full):
2547 + try:
2548 + if backup_dir and backup_journal is not None:
2549 + backup_path = os.path.join(backup_dir, fpath.lstrip("/"))
2550 + os.makedirs(os.path.dirname(backup_path), exist_ok=True)
2551 + os.replace(full, backup_path) # przenieś do backupu (rollback)
2552 + backup_journal.append((backup_path, fpath))
2553 + else:
2554 + os.remove(full)
2555 + removed.append(fpath)
2556 + except OSError:
2557 + pass
2558 + # Usuń wpis `files` dla tego pakietu (stara wersja już go nie zawiera)
2559 + with _db_session() as db:
2560 + db.execute("DELETE FROM files WHERE package=? AND path=?", (pkg_name, fpath))
2561 +
2562 + # Usuń puste katalogi (od najgłębszych)
2563 + dirs = set()
2564 + for fpath in removed:
2565 + parent = os.path.dirname(fpath)
2566 + while parent and parent != "/":
2567 + dirs.add(parent)
2568 + parent = os.path.dirname(parent)
2569 + for d in sorted(dirs, key=len, reverse=True):
2570 + full_d = os.path.join(root, d.lstrip("/"))
2571 + if os.path.isdir(full_d):
2572 + try:
2573 + os.rmdir(full_d)
2574 + except OSError:
2575 + pass # nie jest pusty – OK
2576 +
2577 + if removed:
2578 + print(f" 🧹 Usunięto {len(removed)} nieaktualnych plików ({pkg_name})")
2579 + if skipped:
2580 + print(f" ⚠ {skipped} plików współdzielonych zachowanych")
2581 +
2582 + return len(removed), removed
2583 +
2584 +
2585 +def _new_transaction_backup_root() -> str:
2586 + """Katalog na backupy NADPISYWANYCH plików dla bieżącej transakcji.
2587 +
2588 + Tworzony dla KAŻDEJ transakcji, nie tylko upgrade: „świeża” instalacja
2589 + pakietu też potrafi nadpisać pliki spoza bazy pag (baza rootfs/ISO).
2590 + Gdy transakcja padnie, rollback MUSI mieć co przywrócić – inaczej kasuje
2591 + te pliki (tak zniknął m.in. libpam.so.0 i przestał działać sudo)."""
2592 + txn = datetime.now().strftime("%Y%m%dT%H%M%S") + "-" + str(os.getpid())
2593 + root = os.path.join(STAGING_DIR, "backups", txn)
2594 + os.makedirs(root, exist_ok=True)
2595 + return root
2596 +
2597 +
2598 +def _purge_old_backups(keep_root: str = ""):
2599 + """Usuwa backupy starszych transakcji (zostawia bieżący – dla `pag rollback`)."""
2600 + base = os.path.join(STAGING_DIR, "backups")
2601 + if not os.path.isdir(base):
2602 + return
2603 + for entry in os.listdir(base):
2604 + p = os.path.join(base, entry)
2605 + if p != keep_root and os.path.isdir(p):
2606 + shutil.rmtree(p, ignore_errors=True)
2607 +
2608 +# =============================================================================
2609 +# HOOKI
2610 +# =============================================================================
2611 +# Hooki uruchamiają dowolny plik z pakietu jako root — to naturalna cecha
2612 +# menedżera pakietów (apt/pacman też tak mają), dlatego MUSISZ ufać repozytorium.
2613 +# Aby ograniczyć ryzyko:
2614 +# - hook dostaje minimalne, "czyste" środowisko (bez LD_PRELOAD, BASH_ENV itp.)
2615 +# - hooki można wyłączyć (PAG_NO_HOOKS=1) i ustawić timeout (PAG_HOOK_TIMEOUT)
2616 +# - każde uruchomienie jest logowane do /var/log/pag/audit.log
2617 +# - hook ma wersjonowane API (PKG_HOOK_API)
2618 +# =============================================================================
2619 +
2620 +# Lista wykonanych hooków — trafia do wpisu transakcji (informacja w rejestrze).
2621 +_HOOKS_RUN: List[str] = []
2622 +
2623 +
2624 +def _hook_env(pkg: PackageInfo, hook_name: str) -> dict:
2625 + """Buduje minimalne środowisko dla hooka (bez niebezpiecznych zmiennych)."""
2626 + return {
2627 + "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
2628 + "HOME": "/root",
2629 + "LANG": "C.UTF-8",
2630 + "LC_ALL": "C.UTF-8",
2631 + "PKG_NAME": pkg.name,
2632 + "PKG_VERSION": pkg.version,
2633 + "PKG_ACTION": hook_name,
2634 + "PKG_HOOK_API": HOOK_API_VERSION,
2635 + }
2636 +
2637 +
2638 +def _hook_timeout() -> int:
2639 + try:
2640 + return max(1, int(os.environ.get("PAG_HOOK_TIMEOUT", "60")))
2641 + except Exception:
2642 + return 60
2643 +
2644 +
2645 +def _run_hook(hooks_dir: str, hook_name: str, pkg: PackageInfo) -> bool:
2646 + """Uruchamia skrypt hooka jeśli istnieje.
2647 +
2648 + Zwraca True jeśli hook został WYKONANY (istniał i uruchomiono go), False w
2649 + pozostałych przypadkach (brak pliku, wyłączone hooki, błąd). Obsługuje
2650 + ograniczone środowisko, timeout, logowanie do audytu i rejestr w transakcji.
2651 + """
2652 + hook_path = os.path.join(hooks_dir, hook_name)
2653 + if not os.path.exists(hook_path):
2654 + return False
2655 +
2656 + if os.environ.get("PAG_NO_HOOKS", "") == "1":
2657 + print(f" ⚠ Hook pominięty (PAG_NO_HOOKS=1): {hook_name} dla {pkg.name}")
2658 + _audit(f"hook SKIP {hook_name} {pkg.name}-{pkg.version} (PAG_NO_HOOKS=1)")
2659 + return False
2660 +
2661 + os.chmod(hook_path, 0o755)
2662 + env = _hook_env(pkg, hook_name)
2663 + tag = f"{hook_name} {pkg.name}-{pkg.version}"
2664 + try:
2665 + result = subprocess.run([hook_path], env=env, timeout=_hook_timeout(),
2666 + check=False, capture_output=True, text=True,
2667 + cwd="/")
2668 + _HOOKS_RUN.append(tag)
2669 + if result.returncode != 0:
2670 + print(f" ⚠ Hook {hook_name} dla {pkg.name} zakończony z kodem {result.returncode}")
2671 + if result.stderr:
2672 + print(f" {result.stderr.strip()[-200:]}")
2673 + _audit(f"hook FAIL {tag} rc={result.returncode}")
2674 + else:
2675 + _audit(f"hook OK {tag}")
2676 + return True
2677 + except subprocess.TimeoutExpired:
2678 + print(f" ⚠ Hook {hook_name} dla {pkg.name} przekroczył timeout ({_hook_timeout()}s)")
2679 + _audit(f"hook TIMEOUT {tag}")
2680 + return False
2681 + except Exception as e:
2682 + print(f" ⚠ Hook {hook_name} dla {pkg.name}: {e}")
2683 + _audit(f"hook ERROR {tag}: {e}")
2684 + return False
2685 +
2686 +# =============================================================================
2687 +# TRANSAKCJE I ROLLBACK
2688 +# =============================================================================
2689 +
2690 +def _record_transaction(action, packages, success, snapshot, file_journal=None, hooks=None,
2691 + upgrade_backups=None, upgrade_backup_root=""):
2692 + history = load_json(HISTORY_FILE) if os.path.exists(HISTORY_FILE) else []
2693 + # Rejestr wykonanych hooków – informacja o tym, że uruchomiono kod pakietu
2694 + # jako root. Trafia do historii, by dało się później sprawdzić, co się działo.
2695 + executed_hooks = list(_HOOKS_RUN) if hooks is None else hooks
2696 + _HOOKS_RUN.clear()
2697 + entry = {
2698 + "action": action, "packages": packages, "success": success,
2699 + "timestamp": datetime.now().isoformat(),
2700 + "snapshot": snapshot,
2701 + "file_journal": file_journal, # lista plików do wycofania
2702 + "hooks": executed_hooks, # wykonane hooki (pre/post-install/remove)
2703 + }
2704 + if upgrade_backups:
2705 + entry["upgrade_backups"] = upgrade_backups # {dst: backup_path}
2706 + entry["upgrade_backup_root"] = upgrade_backup_root
2707 + history.append(entry)
2708 + if len(history) > 50:
2709 + history = history[-50:]
2710 + save_json(HISTORY_FILE, history)
2711 +
2712 +def cmd_history():
2713 + if not os.path.exists(HISTORY_FILE):
2714 + print(_("no_history")); return
2715 + history = load_json(HISTORY_FILE)
2716 + if not history:
2717 + print(_("no_history")); return
2718 + print(f"Ostatnie transakcje ({len(history)}):")
2719 + for i, e in enumerate(reversed(history), 1):
2720 + icon = "✅" if e["success"] else "❌"
2721 + pkgs = ", ".join(e["packages"][:5])
2722 + if len(e["packages"]) > 5: pkgs += f" (+{len(e['packages'])-5})"
2723 + print(f" {i}. {icon} {e['action']}: {pkgs}")
2724 + print(f" {e['timestamp']}")
2725 +
2726 +def cmd_rollback():
2727 + if not os.path.exists(HISTORY_FILE):
2728 + print(_("no_history")); return 1
2729 + history = load_json(HISTORY_FILE)
2730 + if not history:
2731 + print(_("no_history")); return 1
2732 +
2733 + last = None
2734 + for e in reversed(history):
2735 + if e["success"] and e.get("snapshot"):
2736 + last = e; break
2737 +
2738 + if not last:
2739 + print("❌ No snapshot to restore."); return 1
2740 +
2741 + print(f"⏪ Rolling back: {last['action']} ({last['timestamp']})")
2742 + print(f" Packages: {', '.join(last['packages'][:10])}")
2743 +
2744 + if not _ask_confirm():
2745 + return 0
2746 +
2747 + # Przywróć installed.json
2748 + save_json(INSTALLED_DB, last["snapshot"])
2749 +
2750 + # Wycofaj fizyczne pliki (jeśli zapisano journal)
2751 + # Deduplikacja: pakiet może zgłosić ten sam plik więcej niż raz (np. przez
2752 + # `provides` lub wspólną ścieżkę), a journal z historii mógł zostać zapisany
2753 + # przed dodaniem deduplikacji.
2754 + file_journal = list(dict.fromkeys(last.get("file_journal", [])))
2755 + upgrade_backups = last.get("upgrade_backups", {}) or {}
2756 + backup_root = last.get("upgrade_backup_root", "")
2757 +
2758 + # Przywróć stare wersje z backupów (upgrade) – nadpisane i usunięte stale pliki
2759 + for dst, bpath in upgrade_backups.items():
2760 + full = os.path.join(PAG_ROOT, dst.lstrip("/"))
2761 + if bpath and os.path.lexists(bpath):
2762 + try:
2763 + os.makedirs(os.path.dirname(full), exist_ok=True)
2764 + os.replace(bpath, full)
2765 + except OSError:
2766 + pass
2767 +
2768 + # Usuń nowe pliki (które nie miały poprzedniej wersji)
2769 + backed = set(upgrade_backups)
2770 + if file_journal:
2771 + for fpath in reversed(file_journal):
2772 + if fpath in backed:
2773 + continue
2774 + full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
2775 + if os.path.exists(full) or os.path.islink(full):
2776 + os.remove(full)
2777 + print(f" {_('rollback_files', len(file_journal))}")
2778 +
2779 + # Sprzątanie pustych katalogów + katalogu backupów
2780 + dirs = set()
2781 + for fpath in file_journal:
2782 + parent = os.path.dirname(fpath)
2783 + while parent and parent != "/":
2784 + dirs.add(parent)
2785 + parent = os.path.dirname(parent)
2786 + for d in sorted(dirs, key=len, reverse=True):
2787 + full_d = os.path.join(PAG_ROOT, d.lstrip("/"))
2788 + if os.path.isdir(full_d):
2789 + try:
2790 + os.rmdir(full_d)
2791 + except OSError:
2792 + pass
2793 + if backup_root:
2794 + shutil.rmtree(backup_root, ignore_errors=True)
2795 +
2796 + print(f"✅ {_('rollback_restored')}")
2797 + _record_transaction("rollback", last["packages"], True, None)
2798 + return 0
2799 +
2800 +# =============================================================================
2801 +# INSTALACJA
2802 +# =============================================================================
2803 +
2804 +def _install_local_pkg_files(paths, install_succeeded):
2805 + """Instaluje lokalne pliki .pkg.tar.xz (bez repozytorium).
2806 + Zgodnie z _atomic_install każdy plik jest instalowany atomowo.
2807 + Zwraca (failed_count, installed_files)."""
2808 + failed = 0
2809 + all_files = []
2810 + for p in paths:
2811 + p = os.path.abspath(p)
2812 + if not os.path.isfile(p):
2813 + print(f" ❌ Nie znaleziono pakietu: {p}")
2814 + failed += 1
2815 + continue
2816 + if not _verify_local_pkg_signature(p):
2817 + failed += 1
2818 + continue
2819 + try:
2820 + with tarfile.open(p, "r:xz") as tf:
2821 + meta = tf.extractfile("metadata.json")
2822 + if meta is None:
2823 + print(f" ❌ {p}: brak metadata.json")
2824 + failed += 1
2825 + continue
2826 + data = json.loads(meta.read())
2827 + except Exception as e:
2828 + print(f" ❌ {p}: nie udało się odczytać pakietu ({e})")
2829 + failed += 1
2830 + continue
2831 + pkg = PackageInfo(data, repo="local")
2832 + print(f" ↓ {pkg.name}-{pkg.version} (lokalny) ... ", end="", flush=True)
2833 + ok, files, _ = _atomic_install(p, pkg)
2834 + if ok:
2835 + install_succeeded(pkg, files)
2836 + all_files.extend(f["path"] for f in files)
2837 + print("✅")
2838 + else:
2839 + print("❌")
2840 + failed += 1
2841 + return failed, all_files
2842 +
2843 +
2844 +def _preflight_disk(total_bytes: int) -> bool:
2845 + """Pre-flight przed transakcją: wolne miejsce + mount read-only.
2846 +
2847 + Zwraca False (przerywa instalację) gdy na partycji docelowej brakuje
2848 + miejsca na pakiety albo katalog stagingu jest zamontowany read-only
2849 + (inaczej instalacja rwałaby się w połowie, zostawiając uszkodzony system).
2850 + """
2851 + target = PAG_ROOT or "/"
2852 + try:
2853 + st = os.statvfs(target)
2854 + free = st.f_bavail * st.f_frsize
2855 + except OSError:
2856 + return True # nie da się sprawdzić – nie blokuj
2857 + need_mb = total_bytes // 1048576
2858 + free_mb = free // 1048576
2859 + if free < total_bytes:
2860 + print(f" ❌ Za mało miejsca na dysku: potrzeba ~{need_mb} MB, "
2861 + f"wolne {free_mb} MB ({target})")
2862 + return False
2863 + if free < total_bytes * 3:
2864 + print(f" ⚠ Mało miejsca na dysku: wolne {free_mb} MB, "
2865 + f"pakiety ~{need_mb} MB (rozpakowane zajmą więcej)")
2866 + # Wykryj mount read-only (test zapisu w stagingu)
2867 + try:
2868 + probe = os.path.join(STAGING_DIR, ".pag-probe")
2869 + with open(probe, "w") as f:
2870 + f.write("x")
2871 + os.remove(probe)
2872 + except OSError:
2873 + print(f" ❌ {target} jest zamontowane tylko-do-odczytu – nie można instalować.")
2874 + return False
2875 + return True
2876 +
2877 +
2878 +def cmd_install(package_names, as_dep=False, upgrade=False):
2879 + ensure_dirs()
2880 + installed_db = load_json(INSTALLED_DB)
2881 + world = load_world()
2882 + pinned = load_json(PINNED_FILE)
2883 +
2884 + # Obsługa lokalnych plików .pkg.tar.xz (zbudowanych przez pagbuild) –
2885 + # nie wymaga repozytorium ani GPG.
2886 + local_files = [p for p in package_names if p.endswith(PKG_EXT) or
2887 + (os.sep in p and os.path.isfile(os.path.abspath(p)))]
2888 + if local_files:
2889 + _local_need = sum(
2890 + os.path.getsize(os.path.abspath(p))
2891 + for p in local_files if os.path.isfile(os.path.abspath(p))
2892 + )
2893 + if not _preflight_disk(_local_need):
2894 + return 1
2895 +
2896 + def _ok(pkg, files):
2897 + installed_db[pkg.name] = {
2898 + "version": pkg.version, "release": pkg.release, "description": pkg.description,
2899 + "dependencies": pkg.dependencies, "size_bytes": pkg.size_bytes,
2900 + "sha256": pkg.sha256, "installed_at": datetime.now().isoformat(),
2901 + "repo": "local",
2902 + "provides": getattr(pkg, "provides", None) or [],
2903 + "provides_so": getattr(pkg, "provides_so", None) or [],
2904 + "requires_so": getattr(pkg, "requires_so", None) or [],
2905 + }
2906 + world.add(pkg.name)
2907 + failed_local, _fl = _install_local_pkg_files(local_files, _ok)
2908 + save_json(INSTALLED_DB, installed_db)
2909 + save_world(world)
2910 + if failed_local:
2911 + return 1
2912 + _refresh_dynamic_linker_cache()
2913 + package_names = [n for n in package_names if n not in
2914 + [os.path.abspath(x) for x in local_files] and
2915 + n not in local_files]
2916 + to_install = []
2917 + if not package_names:
2918 + return 0
2919 + # pozostałe argumenty to nazwy pakietów z repo – kontynuuj
2920 +
2921 + repo_pkgs = fetch_all_packages()
2922 +
2923 + if not repo_pkgs:
2924 + print(f"❌ {_('no_index')}"); return 1
2925 +
2926 + for name in list(package_names):
2927 + if name in pinned:
2928 + print(f"⚠ {name} {_('pinned_to')} {pinned[name]} – skipping")
2929 + package_names.remove(name)
2930 +
2931 + to_install, missing_deps = _resolve_deps(package_names, repo_pkgs, installed_db)
2932 +
2933 + # ── Pakiety, których NIE MA w repo ani nie są zainstalowane ──
2934 + # Zgłoś od razu zamiast mylącego „Do zainstalowania: N (0.00 MB)”
2935 + # i prośby o potwierdzenie (np. `pag install steam` gdy steam nie istnieje).
2936 + not_found = []
2937 + for n in package_names:
2938 + real = _resolve_provides(n, repo_pkgs, installed_db)
2939 + if real not in repo_pkgs and real not in installed_db \
2940 + and not os.path.exists(os.path.abspath(n)):
2941 + not_found.append(n)
2942 + if not_found:
2943 + print(f"\n ❌ {_('pkg_not_found', ', '.join(not_found))}")
2944 + print(f" {_('not_found_hint')}")
2945 + return 1
2946 +
2947 + # --- Tryb upgrade: pakiety już zainstalowane MUSZĄ zostać ponownie
2948 + # zainstalowane z nowszej wersji (zastąpienie w tej samej transakcji).
2949 + if upgrade:
2950 + # `pag update` przekazuje tu tylko pakiety z NOWSZĄ wersją (już
2951 + # przefiltrowane w _pending_updates), a `pag install -f` wymusza
2952 + # reinstalację nawet tej SAMEJ wersji – dlatego nie filtrujemy po
2953 + # _version_newer.
2954 + upgrade_targets = [
2955 + name for name in package_names
2956 + if name in repo_pkgs
2957 + and name in installed_db
2958 + and name not in pinned
2959 + ]
2960 + for name in upgrade_targets:
2961 + if name not in to_install:
2962 + to_install.append(name)
2963 +
2964 + if not to_install and not missing_deps:
2965 + print(f"✅ {_('all_installed')}"); return 0
2966 +
2967 + # ── WERYFIKACJA ZALEŻNOŚCI ──────────────────────────────────────────
2968 + fatal_missing = _verify_dependencies(to_install, repo_pkgs, installed_db)
2969 +
2970 + if fatal_missing > 0:
2971 + print(f"❌ Nie można kontynuować – {fatal_missing} brakujących zależności.")
2972 + print(f" Zainstaluj brakujące pakiety lub dodaj repozytoria.")
2973 + return 1
2974 +
2975 + so_missing = _verify_so_deps(to_install, repo_pkgs, installed_db)
2976 + if so_missing > 0:
2977 + print(" Zainstaluj dostawcę biblioteki lub zaktualizuj repozytorium.")
2978 + return 1
2979 +
2980 + if not to_install:
2981 + print(f"✅ {_('all_installed')}"); return 0
2982 +
2983 + MAX_MB = MAX_PKG_SIZE // 1048576
2984 + for n in to_install:
2985 + if not _validate_pkg_name(n):
2986 + print(f" {_("sec_badname", name=n)}")
2987 + return 1
2988 + sz = repo_pkgs[n].size_bytes if n in repo_pkgs else 0
2989 + if sz > MAX_PKG_SIZE:
2990 + mb = sz // 1048576
2991 + print(f" {_("sec_toobig", size_mb=mb, max_mb=MAX_MB)}")
2992 + return 1
2993 + total_size = sum(repo_pkgs[n].size_bytes for n in to_install if n in repo_pkgs)
2994 + if not _preflight_disk(total_size):
2995 + return 1
2996 + print(f"\n📦 {_('to_install', len(to_install), total_size/1048576)}")
2997 + for name in to_install:
2998 + p = repo_pkgs.get(name)
2999 + if p:
3000 + if name in installed_db:
3001 + marker = " [upgrade]" if upgrade else ""
3002 + else:
3003 + marker = f" [{_('new')}]"
3004 + print(f" {name}-{p.version}{marker}")
3005 +
3006 + # Pakiet z bazy obrazu ISO (nie w installed.json) → ostrzeż, że pliki z ISO
3007 + # zostaną zastąpione pakietem z repo (kopia do `pag rollback`).
3008 + _base_warn_overwrite(to_install)
3009 +
3010 + if not as_dep and not upgrade:
3011 + if not _ask_confirm():
3012 + print(_("cancelled")); return 0
3013 +
3014 + snapshot = copy.deepcopy(installed_db)
3015 + all_installed_files = []
3016 + failed = []
3017 + # Pary (pkg, stare_pliki, nowe_pliki) do usunięcia martwych plików po upgrade
3018 + stale_candidates = []
3019 + # Katalog backupów nadpisywanych plików – dla poprawnego rollbacku.
3020 + # Dla KAŻDEJ transakcji: instalacja „nowego” pakietu także nadpisuje pliki
3021 + # spoza bazy pag (baza rootfs/ISO), a rollback bez backupu by je skasował.
3022 + backup_root = ""
3023 + all_backups: List[Tuple[str, str]] = [] # (backup_path, dst)
3024 + if to_install:
3025 + backup_root = _new_transaction_backup_root()
3026 +
3027 + # --- Dziennik transakcji (dla pełnej atomowości) ---
3028 + # Jeśli którykolwiek pakiet zawiedzie, cofamy WSZYSTKIE zainstalowane
3029 + # w tej transakcji przez _rollback_transaction().
3030 + transaction_journal: List[Tuple[str, str, str]] = [] # (op, src, dst)
3031 +
3032 + # --- Tryb immutable: utwórz nowy deployment ---
3033 + immutable = os.environ.get("PAG_IMMUTABLE", "") == "1"
3034 + deploy_dir = ""
3035 + deploy_id = ""
3036 + if immutable:
3037 + print(f"\n 🏗️ Tworzenie nowego deploymentu...")
3038 + deploy_dir, deploy_id = _create_deployment(to_install, "upgrade" if upgrade else "install")
3039 + target_root = deploy_dir
3040 + else:
3041 + target_root = ""
3042 +
3043 + # --- Faza 1: Równoległe pobieranie wszystkich pakietów ---
3044 + to_download = [repo_pkgs[name] for name in to_install if name in repo_pkgs]
3045 + if len(to_download) > 1:
3046 + print(f"\n ⏬ Pobieranie {len(to_download)} pakietów równolegle...")
3047 + downloaded = _download_packages_parallel(to_download)
3048 + else:
3049 + downloaded = {}
3050 +
3051 + # --- Faza 1b: WERYFIKACJA WSZYSTKICH paczek PRZED instalacją ---
3052 + # KLUCZOWE: GPG i SHA256 sprawdzamy dla WSZYSTKICH paczek, ZANIM
3053 + # zainstalujemy choćby jedną. Inaczej instalowany pakiet może podmienić
3054 + # bibliotekę używaną przez sam gpg (np. libassuan 3.0.1 zmienił namespace
3055 + # symboli LIBASSUAN_1.0 -> LIBASSUAN_2.0) i wtedy weryfikacja kolejnych
3056 + # paczek w tej samej transakcji pada, dając fałszywe
3057 + # „NIEPRAWIDŁOWY PODPIS GPG".
3058 + verified = {}
3059 + _vfail = []
3060 + for _name in to_install:
3061 + _pkg = repo_pkgs.get(_name)
3062 + if not _pkg:
3063 + _vfail.append((_name, _('not_found')))
3064 + continue
3065 + _pp = downloaded.get(_name)
3066 + if not _pp:
3067 + _pp = _download_pkg(_pkg)
3068 + if not _pp:
3069 + _vfail.append((_name, _('download_fail')))
3070 + continue
3071 + _gok, _gmsg = _verify_pkg_gpg(_pp, repo_url=_pkg.repo_url)
3072 + if not _gok:
3073 + _vfail.append((_name, f"{_('gpg_fail')}: {_gmsg[:60]}"))
3074 + continue
3075 + if _pkg.sha256 and _sha256_file(_pp) != _pkg.sha256:
3076 + _vfail.append((_name, _('sha256_mismatch')))
3077 + continue
3078 + verified[_name] = _pp
3079 + if _vfail:
3080 + for _n, _m in _vfail:
3081 + print(f" ❌ {_n}: {_m}")
3082 + print(" ↩ Przerwano PRZED instalacją – żadna paczka nie została zmieniona.")
3083 + return 1
3084 +
3085 + # --- Faza 2: Instalacja – JEDNA nadpisywana linia postępu (jak przy
3086 + # pobieraniu), bez ściany tekstu na każdy pakiet. W trybie
3087 + # nieinteraktywnym (logi, netinstall instalatora) wypisujemy linię na
3088 + # pakiet – tam to pożądane do logu.
3089 + t0 = time.time()
3090 + stdout_tty = sys.stdout.isatty()
3091 +
3092 + # Animowany pasek postępu („drakkar”) – jedna nadpisywana linia; morze
3093 + # faluje nawet wtedy, gdy pojedynczy pakiet instaluje się długo.
3094 + _pbar = _StepBar(len(to_install), icon="📦 ", width=25)
3095 +
3096 + def _bar_draw(idx: int, name: str) -> None:
3097 + _pbar.step(idx, name)
3098 +
3099 + def _bar_end() -> None:
3100 + _pbar.end()
3101 +
3102 + _pkg_i = 0
3103 + for name in to_install:
3104 + pkg = repo_pkgs.get(name)
3105 + if not pkg:
3106 + _bar_end()
3107 + print(f" ❌ {name}: {_('not_found')}")
3108 + failed.append(name)
3109 + break
3110 +
3111 + _pkg_i += 1
3112 + _bar_draw(_pkg_i, f"{name}-{pkg.version}")
3113 +
3114 + # Ścieżka pobrana i ZWERYFIKOWANA w fazie 1b – PRZED jakąkolwiek
3115 + # instalacją (patrz komentarz przy fazie 1b). Dzięki temu podmiana
3116 + # biblioteki używanej przez gpg nie psuje weryfikacji pozostałych.
3117 + pkg_path = verified.get(name)
3118 + if not pkg_path:
3119 + _bar_end()
3120 + print(f" ❌ {name}: {_('download_fail')}")
3121 + failed.append(name)
3122 + break # przerwij transakcję
3123 +
3124 + # Przed instalacją zapamiętaj pliki starej wersji (potrzebne w upgrade)
3125 + old_files = _db_get_package_files(name) if name in installed_db else []
3126 + # Stare sumy SHA256 – do wykrycia zmian użytkownika w plikach /etc (.pacnew)
3127 + old_checksums = _db_get_package_checksums(name) if name in installed_db else None
3128 +
3129 + # Atomowa instalacja (w upgrade backupuje nadpisywane pliki)
3130 + ok, files, backup_j = _atomic_install(pkg_path, pkg, deploy_dir,
3131 + backup_dir=backup_root,
3132 + old_checksums=old_checksums)
3133 + if ok:
3134 + installed_db[name] = {
3135 + "version": pkg.version, "release": pkg.release, "description": pkg.description,
3136 + "dependencies": pkg.dependencies, "size_bytes": pkg.size_bytes,
3137 + "sha256": pkg.sha256, "installed_at": datetime.now().isoformat(),
3138 + "repo": pkg.repo_url,
3139 + "provides": getattr(pkg, "provides", None) or [],
3140 + "provides_so": getattr(pkg, "provides_so", None) or [],
3141 + "requires_so": getattr(pkg, "requires_so", None) or [],
3142 + }
3143 + if not as_dep and name in package_names:
3144 + world.add(name)
3145 + if not stdout_tty:
3146 + print(f" ✓ {name}-{pkg.version}", flush=True)
3147 + all_installed_files.extend(f["path"] for f in files)
3148 + all_backups.extend(backup_j)
3149 +
3150 + # Upgrade: zapamiętaj stare pliki, by po sukcesie usunąć te,
3151 + # których nie ma już w nowej wersji.
3152 + if upgrade and old_files:
3153 + stale_candidates.append((name, old_files, [f["path"] for f in files]))
3154 +
3155 + # Po instalacji kernela – przebuduj initramfs
3156 + if _is_kernel_package(name):
3157 + _rebuild_initramfs(deploy_dir)
3158 + else:
3159 + _bar_end()
3160 + print(f" ❌ {name}: {_('install_failed')}")
3161 + failed.append(name)
3162 + break # PRZERWIJ – błąd instalacji
3163 +
3164 + # Deduplikacja journalu – ten sam plik może trafić tu dwukrotnie (np. przez
3165 + # `provides`); rollback i historia nie potrzebują duplikatów.
3166 + all_installed_files = list(dict.fromkeys(all_installed_files))
3167 +
3168 + # --- Rollback całej transakcji jeśli cokolwiek zawiodło ---
3169 + if failed:
3170 + _bar_end()
3171 + print(f"\n ↩ Cofanie transakcji ({len(failed)} błędów)...")
3172 + _rollback_transaction(installed_db, snapshot, all_installed_files,
3173 + deploy_dir, immutable, backups=all_backups)
3174 + if backup_root:
3175 + shutil.rmtree(backup_root, ignore_errors=True)
3176 + _record_transaction("upgrade" if upgrade else "install", to_install, False, snapshot)
3177 + return 1
3178 +
3179 + # --- Po sukcesie transakcji: usuń nieaktualne pliki starych wersji (upgrade).
3180 + # Usunięte pliki trafiają do backupu, aby `pag rollback` mógł je przywrócić.
3181 + for pkg_name, old_files, new_paths in stale_candidates:
3182 + _remove_stale_files(pkg_name, old_files, new_paths, installed_db, deploy_dir,
3183 + backup_root, all_backups)
3184 +
3185 + save_json(INSTALLED_DB, installed_db)
3186 + save_world(world)
3187 + _record_transaction("upgrade" if upgrade else "install", to_install, True, snapshot,
3188 + file_journal=all_installed_files,
3189 + upgrade_backups={dst: bp for bp, dst in all_backups} if all_backups else None,
3190 + upgrade_backup_root=backup_root)
3191 +
3192 + # Zachowaj backupy bieżącej transakcji (dla `pag rollback`), usuń starsze.
3193 + if backup_root:
3194 + _purge_old_backups(keep_root=backup_root)
3195 +
3196 + _bar_end()
3197 +
3198 + # --- Tryb immutable: przełącz na nowy deployment ---
3199 + if immutable and not failed:
3200 + _refresh_dynamic_linker_cache(deploy_dir)
3201 + print(f"\n 🔄 Przełączanie na deployment {deploy_id}...")
3202 + _switch_deployment(deploy_dir)
3203 + print(f" ✅ Aktywny deployment: {deploy_id}")
3204 + _update_grub_config()
3205 + cmd_deploy_cleanup(keep=5) # Zostawia 5 najnowszych deploymentów
3206 + print(f" 💡 Restart wymagany do przeładowania systemu.")
3207 + else:
3208 + _refresh_dynamic_linker_cache()
3209 + # Hooki zbiorcze – raz na transakcję (fc-cache itp.), tylko gdy pliki
3210 + # trafiły do realnego systemu (nie do deploymentu).
3211 + _process_triggers(all_installed_files)
3212 +
3213 + print(f"\n✅ {_('installed', len(to_install))} ({(time.time()-t0):.0f}s)")
3214 + return 0
3215 +
3216 +
3217 +def _rollback_transaction(installed_db: dict, snapshot: dict,
3218 + installed_files: List[str],
3219 + deploy_dir: str, is_immutable: bool,
3220 + backups: Optional[List[Tuple[str, str]]] = None):
3221 + """
3222 + Cofa WSZYSTKIE pakiety zainstalowane w bieżącej transakcji.
3223 + Przywraca installed_db do stanu sprzed transakcji.
3224 + Usuwa fizyczne pliki z systemu (lub deploymentu w trybie immutable).
3225 + Jeśli podano `backups` (upgrade) – przywraca stare wersje nadpisanych plików.
3226 + """
3227 + # Przywróć installed_db
3228 + installed_db.clear()
3229 + installed_db.update(snapshot)
3230 +
3231 + root = deploy_dir if is_immutable else PAG_ROOT
3232 + backup_map = {dst: src for src, dst in (backups or [])}
3233 +
3234 + # Przywróć stare wersje z backupów (upgrade)
3235 + for dst, bpath in backup_map.items():
3236 + full = os.path.join(root, dst.lstrip("/"))
3237 + if os.path.lexists(bpath):
3238 + try:
3239 + os.makedirs(os.path.dirname(full), exist_ok=True)
3240 + os.replace(bpath, full)
3241 + except OSError:
3242 + pass
3243 +
3244 + # Usuń nowe pliki (które nie miały poprzedniej wersji)
3245 + for fpath in reversed(installed_files):
3246 + if fpath in backup_map:
3247 + continue
3248 + full = os.path.join(root, fpath.lstrip("/"))
3249 + if os.path.isfile(full) or os.path.islink(full):
3250 + try:
3251 + os.remove(full)
3252 + except OSError:
3253 + pass
3254 +
3255 + # Wyczyść puste katalogi
3256 + dirs_to_check = set()
3257 + for fpath in installed_files:
3258 + parent = os.path.dirname(fpath)
3259 + while parent and parent != "/":
3260 + dirs_to_check.add(parent)
3261 + parent = os.path.dirname(parent)
3262 + for d in sorted(dirs_to_check, key=len, reverse=True):
3263 + full_d = os.path.join(root, d.lstrip("/"))
3264 + if os.path.isdir(full_d):
3265 + try:
3266 + os.rmdir(full_d)
3267 + except OSError:
3268 + pass
3269 +
3270 + # W trybie immutable: usuń nieudany deployment
3271 + if is_immutable and deploy_dir:
3272 + shutil.rmtree(deploy_dir, ignore_errors=True)
3273 +
3274 + save_json(INSTALLED_DB, snapshot)
3275 +
3276 +
3277 +# =============================================================================
3278 +# USUWANIE
3279 +# =============================================================================
3280 +
3281 +def cmd_remove(package_names):
3282 + installed_db = load_json(INSTALLED_DB)
3283 + world = load_world()
3284 + snapshot = copy.deepcopy(installed_db)
3285 + removed = []
3286 + removed_files = []
3287 +
3288 + total = len(package_names)
3289 + for i, name in enumerate(package_names, 1):
3290 + if name not in installed_db:
3291 + print(f" ⚠ {name}: not installed"); continue
3292 +
3293 + # Pasek postępu (animowany „drakkar” na TTY)
3294 + pct = (i - 1) / total * 100
3295 + bar = _pagan_bar(pct, 25, time.time(), animated=sys.stderr.isatty())
3296 + print(f" 🗑 [{bar}] {i}/{total} ({pct:.0f}%) ", end="\r", file=sys.stderr, flush=True)
3297 +
3298 + print(f"🗑 {name}-{installed_db[name]['version']} ...", end=" ", flush=True)
3299 +
3300 + # Pre-remove hook (jeśli dostępny w staging)
3301 + _run_hook_for_installed(name, "pre-remove")
3302 +
3303 + count, rm_files = _safe_remove_files(name, installed_db)
3304 + del installed_db[name]
3305 + world.discard(name)
3306 + removed.append(name)
3307 + removed_files.extend(rm_files)
3308 + print(f"✅ ({count} files)")
3309 +
3310 + # Post-remove hook + sprzątanie zapisanych hooków
3311 + _run_hook_for_installed(name, "post-remove")
3312 + shutil.rmtree(os.path.join(PAG_DB, "hooks", name), ignore_errors=True)
3313 +
3314 + save_json(INSTALLED_DB, installed_db)
3315 + save_world(world)
3316 + _record_transaction("remove", removed, True, snapshot)
3317 +
3318 + print(file=sys.stderr) # wyczyść linię paska postępu
3319 +
3320 + if not removed: return 0
3321 + print(f"\n✅ Removed {len(removed)}.")
3322 + _process_triggers(removed_files)
3323 +
3324 + orphans = _find_orphans(installed_db, world)
3325 + if orphans:
3326 + print(f"\n💡 {_('orphans_found', len(orphans), ', '.join(sorted(orphans)[:10]))}")
3327 + print(" 'pag remove-orphans' to clean up.")
3328 + return 0
3329 +
3330 +def _run_hook_for_installed(pkg_name, hook_name):
3331 + """Próbuje uruchomić hook z katalogu pakietu (jeśli został zapisany)."""
3332 + hook_dir = os.path.join(PAG_DB, "hooks", pkg_name)
3333 + if os.path.isdir(hook_dir):
3334 + ver = load_json(INSTALLED_DB).get(pkg_name, {}).get("version", "")
3335 + _run_hook(hook_dir, hook_name, PackageInfo({"name": pkg_name, "version": ver}))
3336 +
3337 +
3338 +# =============================================================================
3339 +# TRIGGERS – hooki zbiorcze (raz na transakcję, nie per pakiet)
3340 +# =============================================================================
3341 +# Wzorem pacman/dpkg: pakiet/administrator deklaruje zainteresowanie ścieżkami,
3342 +# a pasujący trigger uruchamia się DOKŁADNIE RAZ na końcu transakcji
3343 +# (np. fc-cache, glib-compile-schemas, update-desktop-database) zamiast po
3344 +# każdym pakiecie z osobna.
3345 +
3346 +TRIGGERS_DIR = PAG_CONF + "/triggers"
3347 +
3348 +DEFAULT_TRIGGERS = [
3349 + {"name": "font-cache", "paths": ["/usr/share/fonts/", "/usr/local/share/fonts/"],
3350 + "run": "fc-cache -fs"},
3351 + {"name": "glib-schemas", "paths": ["/usr/share/glib-2.0/schemas/"],
3352 + "run": "glib-compile-schemas /usr/share/glib-2.0/schemas"},
3353 + {"name": "desktop-database", "paths": ["/usr/share/applications/"],
3354 + "run": "update-desktop-database -q /usr/share/applications"},
3355 + {"name": "mime-database", "paths": ["/usr/share/mime/"],
3356 + "run": "update-mime-database /usr/share/mime"},
3357 +]
3358 +
3359 +def _load_triggers() -> List[dict]:
3360 + """Ładuje triggery: domyślne (tylko gdy binarka istnieje) + /etc/pag/triggers/*.json."""
3361 + out = []
3362 + for t in DEFAULT_TRIGGERS:
3363 + bin_name = t["run"].split()[0]
3364 + if shutil.which(bin_name):
3365 + out.append(dict(t))
3366 + if os.path.isdir(TRIGGERS_DIR):
3367 + for fn in sorted(os.listdir(TRIGGERS_DIR)):
3368 + if not fn.endswith(".json"):
3369 + continue
3370 + try:
3371 + with open(os.path.join(TRIGGERS_DIR, fn)) as f:
3372 + data = json.load(f)
3373 + except (OSError, json.JSONDecodeError):
3374 + continue
3375 + if isinstance(data, dict):
3376 + data = [data]
3377 + for t in data:
3378 + if isinstance(t, dict) and t.get("name") and t.get("paths") and t.get("run"):
3379 + out.append(t)
3380 + return out
3381 +
3382 +def _process_triggers(touched_paths: List[str]):
3383 + """Uruchamia pasujące triggery RAZ na końcu transakcji (best-effort)."""
3384 + if not touched_paths:
3385 + return
3386 + if os.environ.get("PAG_NO_HOOKS", "") == "1":
3387 + return
3388 + import shlex as _shlex
3389 + matched = []
3390 + for trig in _load_triggers():
3391 + if any(path.startswith(p) for p in trig["paths"] for path in touched_paths):
3392 + matched.append(trig)
3393 + for trig in matched:
3394 + run = trig["run"]
3395 + print(f" ⚡ Trigger: {trig['name']} ({run})")
3396 + try:
3397 + r = subprocess.run(_shlex.split(run), capture_output=True, text=True, timeout=120)
3398 + _audit(f"TRIGGER {trig['name']}: {run} rc={r.returncode}")
3399 + if r.returncode != 0:
3400 + print(f" ⚠ rc={r.returncode}: {(r.stderr or r.stdout or '').strip()[:160]}")
3401 + except subprocess.TimeoutExpired:
3402 + print(f" ⚠ trigger {trig['name']} przekroczył limit czasu (120 s)")
3403 + _audit(f"TRIGGER {trig['name']} TIMEOUT")
3404 + except Exception as e:
3405 + print(f" ⚠ trigger {trig['name']}: {e}")
3406 +
3407 +# =============================================================================
3408 +# UPDATE / UPGRADE / LIST / SEARCH / INFO / VERIFY
3409 +# =============================================================================
3410 +
3411 +def _cleanup_tmp_files(*paths):
3412 + """Usuwa tymczasowe pliki (np. .pag.new) po nieudanej operacji."""
3413 + for p in paths:
3414 + try:
3415 + if os.path.isfile(p):
3416 + os.remove(p)
3417 + except OSError:
3418 + pass
3419 +
3420 +
3421 +def cmd_self_update():
3422 + """Aktualizuje samego klienta pag z repo (podpisany /stable/pag).
3423 +
3424 + Kolejność: pobierz → weryfikacja GPG (+ fingerprint repo) → SHA256 →
3425 + kontrola składni (compile) → backup → atomowe os.replace.
3426 +
3427 + Podmieniamy plik, z którego pag ZOSTAŁ URUCHOMIONY (a nie hardkodowane
3428 + /usr/local/bin/pag): gdy pakiet instaluje /usr/bin/pag, a self-update
3429 + pisał do /usr/local/bin/pag, powstawały DWIE kopie o różnych wersjach
3430 + i zależnie od PATH `pag --version` pokazywał raz jedną, raz drugą."""
3431 + # Dedykowana blokada – patrz SelfUpdateLock. Chroni zapis dst.new oraz
3432 + # os.replace przed równoległą aktualizacją (np. cron + ręcznie).
3433 + with SelfUpdateLock():
3434 + return _self_update_impl()
3435 +
3436 +
3437 +def _self_update_impl():
3438 + repos = get_repos()
3439 + if not repos:
3440 + print("❌ Brak repozytoriów w konfiguracji.")
3441 + return 1
3442 + # Aktualizuj bieżący plik (Python ≥3.9 ustawia __file__ jako ścieżkę
3443 + # bezwzględną). Poza /usr|/usr/local (np. uruchomienie z checkoutu)
3444 + # nie nadpisujemy niczego – wracamy do domyślnej lokalizacji instalacji.
3445 + dst = "/usr/local/bin/pag"
3446 + try:
3447 + cand = os.path.realpath(__file__)
3448 + if cand.startswith(("/usr/", "/usr/local/")):
3449 + dst = cand
3450 + except Exception:
3451 + pass
3452 + base = repos[0]
3453 + dst_new = dst + ".new"
3454 + dst_bak = dst + ".bak"
3455 + print(f"🔄 Sprawdzam aktualizację pag z {base}...")
3456 + try:
3457 + with urlopen(Request(f"{base}/pag", headers={"User-Agent": "pag/3.0"}), timeout=20) as r:
3458 + data = r.read()
3459 + with urlopen(Request(f"{base}/pag.asc", headers={"User-Agent": "pag/3.0"}), timeout=20) as r:
3460 + sig = r.read()
3461 + except Exception as e:
3462 + print(f" ❌ Nie można pobrać pag: {e}")
3463 + return 1
3464 +
3465 + # Zapisz nową wersję w katalogu docelowym (ta sama partycja → atomowy rename)
3466 + with open(dst_new, "wb") as f:
3467 + f.write(data)
3468 + with open(dst_new + ".asc", "wb") as f:
3469 + f.write(sig)
3470 +
3471 + # --- 1. Weryfikacja podpisu GPG – bez tego nie instalujemy ---
3472 + insecure = os.environ.get("PAG_INSECURE", "") == "1"
3473 + ok, fp = _gpg_verify_fp(dst_new + ".asc", dst_new)
3474 + if not ok:
3475 + # Automatyczny import klucza (TOFU) – jak w _verify_repo_sig
3476 + res = _gpg_run("--verify", dst_new + ".asc", dst_new,
3477 + capture_output=True, text=True)
3478 + _stderr = res.stderr.decode(errors="replace") if isinstance(res.stderr, bytes) else (res.stderr or "")
3479 + if "public key" in _stderr.lower() and "no public key" in _stderr.lower():
3480 + try:
3481 + with urlopen(Request(f"{base}/paganos.asc", headers={"User-Agent": "pag/3.0"}), timeout=20) as r:
3482 + keydata = r.read()
3483 + with tempfile.NamedTemporaryFile(delete=False, suffix=".asc") as tmp:
3484 + tmp.write(keydata); tmp.flush()
3485 + _gpg_run("--import", tmp.name, capture_output=True, timeout=30)
3486 + os.unlink(tmp.name)
3487 + print(f" 🔑 Importowano klucz repo z {base}/paganos.asc")
3488 + ok, fp = _gpg_verify_fp(dst_new + ".asc", dst_new)
3489 + except Exception:
3490 + pass
3491 + if not ok:
3492 + if insecure:
3493 + print(" ⚠ Nieprawidłowy podpis aktualizacji (PAG_INSECURE – ignoruję)")
3494 + else:
3495 + print(" ❌ Nieprawidłowy podpis aktualizacji – nie aktualizuję.")
3496 + _cleanup_tmp_files(dst_new, dst_new + ".asc")
3497 + return 1
3498 + # Sprawdź fingerprint względem przypiętego klucza repo
3499 + pinned = _repo_pinned_fp(base)
3500 + if pinned:
3501 + if not fp:
3502 + print(" ❌ Nie można potwierdzić fingerprintu podpisu aktualizacji.")
3503 + _cleanup_tmp_files(dst_new, dst_new + ".asc")
3504 + return 1
3505 + if fp != pinned.upper():
3506 + if insecure:
3507 + print(" ⚠ Podpis aktualizacji innym kluczem (PAG_INSECURE – ignoruję)")
3508 + else:
3509 + print(" ❌ [SECURITY ERROR] Podpis aktualizacji innym kluczem niż repo!")
3510 + print(f" Oczekiwany: {pinned}, Otrzymany: {fp}")
3511 + _cleanup_tmp_files(dst_new, dst_new + ".asc")
3512 + return 1
3513 +
3514 + # --- 2. Weryfikacja SHA256 (jeśli repo publikuje pag.sha256) ---
3515 + try:
3516 + with urlopen(Request(f"{base}/pag.sha256", headers={"User-Agent": "pag/3.0"}), timeout=15) as r:
3517 + sha = r.read().decode().strip().split()[0]
3518 + if sha:
3519 + actual = hashlib.sha256(data).hexdigest()
3520 + if actual.lower() != sha.lower():
3521 + print(f" ❌ SHA256 niezgodny! Oczekiwano {sha}, jest {actual}")
3522 + _cleanup_tmp_files(dst_new, dst_new + ".asc")
3523 + return 1
3524 + print(" ✅ SHA256 zgodny")
3525 + except Exception:
3526 + # Brak pag.sha256 w repo – opcjonalne; nie blokuj aktualizacji.
3527 + pass
3528 +
3529 + # --- 3. Kontrola składni (nie uruchamiaj uszkodzonego/poddanego edycji pliku) ---
3530 + try:
3531 + compile(data, "pag", "exec")
3532 + except SyntaxError as e:
3533 + print(f" ❌ Błąd składni w nowym pag: {e}")
3534 + _cleanup_tmp_files(dst_new, dst_new + ".asc")
3535 + return 1
3536 +
3537 + m = (re.search(rb'PAG_VERSION\s*=\s*"(\d+\.\d+\.\d+[a-z]?)"', data[:3000])
3538 + or re.search(rb"v(\d+\.\d+\.\d+[a-z]?)", data[:3000]))
3539 + new_ver = m.group(1).decode() if m else "?"
3540 + print(f" ✅ Pobrano pag {new_ver} (obecny {PAG_VERSION}), podpis zweryfikowany")
3541 +
3542 + # --- 4. Backup + atomowa podmiana ---
3543 + if os.path.exists(dst):
3544 + shutil.copy2(dst, dst_bak)
3545 + os.chmod(dst_new, 0o755)
3546 + os.replace(dst_new, dst) # atomowe na tym samym FS
3547 + try:
3548 + if os.path.exists(dst_new + ".asc"):
3549 + os.remove(dst_new + ".asc")
3550 + except OSError:
3551 + pass
3552 + print(f" ✅ Zainstalowano nowy pag. Stary zachowany jako {dst_bak}")
3553 + # Ostrzeż, gdy w PATH pierwsza jest INNA kopia `pag` – inaczej
3554 + # `pag --version` dalej pokaże starą wersję i wygląda to jak brak update.
3555 + other = shutil.which("pag")
3556 + if other and os.path.realpath(other) != os.path.realpath(dst):
3557 + print(f" ⚠ W PATH pierwszy jest inny pag: {other} (zaktualizowano {dst})")
3558 + print(f" Usuń starą kopię: sudo rm {other}")
3559 + print(" Uruchom ponownie pag, aby użyć nowej wersji.")
3560 + return 0
3561 +
3562 +
3563 +def _candidate_newer(rp, inst):
3564 + """Czy pakiet z repo jest nowszy od zainstalowanego.
3565 + Porównuje (version, release): sam bump pkgrel (np. auto-rebuild modułów
3566 + po aktualizacji jądra: nvidia-kernel-618 610.57.04-1 -> -2) też musi być
3567 + widziany przez `pag update`. Stare rekordy instalacji (bez pola release)
3568 + traktujemy jak release=1 – nie generują churnu, dopóki nie wrócą do
3569 + reinstalacji/zmiany wersji."""
3570 + rv = getattr(rp, "version", "0")
3571 + iv = inst.get("version", "0")
3572 + if _version_newer(rv, iv):
3573 + return True
3574 + if rv != iv:
3575 + return False
3576 + rr = int(getattr(rp, "release", 1) or 1)
3577 + ir = int(inst.get("release", 1) or 1)
3578 + return rr > ir
3579 +
3580 +
3581 +def _pending_updates() -> List[str]:
3582 + """Zainstalowane pakiety z nowszą wersją/release w repo (bez przypiętych)."""
3583 + installed = load_json(INSTALLED_DB)
3584 + pinned = load_json(PINNED_FILE)
3585 + repo = fetch_all_packages()
3586 + if not repo:
3587 + return []
3588 + return [n for n, i in installed.items()
3589 + if n not in pinned and (rp := repo.get(n)) and _candidate_newer(rp, i)]
3590 +
3591 +# =============================================================================
3592 +# BAZA Z OBRAZU ISO → REPO (`pag base`) – pełny rolling
3593 +# =============================================================================
3594 +# ISO jest zbudowane ZE ŹRÓDEŁ (glibc, gcc, gtk, XFCE, …) – pag tych pakietów
3595 +# nie instalował, więc nie ma ich w installed.json/files.db. Skutki:
3596 +# • `pag upgrade` ich NIE dotyka (nie ma o nich pojęcia),
3597 +# • mimo to `pag install <nazwa>` je NADPISZE – pag robi kopię plików spoza
3598 +# swojej bazy (patrz _new_transaction_backup_root), więc nie są nietykalne.
3599 +#
3600 +# /usr/share/pag/base.json (wypalany przez build-pagan.sh) mówi, co jest w bazie
3601 +# obrazu i w jakiej wersji. `pag base` pokazuje stan, a `pag base adopt` dogrywa
3602 +# te pakiety z repo – po tym zabiegu pag zarządza nimi normalnie, więc
3603 +# `pag upgrade` aktualizuje CAŁY system (rolling), a nie tylko to, co sam
3604 +# wcześniej zainstalował.
3605 +#
3606 +# Nazwy z buildera różnią się od nazw pakietów w repo (builder buduje „libX11”,
3607 +# repo ma pakiet „xorg-libx11”), stąd aliasy poniżej. Nazwy bez odpowiednika
3608 +# w repo zostają w wersji z obrazu – raport mówi o tym wprost, zamiast udawać,
3609 +# że są aktualne.
3610 +BASE_NAME_ALIASES = {
3611 + "atk": "at-spi2-core",
3612 + "dejavu-fonts": "dejavu-ttf",
3613 + "fontconfig": "xorg-fontconfig",
3614 + "gtk": "gtk3",
3615 + "iceauth": "xorg-iceauth",
3616 + "libX11": "xorg-libx11",
3617 + "libXau": "xorg-libxau",
3618 + "libXdmcp": "xorg-libxdmcp",
3619 + "libXext": "xorg-libxext",
3620 + "libXft": "xorg-libxft",
3621 + "libdrm": "xorg-libdrm",
3622 + "libnspr": "nspr",
3623 + "libxkbfile": "xorg-libxkbfile",
3624 + "libxklavier": "xorg-libxklavier",
3625 + "linux-pam": "pam",
3626 + "pixman": "xorg-pixman",
3627 + "sdl2": "sdl",
3628 + "setxkbmap": "xorg-setxkbmap",
3629 + "xauth": "xorg-xauth",
3630 + "xf86-input-libinput": "xorg-xf86-input-libinput",
3631 + "xf86-video-fbdev": "xorg-xf86-video-fbdev",
3632 + "xinit": "xorg-xinit",
3633 + "xkbcomp": "xorg-xkbcomp",
3634 + "xkeyboard-config": "xorg-xkeyboard-config",
3635 + # Builder buduje wpa_supplicant (z podkreślnikiem), a repo ma wpa-supplicant
3636 + # (z myślnikiem) – bez tego aliasu pakiet nie dostawał aktualizacji z repo,
3637 + # mimo że repo.json zna DOKŁADNIE tę samą wersję.
3638 + "wpa_supplicant": "wpa-supplicant",
3639 +}
3640 +
3641 +
3642 +def _base_manifest() -> dict:
3643 + """Manifest bazy z obrazu ({} gdy obraz go nie dostarcza)."""
3644 + _d = load_json(os.path.join(PAG_ROOT, BASE_MANIFEST.lstrip("/")))
3645 + return _d if isinstance(_d, dict) else {}
3646 +
3647 +
3648 +def _base_entries() -> list:
3649 + """[(nazwa_z_buildera, wersja_z_obrazu), ...] z manifestu."""
3650 + _out = []
3651 + for _e in (_base_manifest().get("packages") or []):
3652 + if isinstance(_e, str):
3653 + if _e:
3654 + _out.append((_e, "?"))
3655 + elif isinstance(_e, dict) and _e.get("name"):
3656 + _out.append((str(_e["name"]), str(_e.get("version") or "?")))
3657 + return _out
3658 +
3659 +
3660 +def _base_repo_name(name: str, repo: dict, installed: dict) -> str:
3661 + """Nazwa pakietu w repo dla nazwy z buildera (alias → provides → brak)."""
3662 + if name in repo:
3663 + return name
3664 + _alias = BASE_NAME_ALIASES.get(name)
3665 + if _alias and _alias in repo:
3666 + return _alias
3667 + _real = _resolve_provides(name, repo, installed)
3668 + return _real if _real in repo else ""
3669 +
3670 +
3671 +def _base_summary(repo: Optional[dict] = None) -> dict:
3672 + """Klasyfikacja pakietów bazy z obrazu wobec repo.
3673 +
3674 + repo=None → pobiera indeks repo (potrzebny do listy „do adoptowania”).
3675 + repo={} → bez sieci: rozpoznaje tylko to, czym pag już zarządza.
3676 + """
3677 + _entries = _base_entries()
3678 + if not _entries:
3679 + return {"total": 0, "tracked": 0, "adoptable": [], "unmatched": []}
3680 + if repo is None:
3681 + repo = fetch_all_packages()
3682 + installed = load_json(INSTALLED_DB)
3683 + tracked, adoptable, unmatched = 0, [], []
3684 + for _n, _v in _entries:
3685 + _real = _base_repo_name(_n, repo, installed)
3686 + if _n in installed or (_real and _real in installed):
3687 + tracked += 1
3688 + elif _real:
3689 + adoptable.append((_n, _real, _v))
3690 + else:
3691 + unmatched.append(_n)
3692 + return {"total": len(_entries), "tracked": tracked,
3693 + "adoptable": adoptable, "unmatched": unmatched}
3694 +
3695 +
3696 +def _base_hint_unmanaged() -> None:
3697 + """Jednozdaniowa informacja dla `pag sync/update/upgrade`."""
3698 + try:
3699 + _s = _base_summary()
3700 + except Exception:
3701 + return
3702 + if _s["adoptable"]:
3703 + print(f"\n ℹ {_('base_unmanaged_hint', len(_s['adoptable']))}")
3704 +
3705 +
3706 +def _base_warn_overwrite(names) -> None:
3707 + """Ostrzeżenie w `pag install`, gdy pakiet pochodzi z bazy obrazu ISO."""
3708 + _entries = _base_entries()
3709 + if not _entries:
3710 + return
3711 + _known = set()
3712 + for _n, _v in _entries:
3713 + _known.add(_n)
3714 + _al = BASE_NAME_ALIASES.get(_n)
3715 + if _al:
3716 + _known.add(_al)
3717 + _hit = [n for n in names if n in _known]
3718 + if _hit:
3719 + _listed = ", ".join(_hit[:5]) + (" …" if len(_hit) > 5 else "")
3720 + print(f" ℹ {_('base_overwrite', _listed)}")
3721 +
3722 +
3723 +def cmd_base_status():
3724 + """`pag base` / `pag base status` – co w systemie pochodzi z obrazu,
3725 + czym pag już zarządza i co da się zaadoptować z repo."""
3726 + _man = _base_manifest()
3727 + if not _man:
3728 + print(f" ℹ {_('base_no_manifest')}")
3729 + return 0
3730 + _s = _base_summary()
3731 + print(f"\n {_c('bold', _('base_title'))}")
3732 + print(f" {'─' * 46}")
3733 + _de = _man.get("de") or ""
3734 + print(f" {_('base_iso_version'):<34} {_man.get('iso_version', '?')}" + (f" ({_de})" if _de else ""))
3735 + print(f" {_('base_total'):<34} {_s['total']}")
3736 + print(f" {_('base_tracked'):<34} {_s['tracked']}")
3737 + print(f" {_('base_adoptable'):<34} {len(_s['adoptable'])}")
3738 + print(f" {_('base_unmatched'):<34} {len(_s['unmatched'])}")
3739 + if _s["adoptable"]:
3740 + print(f"\n {_('base_adopt_hint')}")
3741 + for _iso_n, _real, _v in _s["adoptable"][:10]:
3742 + _m = "" if _iso_n == _real else f" ({_iso_n})"
3743 + print(f" {_real}-{_v}{_m}")
3744 + if len(_s["adoptable"]) > 10:
3745 + print(f" … {len(_s['adoptable']) - 10} {_('base_more')}")
3746 + if _s["unmatched"]:
3747 + print(f"\n {_('base_unmatched_hint')}")
3748 + print(" " + ", ".join(_s["unmatched"][:12])
3749 + + (f" … +{len(_s['unmatched']) - 12}" if len(_s["unmatched"]) > 12 else ""))
3750 + return 0
3751 +
3752 +
3753 +def cmd_base_adopt(args):
3754 + """`pag base adopt [pkg...] [--dry-run]` – dograj bazę z obrazu z repo.
3755 +
3756 + Pakiety bazy nie ma w installed.json, więc pag traktuje je jak NOWĄ
3757 + instalację: pliki z obrazu trafiają do kopii transakcji (działa
3758 + `pag rollback`), a po sukcesie pag zarządza nimi jak każdym innym pakietem.
3759 + """
3760 + if not _base_manifest():
3761 + print(f" ℹ {_('base_no_manifest')}")
3762 + return 1
3763 + repo = fetch_all_packages()
3764 + if not repo:
3765 + print(f"❌ {_('no_index')}")
3766 + return 1
3767 + _want = [a for a in args if not a.startswith("-") and a != "adopt"]
3768 + _s = _base_summary(repo)
3769 + plan = _s["adoptable"]
3770 + if _want:
3771 + _sel = set(_want)
3772 + plan = [p for p in plan if p[0] in _sel or p[1] in _sel]
3773 + if not plan:
3774 + print(f" ℹ {_('base_nothing_selected')}")
3775 + return 0
3776 + if not plan:
3777 + print(f"✅ {_('base_all_managed')}")
3778 + return 0
3779 + _size = sum(repo[r].size_bytes for _i, r, _v in plan if r in repo)
3780 + print(f"\n {_('base_adopt_plan', len(plan), _size / 1048576)}")
3781 + for _iso_n, _real, _v in plan[:20]:
3782 + _rv = repo[_real].version if _real in repo else "?"
3783 + _m = "" if _iso_n == _real else f" ({_iso_n} → {_real})"
3784 + print(f" {_real}: {_v} → {_rv}{_m}")
3785 + if len(plan) > 20:
3786 + print(f" … {len(plan) - 20} {_('base_more')}")
3787 + if "-n" in args or "--dry-run" in args:
3788 + print(f" {_('base_dry_run')}")
3789 + return 0
3790 + _rc = cmd_install([r for _i, r, _v in plan])
3791 + if _rc == 0:
3792 + # Wymienione biblioteki/narzędzia (glibc, gcc, GTK…) są już nowe na dysku,
3793 + # ale działające procesy wciąż mają stare w pamięci – restart domyka.
3794 + print(f"\n ℹ {_('base_reboot_hint')}")
3795 + return _rc
3796 +
3797 +
3798 +def _base_cached_index() -> dict:
3799 + """Indeks repo TYLKO z lokalnego cache (zero sieci) – do mapowania nazw.
3800 +
3801 + Potrzebne dla `pag base register`: rejestracja bazy obrazu nie może zależeć
3802 + od sieci (odpala się w buildzie, w chroocie, bez DNS). Cache indeksu powstaje
3803 + przy okazji `pag sync`/`pag install` i po nim wystarcza.
3804 + """
3805 + _out = {}
3806 + try:
3807 + for _r in get_repos():
3808 + _cp = _repo_cache_path(_r)
3809 + if not os.path.exists(_cp):
3810 + continue
3811 + for _pdata in (_load_repo_cache(_cp) or []):
3812 + _n = _pdata.get("name") or _pdata.get("filename", "?").split("-")[0]
3813 + _pkg = PackageInfo(_pdata, _r)
3814 + if _n not in _out or _version_newer(_pkg.version, _out[_n].version):
3815 + _out[_n] = _pkg
3816 + except Exception:
3817 + return _out
3818 + return _out
3819 +
3820 +
3821 +def cmd_base_register(args):
3822 + """`pag base register [--force] [--dry-run]` – wpisz bazę obrazu do installed.json.
3823 +
3824 + PO CO: pakietów zbudowanych przez builder (glibc, gcc, GTK, XFCE…) nie ma
3825 + w installed.json, więc `pag upgrade` ich NIE widzi i system nie da się
3826 + prowadzić w trybie rolling – trzeba by najpierw `pag base adopt`, czyli
3827 + ponownie ŚCIĄGNĄĆ całą bazę z repo. Rejestracja zamiast tego zapisuje je
3828 + jako zainstalowane **z wersją z obrazu** (to ona leży na dysku), więc
3829 + `pag upgrade` porówna ją z repo i podniesie tylko to, co nowsze.
3830 +
3831 + Offline: nic nie pobiera. Cache indeksu repo (jeśli jest) służy WYŁĄCZNIE do
3832 + mapowania nazw builder → repo (BASE_NAME_ALIASES/provides) i metadanych
3833 + (release/opis/zależności). Nazwy bez odpowiednika w repo zostają jak są.
3834 +
3835 + OGRANICZENIE: rejestracja nie zna listy plików pakietu (files.db), więc
3836 + dopóki pakiet nie zostanie zaktualizowany z repo, `pag verify`/`pag remove`
3837 + go nie obejmą (`pag base adopt` nadal jest drogą do pełnego przejęcia).
3838 + """
3839 + _force = "-f" in args or "--force" in args
3840 + _dry = "-n" in args or "--dry-run" in args
3841 +
3842 + _entries = _base_entries()
3843 + if not _entries:
3844 + print(f" ℹ {_('base_no_manifest')}")
3845 + return 1
3846 +
3847 + _repo = _base_cached_index()
3848 + installed = load_json(INSTALLED_DB)
3849 + world = load_world()
3850 + _now = datetime.now().isoformat()
3851 +
3852 + added, skipped, renamed = [], 0, 0
3853 + for _n, _v in _entries:
3854 + _real = _base_repo_name(_n, _repo, installed) if _repo else ""
3855 + _key = _real or _n
3856 + if _real and _real != _n:
3857 + renamed += 1
3858 + if _key in installed and not _force:
3859 + skipped += 1
3860 + continue
3861 + _pkg = _repo.get(_key)
3862 + installed[_key] = {
3863 + "version": _v or (getattr(_pkg, "version", "") or "?"),
3864 + "release": getattr(_pkg, "release", "") or "1",
3865 + "description": (getattr(_pkg, "description", "") or "")
3866 + or "Pagan Linux – pakiet bazy obrazu",
3867 + "dependencies": list(getattr(_pkg, "dependencies", []) or []),
3868 + "size_bytes": getattr(_pkg, "size_bytes", 0) or 0,
3869 + "sha256": "",
3870 + "installed_at": _now,
3871 + "repo": "base",
3872 + "provides": list(getattr(_pkg, "provides", []) or []),
3873 + "provides_so": list(getattr(_pkg, "provides_so", []) or []),
3874 + "requires_so": list(getattr(_pkg, "requires_so", []) or []),
3875 + }
3876 + world.add(_key)
3877 + added.append(_key)
3878 +
3879 + if _dry:
3880 + print(f" ℹ {_('base_register_plan', len(added))}")
3881 + return 0
3882 + if added:
3883 + save_json(INSTALLED_DB, installed)
3884 + save_world(world)
3885 + print(f" ✅ {_('base_register_ok', len(added), skipped)}")
3886 + if renamed:
3887 + print(f" ℹ {_('base_register_renamed', renamed)}")
3888 + if not _repo:
3889 + print(f" ℹ {_('base_register_nocache')}")
3890 + return 0
3891 +
3892 +
3893 +def cmd_update(do_upgrade: bool = False):
3894 + """`pag sync` / `pag update` – odświeżenie indeksów + raport aktualizacji.
3895 +
3896 + sync → tylko odświeżenie indeksów + info: „jest X pakietów do
3897 + zaktualizowania – wpisz: pag update".
3898 + update → odświeżenie indeksów + AKTUALIZACJA PAKIETÓW (pakiety, nie system).
3899 + Pomijamy cache TTL (inaczej nowe pakiety/aktualizacje są niewidoczne nawet
3900 + przez godzinę). Pełne pobranie + weryfikacja GPG przy każdym odświeżeniu.
3901 + """
3902 + force = True
3903 + print("🔄 Refreshing indexes...")
3904 + for repo_url in get_repos():
3905 + pkgs = fetch_repo_index(repo_url, force=force)
3906 + cp = _repo_cache_path(repo_url)
3907 + has_sig = os.path.exists(cp + ".sig")
3908 + print(f" {'✅' if pkgs is not None else '❌'} {repo_url}: {len(pkgs or [])} pkgs {'🔐' if has_sig else '⚠'}")
3909 + print(f"✅ {_('indexes_refreshed')}")
3910 +
3911 + # Powiadomienie o nowszej wersji pag (repo.json["pag_version"])
3912 + try:
3913 + for r in get_repos():
3914 + cp = _repo_cache_path(r)
3915 + if os.path.exists(cp):
3916 + d = json.load(open(cp))
3917 + rv = d.get("pag_version", "")
3918 + if rv and rv != PAG_VERSION:
3919 + print(f" ⚠ Nowa wersja pag {rv} dostępna – uruchom: pag self-update")
3920 + except Exception:
3921 + pass
3922 +
3923 + # Raport: pakiety do aktualizacji
3924 + pending = _pending_updates()
3925 + if not pending:
3926 + print(f"✅ {_('all_up_to_date')}")
3927 + _base_hint_unmanaged()
3928 + return 0
3929 + print(f"{_('updates_available', len(pending))}")
3930 + installed = load_json(INSTALLED_DB)
3931 + repo = fetch_all_packages()
3932 + for n in pending:
3933 + print(f" {n}: {installed.get(n, {}).get('version', '?')} → {repo[n].version}")
3934 + if not do_upgrade:
3935 + _base_hint_unmanaged()
3936 + return 0 # sync: tylko informacja
3937 + if not _ask_confirm():
3938 + return 0
3939 + _rc = cmd_install(pending, upgrade=True)
3940 + _base_hint_unmanaged()
3941 + return _rc
3942 +
3943 +def _initramfs_stale() -> bool:
3944 + """Czy initramfs jest starszy niż najnowsze jądro (wymaga przebudowy)."""
3945 + try:
3946 + kernels = [k for k in os.listdir("/boot") if k.startswith("vmlinuz-")] if os.path.isdir("/boot") else []
3947 + if not kernels:
3948 + return False
3949 + newest = max(os.path.getmtime(os.path.join("/boot", k)) for k in kernels)
3950 + initrd = "/boot/initramfs.img"
3951 + return (not os.path.exists(initrd)) or os.path.getmtime(initrd) < newest
3952 + except Exception:
3953 + return False
3954 +
3955 +def cmd_upgrade():
3956 + """`pag upgrade` – aktualizacja SYSTEMU: pakiety + kernel/initramfs/GRUB."""
3957 + rc = cmd_update(do_upgrade=True)
3958 + if rc != 0:
3959 + return rc
3960 + # System: dopilnuj initramfs (gdyby kernel był nowszy) + GRUB (immutable)
3961 + if _initramfs_stale():
3962 + print(" 🐧 Przebudowa initramfs (nowsze jądro)...")
3963 + _rebuild_initramfs()
3964 + try:
3965 + if _load_deployments():
3966 + _update_grub_config()
3967 + except Exception:
3968 + pass
3969 + return 0
3970 +
3971 +def cmd_list(installed_only=False):
3972 + if installed_only:
3973 + db = load_json(INSTALLED_DB)
3974 + pinned = load_json(PINNED_FILE)
3975 + if not db: print("No packages installed."); return
3976 + print(f"Installed ({len(db)}):")
3977 + for n, i in sorted(db.items()):
3978 + pin = " 📌" if n in pinned else ""
3979 + print(f" {n}-{i['version']}{pin} – {i.get('description','')}")
3980 + else:
3981 + pkgs = fetch_all_packages()
3982 + installed = load_json(INSTALLED_DB)
3983 + pinned = load_json(PINNED_FILE)
3984 + print(f"Available ({len(pkgs)}):")
3985 + for n, p in sorted(pkgs.items()):
3986 + m = "✓" if n in installed else " "
3987 + extra = f" [installed: {installed[n]['version']}]" if n in installed else ""
3988 + if n in pinned: extra += " 📌"
3989 + print(f" [{m}] {n}-{p.version} – {p.description}{extra}")
3990 +
3991 +def cmd_search(query):
3992 + pkgs = fetch_all_packages()
3993 + results = [(n,p) for n,p in pkgs.items() if query.lower() in n.lower() or query.lower() in p.description.lower()]
3994 + if not results: print(f"❌ No results for: {query}"); return
3995 + installed = load_json(INSTALLED_DB)
3996 + print(f"Results for '{query}' ({len(results)}):")
3997 + for n,p in sorted(results):
3998 + print(f" [{'✓' if n in installed else ' '}] {n}-{p.version}")
3999 + print(f" {p.description}")
4000 +
4001 +
4002 +def _smart_search(query: str) -> int:
4003 + """
4004 + Inteligentne wyszukiwanie: repo PaganOS + Flathub.
4005 + Uruchamiane gdy użytkownik wpisze `pag <nazwa>` zamiast `pag install <nazwa>`.
4006 + Pokazuje dostępne źródła i sugeruje komendy instalacji.
4007 + """
4008 + # 1. Repo PaganOS
4009 + try:
4010 + pkgs = fetch_all_packages()
4011 + except Exception:
4012 + pkgs = {}
4013 + repo_lower = [(n, p) for n, p in pkgs.items()
4014 + if query.lower() in n.lower() or query.lower() in p.description.lower()]
4015 +
4016 + # 2. Flathub (jeśli dostępny)
4017 + flat = _flatpak_search_raw(query) if _check_flatpak(quiet=True) else []
4018 +
4019 + if not repo_lower and not flat:
4020 + print(f"\n ❌ '{query}' — nie znaleziono.")
4021 + print(f" Repo PaganOS: pag search {query}")
4022 + if _check_flatpak(quiet=True):
4023 + print(f" Flathub: pag flatpak search {query}")
4024 + print(f" Dodaj repo: pag repo-add <url>")
4025 + return 1
4026 +
4027 + installed = load_json(INSTALLED_DB)
4028 +
4029 + # ── Repo PaganOS ──
4030 + if repo_lower:
4031 + exact = [(n, p) for n, p in repo_lower if n.lower() == query.lower()]
4032 + show = (exact or repo_lower)[:6]
4033 + print(f"\n 📦 PaganOS — '{query}':")
4034 + for n, p in sorted(show):
4035 + mark = "✓" if n in installed else " "
4036 + desc = p.description[:70] if len(p.description) > 75 else p.description
4037 + print(f" [{mark}] {n}-{p.version}")
4038 + if desc:
4039 + print(f" {desc}")
4040 + if len(repo_lower) > 6:
4041 + print(f" ... i {len(repo_lower) - 6} więcej (pag search {query})")
4042 +
4043 + # ── Flathub ──
4044 + if flat:
4045 + print(f"\n 📦 Flathub — '{query}':")
4046 + for r in flat[:5]:
4047 + mark = "✓" if r.get("installed") else " "
4048 + name = r.get("name") or r.get("application", "?")
4049 + desc = (r.get("description") or "")[:65]
4050 + print(f" [{mark}] {name}")
4051 + if desc:
4052 + print(f" {desc}")
4053 + if len(flat) > 5:
4054 + print(f" ... i {len(flat) - 5} więcej (pag flatpak search {query})")
4055 +
4056 + # ── Sugestie instalacji ──
4057 + print()
4058 + if repo_lower:
4059 + best = sorted(repo_lower, key=lambda x: (x[0].lower() != query.lower(), -len(x[1].name if hasattr(x[1], 'name') else 0)))[0][0]
4060 + if best in installed:
4061 + print(f" ✓ {best} jest już zainstalowany ({installed[best]['version']})")
4062 + else:
4063 + print(f" 💡 sudo pag install {best}")
4064 + if flat:
4065 + best_fp = flat[0].get("application") or flat[0].get("name", query)
4066 + print(f" 💡 pag flatpak install {best_fp}")
4067 +
4068 + return 0
4069 +
4070 +def cmd_info(name):
4071 + pkgs = fetch_all_packages()
4072 + p = pkgs.get(name)
4073 + info = load_json(INSTALLED_DB).get(name)
4074 + if not p and not info: print(f"❌ '{name}' not found."); return 1
4075 + print(f"📦 {name}")
4076 + if p:
4077 + print(f" Version (repo): {p.version}")
4078 + print(f" Description: {p.description}")
4079 + print(f" Size: {p.size_bytes/1048576:.1f} MB")
4080 + print(f" SHA256: {p.sha256[:32]}...")
4081 + print(f" GPG: {p.gpg_fp or 'none'}")
4082 + print(f" Dependencies: {', '.join(p.dependencies) if p.dependencies else '(none)'}")
4083 + if info:
4084 + print(f" Installed: {info['version']} ({info.get('installed_at','?')})")
4085 +
4086 +def cmd_files(name):
4087 + if name not in load_json(INSTALLED_DB):
4088 + print(f"❌ '{name}' not installed."); return 1
4089 + files = _db_get_package_files(name)
4090 + print(f"Files in {name} ({len(files)}):")
4091 + for f in sorted(files): print(f" {f}")
4092 +
4093 +def cmd_verify(deep=False):
4094 + installed = load_json(INSTALLED_DB)
4095 + if not installed: print("Nothing to verify."); return
4096 + errors = []
4097 +
4098 + # Wczytaj WSZYSTKIE sumy RAZ (nie w pętli!) – przy 50k plików wywołanie
4099 + # _db_get_all_file_checksums() per-plik dawało O(n²) i godziny zamiast sekund.
4100 + all_checksums = _db_get_all_file_checksums() if deep else {}
4101 + for name in installed:
4102 + for fpath in _db_get_package_files(name):
4103 + full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
4104 + if not (os.path.exists(full) or os.path.islink(full)):
4105 + errors.append(f" ❌ {name}: missing {fpath}")
4106 + elif deep:
4107 + expected = all_checksums.get(fpath, "")
4108 + if expected:
4109 + actual = _sha256_file(full)
4110 + if actual != expected:
4111 + errors.append(f" ❌ {name}: SHA256 mismatch {fpath}")
4112 +
4113 + if errors:
4114 + print(f"❌ {_('verify_errors', len(errors))}")
4115 + for e in errors[:50]: print(e)
4116 + return 1
4117 + total = _db_count_files()
4118 + print(f"✅ {_('verify_ok', total)}")
4119 +
4120 +# =============================================================================
4121 +# PINNING / CLEAN / ORPHANS / REPO / FLATPAK
4122 +# =============================================================================
4123 +
4124 +def cmd_pin(name, version=""):
4125 + pinned = load_json(PINNED_FILE)
4126 + if version:
4127 + pinned[name] = version
4128 + else:
4129 + info = load_json(INSTALLED_DB).get(name, {})
4130 + pinned[name] = info.get("version", "?")
4131 + save_json(PINNED_FILE, pinned)
4132 + print(f"📌 {name} {_('pinned_to')} {pinned[name]}")
4133 +
4134 +def cmd_unpin(name):
4135 + pinned = load_json(PINNED_FILE)
4136 + if name in pinned:
4137 + del pinned[name]; save_json(PINNED_FILE, pinned)
4138 + print(f"🔓 {name} {_('unpinned')}")
4139 + else:
4140 + print(f"⚠ {name} {_('not_pinned')}")
4141 +
4142 +def cmd_pinned():
4143 + pinned = load_json(PINNED_FILE)
4144 + if not pinned: print(_("no_pinned")); return
4145 + print(_("pinned_list", len(pinned)))
4146 + for n,v in sorted(pinned.items()): print(f" 📌 {n} = {v}")
4147 +
4148 +def cmd_clean():
4149 + if os.path.isdir(PAG_CACHE):
4150 + count = size = 0
4151 + for f in os.listdir(PAG_CACHE):
4152 + fp = os.path.join(PAG_CACHE, f)
4153 + if os.path.isfile(fp):
4154 + size += os.path.getsize(fp); os.remove(fp); count += 1
4155 + print(f"✅ {_('cache_cleared', count, size/1048576)}")
4156 +
4157 +def cmd_remove_orphans():
4158 + installed = load_json(INSTALLED_DB)
4159 + world = load_world()
4160 + orphans = _find_orphans(installed, world)
4161 + if not orphans: print("✅ No orphans."); return
4162 + print(f"Orphans ({len(orphans)}):")
4163 + for n in sorted(orphans): print(f" {n}-{installed[n]['version']}")
4164 + if not _ask_confirm():
4165 + return
4166 + cmd_remove(list(orphans))
4167 +
4168 +
4169 +# =============================================================================
4170 +# PROVIDES – PAKIETY WIRTUALNE
4171 +# =============================================================================
4172 +
4173 +PROVIDES_MAP = {
4174 + "pkgconfig(glib-2.0)": "glib",
4175 + "pkgconfig(gobject-introspection-1.0)": "gobject-introspection",
4176 + "pkgconfig(gtk+-3.0)": "gtk",
4177 + "pkgconfig(gtk4)": "gtk",
4178 + "pkgconfig(zlib)": "zlib",
4179 + "pkgconfig(libffi)": "libffi",
4180 + "pkgconfig(expat)": "expat",
4181 + "pkgconfig(libsystemd)": "systemd",
4182 + "pkgconfig(dbus-1)": "dbus",
4183 + "pkgconfig(mount)": "util-linux",
4184 + "pkgconfig(blkid)": "util-linux",
4185 + "pkgconfig(libcap)": "libcap",
4186 + "pkgconfig(liblzma)": "xz",
4187 + "pkgconfig(libzstd)": "zstd",
4188 + "pkgconfig(bzip2)": "bzip2",
4189 + "pkgconfig(libcurl)": "curl",
4190 + "pkgconfig(openssl)": "openssl",
4191 + "pkgconfig(libpcre2-8)": "pcre2",
4192 + "pkgconfig(libxml-2.0)": "libxml2",
4193 + "pkgconfig(libxslt)": "libxslt",
4194 + "pkgconfig(freetype2)": "freetype",
4195 + "pkgconfig(fontconfig)": "fontconfig",
4196 + "pkgconfig(harfbuzz)": "harfbuzz",
4197 + "pkgconfig(cairo)": "cairo",
4198 + "pkgconfig(pango)": "pango",
4199 + "pkgconfig(xt)": "xorg-libxt",
4200 + "pkgconfig(xmu)": "xorg-libxmu",
4201 + "pkgconfig(ice)": "xorg-libice",
4202 + "pkgconfig(sm)": "xorg-libsm",
4203 + "pkgconfig(x11)": "xorg-libx11",
4204 + "pkgconfig(xext)": "xorg-libxext",
4205 + "pkgconfig(xrandr)": "xorg-libxrandr",
4206 + "pkgconfig(xfixes)": "xorg-libxfixes",
4207 + "pkgconfig(xcursor)": "xorg-libxcursor",
4208 + "pkgconfig(xinerama)": "xorg-libxinerama",
4209 + "pkgconfig(xrender)": "xorg-libxrender",
4210 + "pkgconfig(xau)": "xorg-libxau",
4211 + "pkgconfig(xcb)": "xorg-libxcb",
4212 + "pkgconfig(xdamage)": "xorg-libxdamage",
4213 + "pkgconfig(xcomposite)": "xorg-libxcomposite",
4214 + "pkgconfig(xft)": "xorg-libxft",
4215 + "pkgconfig(xss)": "xorg-libxss",
4216 + "pkgconfig(libsoup-3.0)": "libsoup3",
4217 + "pkgconfig(libsoup-2.4)": "libsoup2",
4218 + "pkgconfig(gdk-pixbuf-2.0)": "gdk-pixbuf2",
4219 + "pkgconfig(libpng)": "libpng",
4220 + "pkgconfig(libjpeg)": "libjpeg-turbo",
4221 + "pkgconfig(libtiff-4)": "libtiff",
4222 + "pkgconfig(ffi)": "libffi",
4223 + # ── system / baza ──
4224 + "pkgconfig(libcrypto)": "openssl",
4225 + "pkgconfig(libssl)": "openssl",
4226 + "pkgconfig(libudev)": "systemd",
4227 + "pkgconfig(libmount)": "util-linux",
4228 + "pkgconfig(libblkid)": "util-linux",
4229 + "pkgconfig(uuid)": "util-linux",
4230 + "pkgconfig(libexpat)": "expat",
4231 + "pkgconfig(libpcre)": "pcre",
4232 + "pkgconfig(ncursesw)": "ncurses",
4233 + "pkgconfig(tinfo)": "ncurses",
4234 + "pkgconfig(panel)": "ncurses",
4235 + "pkgconfig(readline)": "readline",
4236 + "pkgconfig(libseccomp)": "libseccomp",
4237 + "pkgconfig(pam)": "linux-pam",
4238 + "pkgconfig(libxcrypt)": "libxcrypt",
4239 + "pkgconfig(libcrypt)": "libxcrypt",
4240 + "pkgconfig(libnsl)": "libnsl",
4241 + "pkgconfig(liblz4)": "lz4",
4242 + "pkgconfig(libevent)": "libevent",
4243 + "pkgconfig(libarchive)": "libarchive",
4244 + "pkgconfig(sqlite3)": "sqlite",
4245 + "pkgconfig(libpq)": "postgresql",
4246 + "pkgconfig(mysqlclient)": "mariadb",
4247 + "pkgconfig(json-c)": "json-c",
4248 + "pkgconfig(json-glib-1.0)": "json-glib",
4249 + "pkgconfig(libunistring)": "libunistring",
4250 + "pkgconfig(libidn2)": "libidn2",
4251 + "pkgconfig(libpsl)": "libpsl",
4252 + "pkgconfig(icu-uc)": "icu",
4253 + "pkgconfig(icu-i18n)": "icu",
4254 + "pkgconfig(icu-io)": "icu",
4255 + "pkgconfig(gnutls)": "gnutls",
4256 + "pkgconfig(nettle)": "nettle",
4257 + "pkgconfig(hogweed)": "nettle",
4258 + "pkgconfig(libgcrypt)": "libgcrypt",
4259 + "pkgconfig(libgpg-error)": "libgpg-error",
4260 + "pkgconfig(libassuan)": "libassuan",
4261 + "pkgconfig(libusb-1.0)": "libusb",
4262 + "pkgconfig(libusb)": "libusb",
4263 + "pkgconfig(libgudev-1.0)": "libgudev",
4264 + "pkgconfig(gudev-1.0)": "libgudev",
4265 + "pkgconfig(polkit-gobject-1)": "polkit",
4266 + "pkgconfig(polkit-agent-1)": "polkit",
4267 + "pkgconfig(libpciaccess)": "libpciaccess",
4268 + "pkgconfig(pixman-1)": "pixman",
4269 + "pkgconfig(libdrm)": "libdrm",
4270 + "pkgconfig(libva)": "libva",
4271 + "pkgconfig(libva-drm)": "libva",
4272 + "pkgconfig(libva-x11)": "libva",
4273 + "pkgconfig(libva-wayland)": "libva",
4274 + "pkgconfig(vdpau)": "libvdpau",
4275 + "pkgconfig(libvdpau)": "libvdpau",
4276 + "pkgconfig(libinput)": "libinput",
4277 + "pkgconfig(libevdev)": "libevdev",
4278 + "pkgconfig(mtdev)": "mtdev",
4279 + # ── grafika / GL / multimedia ──
4280 + "pkgconfig(gbm)": "mesa",
4281 + "pkgconfig(gl)": "libglvnd",
4282 + "pkgconfig(egl)": "libglvnd",
4283 + "pkgconfig(glesv2)": "libglvnd",
4284 + "pkgconfig(glx)": "libglvnd",
4285 + "pkgconfig(vulkan)": "vulkan-loader",
4286 + "pkgconfig(libxkbcommon)": "libxkbcommon",
4287 + "pkgconfig(xkbcommon)": "libxkbcommon",
4288 + "pkgconfig(xkbcommon-x11)": "libxkbcommon",
4289 + "pkgconfig(xcb)": "xorg-libxcb",
4290 + "pkgconfig(xcb-util)": "xcb-util",
4291 + "pkgconfig(xcb-keysyms)": "xcb-util-keysyms",
4292 + "pkgconfig(xcb-icccm)": "xcb-util-wm",
4293 + "pkgconfig(xcb-cursor)": "xcb-util-cursor",
4294 + "pkgconfig(xcb-renderutil)": "xcb-util-renderutil",
4295 + "pkgconfig(xcb-image)": "xcb-util-image",
4296 + "pkgconfig(xcb-errors)": "xcb-util-errors",
4297 + "pkgconfig(wayland-client)": "wayland",
4298 + "pkgconfig(wayland-server)": "wayland",
4299 + "pkgconfig(wayland-cursor)": "wayland",
4300 + "pkgconfig(wayland-egl)": "wayland",
4301 + "pkgconfig(wayland-protocols)": "wayland-protocols",
4302 + "pkgconfig(gstreamer-1.0)": "gstreamer",
4303 + "pkgconfig(gstreamer-base-1.0)": "gstreamer",
4304 + "pkgconfig(gstreamer-check-1.0)": "gstreamer",
4305 + "pkgconfig(gstreamer-controller-1.0)": "gstreamer",
4306 + "pkgconfig(gstreamer-app-1.0)": "gst-plugins-base",
4307 + "pkgconfig(gstreamer-video-1.0)": "gst-plugins-base",
4308 + "pkgconfig(gstreamer-audio-1.0)": "gst-plugins-base",
4309 + "pkgconfig(gstreamer-pbutils-1.0)": "gst-plugins-base",
4310 + "pkgconfig(gstreamer-fft-1.0)": "gst-plugins-base",
4311 + "pkgconfig(gstreamer-riff-1.0)": "gst-plugins-base",
4312 + "pkgconfig(gstreamer-rtp-1.0)": "gst-plugins-base",
4313 + "pkgconfig(gstreamer-rtsp-1.0)": "gst-plugins-base",
4314 + "pkgconfig(gstreamer-sdp-1.0)": "gst-plugins-base",
4315 + "pkgconfig(gstreamer-net-1.0)": "gst-plugins-base",
4316 + "pkgconfig(gstreamer-gl-1.0)": "gst-plugins-base",
4317 + "pkgconfig(libpulse)": "libpulse",
4318 + "pkgconfig(libpulse-simple)": "libpulse",
4319 + "pkgconfig(libpulse-mainloop-glib)": "libpulse",
4320 + "pkgconfig(alsa)": "alsa-lib",
4321 + "pkgconfig(jack)": "jack2",
4322 + "pkgconfig(libsamplerate)": "libsamplerate",
4323 + "pkgconfig(sndfile)": "libsndfile",
4324 + "pkgconfig(libavcodec)": "ffmpeg",
4325 + "pkgconfig(libavformat)": "ffmpeg",
4326 + "pkgconfig(libavutil)": "ffmpeg",
4327 + "pkgconfig(libavfilter)": "ffmpeg",
4328 + "pkgconfig(libswscale)": "ffmpeg",
4329 + "pkgconfig(libswresample)": "ffmpeg",
4330 + "pkgconfig(libpostproc)": "ffmpeg",
4331 + "pkgconfig(SDL2)": "sdl2",
4332 + "pkgconfig(SDL)": "sdl",
4333 + "pkgconfig(SDL2_image)": "sdl2-image",
4334 + "pkgconfig(SDL2_ttf)": "sdl2-ttf",
4335 + "pkgconfig(SDL2_mixer)": "sdl2-mixer",
4336 + "pkgconfig(SDL2_net)": "sdl2-net",
4337 + "pkgconfig(libpng16)": "libpng",
4338 + "pkgconfig(libwebp)": "libwebp",
4339 + "pkgconfig(libwebpmux)": "libwebp",
4340 + "pkgconfig(libwebpdemux)": "libwebp",
4341 + "pkgconfig(libopenjp2)": "openjpeg2",
4342 + "pkgconfig(lcms2)": "lcms2",
4343 + "pkgconfig(libheif)": "libheif",
4344 + "pkgconfig(libde265)": "libde265",
4345 + "pkgconfig(x264)": "x264",
4346 + "pkgconfig(x265)": "x265",
4347 + # ── glib / gio ──
4348 + "pkgconfig(gio-unix-2.0)": "glib",
4349 + "pkgconfig(gmodule-2.0)": "glib",
4350 + "pkgconfig(gthread-2.0)": "glib",
4351 + "pkgconfig(girepository-2.0)": "gobject-introspection",
4352 + "pkgconfig(girepository-1.0)": "gobject-introspection",
4353 + "pkgconfig(libglib-2.0)": "glib",
4354 + "pkgconfig(libgobject-2.0)": "glib",
4355 +}
4356 +
4357 +# Ostrzeżenia o wielu dostawcach tej samej wirtualnej nazwy – raz na proces.
4358 +_PROVIDES_WARNED = set()
4359 +# Cache indeksu provides dla danego obiektu repo: (repo_obj, {virtual: [pkg,...]}).
4360 +# Trzymamy referencję do repo, by uniknąć pomyłki przy ponownym użyciu id().
4361 +_provides_cache = (None, {})
4362 +
4363 +def _provides_index(repo: dict) -> dict:
4364 + """Buduje (i cache’uje) mapę wirtualna nazwa → lista dostawców w repo.
4365 +
4366 + Pozwala wybrać dostawcę DETERMINISTYCZNIE (posortowanego) zamiast zależeć
4367 + od kolejności wstawiania w repo.json, oraz ostrzec o konflikcie provides."""
4368 + global _provides_cache
4369 + cached_repo, idx = _provides_cache
4370 + if cached_repo is repo:
4371 + return idx
4372 + idx = {}
4373 + for _pn, _p in repo.items():
4374 + for _prov in (getattr(_p, "provides", None) or []):
4375 + idx.setdefault(_prov, []).append(_pn)
4376 + for _prov, _pns in idx.items():
4377 + if len(_pns) > 1 and _prov not in _PROVIDES_WARNED:
4378 + _PROVIDES_WARNED.add(_prov)
4379 + _sorted = sorted(_pns)
4380 + print(f" ⚠ {_('provides_conflict', name=_prov, providers=', '.join(_sorted), chosen=_sorted[0])}",
4381 + file=sys.stderr)
4382 + _provides_cache = (repo, idx)
4383 + return idx
4384 +
4385 +
4386 +def _resolve_provides(name: str, repo: dict, installed: Optional[dict] = None) -> str:
4387 + """Rozwija wirtualną nazwę pakietu do rzeczywistej nazwy.
4388 +
4389 + Kolejność: repo → PROVIDES_MAP → wzorce → provides z repo.json →
4390 + provides ZAINSTALOWANYCH pakietów (lokalnie zbudowane poza repo też
4391 + dostarczają wirtualne zależności) → fallback pkgconfig (czyszczenie nazwy).
4392 + """
4393 + if name in repo:
4394 + return name
4395 + if name in PROVIDES_MAP:
4396 + real = PROVIDES_MAP[name]
4397 + if real in repo:
4398 + return real
4399 + # Wzorce: moduły Qt (Qt5Core/Qt6Widgets) i GStreamer (gstreamer-video-1.0)
4400 + if name.startswith("pkgconfig(Qt5"):
4401 + real = "qt5"
4402 + if real in repo:
4403 + return real
4404 + if name.startswith("pkgconfig(Qt6"):
4405 + real = "qt6"
4406 + if real in repo:
4407 + return real
4408 + if name.startswith("pkgconfig(gstreamer-") and name.endswith("-1.0)"):
4409 + real = "gstreamer"
4410 + if real in repo:
4411 + return real
4412 + if name.startswith("pkgconfig(gst-"):
4413 + real = "gst-plugins-base"
4414 + if real in repo:
4415 + return real
4416 + # Dynamiczne provides z repo.json (sekcja provides: w PAGBUILD.yaml)
4417 + # Determinizm: przy wielu dostawcach wybieramy posortowanego pierwszego
4418 + # (i ostrzegamy raz), zamiast zależeć od kolejności w repo.json.
4419 + _idx = _provides_index(repo)
4420 + if name in _idx:
4421 + return min(_idx[name])
4422 + # provides ZAINSTALOWANYCH pakietów – lokalnie zbudowane (pagbuild, poza
4423 + # repo) też dostarczają wirtualne zależności i muszą być rozpoznawane.
4424 + if installed:
4425 + _inst_cands = [pn for pn, meta in installed.items()
4426 + if isinstance(meta, dict) and name in (meta.get("provides") or [])]
4427 + if _inst_cands:
4428 + return min(_inst_cands)
4429 + clean = name
4430 + if name.startswith("pkgconfig(") and ")" in name:
4431 + clean = name.split("(", 1)[1].rstrip(")")
4432 + elif name.startswith("pkgconfig32(") and ")" in name:
4433 + clean = name.split("(", 1)[1].rstrip(")")
4434 + if clean != name and clean in repo:
4435 + return clean
4436 + return name
4437 +
4438 +
4439 +def cmd_why(pkg_name: str):
4440 + """Pokazuje dlaczego pakiet jest zainstalowany."""
4441 + installed = load_json(INSTALLED_DB)
4442 + world = load_world()
4443 + if pkg_name not in installed:
4444 + print(f" {pkg_name}: {_('why_not_installed')}"); return 1
4445 + if pkg_name in world:
4446 + print(f" {pkg_name}-{installed[pkg_name]['version']}: {_('why_explicit')}")
4447 + return 0
4448 + parents = set()
4449 + for w in world:
4450 + _find_dep_path(w, pkg_name, installed, set(), [], parents)
4451 + if parents:
4452 + for pp in sorted(parents):
4453 + print(f" {pkg_name}: {_('why_dependency')} {' → '.join(pp)}")
4454 + else:
4455 + print(f" {pkg_name}: {_('why_dependency')} (unknown/orphan)")
4456 + return 0
4457 +
4458 +
4459 +def _find_dep_path(cur, target, installed, visited, path, results):
4460 + if cur in visited: return
4461 + visited.add(cur); path.append(cur)
4462 + if cur == target:
4463 + results.add(tuple(path))
4464 + else:
4465 + for dep in installed.get(cur, {}).get("dependencies", []):
4466 + _find_dep_path(dep, target, installed, visited, path, results)
4467 + path.pop(); visited.discard(cur)
4468 +
4469 +
4470 +def cmd_rdepends(pkg_name: str):
4471 + """Pokazuje które pakiety zależą od danego pakietu (reverse dependencies).
4472 +
4473 + Odwrotność `pag why`: dla każdego zainstalowanego pakietu sprawdza, czy
4474 + któraś z jego zależności (także wirtualna, przez provides) wskazuje na
4475 + pkg_name. Przydatne przed `pag remove` – pokazuje, co przestanie działać.
4476 + """
4477 + installed = load_json(INSTALLED_DB)
4478 + if pkg_name not in installed:
4479 + print(f" {pkg_name}: {_('why_not_installed')}"); return 1
4480 + world = load_world()
4481 + # Nazwy, które zależą od pkg_name – sama nazwa plus jej wirtualne provides.
4482 + provided = {pkg_name} | set(installed[pkg_name].get("provides") or [])
4483 + rev = []
4484 + for name, meta in installed.items():
4485 + if name == pkg_name:
4486 + continue
4487 + for dep in (meta.get("dependencies") or []):
4488 + if dep in provided or _resolve_provides(dep, {}, installed) == pkg_name:
4489 + rev.append(name); break
4490 + if not rev:
4491 + print(f" {pkg_name}: {_('rdepends_none')}")
4492 + return 0
4493 + print(f"🔗 {_('rdepends_title', pkg_name, len(rev))}")
4494 + for n in sorted(rev):
4495 + kind = _("why_explicit") if n in world else _("why_dependency")
4496 + print(f" {n}-{installed[n].get('version', '?')} ({kind})")
4497 + return 0
4498 +
4499 +
4500 +def cmd_autoremove():
4501 + """Automatycznie usuwa osierocone zależności bez pytania."""
4502 + installed = load_json(INSTALLED_DB)
4503 + world = load_world()
4504 + orphans = _find_orphans(installed, world)
4505 + if not orphans: print(f"✅ {_('autoremove_none')}"); return 0
4506 + print(f"🗑 {_('orphans_found', len(orphans), ', '.join(sorted(orphans)[:10]))}")
4507 + return cmd_remove(list(orphans))
4508 +
4509 +
4510 +def cmd_download(package_names):
4511 + """Pobiera pakiety do cache bez instalowania."""
4512 + ensure_dirs()
4513 + repo = fetch_all_packages()
4514 + if not repo: print(f"❌ {_('no_index')}"); return 1
4515 + total_size = 0; downloaded = []
4516 + for name in package_names:
4517 + pkg = repo.get(name)
4518 + if not pkg:
4519 + print(f" ❌ {name}: {_('not_found')}"); continue
4520 + print(f" ↓ {name}-{pkg.version} ...", end=" ", flush=True)
4521 + path = _download_pkg(pkg)
4522 + if path:
4523 + total_size += os.path.getsize(path)
4524 + downloaded.append(name)
4525 + print(_c("green", "✓"))
4526 + else:
4527 + print(_c("red", "✗"))
4528 + if downloaded:
4529 + print(f"\n✅ {_('downloaded', len(downloaded), total_size/1048576)}")
4530 + return 0 if len(downloaded) == len(package_names) else 1
4531 +
4532 +
4533 +def cmd_stats():
4534 + """Wyświetla statystyki PAG."""
4535 + installed = load_json(INSTALLED_DB)
4536 + history = load_json(HISTORY_FILE) if os.path.exists(HISTORY_FILE) else []
4537 + total_size = sum(i.get("size_bytes", 0) for i in installed.values())
4538 + total_files = _db_count_files()
4539 + cache_size = sum(
4540 + os.path.getsize(os.path.join(PAG_CACHE, f))
4541 + for f in os.listdir(PAG_CACHE)
4542 + if os.path.isfile(os.path.join(PAG_CACHE, f))
4543 + ) if os.path.isdir(PAG_CACHE) else 0
4544 + last_update = "never"
4545 + for e in reversed(history):
4546 + if e.get("action") in ("install", "upgrade") and e.get("success"):
4547 + last_update = e.get("timestamp", "?")[:19]; break
4548 + print(f"\n {_c('bold', _('stats_title'))}")
4549 + print(f" {'─' * 40}")
4550 + print(f" {_('stats_packages'):<30} {len(installed)}")
4551 + print(f" {_('stats_files'):<30} {total_files}")
4552 + print(f" {_('stats_size'):<30} {total_size/1048576:.1f} MB")
4553 + print(f" {_('stats_cache'):<30} {cache_size/1048576:.1f} MB")
4554 + print(f" {_('stats_history'):<30} {len(history)}")
4555 + print(f" {_('stats_last_update'):<30} {last_update}")
4556 + _bs = _base_summary(repo={}) # bez sieci – tylko stan zarządzania bazą
4557 + if _bs["total"]:
4558 + _bt = f"{_bs['tracked']}/{_bs['total']}"
4559 + if _bs["tracked"] < _bs["total"]:
4560 + _bt += " (sudo pag base adopt)"
4561 + print(f" {_('stats_base'):<30} {_bt}")
4562 + by_size = sorted(installed.items(), key=lambda x: x[1].get("size_bytes", 0), reverse=True)[:5]
4563 + if by_size:
4564 + print(f"\n {_c('dim', 'Top 5:')}")
4565 + for n, i in by_size:
4566 + print(f" {n}-{i['version']} {i.get('size_bytes',0)/1048576:.1f} MB")
4567 + return 0
4568 +
4569 +
4570 +def cmd_repo_add(url, name=None):
4571 + if not url.startswith("https://") and not os.environ.get("PAG_INSECURE"):
4572 + print(f" {_('sec_https')}"); return 1
4573 + ensure_dirs()
4574 + url = url.rstrip("/")
4575 + repos = get_repos()
4576 + if url in repos: print(f"⚠ {_('repo_exists', url)}"); return
4577 + if name:
4578 + # Drop-in: /etc/pag/repos/<nazwa>.conf (jak `echo url > .../stable.conf`)
4579 + os.makedirs(REPOS_DIR, exist_ok=True)
4580 + target = os.path.join(REPOS_DIR, name.rstrip("/").replace("/", "_") + ".conf")
4581 + with open(target, "w") as f: f.write(f"{url}\n")
4582 + print(f"✅ {_('repo_added', url)} → {target}")
4583 + return
4584 + with open(REPOS_CONF, "a") as f: f.write(f"{url}\n")
4585 + print(f"✅ {_('repo_added', url)}")
4586 +
4587 +def cmd_repo_list():
4588 + for i, url in enumerate(get_repos(), 1): print(f" {i}. {url}")
4589 +
4590 +FLATPAK_REMOTE_URL = "https://flathub.org/repo/flathub.flatpakrepo"
4591 +
4592 +def _check_flatpak(quiet: bool = False):
4593 + if not shutil.which("flatpak"):
4594 + if not quiet:
4595 + print(f"❌ {_('flatpak_missing')}")
4596 + return False
4597 + r = subprocess.run(["flatpak", "remotes"], capture_output=True, text=True)
4598 + if "flathub" not in r.stdout:
4599 + print(f"⚠ {_('flatpak_adding')}")
4600 + # Jako root dodajemy remote systemowy; bez roota – w instalacji użytkownika,
4601 + # żeby remote i miejsce instalacji były spójne (patrz _flatpak_do_install).
4602 + add = ["flatpak", "remote-add", "--if-not-exists"]
4603 + if os.geteuid() != 0:
4604 + add.append("--user")
4605 + subprocess.run(add + ["flathub", FLATPAK_REMOTE_URL], check=False)
4606 + return True
4607 +
4608 +def _spinner(msg: str):
4609 + """Prosty spinner „myślenia” w osobnym wątku. Zwraca funkcję stop()."""
4610 + stop = threading.Event()
4611 + def _spin():
4612 + for c in itertools.cycle("|/-\\"):
4613 + if stop.is_set():
4614 + break
4615 + sys.stdout.write(f"\r {msg} {c}")
4616 + sys.stdout.flush()
4617 + time.sleep(0.1)
4618 + t = threading.Thread(target=_spin, daemon=True)
4619 + t.start()
4620 + def _stop():
4621 + stop.set()
4622 + t.join(timeout=0.3)
4623 + sys.stdout.write("\r" + " " * (len(msg) + 4) + "\r")
4624 + sys.stdout.flush()
4625 + return _stop
4626 +
4627 +
4628 +def _flatpak_search_raw(query: str) -> List[dict]:
4629 + """Szuka we Flathub i zwraca listę wyników jako słowniki."""
4630 + if not _check_flatpak():
4631 + return []
4632 + stop = _spinner("Szukam we Flathub...")
4633 + try:
4634 + try:
4635 + r = subprocess.run(
4636 + ["flatpak", "search", "--columns=name,description,application,version,branch,remotes", query],
4637 + capture_output=True, text=True, timeout=120
4638 + )
4639 + finally:
4640 + stop()
4641 + if r.returncode != 0 and "No matches found" not in r.stdout and not r.stdout.strip():
4642 + print(f" ⚠ flatpak search: {r.stderr.strip()[:150]}")
4643 + results = []
4644 + for line in r.stdout.strip().split("\n"):
4645 + parts = line.split("\t")
4646 + if len(parts) >= 3:
4647 + results.append({
4648 + "name": parts[0].strip(),
4649 + "description": parts[1].strip() if len(parts) > 1 else "",
4650 + "app_id": parts[2].strip() if len(parts) > 2 else "",
4651 + "version": parts[3].strip() if len(parts) > 3 else "",
4652 + "branch": parts[4].strip() if len(parts) > 4 else "stable",
4653 + "origin": parts[5].strip() if len(parts) > 5 else "flathub",
4654 + })
4655 + return results
4656 + except Exception as e:
4657 + print(f" ⚠ Błąd wyszukiwania: {e}", file=sys.stderr)
4658 + return []
4659 +
4660 +def _flatpak_find_best(query: str) -> Optional[dict]:
4661 + """
4662 + Szuka we Flathub i próbuje znaleźć najlepsze dopasowanie.
4663 + - Jeśli query dokładnie pasuje do app_id → zwraca od razu
4664 + - Jeśli query pasuje do nazwy → zwraca pierwsze
4665 + - Jeśli wiele wyników → wyświetla listę i pyta użytkownika
4666 + - Jeśli brak → zwraca None
4667 + """
4668 + results = _flatpak_search_raw(query)
4669 + if not results:
4670 + return None
4671 +
4672 + # Dokładne dopasowanie app_id
4673 + exact = [r for r in results if r["app_id"].lower() == query.lower()]
4674 + if exact:
4675 + return exact[0]
4676 +
4677 + # Dokładne dopasowanie nazwy
4678 + exact_name = [r for r in results if r["name"].lower() == query.lower()]
4679 + if exact_name:
4680 + return exact_name[0]
4681 +
4682 + # Jednoznaczne dopasowanie (tylko 1 wynik)
4683 + if len(results) == 1:
4684 + return results[0]
4685 +
4686 + # Wiele wyników – pokaż użytkownikowi
4687 + print(f"\n {_('flatpak_found', len(results))}")
4688 + for i, r in enumerate(results):
4689 + print(f" {i+1}. {_c('bold', r['name'])} ({r['app_id']})")
4690 + if r["version"]:
4691 + print(f" {_('flatpak_info_version')}: {r['version']}")
4692 + if r["description"]:
4693 + desc = r["description"][:80] + ("..." if len(r["description"]) > 80 else "")
4694 + print(f" {desc}")
4695 +
4696 + try:
4697 + choice = input(f"\n Wybierz numer (1-{len(results)}) lub Enter aby anulować: ").strip()
4698 + if not choice:
4699 + return None
4700 + idx = int(choice) - 1
4701 + if 0 <= idx < len(results):
4702 + return results[idx]
4703 + except (EOFError, ValueError, IndexError):
4704 + pass
4705 + return None
4706 +
4707 +def _flatpak_get_installed_info(app_id: str) -> Optional[dict]:
4708 + """Zwraca info o zainstalowanym flatpaku lub None."""
4709 + try:
4710 + r = subprocess.run(
4711 + ["flatpak", "info", "--columns=name,version,branch,origin,installed-size,description", app_id],
4712 + capture_output=True, text=True, timeout=10
4713 + )
4714 + if r.returncode != 0:
4715 + return None
4716 + parts = r.stdout.strip().split("\t")
4717 + if len(parts) < 3:
4718 + return None
4719 + return {
4720 + "name": parts[0].strip(),
4721 + "version": parts[1].strip() if len(parts) > 1 else "",
4722 + "branch": parts[2].strip() if len(parts) > 2 else "",
4723 + "origin": parts[3].strip() if len(parts) > 3 else "",
4724 + "size": parts[4].strip() if len(parts) > 4 else "",
4725 + "description": parts[5].strip() if len(parts) > 5 else "",
4726 + }
4727 + except Exception:
4728 + return None
4729 +
4730 +def _flatpak_is_installed(app_id: str) -> bool:
4731 + """Sprawdza czy flatpak o danym ID jest zainstalowany."""
4732 + try:
4733 + r = subprocess.run(
4734 + ["flatpak", "info", app_id],
4735 + capture_output=True, text=True, timeout=10
4736 + )
4737 + return r.returncode == 0
4738 + except Exception:
4739 + return False
4740 +
4741 +# =============================================================================
4742 +# FLATPAK – KOMENDY GŁÓWNE (zunifikowany interfejs)
4743 +# =============================================================================
4744 +# pag flatpak <query> → szuka i proponuje instalację (jeśli nie zainstalowany)
4745 +# pag flatpak search <query> → tylko szuka
4746 +# pag flatpak install <query> → instaluje
4747 +# pag flatpak remove <id> → usuwa
4748 +# pag flatpak list → lista zainstalowanych
4749 +# pag flatpak update → aktualizuje wszystkie
4750 +# pag flatpak info <id> → szczegóły flatpaka
4751 +
4752 +def cmd_flatpak(args: list):
4753 + """
4754 + Główna komenda flatpak – inteligentnie rozpoznaje intencję:
4755 + pag flatpak firefox → szuka i instaluje (jeśli nieznaleziony → szuka)
4756 + pag flatpak search firefox → tylko wyszukiwanie
4757 + pag flatpak install ... → bezpośrednia instalacja
4758 + pag flatpak remove ... → odinstalowanie
4759 + pag flatpak list → lista
4760 + pag flatpak update → aktualizacja
4761 + pag flatpak info ... → szczegóły
4762 + """
4763 + if not _check_flatpak():
4764 + return 1
4765 +
4766 + if not args:
4767 + # Bez argumentów – domyślnie lista
4768 + return cmd_flatpak_list()
4769 +
4770 + subcmd = args[0].lower()
4771 + rest = args[1:]
4772 +
4773 + # ── Podkomendy jawne ────────────────────────────────────────────────
4774 + if subcmd == "search":
4775 + if not rest:
4776 + print(_("flatpak_usage")); return 1
4777 + return cmd_flatpak_search(" ".join(rest))
4778 +
4779 + elif subcmd == "install":
4780 + if not rest:
4781 + print(_("flatpak_usage")); return 1
4782 + return _flatpak_smart_install(rest)
4783 +
4784 + elif subcmd == "remove" or subcmd == "uninstall":
4785 + if not rest:
4786 + print(_("flatpak_usage")); return 1
4787 + return _flatpak_smart_remove(rest)
4788 +
4789 + elif subcmd == "list":
4790 + return cmd_flatpak_list()
4791 +
4792 + elif subcmd == "update":
4793 + return cmd_flatpak_update()
4794 +
4795 + elif subcmd == "info":
4796 + if not rest:
4797 + print(_("flatpak_usage")); return 1
4798 + return cmd_flatpak_info(rest[0])
4799 +
4800 + else:
4801 + # ── Inteligentne wykrywanie: pag flatpak <nazwa> ────────────────
4802 + # Sprawdź czy to zainstalowany flatpak → pokaż info
4803 + # Jeśli nie → szukaj i zaproponuj instalację
4804 + query = " ".join(args)
4805 +
4806 + # Najpierw sprawdź czy już zainstalowany
4807 + if _flatpak_is_installed(query):
4808 + print(f" 📦 {_c('green', query)} – already installed (use 'pag flatpak info {query}' for details)")
4809 + return cmd_flatpak_info(query)
4810 +
4811 + # Szukaj we Flathub
4812 + print(f" {_('flatpak_searching', query)}")
4813 + best = _flatpak_find_best(query)
4814 + if not best:
4815 + print(f" ❌ '{query}' – {_('flatpak_not_found')}")
4816 + return 1
4817 +
4818 + print(f"\n {_c('cyan', best['name'])} ({best['app_id']})")
4819 + if best["version"]:
4820 + print(f" {_('flatpak_info_version')}: {best['version']}")
4821 + if best["description"]:
4822 + print(f" {best['description']}")
4823 +
4824 + try:
4825 + ans = input(f"\n {_('flatpak_install_prompt', best['name'])}").strip().lower()
4826 + except (EOFError, KeyboardInterrupt):
4827 + print(f"\n ⚠ {_('no_tty')}")
4828 + return 0
4829 + if ans and ans not in ("t", "y"):
4830 + print(_("cancelled"))
4831 + return 0
4832 +
4833 + return _flatpak_do_install(best["app_id"])
4834 +
4835 +def _flatpak_smart_install(names: list) -> int:
4836 + """Instaluje flatpaki – obsługuje nazwy częściowe (wyszukuje przed instalacją)."""
4837 + failed = 0
4838 + for name in names:
4839 + if "." in name and "/" not in name:
4840 + # Wygląda na pełne app_id (np. org.mozilla.firefox)
4841 + app_id = name
4842 + else:
4843 + # Szukaj najlepszego dopasowania
4844 + best = _flatpak_find_best(name)
4845 + if not best:
4846 + print(f" ❌ '{name}' – {_('flatpak_not_found')}")
4847 + failed += 1
4848 + continue
4849 + app_id = best["app_id"]
4850 + print(f" → {best['name']} ({app_id})")
4851 +
4852 + if _flatpak_do_install(app_id) != 0:
4853 + failed += 1
4854 + return 1 if failed else 0
4855 +
4856 +def _flatpak_export_dirs() -> List[str]:
4857 + """Katalogi eksportów Flatpaka (system + użytkownika) obecne na dysku.
4858 +
4859 + Instalacja użytkownika roota (/root/.local/share/flatpak) jest świadomie
4860 + POMIJANA – to wewnętrzny artefakt roota, którego sesja użytkownika nigdy
4861 + nie zobaczy (patrz _flatpak_do_install)."""
4862 + dirs = ["/var/lib/flatpak/exports"]
4863 + home = os.path.expanduser("~")
4864 + if home and home not in ("/root", "/"):
4865 + dirs.append(os.path.join(home, ".local", "share", "flatpak", "exports"))
4866 + return [d for d in dirs if os.path.isdir(d)]
4867 +
4868 +
4869 +def _flatpak_refresh_caches() -> None:
4870 + """Odświeża cache pulpitu i ikon po zmianie w Flatpaku (best-effort).
4871 +
4872 + Flatpak robi to sam, ale tylko gdy `update-desktop-database` jest w PATH.
4873 + Bez tego nowo zainstalowana aplikacja bywa nieobecna w menu."""
4874 + for exports in _flatpak_export_dirs():
4875 + apps = os.path.join(exports, "share", "applications")
4876 + if os.path.isdir(apps) and shutil.which("update-desktop-database"):
4877 + subprocess.run(["update-desktop-database", apps],
4878 + capture_output=True, check=False, timeout=60)
4879 + icons = os.path.join(exports, "share", "icons", "hicolor")
4880 + if os.path.isdir(icons) and shutil.which("gtk-update-icon-cache"):
4881 + subprocess.run(["gtk-update-icon-cache", "-q", "-t", "-f", icons],
4882 + capture_output=True, check=False, timeout=120)
4883 +
4884 +
4885 +def _flatpak_session_sees_exports() -> bool:
4886 + """Czy bieżąca sesja ma eksporty Flatpaka w XDG_DATA_DIRS."""
4887 + raw = os.environ.get("XDG_DATA_DIRS", "")
4888 + dirs = {d for d in raw.split(":") if d} or {"/usr/local/share", "/usr/share"}
4889 + return any(os.path.join(e, "share") in dirs for e in _flatpak_export_dirs())
4890 +
4891 +
4892 +def _flatpak_warn_if_invisible() -> None:
4893 + """Ostrzega, gdy sesja nie widzi eksportów – inaczej wygląda to jak
4894 + „zainstalowało się, ale nie ma go w menu / na PC”."""
4895 + if not _flatpak_session_sees_exports():
4896 + print(f" ⚠ {_('flatpak_menu_hint')}")
4897 + print(f" {_('flatpak_menu_fix')}")
4898 +
4899 +
4900 +def _flatpak_do_install(app_id: str) -> int:
4901 + """Wykonuje właściwą instalację flatpaka.
4902 +
4903 + Jako root wymuszamy instalację SYSTEMOWĄ (--system). Bez tego `flatpak`
4904 + uruchomiony jako root potrafi zainstalować aplikację w instalacji
4905 + użytkownika roota (/root/.local/share/flatpak) – widocznej dla roota, ale
4906 + nie dla zalogowanego użytkownika. To dokładnie efekt „instaluje, ale nie
4907 + mam tego na PC”. Bez roota próbujemy instalacji systemowej (polkit),
4908 + a w razie niepowodzenia cofamy się do instalacji użytkownika (--user).
4909 +
4910 + Zakres (scope) ma znaczenie: instalacja SYSTEMOWA (--system) jest widoczna
4911 + dla wszystkich użytkowników, a --user tylko dla bieżącego (dla roota:
4912 + /root/.local/... → niewidoczna dla sesji). `flatpak list` bez flag pokazuje
4913 + oba zakresy, więc systemowa instalacja roota jest widoczna też dla
4914 + zwykłego użytkownika."""
4915 + print(f" {_('flatpak_installing', app_id)}")
4916 + if os.geteuid() == 0:
4917 + result = subprocess.run(
4918 + ["flatpak", "install", "-y", "--system", "flathub", app_id],
4919 + check=False, timeout=600)
4920 + else:
4921 + result = subprocess.run(
4922 + ["flatpak", "install", "-y", "flathub", app_id],
4923 + check=False, timeout=600)
4924 + if result.returncode != 0:
4925 + # Flathub tylko dla użytkownika / brak agenta polkit – instalacja
4926 + # lokalna użytkownika jest lepsza niż twardy błąd.
4927 + subprocess.run(
4928 + ["flatpak", "remote-add", "--if-not-exists", "--user",
4929 + "flathub", FLATPAK_REMOTE_URL], check=False, timeout=60)
4930 + result = subprocess.run(
4931 + ["flatpak", "install", "-y", "--user", "flathub", app_id],
4932 + check=False, timeout=600)
4933 + if result.returncode != 0:
4934 + print(f" ❌ {_('download_fail')}: {app_id}")
4935 + return 1
4936 + _flatpak_refresh_caches()
4937 + print(f" ✅ {_('flatpak_installed', app_id)}")
4938 + _flatpak_warn_if_invisible()
4939 + return 0
4940 +
4941 +def _flatpak_smart_remove(names: list) -> int:
4942 + """Usuwa flatpaki – obsługuje nazwy częściowe."""
4943 + # Pobierz listę zainstalowanych
4944 + try:
4945 + r = subprocess.run(
4946 + ["flatpak", "list", "--columns=application,name"],
4947 + capture_output=True, text=True, timeout=10
4948 + )
4949 + installed = {}
4950 + for line in r.stdout.strip().split("\n"):
4951 + parts = line.split("\t")
4952 + if len(parts) >= 2:
4953 + installed[parts[0].strip()] = parts[1].strip()
4954 + except Exception:
4955 + installed = {}
4956 +
4957 + failed = 0
4958 + for name in names:
4959 + app_id = name
4960 +
4961 + # Jeśli nie podano pełnego ID – spróbuj dopasować
4962 + if name not in installed:
4963 + matches = {aid: aname for aid, aname in installed.items()
4964 + if name.lower() in aid.lower() or name.lower() in aname.lower()}
4965 + if len(matches) == 0:
4966 + print(f" ❌ '{name}' – {_('flatpak_not_installed', name)}")
4967 + failed += 1
4968 + continue
4969 + elif len(matches) == 1:
4970 + app_id = list(matches.keys())[0]
4971 + print(f" → {matches[app_id]} ({app_id})")
4972 + else:
4973 + print(f"\n Wiele dopasowań dla '{name}':")
4974 + for i, (aid, aname) in enumerate(sorted(matches.items()), 1):
4975 + print(f" {i}. {aname} ({aid})")
4976 + try:
4977 + choice = input(f"\n Wybierz numer (1-{len(matches)}) lub Enter: ").strip()
4978 + if not choice:
4979 + failed += 1
4980 + continue
4981 + aid_list = sorted(matches.keys())
4982 + app_id = aid_list[int(choice) - 1]
4983 + except (EOFError, ValueError, IndexError):
4984 + failed += 1
4985 + continue
4986 +
4987 + print(f" 🗑 {app_id} ...", end=" ", flush=True)
4988 + result = subprocess.run(
4989 + ["flatpak", "uninstall", "-y", app_id],
4990 + capture_output=True, text=True, timeout=120
4991 + )
4992 + if result.returncode == 0:
4993 + print("✅")
4994 + print(f" {_('flatpak_removed', app_id)}")
4995 + else:
4996 + print("❌")
4997 + failed += 1
4998 + if not failed:
4999 + _flatpak_refresh_caches()
5000 + return 1 if failed else 0
5001 +
5002 +def cmd_flatpak_search(q: str):
5003 + """Wyszukuje we Flathub i wyświetla wyniki (z możliwością wyboru do instalacji)."""
5004 + if not _check_flatpak():
5005 + return 1
5006 + results = _flatpak_search_raw(q)
5007 + if not results:
5008 + print(f" ❌ '{q}' – {_('flatpak_not_found')}")
5009 + return 1
5010 + print(f"\n {_('flatpak_found', len(results))}")
5011 + shown = results[:30] # max 30 wyników
5012 + for i, r in enumerate(shown, 1):
5013 + installed = "📦 " if _flatpak_is_installed(r["app_id"]) else " "
5014 + print(f" {i:>2}. {installed}{_c('bold', r['name'])} ({r['app_id']})")
5015 + if r["version"]:
5016 + print(f" {_('flatpak_info_version')}: {r['version']} | {_('flatpak_info_branch')}: {r['branch']}")
5017 + if r["description"]:
5018 + desc = r["description"][:100] + ("..." if len(r["description"]) > 100 else "")
5019 + print(f" {_c('dim', desc)}")
5020 + if len(results) > 30:
5021 + print(f" ... i {len(results) - 30} więcej. Doprecyzuj zapytanie.")
5022 +
5023 + # Interaktywny wybór – wpisz numer, aby zainstalować (Enter = anuluj)
5024 + try:
5025 + ans = input(f"\n Wybierz numer do zainstalowania (1-{len(shown)}) lub Enter aby anulować: ").strip()
5026 + except (EOFError, KeyboardInterrupt):
5027 + return 0
5028 + if ans:
5029 + try:
5030 + idx = int(ans) - 1
5031 + if 0 <= idx < len(shown):
5032 + return _flatpak_do_install(shown[idx]["app_id"])
5033 + print(_("cancelled"))
5034 + except (ValueError, IndexError):
5035 + print(_("cancelled"))
5036 + return 0
5037 +
5038 +def cmd_flatpak_list():
5039 + """Wyświetla zainstalowane flatpaki."""
5040 + if not _check_flatpak():
5041 + return 1
5042 + r = subprocess.run(
5043 + ["flatpak", "list", "--columns=application,name,version,origin,installation,installed-size"],
5044 + capture_output=True, text=True, timeout=10
5045 + )
5046 + lines = [l for l in r.stdout.strip().split("\n") if l.strip()]
5047 + if not lines:
5048 + print(" (brak zainstalowanych flatpaków)")
5049 + return 0
5050 + print(f" Zainstalowane flatpaki ({len(lines)}):")
5051 + for line in lines:
5052 + parts = line.split("\t")
5053 + if len(parts) >= 3:
5054 + app_id, name, version = parts[0], parts[1], parts[2]
5055 + scope = parts[4] if len(parts) > 4 else ""
5056 + size = parts[5] if len(parts) > 5 else ""
5057 + size_str = f" ({size})" if size else ""
5058 + scope_str = f" [{scope}]" if scope else ""
5059 + print(f" 📦 {_c('bold', name)} {version}{scope_str}{size_str}")
5060 + print(f" {_c('dim', app_id)}")
5061 + return 0
5062 +
5063 +def cmd_flatpak_update():
5064 + """Aktualizuje wszystkie flatpaki."""
5065 + if not _check_flatpak():
5066 + return 1
5067 + print(" 🔄 Aktualizacja flatpaków...")
5068 + result = subprocess.run(["flatpak", "update", "-y"], check=False, timeout=600)
5069 + if result.returncode == 0:
5070 + _flatpak_refresh_caches()
5071 + print(f" ✅ {_('flatpak_updated')}")
5072 + return result.returncode
5073 +
5074 +def cmd_flatpak_info(app_id: str):
5075 + """Wyświetla szczegóły flatpaka (zainstalowanego lub z Flathub)."""
5076 + if not _check_flatpak():
5077 + return 1
5078 +
5079 + # Najpierw sprawdź zainstalowany
5080 + info = _flatpak_get_installed_info(app_id)
5081 + if info:
5082 + print(f"\n 📦 {_c('bold', info['name'])} {_c('green', '[zainstalowany]')}")
5083 + print(f" {'─' * 45}")
5084 + print(f" {_('flatpak_info_id'):<16} {app_id}")
5085 + print(f" {_('flatpak_info_version'):<16} {info['version']}")
5086 + print(f" {_('flatpak_info_branch'):<16} {info['branch']}")
5087 + print(f" {_('flatpak_info_origin'):<16} {info['origin']}")
5088 + if info["size"]:
5089 + print(f" {_('flatpak_info_size'):<16} {info['size']}")
5090 + if info["description"]:
5091 + print(f" {_('flatpak_info_desc'):<16} {info['description']}")
5092 + return 0
5093 +
5094 + # Szukaj we Flathub
5095 + results = _flatpak_search_raw(app_id)
5096 + exact = [r for r in results if r["app_id"].lower() == app_id.lower()]
5097 + if not exact:
5098 + # Spróbuj częściowego dopasowania
5099 + if results:
5100 + exact = [results[0]]
5101 + else:
5102 + print(f" ❌ '{app_id}' – {_('flatpak_not_found')}")
5103 + return 1
5104 +
5105 + r = exact[0]
5106 + print(f"\n 📦 {_c('bold', r['name'])} (Flathub)")
5107 + print(f" {'─' * 45}")
5108 + print(f" {_('flatpak_info_id'):<16} {r['app_id']}")
5109 + print(f" {_('flatpak_info_version'):<16} {r['version']}")
5110 + if r["description"]:
5111 + print(f" {_('flatpak_info_desc'):<16} {r['description']}")
5112 + print(f"\n 💡 Aby zainstalować: pag flatpak install {r['app_id']}")
5113 + return 0
5114 +
5115 +# =============================================================================
5116 +# IMMUTABLE OS – KOMENDY DEPLOYMENTOWE
5117 +# =============================================================================
5118 +
5119 +# Pakiety jądra – po ich instalacji trzeba przebudować initramfs
5120 +KERNEL_PACKAGE_PATTERNS = ["linux", "kernel", "linux-kernel", "linux-lts"]
5121 +
5122 +def _is_kernel_package(name: str) -> bool:
5123 + """Sprawdza czy pakiet to jądro (wymaga przebudowy initramfs)."""
5124 + name_lower = name.lower()
5125 + return any(pattern in name_lower for pattern in KERNEL_PACKAGE_PATTERNS)
5126 +
5127 +def _rebuild_initramfs(deploy_dir: str = "") -> bool:
5128 + """
5129 + Przebudowuje initramfs dla aktywnego (lub podanego) deploymentu.
5130 + Używa skryptu pag-initramfs lub ręcznego cpio.
5131 + """
5132 + if deploy_dir:
5133 + root = deploy_dir
5134 + else:
5135 + root = _get_deployment_root()
5136 +
5137 + if root == PAG_ROOT:
5138 + # Zwykły system – użyj dracut jeśli dostępny
5139 + if shutil.which("dracut"):
5140 + print(" 🔧 Przebudowa initramfs (dracut)...")
5141 + result = subprocess.run(
5142 + ["dracut", "--force", "/boot/initramfs.img"],
5143 + capture_output=True, text=True, timeout=120
5144 + )
5145 + return result.returncode == 0
5146 + elif shutil.which("mkinitcpio"):
5147 + print(" 🔧 Przebudowa initramfs (mkinitcpio)...")
5148 + result = subprocess.run(
5149 + ["mkinitcpio", "-g", "/boot/initramfs.img"],
5150 + capture_output=True, text=True, timeout=120
5151 + )
5152 + return result.returncode == 0
5153 + else:
5154 + print(" ⚠ Brak dracut/mkinitcpio – initramfs nie został przebudowany")
5155 + return False
5156 +
5157 + # Tryb immutable – budujemy initramfs dla deploymentu
5158 + print(" 🔧 Budowanie initramfs dla deploymentu...")
5159 +
5160 + # Sprawdź czy mamy nasz skrypt init
5161 + pag_init_script = "/usr/share/pag/initramfs-init"
5162 + if not os.path.exists(pag_init_script):
5163 + # Szukaj w źródłach (developerski fallback)
5164 + alt_paths = [
5165 + os.path.join(os.path.dirname(os.path.abspath(__file__)), "scripts", "initramfs-init"),
5166 + "/usr/share/pag/init",
5167 + ]
5168 + for p in alt_paths:
5169 + if os.path.exists(p):
5170 + pag_init_script = p
5171 + break
5172 +
5173 + if not os.path.exists(pag_init_script):
5174 + print(" ⚠ Nie znaleziono pag-initramfs-init – pomijam budowę initramfs")
5175 + return False
5176 +
5177 + boot_dir = os.path.join(root, "boot")
5178 + os.makedirs(boot_dir, exist_ok=True)
5179 +
5180 + # Znajdź jądro (vmlinuz-*)
5181 + kernels = sorted(
5182 + [f for f in os.listdir(boot_dir) if f.startswith("vmlinuz-")],
5183 + reverse=True
5184 + ) if os.path.exists(boot_dir) else []
5185 + if not kernels:
5186 + print(" ⚠ Nie znaleziono vmlinuz-* w /boot deploymentu")
5187 + return False
5188 +
5189 + kernel_ver = kernels[0].replace("vmlinuz-", "")
5190 + print(f" 🐧 Jądro: {kernel_ver}")
5191 +
5192 + # Buduj initramfs ręcznie (cpio)
5193 + tmpdir = tempfile.mkdtemp(prefix="pag-initramfs-")
5194 + try:
5195 + # Podstawowa struktura
5196 + for d in ["bin", "sbin", "dev", "proc", "sys", "run", "new_root",
5197 + "usr/bin", "usr/sbin", "lib", "lib64", "etc"]:
5198 + os.makedirs(os.path.join(tmpdir, d), exist_ok=True)
5199 +
5200 + # Skopiuj init
5201 + shutil.copy2(pag_init_script, os.path.join(tmpdir, "init"))
5202 + os.chmod(os.path.join(tmpdir, "init"), 0o755)
5203 +
5204 + # Skopiuj niezbędne binaria (busybox lub podstawowe narzędzia)
5205 + busybox_paths = [
5206 + os.path.join(root, "usr/bin/busybox"),
5207 + os.path.join(root, "bin/busybox"),
5208 + "/usr/bin/busybox",
5209 + "/bin/busybox",
5210 + ]
5211 + busybox = None
5212 + for bp in busybox_paths:
5213 + if os.path.exists(bp):
5214 + busybox = bp
5215 + break
5216 +
5217 + if busybox:
5218 + shutil.copy2(busybox, os.path.join(tmpdir, "bin/busybox"))
5219 + # Utwórz symlinki dla podstawowych komend
5220 + for cmd in ["sh", "mount", "umount", "ls", "cat", "echo", "sleep",
5221 + "readlink", "mkdir", "switch_root", "cp", "rm"]:
5222 + link = os.path.join(tmpdir, "bin", cmd)
5223 + if not os.path.exists(link):
5224 + os.symlink("busybox", link)
5225 + # /bin/sh → busybox
5226 + if not os.path.exists(os.path.join(tmpdir, "bin/sh")):
5227 + os.symlink("busybox", os.path.join(tmpdir, "bin/sh"))
5228 + else:
5229 + # Bez busybox – kopiuj podstawowe narzędzia z deploymentu
5230 + for tool in ["bash", "mount", "umount", "readlink", "mkdir", "cat", "sleep", "cp", "rm"]:
5231 + src = os.path.join(root, "usr/bin", tool)
5232 + if not os.path.exists(src):
5233 + src = os.path.join(root, "bin", tool)
5234 + if os.path.exists(src):
5235 + dest = os.path.join(tmpdir, "bin", os.path.basename(tool))
5236 + shutil.copy2(src, dest)
5237 + # Kopiuj zależności .so
5238 + _copy_libs_for_binary(src, tmpdir, root)
5239 +
5240 + # Dodaj moduły jądra (opcjonalnie – dla sterowników dyskowych)
5241 + modules_src = os.path.join(root, "lib/modules", kernel_ver)
5242 + if os.path.isdir(modules_src):
5243 + modules_dst = os.path.join(tmpdir, "lib/modules", kernel_ver)
5244 + # Kopiuj tylko niezbędne (fs, block, drivers/ata, drivers/nvme)
5245 + for sub in ["kernel/fs", "kernel/drivers/ata", "kernel/drivers/nvme",
5246 + "kernel/drivers/scsi", "kernel/drivers/virtio",
5247 + "modules.order", "modules.builtin"]:
5248 + src_sub = os.path.join(modules_src, sub)
5249 + if os.path.exists(src_sub):
5250 + dst_sub = os.path.join(modules_dst, sub)
5251 + os.makedirs(os.path.dirname(dst_sub), exist_ok=True)
5252 + if os.path.isdir(src_sub):
5253 + try:
5254 + shutil.copytree(src_sub, dst_sub, dirs_exist_ok=True, symlinks=True,
5255 + ignore_dangling_symlinks=True)
5256 + except (FileNotFoundError, PermissionError):
5257 + print(f" ⚠ Pomijam niedostępne pliki: {sub}")
5258 + else:
5259 + try:
5260 + shutil.copy2(src_sub, dst_sub)
5261 + except (FileNotFoundError, PermissionError):
5262 + print(f" ⚠ Pomijam niedostępny plik: {sub}")
5263 +
5264 + # Pakuj do initramfs.img
5265 + initramfs_path = os.path.join(boot_dir, "initramfs.img")
5266 + old_cwd = os.getcwd()
5267 + os.chdir(tmpdir)
5268 + try:
5269 + with open(initramfs_path + ".tmp", "wb") as out:
5270 + _run_cpio_pipeline(tmpdir, out)
5271 + os.rename(initramfs_path + ".tmp", initramfs_path)
5272 + finally:
5273 + os.chdir(old_cwd)
5274 +
5275 + size_mb = os.path.getsize(initramfs_path) / 1048576
5276 + print(f" ✅ initramfs.img ({size_mb:.1f} MB) → {initramfs_path}")
5277 + return True
5278 +
5279 + except Exception as e:
5280 + print(f" ❌ Błąd budowy initramfs: {e}")
5281 + return False
5282 + finally:
5283 + shutil.rmtree(tmpdir, ignore_errors=True)
5284 +
5285 +
5286 +def _run_cpio_pipeline(tmpdir: str, out):
5287 + """find . -print0 | cpio --null -oH newc | gzip — bez shell=True.
5288 +
5289 + Buduje pipeline przez subprocess.Popen, unikając pośrednika powłoki
5290 + (brak ryzyka injection i niepotrzebnego procesu sh). Wykonuje się w cwd=tmpdir.
5291 + Separatory NUL (\0): plik/katalog ze znakiem nowej linii w nazwie nie
5292 + rozjeżdża cpio (inaczej uszkodzone archiwum → kernel panic przy rozruchu).
5293 + """
5294 + find = subprocess.Popen(["find", ".", "-print0"], cwd=tmpdir, stdout=subprocess.PIPE)
5295 + cpio = subprocess.Popen(["cpio", "--null", "-oH", "newc"], cwd=tmpdir,
5296 + stdin=find.stdout, stdout=subprocess.PIPE)
5297 + find.stdout.close() # zwolnij uchwyt – cpio dostanie SIGPIPE po zakończeniu find
5298 + gzip = subprocess.Popen(["gzip"], stdin=cpio.stdout, stdout=out)
5299 + cpio.stdout.close()
5300 + try:
5301 + gzip.wait(timeout=120)
5302 + if gzip.returncode != 0:
5303 + raise subprocess.CalledProcessError(gzip.returncode, ["gzip"])
5304 + cpio.wait(timeout=30)
5305 + find.wait(timeout=30)
5306 + except subprocess.TimeoutExpired:
5307 + for p in (gzip, cpio, find):
5308 + p.kill()
5309 + raise
5310 + finally:
5311 + for p in (find, cpio, gzip):
5312 + if p.poll() is None:
5313 + p.kill()
5314 + # Skontroluj też kody procesów pośrednich (cpio/find mogą zawieść, a gzip zwrócić 0)
5315 + if cpio.returncode != 0:
5316 + raise subprocess.CalledProcessError(cpio.returncode, ["cpio"])
5317 + if find.returncode != 0:
5318 + raise subprocess.CalledProcessError(find.returncode, ["find"])
5319 +
5320 +
5321 +def _copy_libs_for_binary(binary: str, dest_dir: str, root: str):
5322 + """Kopiuje zależności .so dla binarki do initramfs (uproszczone ldd)."""
5323 + try:
5324 + result = subprocess.run(
5325 + ["ldd", binary], capture_output=True, text=True, timeout=10
5326 + )
5327 + for line in result.stdout.split("\n"):
5328 + m = re.search(r'=>\s+(/\S+)', line)
5329 + if m:
5330 + lib_path = m.group(1)
5331 + lib_rel = lib_path.lstrip("/")
5332 + lib_dest = os.path.join(dest_dir, lib_rel)
5333 + if not os.path.exists(lib_dest):
5334 + os.makedirs(os.path.dirname(lib_dest), exist_ok=True)
5335 + # Szukaj w deployment root lub systemie
5336 + if os.path.exists(lib_path):
5337 + shutil.copy2(lib_path, lib_dest)
5338 + else:
5339 + alt = os.path.join(root, lib_rel)
5340 + if os.path.exists(alt):
5341 + shutil.copy2(alt, lib_dest)
5342 + except Exception:
5343 + pass
5344 +
5345 +
5346 +def cmd_initramfs_update():
5347 + """Ręcznie przebudowuje initramfs dla bieżącego deploymentu."""
5348 + ensure_dirs()
5349 + deploy_dir = _get_deployment_root()
5350 + if deploy_dir != PAG_ROOT:
5351 + print(f"🏗️ Deployment: {os.path.basename(deploy_dir)}")
5352 + ok = _rebuild_initramfs(deploy_dir)
5353 + if ok:
5354 + print("✅ Initramfs zaktualizowany.")
5355 + # Po initramfs – zaktualizuj też GRUB
5356 + _update_grub_config()
5357 + else:
5358 + print("❌ Błąd aktualizacji initramfs.")
5359 + return 0 if ok else 1
5360 +
5361 +
5362 +def _update_grub_config():
5363 + """
5364 + Generuje wpisy GRUB dla wszystkich deploymentów.
5365 + Każdy deployment dostaje własny wpis – rollback możliwy z bootloadera.
5366 + """
5367 + grub_cfg = "/boot/grub/grub.cfg"
5368 + if not os.path.exists(os.path.dirname(grub_cfg)):
5369 + return # brak GRUB
5370 +
5371 + deployments = _load_deployments()
5372 + root_dev = _detect_root_device()
5373 + if not root_dev:
5374 + print(" ⚠ Nie udało się wykryć partycji root – wpisy GRUB nie dostaną root=.",
5375 + file=sys.stderr)
5376 + print(" Ustaw PAG_ROOT_DEVICE=/dev/... (lub PAG_GRUB_ROOT) i powtórz.",
5377 + file=sys.stderr)
5378 + root_arg = f" root={root_dev}" if root_dev else ""
5379 +
5380 + lines = [
5381 + "# =====================================================================",
5382 + "# Pagan Linux – GRUB config (wygenerowane przez pag grub-update)",
5383 + f"# Data: {datetime.now().isoformat()}",
5384 + "# =====================================================================",
5385 + "",
5386 + ]
5387 +
5388 + # Domyślny – ostatni (najnowszy) deployment
5389 + if deployments:
5390 + latest = deployments[-1]["id"]
5391 + lines.append(f"set default=0")
5392 + lines.append(f"set timeout=5")
5393 + else:
5394 + lines.append("set default=0")
5395 + lines.append("set timeout=5")
5396 + lines.append("")
5397 +
5398 + # Wpisy dla każdego deploymentu (od najnowszego)
5399 + entry_num = 0
5400 + for d in reversed(deployments):
5401 + deploy_dir = os.path.join(DEPLOYMENTS_DIR, d["id"])
5402 + boot_dir = os.path.join(deploy_dir, "boot")
5403 + kernels = sorted(
5404 + [f for f in os.listdir(boot_dir) if f.startswith("vmlinuz-")],
5405 + reverse=True
5406 + ) if os.path.isdir(boot_dir) else []
5407 +
5408 + kernel_path = f"/.deployments/{d['id']}/boot/{kernels[0]}" if kernels else ""
5409 + initrd_path = f"/.deployments/{d['id']}/boot/initramfs.img"
5410 + initrd_line = f"initrd {initrd_path}" if os.path.exists(os.path.join(boot_dir, "initramfs.img")) else ""
5411 +
5412 + active_mark = " [AKTYWNY]" if d.get("active") else ""
5413 + pkg_list = ", ".join(d.get("packages", [])[:3])
5414 + label = f"Pagan Linux – {d['id']}{active_mark}"
5415 +
5416 + lines.append(f"menuentry '{label}' {{")
5417 + if kernel_path:
5418 + lines.append(f" linux {kernel_path}{root_arg} rw quiet")
5419 + else:
5420 + lines.append(f" # Brak jądra w tym deploymencie")
5421 + if initrd_line:
5422 + lines.append(f" {initrd_line}")
5423 + lines.append("}")
5424 + lines.append("")
5425 + entry_num += 1
5426 +
5427 + # Wpis fallback: zwykły root (gdyby wszystko padło).
5428 + # Uwaga: GRUB NIE rozwija globów – trzeba podać KONKRETNY plik jądra
5429 + # (wcześniejsze `linux /boot/vmlinuz-*` było niepoprawne).
5430 + fallback_kernels = sorted(
5431 + [f for f in os.listdir("/boot") if f.startswith("vmlinuz-")],
5432 + reverse=True
5433 + ) if os.path.isdir("/boot") else []
5434 + lines.append("menuentry 'Pagan Linux – fallback (zwykły root)' {")
5435 + if fallback_kernels:
5436 + lines.append(f" linux /boot/{fallback_kernels[0]}{root_arg} rw quiet")
5437 + else:
5438 + lines.append(" # Brak jądra w /boot")
5439 + lines.append(f" initrd /boot/initramfs.img")
5440 + lines.append("}")
5441 + lines.append("")
5442 +
5443 + # Zapisz
5444 + os.makedirs(os.path.dirname(grub_cfg), exist_ok=True)
5445 + with open(grub_cfg, "w") as f:
5446 + f.write("\n".join(lines))
5447 +
5448 + print(" 📋 GRUB config zaktualizowany – wpisy dla każdego deploymentu")
5449 +
5450 +
5451 +def _root_device_from_fstab(path: str = "/etc/fstab") -> str:
5452 + """Zwraca DEVICE z wpisu dla '/' w fstab (pomija komentarze)."""
5453 + try:
5454 + with open(path, "r", encoding="utf-8", errors="replace") as fh:
5455 + for line in fh:
5456 + line = line.split("#", 1)[0].strip()
5457 + if not line:
5458 + continue
5459 + parts = line.split()
5460 + if len(parts) >= 2 and parts[1] == "/":
5461 + return parts[0]
5462 + except OSError:
5463 + pass
5464 + return ""
5465 +
5466 +
5467 +def _in_chroot() -> bool:
5468 + """Heurystyka: czy działamy w chrocie (build ISO/IMG)?
5469 +
5470 + W chrocie /proc/1/root to root HOSTA – inny system plików niż nasz '/'.
5471 + Na zwykłym systemie PID 1 ma root równy '/'. PAGAN_ROOT ustawiają skrypty
5472 + budujące i jest dziedziczony przez chroot (dodatkowa wskazówka).
5473 + """
5474 + if os.environ.get("PAG_IN_CHROOT") == "1":
5475 + return True
5476 + if os.environ.get("PAGAN_ROOT"):
5477 + return True
5478 + try:
5479 + return os.stat("/").st_dev != os.stat("/proc/1/root").st_dev
5480 + except OSError:
5481 + return False
5482 +
5483 +
5484 +def _detect_root_device() -> str:
5485 + """Wykrywa urządzenie/identyfikator partycji root dla GRUB (root=...).
5486 +
5487 + Kolejność (od najbardziej wiarygodnego w danym kontekście):
5488 + 1) PAG_ROOT_DEVICE / PAG_GRUB_ROOT – jawny override (build ISO/IMG,
5489 + instalator); najpewniejszy, bo nie zgadujemy.
5490 + 2) /etc/fstab TARGETU – w chrocie findmnt '/' zwraca partycję HOSTA,
5491 + a fstab opisuje target (np. root=/dev/sda2 dla obrazu IMG).
5492 + 3) findmnt '/' – na żywym systemie (obsługuje UUID/LUKS/subvol).
5493 + Zwraca "" gdy nie da się ustalić – wtedy GRUB nie dostaje błędnego root=.
5494 + """
5495 + explicit = (os.environ.get("PAG_ROOT_DEVICE")
5496 + or os.environ.get("PAG_GRUB_ROOT") or "").strip()
5497 + if explicit:
5498 + return explicit
5499 +
5500 + fstab_dev = _root_device_from_fstab()
5501 + if _in_chroot() and fstab_dev:
5502 + return fstab_dev
5503 +
5504 + try:
5505 + result = subprocess.run(
5506 + ["findmnt", "-n", "-o", "SOURCE", "/"],
5507 + capture_output=True, text=True, timeout=5
5508 + )
5509 + if result.returncode == 0 and result.stdout.strip():
5510 + return result.stdout.strip()
5511 + except Exception:
5512 + pass
5513 +
5514 + # Ostatnia deska: fstab targetu (lepsze niż hardkodowane /dev/sda1,
5515 + # które na sprzęcie z NVMe dawało niebootowalny system).
5516 + return fstab_dev
5517 +
5518 +
5519 +def cmd_grub_update():
5520 + """Ręcznie regeneruje konfigurację GRUB (wpisy dla deploymentów)."""
5521 + ensure_dirs()
5522 + print("📋 Aktualizacja konfiguracji GRUB...")
5523 + _update_grub_config()
5524 + print("✅ GRUB zaktualizowany.")
5525 + return 0
5526 +
5527 +def cmd_deploy_list():
5528 + """Wyświetla listę wszystkich deploymentów."""
5529 + deployments = _load_deployments()
5530 + if not deployments:
5531 + print(_("no_deployments")); return
5532 +
5533 + print(_("deployments_list", len(deployments)))
5534 + active = os.readlink(ACTIVE_LINK) if os.path.islink(ACTIVE_LINK) else ""
5535 +
5536 + for d in reversed(deployments):
5537 + marker = f" ◀ {_('active_deployment')}" if d.get("active") or d["id"] == os.path.basename(active) else ""
5538 + print(f" {d['id']}{marker}")
5539 + print(f" {d['action']}: {', '.join(d['packages'][:5])}")
5540 + if len(d.get('packages', [])) > 5:
5541 + print(f" +{len(d['packages']) - 5} więcej...")
5542 + print(f" {d['timestamp']}")
5543 +
5544 +
5545 +def cmd_deploy_rollback():
5546 + """Przełącza na poprzedni deployment."""
5547 + deployments = _load_deployments()
5548 + active_indices = [i for i, d in enumerate(deployments) if d.get("active")]
5549 +
5550 + if len(deployments) < 2:
5551 + print(f"❌ {_('deploy_rollback_fail')}"); return 1
5552 +
5553 + current_idx = active_indices[0] if active_indices else len(deployments) - 1
5554 + prev_idx = current_idx - 1 if current_idx > 0 else -1
5555 +
5556 + if prev_idx < 0:
5557 + print(f"❌ {_('deploy_rollback_fail')}"); return 1
5558 +
5559 + prev = deployments[prev_idx]
5560 + prev_dir = os.path.join(DEPLOYMENTS_DIR, prev["id"])
5561 +
5562 + if not os.path.isdir(prev_dir):
5563 + print(f"❌ Deployment {prev['id']} nie istnieje na dysku"); return 1
5564 +
5565 + print(f"⏪ Przywracanie deploymentu: {prev['id']}")
5566 + print(f" {prev['action']}: {', '.join(prev['packages'][:5])}")
5567 +
5568 + if not _ask_confirm():
5569 + return 0
5570 +
5571 + _switch_deployment(prev_dir)
5572 +
5573 + for d in deployments:
5574 + d["active"] = (d["id"] == prev["id"])
5575 + _save_deployments(deployments)
5576 +
5577 + _update_grub_config()
5578 + print(f"✅ {_('deploy_rollback_ok', prev['id'])}")
5579 + print(" 💡 Restart wymagany do przeładowania systemu.")
5580 + return 0
5581 +
5582 +
5583 +def cmd_deploy_cleanup(keep: int = 3):
5584 + """Usuwa stare deploymenty, zachowując ostatnie `keep`."""
5585 + deployments = _load_deployments()
5586 +
5587 + if len(deployments) <= keep:
5588 + print(f"✅ {_('deploy_cleanup_none', keep)}"); return 0
5589 +
5590 + to_remove = deployments[:-keep]
5591 + removed = 0
5592 +
5593 + for d in to_remove:
5594 + deploy_dir = os.path.join(DEPLOYMENTS_DIR, d["id"])
5595 + if os.path.isdir(deploy_dir):
5596 + shutil.rmtree(deploy_dir, ignore_errors=True)
5597 + removed += 1
5598 +
5599 + remaining = deployments[-keep:]
5600 + _save_deployments(remaining)
5601 +
5602 + print(f"✅ {_('deploy_cleanup_ok', removed)}")
5603 + return 0
5604 +
5605 +
5606 +# =============================================================================
5607 +# POMOCNICZE
5608 +# =============================================================================
5609 +
5610 +# Pakiety dostarczane przez bazowy system (zawsze "zainstalowane"). Wchodzą do
5611 +# rootfs z ISO przez data.tar.xz, więc NIE ma ich w repo.json ani w bazie pag –
5612 +# każda zależność od nich (glibc, bash, python3…) wyglądałaby na "brakującą".
5613 +# Współdzielone przez rozwijanie i weryfikację zależności.
5614 +SYSTEM_BASE = {
5615 + "glibc", "libc", "gcc", "g++", "make", "binutils", "coreutils", "bash",
5616 + "linux-api-headers", "kernel-headers", "zlib", "pkg-config", "pkgconf",
5617 + "tar", "gzip", "xz", "bzip2", "findutils", "grep", "sed", "gawk", "awk",
5618 + "diffutils", "patch", "file", "m4", "perl", "python3", "sh",
5619 +}
5620 +
5621 +
5622 +def _resolve_deps(names, repo, installed):
5623 + resolved, visited = [], set()
5624 + missing = [] # zależności których nie ma ani w repo ani zainstalowane
5625 +
5626 + def _is_base(dep):
5627 + """True, gdy zależność dostarcza bazowy system (także przez provides)."""
5628 + return dep in SYSTEM_BASE \
5629 + or _resolve_provides(dep, repo, installed) in SYSTEM_BASE
5630 +
5631 + def visit(name, explicit=False):
5632 + if name in visited: return
5633 +
5634 + # Rozwijanie wirtualnych zależności przez provides
5635 + target = _resolve_provides(name, repo, installed)
5636 +
5637 + # Zależność dostarczana przez bazowy system – nie ma jej w repo ani w
5638 + # bazie pag, więc nie "brakuje" jej i nie próbujemy jej instalować.
5639 + # Wyjątek: nazwa podana wprost przez użytkownika (explicit=True).
5640 + if not explicit and target in SYSTEM_BASE:
5641 + return
5642 +
5643 + if target in visited: return
5644 + visited.add(target)
5645 + if target in repo:
5646 + for dep in repo[target].dependencies:
5647 + real_dep = _resolve_provides(dep, repo, installed)
5648 + real_target = real_dep if real_dep in repo else dep
5649 +
5650 + if _is_base(dep):
5651 + continue
5652 +
5653 + # Sprawdź czy zależność jest dostępna
5654 + if real_target not in installed and real_target not in repo:
5655 + if dep not in missing:
5656 + missing.append(dep)
5657 +
5658 + if dep not in installed:
5659 + visit(real_target)
5660 + elif target not in installed:
5661 + # Pakiet nie istnieje ani w repo ani zainstalowany
5662 + if target not in missing:
5663 + missing.append(target)
5664 +
5665 + if target not in installed and target not in resolved:
5666 + resolved.append(target)
5667 +
5668 + for name in names:
5669 + visit(name, explicit=True)
5670 +
5671 + # Zwróć brakujące (do sprawdzenia przez wywołującego)
5672 + return resolved, missing
5673 +
5674 +def _verify_dependencies(to_install: list, repo: dict, installed: dict) -> int:
5675 + """
5676 + Sprawdza czy wszystkie zależności pakietów do instalacji są spełnione.
5677 + Zwraca liczbę brakujących zależności.
5678 + """
5679 + all_missing = []
5680 + all_warnings = []
5681 +
5682 + for pkg_name in to_install:
5683 + pkg = repo.get(pkg_name)
5684 + if not pkg:
5685 + continue
5686 +
5687 + for dep in pkg.dependencies:
5688 + if dep in SYSTEM_BASE:
5689 + continue # bazowy system dostarcza tę zależność
5690 + real_dep = _resolve_provides(dep, repo, installed)
5691 + # Sprawdź czy zależność jest dostępna (w repo lub już zainstalowana)
5692 + in_repo = real_dep in repo
5693 + in_installed = real_dep in installed
5694 + will_be_installed = real_dep in to_install
5695 +
5696 + if not in_repo and not in_installed and not will_be_installed:
5697 + if dep not in all_missing:
5698 + all_missing.append((pkg_name, dep))
5699 + elif in_repo and not in_installed and not will_be_installed:
5700 + if dep not in [w[1] for w in all_warnings]:
5701 + all_warnings.append((pkg_name, dep, real_dep))
5702 +
5703 + if all_missing:
5704 + print(f"\n❌ {_c('red', 'BRAKUJĄCE ZALEŻNOŚCI')} – nie można zainstalować:")
5705 + for pkg, dep in all_missing:
5706 + print(f" {pkg} → potrzebuje {_c('red', dep)} (brak w repozytoriach)")
5707 + print()
5708 +
5709 + if all_warnings:
5710 + print(f"\n⚠ {_c('yellow', 'NIESPEŁNIONE ZALEŻNOŚCI')} – zostaną doinstalowane:")
5711 + for pkg, dep, real in all_warnings:
5712 + print(f" {pkg} → {dep} ({_c('green', real)} – będzie pobrane)")
5713 + print()
5714 +
5715 + return len(all_missing)
5716 +
5717 +# Biblioteki bazowe (glibc/gcc runtime) – zawsze dostępne, nie wymagają pakietu
5718 +BASE_SO = {
5719 + "libc.so.6", "libm.so.6", "libpthread.so.0", "libdl.so.2", "librt.so.1",
5720 + "libutil.so.1", "libresolv.so.2", "libnsl.so.1", "libcrypt.so.1",
5721 + "ld-linux.so.2", "ld-linux-x86-64.so.2", "ld-linux-aarch64.so.1",
5722 + "libgcc_s.so.1", "linux-vdso.so.1",
5723 +}
5724 +
5725 +def _verify_so_deps(to_install: list, repo: dict, installed: dict) -> int:
5726 + """Sprawdza wymagania ABI (provides_so / requires_so z metadata.json).
5727 +
5728 + Fail-closed TYLKO gdy metadata jawnie deklaruje requires_so, a żaden pakiet
5729 + (bazowy, zainstalowany lub instalowany w tej transakcji) nie dostarcza
5730 + wymaganej wersji biblioteki. Stare pakiety bez tych pól są pomijane.
5731 + """
5732 + provided = set(BASE_SO)
5733 + for n in to_install:
5734 + p = repo.get(n)
5735 + if p:
5736 + provided.update(p.provides_so or [])
5737 + for n, info in installed.items():
5738 + provided.update(info.get("provides_so", []) or [])
5739 +
5740 + missing = []
5741 + for n in sorted(to_install):
5742 + p = repo.get(n)
5743 + if not p:
5744 + continue
5745 + for so in (p.requires_so or []):
5746 + if so not in provided:
5747 + missing.append((n, so))
5748 +
5749 + if missing:
5750 + print(f"\n❌ {_c('red', 'BRAK WYMAGANYCH BIBLIOTEK (ABI so-name)')}:")
5751 + for n, so in missing:
5752 + print(f" {n} → wymaga {_c('red', so)} – żaden pakiet nie dostarcza tej wersji")
5753 + print()
5754 + return len(missing)
5755 +
5756 +def _download_pkg(pkg, attempts: int = 3, progress: bool = True):
5757 + """Pobiera pakiet do cache. `progress=False` wycisza pasek (np. gdy
5758 + równoległy pobierający pokazuje własny pasek zbiorczy)."""
5759 + url = f"{pkg.repo_url}/{pkg.filename}"
5760 + dest = os.path.join(PAG_CACHE, pkg.filename)
5761 + if os.path.exists(dest) and (not pkg.sha256 or _sha256_file(dest) == pkg.sha256):
5762 + _download_pkg_sig(pkg, dest) # upewnij się, że sygnatura jest w cache
5763 + return dest
5764 + last_err = None
5765 + for attempt in range(1, attempts + 1):
5766 + try:
5767 + req = Request(url, headers={"User-Agent":"pag/3.0"})
5768 + with urlopen(req, timeout=600) as resp:
5769 + total = int(resp.headers.get("Content-Length", 0))
5770 + bar = DownloadBar(pkg.filename, total) if progress else None
5771 + with open(dest, "wb") as f:
5772 + while True:
5773 + chunk = resp.read(65536)
5774 + if not chunk:
5775 + break
5776 + f.write(chunk)
5777 + if bar is not None:
5778 + bar.update(len(chunk))
5779 + if bar is not None:
5780 + bar.close()
5781 + if pkg.sha256 and _sha256_file(dest) != pkg.sha256:
5782 + last_err = "SHA256 mismatch"
5783 + try:
5784 + os.remove(dest)
5785 + except OSError:
5786 + pass
5787 + if attempt < attempts:
5788 + print(f" ↻ Ponawiam pobieranie {pkg.filename} "
5789 + f"({attempt}/{attempts - 1})...", file=sys.stderr)
5790 + time.sleep(attempt)
5791 + continue
5792 + return None
5793 + _download_pkg_sig(pkg, dest)
5794 + return dest
5795 + except Exception as e:
5796 + last_err = e
5797 + # Usuń częściowy plik – bez tego mógłby zostać użyty jako „cache”
5798 + # (gdy pakiet nie ma sha256) albo mylić kolejną próbę.
5799 + try:
5800 + if os.path.exists(dest):
5801 + os.remove(dest)
5802 + except OSError:
5803 + pass
5804 + if attempt < attempts:
5805 + print(f" ↻ Ponawiam pobieranie {pkg.filename} "
5806 + f"({attempt}/{attempts - 1})...", file=sys.stderr)
5807 + time.sleep(attempt)
5808 + continue
5809 + print(f" ⚠ Błąd pobierania {pkg.filename}: {last_err}", file=sys.stderr)
5810 + return None
5811 +
5812 +def _download_pkg_sig(pkg, dest):
5813 + """Zapewnia AKTUALNY podpis pakietu (.asc, fallback .sig) w cache.
5814 +
5815 + Istniejący podpis jest używany tylko wtedy, gdy faktycznie weryfikuje TĘ
5816 + paczkę. Inaczej po przebudowie tej samej wersji (ten sam plik, nowy sha256)
5817 + stary podpis zostawał obok nowej paczki i weryfikacja dawała fałszywe
5818 + „NIEPRAWIDŁOWY PODPIS GPG”.
5819 + """
5820 + for ext in (".asc", ".sig"):
5821 + sig_dest = dest + ext
5822 + if os.path.exists(sig_dest):
5823 + ok, _fp = _gpg_verify_fp(sig_dest, dest)
5824 + if ok:
5825 + return
5826 + for ext in (".asc", ".sig"):
5827 + sig_dest = dest + ext
5828 + try:
5829 + req = Request(f"{pkg.repo_url}/{pkg.filename}{ext}", headers={"User-Agent":"pag/3.0"})
5830 + with urlopen(req, timeout=30) as resp:
5831 + data = resp.read()
5832 + except Exception:
5833 + continue
5834 + # nie mieszaj rozszerzeń – zostaje tylko ten wariant podpisu
5835 + for other in (".asc", ".sig"):
5836 + if other != ext:
5837 + try:
5838 + os.remove(dest + other)
5839 + except OSError:
5840 + pass
5841 + with open(sig_dest, "wb") as f:
5842 + f.write(data)
5843 + return
5844 + # Nie udało się pobrać podpisu – usuń nieaktualny z cache, żeby weryfikacja
5845 + # nie porównywała paczki z podpisem od innej wersji (czytelny „BRAK PODPISU”).
5846 + for other in (".asc", ".sig"):
5847 + try:
5848 + os.remove(dest + other)
5849 + except OSError:
5850 + pass
5851 +
5852 +def _download_packages_parallel(pkgs: List[PackageInfo], max_workers: int = 4) -> Dict[str, Optional[str]]:
5853 + """
5854 + Równoległe pobieranie wielu pakietów przez ThreadPoolExecutor.
5855 + Znacząco przyspiesza przy dużych aktualizacjach (50+ pakietów).
5856 + Zwraca słownik {nazwa_pakietu: ścieżka_lub_None}.
5857 + """
5858 + results = {}
5859 + total = len(pkgs)
5860 + completed = 0
5861 + with ThreadPoolExecutor(max_workers=max_workers) as executor:
5862 + future_to_pkg = {executor.submit(_download_pkg, pkg, progress=False): pkg for pkg in pkgs}
5863 + for future in as_completed(future_to_pkg):
5864 + pkg = future_to_pkg[future]
5865 + try:
5866 + results[pkg.name] = future.result()
5867 + except Exception:
5868 + results[pkg.name] = None
5869 + completed += 1
5870 + # Pasek postępu (animowany „drakkar” na TTY)
5871 + pct = completed / total * 100
5872 + bar = _pagan_bar(pct, 20, time.time(), animated=sys.stderr.isatty())
5873 + print(f"\r ⏬ [{bar}] {completed}/{total} ({pct:.0f}%)", end="", file=sys.stderr, flush=True)
5874 + print(file=sys.stderr) # nowa linia po zakończeniu
5875 + return results
5876 +
5877 +def load_world():
5878 + if not os.path.exists(WORLD_FILE): return set()
5879 + return {l.strip() for l in open(WORLD_FILE) if l.strip()}
5880 +
5881 +def save_world(w):
5882 + with open(WORLD_FILE,"w") as f:
5883 + for n in sorted(w): f.write(f"{n}\n")
5884 +
5885 +def _find_orphans(installed, world):
5886 + needed = set(world)
5887 + changed = True
5888 + while changed:
5889 + changed = False
5890 + for n in list(needed):
5891 + for dep in installed.get(n,{}).get("dependencies",[]):
5892 + if dep not in needed and dep in installed:
5893 + needed.add(dep); changed = True
5894 + return {n for n in installed if n not in needed}
5895 +
5896 +# =============================================================================
5897 +# MAIN
5898 +# =============================================================================
5899 +
5900 +def cmd_sbom(argv):
5901 + """pag sbom export [spdx|cyclonedx] – manifest SBOM zainstalowanych pakietów.
5902 +
5903 + Wypisuje na stdout JSON (SPDX 2.3 lub CycloneDX 1.5) z listą
5904 + zainstalowanych pakietów, wersji, licencji i sum SHA256.
5905 + """
5906 + fmt = (argv[0] if argv else "spdx").lower()
5907 + if fmt not in ("spdx", "cyclonedx"):
5908 + print("❌ Format: spdx | cyclonedx")
5909 + return 1
5910 + installed = load_json(INSTALLED_DB)
5911 + if not installed:
5912 + print("{}") if fmt == "cyclonedx" else print("{\"packages\": []}")
5913 + return 0
5914 + # metadata repo (licencje) – best-effort
5915 + try:
5916 + repo = fetch_all_packages()
5917 + except Exception:
5918 + repo = {}
5919 + names = sorted(installed)
5920 + created = datetime.now().astimezone().isoformat(timespec="seconds")
5921 +
5922 + def _license_of(name):
5923 + p = repo.get(name)
5924 + lic = getattr(p, "license", None) or []
5925 + if isinstance(lic, list):
5926 + lic = ", ".join(x for x in lic if x)
5927 + return lic or "NOASSERTION"
5928 +
5929 + if fmt == "spdx":
5930 + doc = {
5931 + "spdxVersion": "SPDX-2.3",
5932 + "dataLicense": "CC0-1.0",
5933 + "SPDXID": "SPDXRef-DOCUMENT",
5934 + "name": "PaganOS-installed",
5935 + "documentNamespace": f"https://repo.paganlinux.eu/sbom/installed-{int(time.time())}",
5936 + "creationInfo": {
5937 + "created": created,
5938 + "creators": [f"Tool: pag-{PAG_VERSION}"],
5939 + },
5940 + "packages": [],
5941 + }
5942 + for i, n in enumerate(names):
5943 + info = installed[n]
5944 + doc["packages"].append({
5945 + "SPDXID": f"SPDXRef-Package-{i+1}",
5946 + "name": n,
5947 + "versionInfo": info.get("version", ""),
5948 + "downloadLocation": info.get("repo", "NOASSERTION"),
5949 + "filesAnalyzed": False,
5950 + "licenseConcluded": _license_of(n),
5951 + "checksums": [{"algorithm": "SHA256", "checksumValue": info.get("sha256", "")}],
5952 + })
5953 + else: # cyclonedx
5954 + doc = {
5955 + "bomFormat": "CycloneDX",
5956 + "specVersion": "1.5",
5957 + "serialNumber": f"urn:uuid:{str(uuid.uuid4())}",
5958 + "version": 1,
5959 + "metadata": {
5960 + "timestamp": created,
5961 + "tools": [{"vendor": "PaganOS", "name": "pag", "version": PAG_VERSION}],
5962 + },
5963 + "components": [],
5964 + }
5965 + for n in names:
5966 + info = installed[n]
5967 + lic = _license_of(n)
5968 + comp = {
5969 + "type": "library",
5970 + "name": n,
5971 + "version": info.get("version", ""),
5972 + "hashes": [{"alg": "SHA-256", "content": info.get("sha256", "")}],
5973 + }
5974 + if lic != "NOASSERTION":
5975 + comp["licenses"] = [{"license": {"id": lic}}]
5976 + doc["components"].append(comp)
5977 + print(json.dumps(doc, indent=2, ensure_ascii=False))
5978 + return 0
5979 +
5980 +
5981 +USAGE_EN = """pag v3 – Pagan Linux Package Manager
5982 +
5983 +BASIC:
5984 + pag install <pkg>... Install packages
5985 + pag remove <pkg>... Remove packages
5986 + pag update Update PACKAGES (refreshes indexes first)
5987 + pag sync Refresh indexes + show pending package updates
5988 + pag upgrade Update SYSTEM (packages + kernel/initramfs/GRUB)
5989 + pag list [--installed] List available / installed
5990 + pag search <query> Search packages
5991 + pag info <pkg> Package details
5992 + pag files <pkg> List package files
5993 + pag verify [--deep] Verify integrity (--deep = SHA256 per file)
5994 + pag clean Clear download cache
5995 + pag stats System statistics
5996 + pag download <pkg>... Download packages to cache (offline prep)
5997 +
5998 +ROLLING (base baked into the image):
5999 + pag base [status] Image packages vs. repo (what pag manages)
6000 + pag base adopt [pkg...] Adopt base packages from the repo (--dry-run = preview)
6001 +
6002 +SECURITY:
6003 + pag key-add <url|file> Import GPG key
6004 + pag key-list List trusted keys
6005 + pag key-remove <id> Remove key
6006 + pag key-trust <repo> Pin repo signing key fingerprint (no TOFU)
6007 + pag key-untrust <repo> Forget repo fingerprint (back to TOFU)
6008 + pag key-trusted List pinned repo fingerprints
6009 +
6010 +ADVANCED:
6011 + pag why <pkg> Show why a package is installed
6012 + pag rdepends <pkg> Show which packages depend on a package
6013 + pag autoremove Auto-remove orphaned dependencies
6014 + pag pin <pkg> [ver] Pin package version
6015 + pag unpin <pkg> Unpin
6016 + pag pinned List pinned
6017 + pag history Transaction history
6018 + pag rollback Rollback last transaction
6019 + pag remove-orphans Remove orphaned deps
6020 + pag repo-add <url> [name] Add repository (drop-in /etc/pag/repos/)
6021 + pag repo-list List repositories
6022 + pag sbom export [fmt] SBOM manifest (spdx|cyclonedx)
6023 +
6024 +FLATPAK:
6025 + pag flatpak [<query>] Search & install (smart)
6026 + pag flatpak search <q> Search Flathub
6027 + pag flatpak install <id> Install flatpak
6028 + pag flatpak remove <id> Remove flatpak
6029 + pag flatpak list List installed flatpaks
6030 + pag flatpak update Update all flatpaks
6031 + pag flatpak info <id> Show flatpak details
6032 +
6033 +IMMUTABLE OS (PAG_IMMUTABLE=1):
6034 + pag deploy-list List all deployments
6035 + pag deploy-rollback Switch to previous deployment
6036 + pag deploy-cleanup [N] Remove old deployments (keep last N, default 3)
6037 + pag initramfs-update Rebuild initramfs for current kernel/deployment
6038 + pag grub-update Regenerate GRUB entries for all deployments
6039 +"""
6040 +
6041 +USAGE_PL = """pag v3 – Pagan Linux Package Manager
6042 +
6043 +PODSTAWOWE:
6044 + pag install <pkg>... Instalacja pakietów
6045 + pag remove <pkg>... Usuwanie pakietów
6046 + pag update Aktualizacja PAKIETÓW (odświeża indeksy)
6047 + pag sync Odśwież indeksy + info o aktualizacjach
6048 + pag upgrade Aktualizacja SYSTEMU (pakiety + kernel/initramfs/GRUB)
6049 + pag list [--installed] Lista dostępnych / zainstalowanych
6050 + pag search <query> Szukaj pakietów
6051 + pag info <pkg> Szczegóły pakietu
6052 + pag files <pkg> Lista plików pakietu
6053 + pag verify [--deep] Weryfikacja integralności
6054 + pag clean Wyczyść cache pobierania
6055 + pag stats Statystyki systemu
6056 + pag download <pkg>... Pobierz do cache (offline)
6057 +
6058 +ROLLING (baza wypalona w obrazie):
6059 + pag base [status] Pakiety z obrazu vs repo (czym pag zarządza)
6060 + pag base adopt [pkg...] Adoptuj pakiety bazy z repo (--dry-run = podgląd)
6061 +
6062 +BEZPIECZEŃSTWO:
6063 + pag key-add <url|file> Importuj klucz GPG
6064 + pag key-list Lista zaufanych kluczy
6065 + pag key-remove <id> Usuń klucz
6066 + pag key-trust <repo> Przypnij fingerprint klucza repo (bez TOFU)
6067 + pag key-untrust <repo> Zapomnij fingerprint repo (powrót do TOFU)
6068 + pag key-trusted Lista przypiętych fingerprintów repo
6069 +
6070 +ZAAWANSOWANE:
6071 + pag why <pkg> Dlaczego pakiet jest zainstalowany
6072 + pag rdepends <pkg> Które pakiety zależą od pakietu
6073 + pag autoremove Usuń osierocone zależności
6074 + pag pin <pkg> [ver] Przypnij wersję pakietu
6075 + pag unpin <pkg> Odepnij
6076 + pag pinned Lista przypiętych
6077 + pag history Historia transakcji
6078 + pag rollback Cofnij ostatnią transakcję
6079 + pag remove-orphans Usuń osierocone zależności
6080 + pag repo-add <url> [nazwa] Dodaj repozytorium (drop-in w /etc/pag/repos/)
6081 + pag repo-list Lista repozytoriów
6082 + pag sbom export [fmt] Manifest SBOM (spdx|cyclonedx)
6083 +
6084 +FLATPAK:
6085 + pag flatpak [<query>] Szukaj i instaluj
6086 + pag flatpak search <q> Szukaj na Flathub
6087 + pag flatpak install <id> Zainstaluj flatpak
6088 + pag flatpak remove <id> Usuń flatpak
6089 + pag flatpak list Lista zainstalowanych
6090 + pag flatpak update Aktualizuj wszystkie
6091 + pag flatpak info <id> Szczegóły flatpaka
6092 +
6093 +IMMUTABLE OS (PAG_IMMUTABLE=1):
6094 + pag deploy-list Lista wdrożeń
6095 + pag deploy-rollback Przełącz na poprzednie wdrożenie
6096 + pag deploy-cleanup [N] Usuń stare wdrożenia (zachowaj N, domyślnie 3)
6097 + pag initramfs-update Przebuduj initramfs
6098 + pag grub-update Regeneruj wpisy GRUB"""
6099 +
6100 +def _get_usage():
6101 + # Plik językowy może dostarczyć klucz "usage" – wtedy wygrywa z wbudowanym.
6102 + _u = T.get(LANG, {}).get("usage")
6103 + if _u:
6104 + return _u
6105 + if LANG == "pl":
6106 + return USAGE_PL
6107 + return USAGE_EN
6108 +
6109 +
6110 +def _extract_lang(outdir: str) -> int:
6111 + """Eksport wbudowanych tłumaczeń do outdir/{pl,en}.json (+ klucz "usage").
6112 +
6113 + Używane przez recepturę pakietu (pag.pag), żeby tłumaczenia jechały RAZEM
6114 + z wersją paga – po `pag install/upgrade pag` i self-update są zawsze zgodne.
6115 + """
6116 + os.makedirs(outdir, exist_ok=True)
6117 + for _code in ("pl", "en"):
6118 + _d = dict(T.get(_code, {}))
6119 + _u = globals().get(f"USAGE_{_code.upper()}", "")
6120 + if _u:
6121 + _d["usage"] = _u
6122 + _p = os.path.join(outdir, f"{_code}.json")
6123 + with open(_p, "w", encoding="utf-8") as _fh:
6124 + json.dump(_d, _fh, ensure_ascii=False, indent=2, sort_keys=True)
6125 + print(f" ✓ {_p} ({len(_d)} kluczy)")
6126 + return 0
6127 +
6128 +
6129 +def main():
6130 + # Ukryte (używane przy budowie pakietu): eksport tłumaczeń do plików
6131 + if len(sys.argv) >= 3 and sys.argv[1] == "--lang-extract":
6132 + sys.exit(_extract_lang(sys.argv[2]))
6133 + if len(sys.argv) >= 2 and sys.argv[1] in ("--version", "-V", "version"):
6134 + print(f"pag {PAG_VERSION}")
6135 + sys.exit(0)
6136 + if len(sys.argv) == 2 and sys.argv[1] in ("--help", "-h", "help"):
6137 + print(_get_usage()); sys.exit(0)
6138 + if len(sys.argv) < 2:
6139 + print(_get_usage()); sys.exit(0)
6140 +
6141 + cmd = sys.argv[1]
6142 + args = sys.argv[2:]
6143 +
6144 + # Python bez modułu ssl = brak HTTPS w urllib. Powiedz to wprost, zamiast
6145 + # pokazywać mylące „unknown url type: https” przy każdej operacji sieciowej.
6146 + if not _ssl_ok():
6147 + print(f" ⚠ {_('ssl_broken')}", file=sys.stderr)
6148 +
6149 + # --- Komendy TYLKO DO ODCZYTU (nie wymagają roota) ---
6150 + READ_ONLY = {
6151 + "list": lambda: cmd_list("--installed" in args),
6152 + "search": lambda: cmd_search(args[0]) if args else print("Usage: pag search <query>"),
6153 + "info": lambda: cmd_info(args[0]) if args else print("Usage: pag info <pkg>"),
6154 + "files": lambda: cmd_files(args[0]) if args else print("Usage: pag files <pkg>"),
6155 + "verify": lambda: cmd_verify("--deep" in args),
6156 + "why": lambda: cmd_why(args[0]) if args else print("Usage: pag why <pkg>"),
6157 + "rdepends": lambda: cmd_rdepends(args[0]) if args else print("Usage: pag rdepends <pkg>"),
6158 + "stats": cmd_stats,
6159 + "pinned": cmd_pinned,
6160 + "history": cmd_history,
6161 + "repo-list": cmd_repo_list,
6162 + "key-list": cmd_key_list,
6163 + "key-trusted": cmd_key_trusted,
6164 + "flatpak": lambda: cmd_flatpak(args),
6165 + "flatpak-search": lambda: cmd_flatpak_search(args[0]) if args else print("Usage: pag flatpak-search <query>"),
6166 + "flatpak-list": cmd_flatpak_list,
6167 + "flatpak-info": lambda: cmd_flatpak_info(args[0]) if args else print("Usage: pag flatpak-info <id>"),
6168 + "deploy-list": cmd_deploy_list,
6169 + "deploy": cmd_deploy_list,
6170 + "sbom": lambda: cmd_sbom(args),
6171 + }
6172 +
6173 + if cmd in READ_ONLY:
6174 + sys.exit(READ_ONLY[cmd]() or 0)
6175 +
6176 + # --- `pag base` / `pag base status`: tylko odczyt (bez roota i bez locka) ---
6177 + # `pag base adopt` NIE wpada tutaj – idzie ścieżką komend zapisu (roota + lock
6178 + # pilnuje wspólna obsługa niżej), żeby transakcja była bezpieczna.
6179 + if cmd in ("base", "base-status") and not (args and args[0] in ("adopt", "register")):
6180 + sys.exit(cmd_base_status() or 0)
6181 +
6182 + # --- Smart search: `pag <nazwa-pakietu>` → repo + Flathub + sugestie ---
6183 + WRITE_CMDS = {
6184 + "install", "remove", "update", "sync", "upgrade", "clean", "download",
6185 + "autoremove", "remove-orphans", "pin", "unpin", "rollback",
6186 + "repo-add", "key-add", "key-remove", "key-trust", "key-untrust",
6187 + "self-update",
6188 + "flatpak", "flatpak-install", "flatpak-remove", "flatpak-update",
6189 + "deploy-rollback", "deploy-cleanup", "initramfs-update", "grub-update",
6190 + "base", "base-adopt", "base-register",
6191 + }
6192 + if cmd not in WRITE_CMDS:
6193 + # Literówka komendy? (np. `pag instal steam` zamiast `pag install`) –
6194 + # zasugeruj poprawną komendę ZAMIAST wpadać w smart search (który
6195 + # potrafi wisieć na `flatpak search` aż do Ctrl-C).
6196 + _known = set(READ_ONLY) | set(WRITE_CMDS)
6197 + _close = difflib.get_close_matches(cmd, _known, n=1, cutoff=0.75)
6198 + if _close:
6199 + print(f"❌ Nieznana komenda: '{cmd}'. Czy chodziło o '{_close[0]}'?")
6200 + print(f" Uruchom 'pag' bez argumentów, aby zobaczyć listę komend.")
6201 + sys.exit(1)
6202 + sys.exit(_smart_search(" ".join([cmd] + args)) or 0)
6203 +
6204 + # Obsługa flag globalnych (-y/--yes)
6205 + global_args = []
6206 + for a in args:
6207 + if a in ("-y", "--yes"):
6208 + os.environ["PAG_YES"] = "1"
6209 + else:
6210 + global_args.append(a)
6211 + args = global_args
6212 +
6213 + # --- Komendy ZAPISU (wymagają roota) ---
6214 + if os.geteuid() != 0:
6215 + print(f"❌ {_('root_required')}", file=sys.stderr); sys.exit(1)
6216 +
6217 + ensure_dirs()
6218 +
6219 + with DatabaseLock():
6220 + WRITE_COMMANDS = {
6221 + "install": lambda: cmd_install(
6222 + [a for a in args if a not in ("-f", "--force", "--")],
6223 + upgrade=("-f" in args or "--force" in args)),
6224 + "remove": lambda: cmd_remove(args),
6225 + "update": lambda: cmd_update(do_upgrade=True),
6226 + "sync": lambda: cmd_update(do_upgrade=False),
6227 + "upgrade": cmd_upgrade,
6228 + "clean": cmd_clean,
6229 + "download": lambda: cmd_download(args),
6230 + "autoremove": cmd_autoremove,
6231 + "remove-orphans": cmd_remove_orphans,
6232 + "pin": lambda: cmd_pin(args[0], args[1] if len(args)>1 else ""),
6233 + "unpin": lambda: cmd_unpin(args[0]) if args else print("Usage: pag unpin <pkg>"),
6234 + "rollback": cmd_rollback,
6235 + "repo-add": lambda: cmd_repo_add(args[0], args[1] if len(args) > 1 else "") if args else print("Usage: pag repo-add <url> [name]"),
6236 + "key-add": lambda: cmd_key_add(args[0]) if args else print("Usage: pag key-add <url|file>"),
6237 + "key-remove": lambda: cmd_key_remove(args[0]) if args else print("Usage: pag key-remove <id>"),
6238 + "key-trust": lambda: cmd_key_trust(args[0]) if args else print("Usage: pag key-trust <repo_url>"),
6239 + "key-untrust": lambda: cmd_key_untrust(args[0]) if args else print("Usage: pag key-untrust <repo_url>"),
6240 + "self-update": cmd_self_update,
6241 + "flatpak": lambda: cmd_flatpak(args),
6242 + "flatpak-install": lambda: _flatpak_smart_install(args) if args else print("Usage: pag flatpak-install <app>"),
6243 + "flatpak-remove": lambda: _flatpak_smart_remove(args) if args else print("Usage: pag flatpak-remove <app>"),
6244 + "flatpak-update": cmd_flatpak_update,
6245 + "deploy-rollback": cmd_deploy_rollback,
6246 + "deploy-cleanup": lambda: cmd_deploy_cleanup(int(args[0]) if args else 3),
6247 + "initramfs-update": cmd_initramfs_update,
6248 + "grub-update": cmd_grub_update,
6249 + "base": lambda: cmd_base_register(args) if (args and args[0] == "register") else cmd_base_adopt(args),
6250 + "base-adopt": lambda: cmd_base_adopt(args),
6251 + "base-register": lambda: cmd_base_register(args),
6252 + }
6253 +
6254 + fn = WRITE_COMMANDS.get(cmd)
6255 + if fn:
6256 + sys.exit(fn() or 0)
6257 + # Should never reach here – _smart_search handles unknowns
6258 + sys.exit(_smart_search(" ".join([cmd] + args)) or 0)
6259 +
6260 +if __name__ == "__main__":
6261 + try:
6262 + main()
6263 + except KeyboardInterrupt:
6264 + # Ctrl-C (np. podczas flatpak search / pobierania) – bez tracebacka
6265 + print("\n ⚠ Przerwano (Ctrl-C).")
6229 6266 sys.exit(130)