PaganOS Luna 0.6.0
PL EN DE
← pag

Commit de2908b

3
plików
+8131
dodanych
-7388
usuniętych
@@ -1,7384 +1,7649 @@
1 1 #!/usr/bin/env python3
2 -"""
3 -╔══════════════════════════════════════════════════════════════════════════════╗
4 -║ PAG - Pagan Linux Package Manager v4.1.0 ║
5 -║ Produkcyjny menedżer pakietów – atomowy, bezpieczny, i18n ║
6 -╚══════════════════════════════════════════════════════════════════════════════╝
7 -
8 -KLUCZOWE CECHY:
9 - - Transakcja grupowa: staging CAŁEJ grupy → commit (błąd paczki nie psuje systemu)
10 - - Snapshoty btrfs przed transakcją + wpisy GRUB (rollback przy starcie)
11 - - Atomowa instalacja przez staging (tmpdir → rename) – brak pół-instalacji
12 - - Bezpieczne usuwanie – sprawdza czy plik nie jest współdzielony
13 - - SQLite dla bazy plików – miliony plików bez problemu
14 - - GPG: weryfikacja repo.json + podpisy pakietów + pinning fingerprintu
15 - - Hooki: pre/post-install, pre/post-remove (piaskownica env, timeout, audit)
16 - - Głęboka weryfikacja SHA256 per-plik
17 - - Pełny rollback – cofa fizyczne pliki
18 - - Blokada flock – tylko jedna instancja
19 - - Transakcje z migawkami + rejestr wykonanych hooków
20 - - Cache HTTP (ETag/If-Modified-Since)
21 - - Wielojęzyczność (i18n) – PL, EN
22 -
23 -FORMAT PAKIETU (.pag):
24 - ├── data.tar.xz – pliki + sums.json (SHA256 per plik)
25 - ├── metadata.json – nazwa, wersja, zależności
26 - └── hooks/ – pre-install, post-install, pre-remove, post-remove
27 -
28 -MODEL ZAUFANIA / BEZPIECZEŃSTWO:
29 - - Repozytorium MUSI być zaufane: podpisy GPG zweryfikowane; fingerprint
30 - klucza przypiętego do repo (TOFU przy pierwszym użyciu, potem pinning).
31 - - Hooki uruchamiają dowolny plik z pakietu jako ROOT (jak apt/pacman).
32 - Ograniczamy je (czyste env, timeout, PAG_NO_HOOKS=1, log do
33 - /var/log/pag/audit.log) i rejestrujemy w transakcji, ale ostatecznie
34 - instalujesz kod, któremu ufasz.
35 - - self-update: weryfikacja podpisu + SHA256 + składnia, atomowa podmiana.
36 -"""
37 -
38 -import os, sys, json, copy, shutil, hashlib, tarfile, tempfile, subprocess, time, fcntl, locale, re, difflib
39 -
40 -# Twarde moduły Pythona. Zamiast tracebacku dajemy jasny komunikat, bo brak
41 -# tych modułów oznacza zwykle niezadeklarowaną zależność pakietu (sqlite/xz).
42 -try:
43 - import sqlite3
44 -except ImportError:
45 - sys.stderr.write("pag: Python bez modułu sqlite3 – zainstaluj pakiet sqlite "
46 - "(libsqlite3) i przebuduj python.\n")
47 - sys.exit(1)
48 -try:
49 - import lzma # noqa: F401 – potrzebny do paczek .pag (XZ)
50 -except ImportError:
51 - sys.stderr.write("pag: Python bez modułu lzma – zainstaluj pakiet xz "
52 - "(liblzma) i przebuduj python.\n")
53 - sys.exit(1)
54 -
55 -# Fix TLS trust inside the Pagan chroot: point Python at the CA bundle that
56 -# pag ships, otherwise urlopen() fails with "unable to get local issuer
57 -# certificate" (no default capath/cafile is resolved in the chroot).
58 -for _cafile in (
59 - "/etc/ssl/certs/ca-certificates.crt",
60 - "/etc/ssl/cert.pem",
61 -):
62 - if os.path.isfile(_cafile):
63 - os.environ["SSL_CERT_FILE"] = _cafile
64 - break
65 -
66 -from pathlib import Path
67 -from datetime import datetime, timezone
68 -from typing import Dict, List, Optional, Tuple, Set
69 -from concurrent.futures import ThreadPoolExecutor, as_completed
70 -from urllib.request import urlopen, Request
71 -import threading, itertools
72 -import uuid # serialNumber SBOM (CycloneDX)
73 -
74 -# Wersja klienta – do porównania z repo.json["pag_version"] (self-update)
75 -PAG_VERSION = "4.1.0"
76 -from urllib.error import URLError, HTTPError
77 -
78 -# =============================================================================
79 -# Pagan progress — animowany pasek „Drakkar” (własny motyw Pagan/Loki)
80 -# -----------------------------------------------------------------------------
81 -# Zamiast statycznego „█” pasek jest animowany: łódź wikingów płynie po
82 -# falującym morzu, a za nią ciągnie się smuga z wędrującym refleksem. Animacja
83 -# jest funkcją czasu, więc „płynie” nawet gdy postęp stoi w miejscu (długa
84 -# instalacja jednego pakietu, przerwa między fragmentami pobierania).
85 -#
86 -# Konfiguracja (zmienne środowiskowe):
87 -# PAG_NO_ANIM=1 – wyłącz animację (zostaje klasyczny statyczny pasek)
88 -# PAG_BAR_STYLE=<styl> – drakkar (domyślnie) | snake | classic
89 -# Poza TTY animacja jest automatycznie wyłączona (czyste logi w plikach).
90 -# =============================================================================
91 -
92 -_PAGAN_ANIM = os.environ.get("PAG_NO_ANIM", "") not in ("1", "true", "yes", "on")
93 -_PAGAN_STYLE = os.environ.get("PAG_BAR_STYLE", "drakkar").strip().lower()
94 -_DRAW_LOCK = threading.Lock() # serializacja zapisów wielu pasków
95 -
96 -# Dwie fazy fali – przesuwane w czasie dają wrażenie ruchu morza.
97 -_WAVE_PHASES = ("~_", "_~")
98 -
99 -# Zapas kolumn przy rysowaniu paska: ostatnia kolumna terminala wywołuje
100 -# „auto-wrap”, a glify szerokie (np. emoji 📦) liczą się jako 1 w `len()`, ale
101 -# zajmują 2 kolumny – margines chroni przed zawinięciem linii.
102 -_BAR_MARGIN = 2
103 -
104 -
105 -def _term_width(stream=None, default: int = 80) -> int:
106 - """Szerokość terminala (w kolumnach) dla strumienia paska.
107 -
108 - Pasek MUSI zmieścić się w jednej linii: gdy jest szerszy niż terminal, ten
109 - sam go zawija i KAŻDA aktualizacja trafia do nowej linii zamiast nadpisywać
110 - poprzednią. Pytamy o rozmiar konkretnego `stream` (pasek pisze na stderr),
111 - a nie domyślnego stdout – inaczej przy przekierowanym stdout dostalibyśmy
112 - fałszywe 80 kolumn.
113 - """
114 - fd = None
115 - if stream is not None:
116 - try:
117 - fd = stream.fileno()
118 - except Exception:
119 - fd = None
120 - if fd is not None:
121 - try:
122 - cols = os.get_terminal_size(fd).columns
123 - if cols > 0:
124 - return cols
125 - except OSError:
126 - pass
127 - try:
128 - cols = shutil.get_terminal_size((default, 24)).columns
129 - except Exception:
130 - cols = default
131 - return cols if cols > 0 else default
132 -
133 -
134 -def _classic_bar(pct: float, width: int) -> str:
135 - """Klasyczny statyczny pasek █/░ (fallback dla logów i PAG_NO_ANIM)."""
136 - filled = int(round(width * max(0.0, min(100.0, pct)) / 100.0))
137 - return "█" * filled + "░" * (width - filled)
138 -
139 -
140 -def _drakkar_bar(pct: float, width: int, t: float, filled: int) -> str:
141 - """Drakkar (łódź wikingów) płynący po falującym morzu.
142 -
143 - - przed łodzią: falujące morze (~ _ przesuwane w czasie),
144 - - dziób łodzi: » (kolumna = bieżący postęp),
145 - - za łodzią: smuga z wędrującym refleksem światła.
146 - """
147 - done = pct >= 100.0
148 - wave = _WAVE_PHASES[int(t * 6) % len(_WAVE_PHASES)]
149 - ship = min(filled, width - 1)
150 - glow = int(t * 10) % ship if ship > 0 else -1
151 - out = []
152 - for i in range(width):
153 - if done:
154 - out.append("»" if i == width - 1 else "█") # łódź zacumowana
155 - elif i < ship:
156 - out.append("█" if i == glow else "▓")
157 - elif i == ship:
158 - out.append("»")
159 - else:
160 - out.append(wave[i & 1])
161 - return "".join(out)
162 -
163 -
164 -def _snake_bar(pct: float, width: int, t: float, filled: int) -> str:
165 - """Jörmungandr – wąż sunący przez pasek (głowa @, łuski o/~, ogon ·)."""
166 - done = pct >= 100.0
167 - head = min(filled, width - 1)
168 - out = []
169 - for i in range(width):
170 - if done:
171 - out.append("@" if i == width - 1 else "o")
172 - elif i < head:
173 - out.append("o" if (i + int(t * 6)) & 1 else "~")
174 - elif i == head:
175 - out.append("@")
176 - else:
177 - out.append("·")
178 - return "".join(out)
179 -
180 -
181 -def _pagan_bar(pct: float, width: int = 30, t: float = 0.0,
182 - style: Optional[str] = None, animated: bool = True) -> str:
183 - """Zwraca jednoliniowy pasek postępu o STAŁEJ szerokości `width`.
184 -
185 - `pct` – postęp 0..100
186 - `t` – czas (s); różne `t` → inna klatka animacji
187 - `animated` – False wymusza klasyczny statyczny pasek (np. brak TTY)
188 - """
189 - width = max(6, int(width))
190 - pct = max(0.0, min(100.0, float(pct)))
191 - style = style or _PAGAN_STYLE
192 - if not animated or not _PAGAN_ANIM or style == "classic":
193 - return _classic_bar(pct, width)
194 - filled = int(round(width * pct / 100.0))
195 - if style == "snake":
196 - return _snake_bar(pct, width, t, filled)
197 - return _drakkar_bar(pct, width, t, filled)
198 -
199 -
200 -class _Bar:
201 - """Baza animowanych pasków: rysują JEDNĄ nadpisywaną linię na `stream`.
202 -
203 - Gdy mamy TTY, wątek w tle odświeża pasek ~10×/s, dzięki czemu morze faluje
204 - także wtedy, gdy postęp chwilowo się nie zmienia.
205 - """
206 - def __init__(self, width: int, stream=None):
207 - self.width = width
208 - self.stream = stream if stream is not None else sys.stderr
209 - self.tty = self.stream.isatty()
210 - self._lock = threading.RLock()
211 - self._last_len = 0
212 - self._stop = threading.Event()
213 - self._thread = None
214 -
215 - # -- wątek animacji -------------------------------------------------------
216 - def _start_anim(self):
217 - if _PAGAN_ANIM and self.tty and self._thread is None:
218 - self._thread = threading.Thread(target=self._anim_loop, daemon=True)
219 - self._thread.start()
220 -
221 - def _anim_loop(self):
222 - while not self._stop.wait(0.1):
223 - with self._lock:
224 - if self._stop.is_set():
225 - break
226 - self._write(self._line())
227 -
228 - def _stop_anim(self):
229 - self._stop.set()
230 - if self._thread is not None:
231 - self._thread.join(timeout=0.3)
232 - self._thread = None
233 -
234 - # -- rysowanie ------------------------------------------------------------
235 - def _cap(self) -> int:
236 - """Maksymalna liczba kolumn jednej linii paska (z zapasem na wrap)."""
237 - return _term_width(self.stream) - _BAR_MARGIN
238 -
239 - def _shrink(self, text: str, fixed: int) -> str:
240 - """Skróć `text` tak, by `text` + `fixed` kolumn zmieściło się w linii."""
241 - room = self._cap() - fixed
242 - if room >= 1 and len(text) > room:
243 - return "…" if room == 1 else text[:room - 1] + "…"
244 - return text
245 -
246 - def _fit(self, line: str) -> str:
247 - """Ostatnia linia obrony: przytnij linię do szerokości terminala.
248 -
249 - Wycinamy ŚRODEK (wielokropek), więc widoczne zostają początek (nazwa)
250 - i koniec (%, prędkość, ETA). Bez tego zawinięta linia = nowa linia przy
251 - każdym odświeżeniu zamiast nadpisywania poprzedniej.
252 - """
253 - cap = self._cap()
254 - if cap <= 0 or len(line) <= cap:
255 - return line
256 - keep = cap - 1 # miejsce na wielokropek „…”
257 - head = (keep + 1) // 2
258 - tail = keep - head
259 - return line[:head] + "…" + (line[-tail:] if tail > 0 else "")
260 -
261 - def _write(self, line: str):
262 - line = self._fit(line)
263 - clear = " " * max(0, self._last_len - len(line))
264 - with _DRAW_LOCK:
265 - self.stream.write(f"\r{line}{clear}")
266 - self.stream.flush()
267 - self._last_len = len(line)
268 -
269 - def _line(self) -> str:
270 - raise NotImplementedError
271 -
272 - def _clear_line(self):
273 - if self.tty and self._last_len:
274 - with _DRAW_LOCK:
275 - self.stream.write("\r" + " " * self._last_len + "\r")
276 - self.stream.flush()
277 - self._last_len = 0
278 -
279 - def _newline(self):
280 - if self.tty and self._last_len:
281 - self.stream.write("\n")
282 - self.stream.flush()
283 - self._last_len = 0
284 -
285 -
286 -class ProgressBar(_Bar):
287 - """Pasek postępu dla N elementów — animowany („drakkar”) na TTY."""
288 - def __init__(self, total: int, desc: str = "", unit: str = "", width: int = 30):
289 - super().__init__(width)
290 - self.total = max(total, 1)
291 - self.desc = desc
292 - self.unit = unit
293 - self.n = 0
294 - self.suffix = ""
295 - self.start = time.time()
296 - self._start_anim()
297 -
298 - def _line(self) -> str:
299 - pct = self.n / self.total * 100
300 - elapsed = time.time() - self.start
301 - speed = self.n / elapsed if elapsed > 0 else 0
302 - if self.n >= self.total:
303 - eta_str = "done"
304 - elif speed > 0:
305 - eta = (self.total - self.n) / speed
306 - eta_str = f"{eta:.0f}s" if eta < 60 else f"{eta/60:.1f}m"
307 - else:
308 - eta_str = "?..."
309 - bar = _pagan_bar(pct, self.width, time.time(), animated=self.tty)
310 - tail = f" [{bar}] {self.n}/{self.total} ({pct:.0f}%) ETA {eta_str}{self.suffix}"
311 - desc = self._shrink(self.desc, 2 + len(tail))
312 - return f" {desc}{tail}"
313 -
314 - def update(self, n: Optional[int] = None, suffix: str = ""):
315 - with self._lock:
316 - if n is not None:
317 - self.n = n
318 - else:
319 - self.n += 1
320 - self.suffix = suffix
321 - if self.tty:
322 - self._write(self._line())
323 - elif (self.n == 1 or self.n >= self.total
324 - or self.n % max(1, self.total // 10) == 0):
325 - # Bez TTY – tylko kamienie milowe (czysty log)
326 - print(self._line(), file=self.stream)
327 -
328 - def close(self):
329 - self._stop_anim()
330 - with self._lock:
331 - self._newline()
332 -
333 - def __enter__(self):
334 - return self
335 -
336 - def __exit__(self, *args):
337 - self.close()
338 -
339 -
340 -class DownloadBar(_Bar):
341 - """Animowany pasek pobierania (na podstawie Content-Length)."""
342 - def __init__(self, filename: str, total_bytes: int):
343 - super().__init__(25)
344 - self.filename = filename
345 - self.total = total_bytes
346 - self.downloaded = 0
347 - self.start = time.time()
348 - self._start_anim()
349 -
350 - def _line(self) -> str:
351 - pct = self.downloaded / self.total * 100 if self.total > 0 else 0.0
352 - elapsed = time.time() - self.start
353 - speed = self.downloaded / elapsed if elapsed > 0 else 0
354 - if self.total > 0 and speed > 0:
355 - eta = (self.total - self.downloaded) / speed
356 - eta_str = f"{eta:.0f}s" if eta < 60 else f"{eta/60:.1f}m"
357 - else:
358 - eta_str = "?..."
359 - bar = _pagan_bar(pct, self.width, time.time(), animated=self.tty)
360 - sz = self._fmt_size(self.total)
361 - spd = self._fmt_size(int(speed))
362 - tail = f" [{bar}] {pct:.0f}% {sz} {spd}/s ETA {eta_str}"
363 - # Nazwa pliku bywa długa (np. linux-firmware-…-1.pag) i wtedy CAŁA linia
364 - # nie mieści się w terminalu (zawijanie → nowa linia przy każdym %).
365 - # Skracamy WYŁĄCZNIE nazwę – pełny pasek, prędkość i ETA zostają.
366 - name = self._shrink(self.filename, 4 + len(tail)) # prefiks „ ↓ ” = 4 kolumny
367 - return f" ↓ {name}{tail}"
368 -
369 - def update(self, chunk_size: int):
370 - with self._lock:
371 - self.downloaded += chunk_size
372 - if self.tty and self.total > 0:
373 - self._write(self._line())
374 -
375 - def close(self):
376 - self._stop_anim()
377 - with self._lock:
378 - if self.total > 0:
379 - self._newline()
380 -
381 - @staticmethod
382 - def _fmt_size(n: int) -> str:
383 - for unit in ("B", "KB", "MB", "GB"):
384 - if n < 1024:
385 - return f"{n:.1f} {unit}"
386 - n /= 1024
387 - return f"{n:.1f} TB"
388 -
389 -
390 -class _StepBar(_Bar):
391 - """Animowany pasek dla pętli „krok po kroku” (instalacja/aktualizacja).
392 -
393 - Pasek nie skacze skokowo co pakiet – między krokami łagodnie „dopełza”
394 - w stronę kolejnego progu (jak w instalatorach), więc rośnie w sposób
395 - ciągły. Wątek animacji odświeża go ~10×/s.
396 - """
397 - def __init__(self, total: int, icon: str = "", width: int = 25,
398 - creep_tau: float = 3.0):
399 - super().__init__(width)
400 - self.total = max(total, 1)
401 - self.icon = icon
402 - self.creep_tau = creep_tau # „stała czasu” dopełzania (s)
403 - self.idx = 0
404 - self.label = ""
405 - self.t0 = time.time()
406 - self._step_t = time.time() # start bieżącego pakietu
407 - self._start_anim()
408 -
409 - def _frac(self) -> float:
410 - """Ukończona część [0..1]: kroki + wygładzone dopełzanie w bieżącym."""
411 - done = max(0, self.idx - 1)
412 - if done >= self.total:
413 - return 1.0
414 - # 0.5 ** (dt/tau): 0 → ~1 asymptotycznie; cap 0.9, by krok był widoczny
415 - creep = 1.0 - 0.5 ** ((time.time() - self._step_t) / self.creep_tau)
416 - return (done + min(creep, 0.9)) / self.total
417 -
418 - def _line(self) -> str:
419 - pct = self._frac() * 100.0
420 - eta_s = ""
421 - if self.idx > 1:
422 - avg = (time.time() - self.t0) / (self.idx - 1)
423 - rem = avg * (self.total - self.idx + 1)
424 - eta_s = f" ~{rem:.0f}s" if rem < 60 else f" ~{rem/60:.1f}m"
425 - bar = _pagan_bar(pct, self.width, time.time(), animated=self.tty)
426 - tail = f"[{bar}] {self.idx}/{self.total} ({pct:.0f}%) "
427 - label = self._shrink(self.label, 2 + len(self.icon) + len(tail) + len(eta_s))
428 - return f" {self.icon}{tail}{label}{eta_s}"
429 -
430 - def step(self, idx: int, label: str):
431 - with self._lock:
432 - self.idx = idx
433 - self.label = label
434 - self._step_t = time.time()
435 - if self.tty:
436 - self._write(self._line())
437 - else:
438 - print(self._line(), file=self.stream)
439 -
440 - def end(self):
441 - self._stop_anim()
442 - with self._lock:
443 - self._clear_line()
444 -
445 -# =============================================================================
446 -# GPG – BEZPIECZNE WYWOŁYWANIE (odporne na brak binarki gpg)
447 -# =============================================================================
448 -
449 -GPG_BINARY = shutil.which("gpg2") or shutil.which("gpg") or "gpg"
450 -GPG_HOME = "/etc/pag/gpg" # izolowany keyring (działa z keyboxd GPG 2.4+)
451 -
452 -def _ssl_ok() -> bool:
453 - """Czy Python ma działający moduł ssl (HTTPS w urllib).
454 -
455 - Bez niego urllib nie zna schematu https i każda operacja sieciowa kończy
456 - się „unknown url type: https” – myląco, bo wygląda jak błąd adresu.
457 - """
458 - try:
459 - import ssl # noqa: F401
460 - return True
461 - except Exception:
462 - return False
463 -
464 -
465 -def _gpg_run(*args, timeout: int = 30, **kwargs) -> subprocess.CompletedProcess:
466 - """
467 - Bezpieczne wywołanie GPG – przechwytuje FileNotFoundError,
468 - gdyby gpg/gpg2 nie było zainstalowane w minimalnym środowisku.
469 - Wymusza LC_ALL=C aby komunikaty GPG były zawsze po angielsku
470 - (niezależnie od locale systemu) – kluczowe dla parsowania stderr.
471 - """
472 - env = kwargs.pop("env", None) or os.environ.copy()
473 - env["LC_ALL"] = "C"
474 - env["GNUPGHOME"] = GPG_HOME
475 - try:
476 - return subprocess.run([GPG_BINARY, *args], timeout=timeout, env=env, **kwargs)
477 - except FileNotFoundError:
478 - # GPG nie jest dostępne – zwróć błąd z komunikatem
479 - # (szanuj text=True – inaczej caller dostaje bytes i może wybuchnąć TypeError)
480 - _text = bool(kwargs.get("text") or kwargs.get("universal_newlines"))
481 - _msg = f"GPG binary not found ({GPG_BINARY})"
482 - return subprocess.CompletedProcess(
483 - [GPG_BINARY, *args], 127,
484 - stdout=("" if _text else b""),
485 - stderr=(_msg if _text else _msg.encode()),
486 - )
487 - except subprocess.TimeoutExpired:
488 - return subprocess.CompletedProcess(
489 - [GPG_BINARY, *args], 124,
490 - stdout=b"", stderr=b"GPG operation timed out"
491 - )
492 -
493 -def _load_trust_db() -> dict:
494 - """Mapa repo_url → fingerprint klucza podpisującego (baza zaufania)."""
495 - try:
496 - with open(TRUST_DB) as f:
497 - return json.load(f)
498 - except (FileNotFoundError, json.JSONDecodeError):
499 - return {}
500 -
501 -
502 -def _save_trust_db(db: dict):
503 - os.makedirs(os.path.dirname(TRUST_DB), exist_ok=True)
504 - with open(TRUST_DB, "w") as f:
505 - json.dump(db, f, indent=2)
506 -
507 -
508 -def _gpg_verify_fp(sig_path: str, data_path: str, timeout: int = 30):
509 - """Weryfikuje podpis i odczytuje fingerprint podpisującego.
510 -
511 - Używa --status-fd=1 i linii VALIDSIG <fingerprint>. Zwraca (ok, fingerprint).
512 -
513 - FAIL-CLOSED: OK tylko gdy GPG zwrócił 0 ORAZ w statusie maszynowym jest
514 - linia VALIDSIG. Nie zakładamy sukcesu na podstawie samego kodu wyjścia –
515 - gdyby format --status-fd się zmienił, wolimy odrzucić podpis niż przyjąć
516 - niezaufany pakiet (wywołujący traktuje fp=None jako brak potwierdzenia).
517 - """
518 - env = os.environ.copy()
519 - res = _gpg_run("--verify", "--status-fd", "1", sig_path, data_path,
520 - capture_output=True, text=True, timeout=timeout, env=env)
521 - out = res.stdout or ""
522 - m = re.search(r"\[GNUPG:\]\s+VALIDSIG\s+([0-9A-Fa-f]{16,})", out)
523 - if not m:
524 - m = re.search(r"\bVALIDSIG\s+([0-9A-Fa-f]{16,})", out)
525 - if res.returncode != 0 or not m:
526 - return False, None
527 - return True, m.group(1).upper()
528 -
529 -
530 -def _verify_local_pkg_signature(pkg_path: str) -> bool:
531 - """Weryfikuje lokalny .pag tym samym kluczem co zaufane repo."""
532 - # PAG_INSECURE=1 – spójnie z _verify_repo_sig() i _verify_pkg_signature().
533 - # Potrzebne w środowisku BUILDA: instalator buduje własne .pag (np. `kernel`)
534 - # lokalnie, nie ma dla nich pliku .asc, a klucza prywatnego repo celowo NIE ma
535 - # na maszynie budującej. Wcześniej ta funkcja jako jedyna ignorowała
536 - # PAG_INSECURE, więc obejście używane przez resztę builda tu nie działało.
537 - if os.environ.get("PAG_INSECURE", "") == "1":
538 - print(" ⚠ PAG_INSECURE=1 – pomijam weryfikację podpisu pakietu lokalnego")
539 - return True
540 - sig_path = next((pkg_path + ext for ext in (".asc", ".sig")
541 - if os.path.isfile(pkg_path + ext)), "")
542 - if not sig_path:
543 - print(f" ❌ Brak podpisu dla pakietu: {pkg_path}")
544 - print(" Wymagany jest plik .pag.asc/.pag.sig z tego samego źródła.")
545 - return False
546 - ok, fingerprint = _gpg_verify_fp(sig_path, pkg_path)
547 - if not ok or not fingerprint:
548 - print(f" ❌ Nieprawidłowy podpis pakietu: {pkg_path}")
549 - return False
550 - expected = _repo_pinned_fp(DEFAULT_REPOS[0])
551 - if not expected:
552 - print(" ❌ Brak przypiętego klucza repo dla lokalnego pakietu.")
553 - print(" Uruchom najpierw: sudo pag sync")
554 - return False
555 - if fingerprint != expected.upper():
556 - print(" ❌ [SECURITY ERROR] Pakiet podpisano innym kluczem repo.")
557 - print(f" Oczekiwany: {expected}")
558 - print(f" Otrzymany: {fingerprint}")
559 - return False
560 - print(f" 🔐 Podpis pakietu OK ({fingerprint})")
561 - return True
562 -
563 -
564 -# =============================================================================
565 -# i18n – WIELOJĘZYCZNOŚĆ
566 -# =============================================================================
567 -
568 -LANG = os.environ.get("LANG", "en_US.UTF-8")[:2] # pl, en, de...
569 -COLOR = os.environ.get("NO_COLOR", "") == "" and sys.stdout.isatty()
570 -
571 -def _c(code: str, text: str) -> str:
572 - """Dodaje kody ANSI jeśli kolor jest włączony."""
573 - if not COLOR:
574 - return text
575 - colors = {
576 - "green": "\033[32m", "red": "\033[31m", "yellow": "\033[33m",
577 - "cyan": "\033[36m", "bold": "\033[1m", "dim": "\033[2m",
578 - "reset": "\033[0m",
579 - }
580 - return f"{colors.get(code,'')}{text}{colors['reset']}"
581 -
582 -T = {
583 - "en": {
584 - "root_required": "pag requires root privileges (sudo).",
585 - "db_locked": "Another pag instance is running.",
586 - "db_lock_hint": "If no other pag process is running, wait a moment and retry.",
587 - "no_index": "Cannot fetch repository indexes. Run 'pag update'.",
588 - "cache_ro": "Repo cache is read-only ({cache}) – using local index (may be outdated).\n Refresh as root: sudo pag sync",
589 - "all_installed": "All packages are already installed.",
590 - "to_install": "To install: {} packages ({:.2f} MB)",
591 - "new": "NEW",
592 - "continue_q": "Continue? [Y/n] ",
593 - "no_tty": "No TTY / stdin closed (EOF) – cancelling.",
594 - "cancelled": "Cancelled.",
595 - "not_found": "not found in repos",
596 - "pkg_not_found": "Package not found: {} (not in any repo)",
597 - "not_found_hint": "Check the spelling or run 'pag search <query>'.",
598 - "downloading": "Downloading",
599 - "download_fail": "download failed",
600 - "gpg_fail": "GPG verification failed",
601 - "sha256_mismatch": "SHA256 mismatch",
602 - "install_failed": "installation failed",
603 - "installed": "Installed {} packages.",
604 - "rollback_restored": "Restored previous state from snapshot.",
605 - "rollback_files": "Rolled back {} files.",
606 - "no_history": "No transaction history.",
607 - "pinned_list": "Pinned packages ({}):",
608 - "no_pinned": "No pinned packages.",
609 - "pinned_to": "pinned to",
610 - "unpinned": "unpinned.",
611 - "not_pinned": "was not pinned.",
612 - "repo_added": "Added repository: {}",
613 - "repo_exists": "Repository already exists: {}",
614 - "updated_done": "Index refresh complete. {} packages cached.",
615 - "indexes_refreshed": "Indexes refreshed.",
616 - "updates_available": "⚠ {} packages have updates – run: pag update",
617 - "upgrading": "Upgrading: {} packages",
618 - "all_up_to_date": "All packages are up to date.",
619 - "removing": "Removing",
620 - "orphans_found": "Orphaned dependencies ({}): {}",
621 - "flatpak_missing": "Flatpak is not installed.",
622 - "flatpak_adding": "Adding Flathub remote...",
623 - "flatpak_searching": "Searching Flathub for '{}'...",
624 - "flatpak_found": "Found {} results:",
625 - "flatpak_not_found": "not found on Flathub",
626 - "flatpak_install_prompt": "Install {}? [Y/n] ",
627 - "flatpak_installing": "Installing {}...",
628 - "flatpak_installed": "Flatpak {} installed.",
629 - "flatpak_removed": "Flatpak {} removed.",
630 - "flatpak_not_installed": "Flatpak {} is not installed.",
631 - "flatpak_info_id": "ID",
632 - "flatpak_info_version": "Version",
633 - "flatpak_info_branch": "Branch",
634 - "flatpak_info_origin": "Origin",
635 - "flatpak_info_size": "Installed size",
636 - "flatpak_info_desc": "Description",
637 - "flatpak_updated": "Flatpaks updated.",
638 - "flatpak_usage": "Usage: pag flatpak <search|install|remove|list|update|info> [args]",
639 - "flatpak_scope": "Installation",
640 - "flatpak_menu_hint": "Installed and verified, but this session may not show it in the menu: Flatpak exports are missing from XDG_DATA_DIRS.",
641 - "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.",
642 - "key_imported": "Key imported successfully.",
643 - "key_removed": "Key removed: {}",
644 - "no_keys": "No trusted GPG keys.",
645 - "gpg_missing": "GNUPG MISSING – install gnupg and retry",
646 - "ssl_broken": "Python has no working ssl module (HTTPS impossible) – fix the python/openssl packages (e.g. sudo pag install -f python).",
647 - "key_add_failed": "Key import failed (gpg error) – key was NOT added.",
648 - "verify_ok": "All {} files intact.",
649 - "verify_errors": "{} problems found:",
650 - "cache_cleared": "{} files ({:.2f} MB) cleared from cache.",
651 - "deployments_list": "Deployments ({}):",
652 - "no_deployments": "No deployments.",
653 - "active_deployment": "ACTIVE",
654 - "deploy_rollback_ok": "Switched to deployment: {}",
655 - "deploy_rollback_fail": "No previous deployment.",
656 - "deploy_cleanup_ok": "Removed {} old deployments.",
657 - "deploy_cleanup_none": "No deployments to clean (minimum {}).",
658 - "snapshot_none": "No system snapshots.",
659 - "snapshot_list": "System snapshots ({}):",
660 - "snapshot_created": "Snapshot created: {}.",
661 - "snapshot_deleted": "Snapshot removed: {}.",
662 - "snapshot_not_found": "Snapshot not found: {}",
663 - "snapshot_unsupported": "Snapshots unavailable: {}",
664 - "snapshot_rollback_next": "Next boot set to snapshot: {}",
665 - "snapshot_rollback_hint": "Select this entry in the GRUB menu: {}",
666 - "staging_prepare": "Preparing {} packages in staging (system unchanged)...",
667 - "staging_failed": "Staging failed – the system was NOT modified.",
668 - "staging_commit": "All packages prepared – applying changes...",
669 - "dry_run_done": "Dry run – nothing was changed.",
670 - "dry_run_plan": "Dry run – transaction plan (no changes):",
671 - "why_explicit": "explicitly installed",
672 - "why_dependency": "dependency of",
673 - "why_not_installed": "not installed",
674 - "rdepends_title": "Reverse dependencies of {} ({}):",
675 - "rdepends_none": "nothing depends on it.",
676 - "optional_deps": "Optional dependencies (not installed automatically):",
677 - "autoremove_ok": "Removed {} orphaned packages.",
678 - "autoremove_none": "No orphaned packages.",
679 - "downloaded": "Downloaded {} to cache ({:.2f} MB).",
680 - "provides_mapped": "{} → {} (provides)",
681 - "stats_title": "PAG Statistics",
682 - "stats_packages": "Installed packages",
683 - "stats_files": "Tracked files",
684 - "stats_size": "Total size",
685 - "stats_cache": "Cache size",
686 - "stats_history": "Transactions",
687 - "stats_last_update": "Last update",
688 - # Komunikaty bezpieczeństwa (baza EN; PL w tabeli "pl" jako sec_*_pl)
689 - "sec_downgrade": "Downgrade blocked: {pkg} {new} < {old}",
690 - "sec_suid": "SUID stripped from {path}",
691 - "sec_https": "HTTPS required for repos",
692 - "sec_badname": "Invalid package name: {name}",
693 - "sec_toobig": "Package too large: {size_mb}MB > {max_mb}MB",
694 - "sec_conflict": "File conflict: {path} owned by {owner}",
695 - "sec_audit": "{pkg} installed by {user}",
696 - "sec_locked": "Another pag process is running",
697 - # Konfiguracja (/etc) – zachowanie zmian użytkownika
698 - "conf_pacnew": "Modified config kept; new version saved as {path}",
699 - "conf_pacsave": "Modified config kept as {path}",
700 - # Zależności wirtualne (provides)
701 - "provides_conflict": "Multiple providers for '{name}' ({providers}) – using '{chosen}'",
702 -
703 - # Base baked into the ISO image (pag base / base adopt)
704 - "base_title": "Base from the ISO image",
705 - "base_no_manifest": "This system carries no base manifest (/usr/share/pag/base.json) – nothing to adopt.",
706 - "base_iso_version": "Image version",
707 - "base_total": "Base packages (from image)",
708 - "base_tracked": "Managed by pag",
709 - "base_adoptable": "Adoptable from repo",
710 - "base_unmatched": "No counterpart in repo",
711 - "base_adopt_hint": "Adopt them (image files get replaced by repo packages): sudo pag base adopt",
712 - "base_unmatched_hint": "These stay at the image version (no such package in repo):",
713 - "base_more": "more",
714 - "base_nothing_selected": "None of the given names is on the adopt list.",
715 - "base_all_managed": "Every base package is already managed by pag.",
716 - "base_adopt_plan": "Adopting {} base packages from the repo (~{:.0f} MB):",
717 - "base_dry_run": "Dry run – nothing was installed.",
718 - "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).",
719 - "base_overwrite": "{} comes from the ISO image – its files will be replaced (backup kept for 'pag rollback').",
720 - "base_reboot_hint": "Base adopted from the repo – reboot before using the new libraries/toolchain.",
721 - "base_register_ok": "Registered {} base packages in the package DB ({} were already tracked).",
722 - "base_register_plan": "Dry run – would register {} base packages.",
723 - "base_register_nocache": "No cached repo index – builder names kept as-is (run 'sudo pag sync' and 'pag base register' again to map them to repo names).",
724 - "base_register_renamed": "{} names were matched to their repo package names.",
725 - "stats_base": "Base (image) managed",
726 - },
727 - "pl": {
728 - "root_required": "pag wymaga uprawnień root (sudo).",
729 - "db_locked": "Inna instancja pag jest uruchomiona.",
730 - "db_lock_hint": "Jeśli żaden inny proces pag nie działa, poczekaj chwilę i spróbuj ponownie.",
731 - "no_index": "Nie można pobrać indeksów repozytoriów. Uruchom 'pag update'.",
732 - "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",
733 - "all_installed": "Wszystkie pakiety są już zainstalowane.",
734 - "to_install": "Do zainstalowania: {} pakietów ({:.2f} MB)",
735 - "new": "NOWY",
736 - "continue_q": "Kontynuować? [T/n] ",
737 - "no_tty": "Brak terminala (EOF) – anuluję.",
738 - "cancelled": "Anulowano.",
739 - "not_found": "brak w repozytoriach",
740 - "pkg_not_found": "Nie znaleziono pakietu: {} (brak w repozytoriach)",
741 - "not_found_hint": "Sprawdź pisownię lub uruchom 'pag search <fraza>'.",
742 - "downloading": "Pobieranie",
743 - "download_fail": "błąd pobierania",
744 - "gpg_fail": "błąd weryfikacji GPG",
745 - "sha256_mismatch": "niezgodność SHA256",
746 - "install_failed": "błąd instalacji",
747 - "installed": "Zainstalowano {} pakietów.",
748 - "rollback_restored": "Przywrócono poprzedni stan z migawki.",
749 - "rollback_files": "Wycofano {} plików.",
750 - "no_history": "Brak historii transakcji.",
751 - "pinned_list": "Przypięte pakiety ({}):",
752 - "no_pinned": "Brak przypiętych pakietów.",
753 - "pinned_to": "przypięty do",
754 - "unpinned": "odpięty.",
755 - "not_pinned": "nie był przypięty.",
756 - "repo_added": "Dodano repozytorium: {}",
757 - "repo_exists": "Repozytorium już istnieje: {}",
758 - "updated_done": "Odświeżanie zakończone. {} pakietów w cache.",
759 - "indexes_refreshed": "Indeksy odświeżone.",
760 - "updates_available": "⚠ jest {} pakietów do zaktualizowania – wpisz: pag update",
761 - "upgrading": "Aktualizacje: {} pakietów",
762 - "all_up_to_date": "Wszystkie pakiety są aktualne.",
763 - "removing": "Usuwanie",
764 - "orphans_found": "Osierocone zależności ({}): {}",
765 - "flatpak_missing": "Flatpak nie jest zainstalowany.",
766 - "flatpak_adding": "Dodaję zdalne repozytorium Flathub...",
767 - "flatpak_searching": "Szukam '{}' we Flathub...",
768 - "flatpak_found": "Znaleziono {} wyników:",
769 - "flatpak_not_found": "nie znaleziono we Flathub",
770 - "flatpak_install_prompt": "Zainstalować {}? [T/n] ",
771 - "flatpak_installing": "Instalowanie {}...",
772 - "flatpak_installed": "Flatpak {} zainstalowany.",
773 - "flatpak_removed": "Flatpak {} usunięty.",
774 - "flatpak_not_installed": "Flatpak {} nie jest zainstalowany.",
775 - "flatpak_info_id": "ID",
776 - "flatpak_info_version": "Wersja",
777 - "flatpak_info_branch": "Gałąź",
778 - "flatpak_info_origin": "Źródło",
779 - "flatpak_info_size": "Rozmiar",
780 - "flatpak_info_desc": "Opis",
781 - "flatpak_updated": "Flapaki zaktualizowane.",
782 - "flatpak_usage": "Użycie: pag flatpak <search|install|remove|list|update|info> [args]",
783 - "flatpak_scope": "Instalacja",
784 - "flatpak_menu_hint": "Zainstalowano i zweryfikowano, ale sesja może jej nie pokazać w menu: brak eksportów Flatpaka w XDG_DATA_DIRS.",
785 - "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.",
786 - "key_imported": "Klucz zaimportowany pomyślnie.",
787 - "key_removed": "Klucz usunięty: {}",
788 - "no_keys": "Brak zaufanych kluczy GPG.",
789 - "gpg_missing": "BRAK GNUPG – zainstaluj gnupg i spróbuj ponownie",
790 - "ssl_broken": "Python bez działającego modułu ssl (HTTPS niemożliwe) – napraw pakiety python/openssl (np. sudo pag install -f python).",
791 - "key_add_failed": "Import klucza nie powiódł się (błąd gpg) – klucz NIE został dodany.",
792 - "verify_ok": "Wszystkie {} plików sprawne.",
793 - "verify_errors": "Znaleziono {} problemów:",
794 - "cache_cleared": "{} plików ({:.2f} MB) usuniętych z cache.",
795 - "deployments_list": "Deploymenty ({}):",
796 - "no_deployments": "Brak deploymentów.",
797 - "active_deployment": "AKTYWNY",
798 - "deploy_rollback_ok": "Przełączono na deployment: {}",
799 - "deploy_rollback_fail": "Brak poprzedniego deploymentu.",
800 - "deploy_cleanup_ok": "Usunięto {} starych deploymentów.",
801 - "deploy_cleanup_none": "Nie ma deploymentów do wyczyszczenia (minimum {}).",
802 - "snapshot_none": "Brak snapshotów systemu.",
803 - "snapshot_list": "Snapshoty systemu ({}):",
804 - "snapshot_created": "Utworzono snapshot: {}.",
805 - "snapshot_deleted": "Usunięto snapshot: {}.",
806 - "snapshot_not_found": "Nie znaleziono snapshotu: {}",
807 - "snapshot_unsupported": "Snapshoty niedostępne: {}",
808 - "snapshot_rollback_next": "Następny start ustawiono na snapshot: {}",
809 - "snapshot_rollback_hint": "Wybierz ten wpis w menu GRUB: {}",
810 - "staging_prepare": "Przygotowuję {} pakietów w stagingu (system bez zmian)...",
811 - "staging_failed": "Etap przygotowania nieudany – system NIE został zmieniony.",
812 - "staging_commit": "Wszystkie pakiety przygotowane – nakładam zmiany...",
813 - "dry_run_done": "Dry-run – nic nie zmieniono.",
814 - "dry_run_plan": "Dry-run – plan transakcji (bez zmian):",
815 - "why_explicit": "zainstalowany jawnie",
816 - "why_dependency": "zależność od",
817 - "why_not_installed": "niezainstalowany",
818 - "rdepends_title": "Odwrotne zależności {} ({}):",
819 - "rdepends_none": "nic od niego nie zależy.",
820 - "optional_deps": "Opcjonalne zależności (nie są instalowane automatycznie):",
821 - "autoremove_ok": "Usunięto {} osieroconych pakietów.",
822 - "autoremove_none": "Brak osieroconych pakietów.",
823 - "downloaded": "Pobrano {} do cache ({:.2f} MB).",
824 - "sec_downgrade": "Downgrade blocked: {pkg} {new} < {old}",
825 - "sec_suid": "SUID stripped from {path}",
826 - "sec_https": "HTTPS required for repos",
827 - "sec_badname": "Invalid package name: {name}",
828 - "sec_toobig": "Package too large: {size_mb}MB > {max_mb}MB",
829 - "sec_conflict": "File conflict: {path} owned by {owner}",
830 - "sec_audit": "{pkg} installed by {user}",
831 - "sec_locked": "Another pag process is running",
832 - "sec_downgrade_pl": "Blokada downgrade: {pkg} {new} < {old}",
833 - "sec_suid_pl": "SUID usuniety z {path}",
834 - "sec_https_pl": "Repozytorium wymaga HTTPS",
835 - "sec_badname_pl": "Nieprawidlowa nazwa pakietu: {name}",
836 - "sec_toobig_pl": "Paczka za duza: {size_mb}MB > {max_mb}MB",
837 - "sec_conflict_pl": "Konflikt plikow: {path} nalezy do {owner}",
838 - "sec_audit_pl": "{pkg} zainstalowany przez {user}",
839 - "sec_locked_pl": "Inny proces pag juz dziala",
840 -
841 - "provides_mapped": "{} → {} (provides)",
842 - "stats_title": "Statystyki PAG",
843 - "stats_packages": "Zainstalowane pakiety",
844 - "stats_files": "Śledzone pliki",
845 - "stats_size": "Całkowity rozmiar",
846 - "stats_cache": "Rozmiar cache",
847 - "stats_history": "Transakcje",
848 - "stats_last_update": "Ostatnia aktualizacja",
849 - "conf_pacnew": "Zmieniony plik konfiguracyjny zachowany; nowa wersja: {path}",
850 - "conf_pacsave": "Zmieniony plik konfiguracyjny zachowany jako {path}",
851 - "provides_conflict": "Wielu dostawców dla '{name}' ({providers}) – używam '{chosen}'",
852 -
853 - # Baza wypalona w obrazie ISO (pag base / base adopt)
854 - "base_title": "Baza z obrazu ISO",
855 - "base_no_manifest": "Ten system nie ma manifestu bazy (/usr/share/pag/base.json) – nie ma czego adoptować.",
856 - "base_iso_version": "Wersja obrazu",
857 - "base_total": "Pakiety bazy (z obrazu)",
858 - "base_tracked": "Zarządzane przez pag",
859 - "base_adoptable": "Do adoptowania z repo",
860 - "base_unmatched": "Bez odpowiednika w repo",
861 - "base_adopt_hint": "Adoptuj (pliki z obrazu zostaną zastąpione pakietami z repo): sudo pag base adopt",
862 - "base_unmatched_hint": "Te zostaną w wersji z obrazu (brak takiego pakietu w repo):",
863 - "base_more": "więcej",
864 - "base_nothing_selected": "Żadna z podanych nazw nie jest na liście do adoptowania.",
865 - "base_all_managed": "Wszystkie pakiety bazy są już zarządzane przez pag.",
866 - "base_adopt_plan": "Adoptowanie {} pakietów bazy z repo (~{:.0f} MB):",
867 - "base_dry_run": "Próba na sucho – nic nie zainstalowano.",
868 - "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).",
869 - "base_overwrite": "{} pochodzi z obrazu ISO – pliki zostaną zastąpione (kopia zapasowa dla 'pag rollback').",
870 - "base_reboot_hint": "Baza zaadoptowana z repo – zrestartuj system, zanim zaczniesz używać nowych bibliotek/narzędzi.",
871 - "base_register_ok": "Zarejestrowano {} pakietów bazy w bazie pakietów ({} już było).",
872 - "base_register_plan": "Dry-run – zarejestrowałbym {} pakietów bazy.",
873 - "base_register_nocache": "Brak cache indeksu repo – zostawiono nazwy z buildera (uruchom 'sudo pag sync' i ponownie 'pag base register', aby je zmapować).",
874 - "base_register_renamed": "{} nazw dopasowano do nazw pakietów w repo.",
875 - "stats_base": "Baza (obraz) zarządzana",
876 - },
877 -}
878 -
879 -# ── Tłumaczenia z PLIKÓW (nadpisują/rozszerzają wbudowane PL/EN) ─────────────
880 -# Kolejność: PAG_LANG_DIR (env) → /etc/pag/lang → /usr/share/pag/lang →
881 -# ./pag-lang obok binarki (dev). Brak plików NIE jest błędem – zostaje
882 -# wbudowany słownik T (fallback), więc pag zawsze działa.
883 -# Przykład pliku (pag-lang/pl.json): {"app_title": "...", "usage": "..."}.
884 -def _load_lang_files() -> None:
885 - # PAG_LANG_NO_FILES=1 → pomiń pliki (używane przy eksporcie --lang-extract,
886 - # żeby wyeksportować CZYSTE wbudowane słowniki, bez starych nadpisań).
887 - if os.environ.get("PAG_LANG_NO_FILES") == "1":
888 - return
889 - dirs = []
890 - _env = os.environ.get("PAG_LANG_DIR")
891 - if _env:
892 - dirs.append(_env)
893 - # __file__ bywa niedostępne, gdy moduł jest exec/frozen (np. harness
894 - # instalacyjny) – liczymy wtedy od ścieżki programu, zamiast wywalać
895 - # NameError przy samym imporcie.
896 - _self = globals().get("__file__") or sys.argv[0] or "pag"
897 - dirs += ["/etc/pag/lang", "/usr/share/pag/lang",
898 - os.path.join(os.path.dirname(os.path.abspath(_self)), "pag-lang")]
899 - for _d in dirs:
900 - for _code in list(T.keys()) + ["pl", "en", "de"]:
901 - _p = os.path.join(_d, f"{_code}.json")
902 - try:
903 - with open(_p, "r", encoding="utf-8") as _fh:
904 - _data = json.load(_fh)
905 - if isinstance(_data, dict):
906 - # Merge (nie replace): klucze nieobecne w pliku zachowują
907 - # wbudowane tłumaczenie. Puste wartości pomijamy, żeby
908 - # niekompletny/uszkodzony plik nie wyczyścił komunikatu.
909 - _clean = {str(k): str(v) for k, v in _data.items()
910 - if str(v).strip()}
911 - T.setdefault(_code, {}).update(_clean)
912 - except (OSError, ValueError):
913 - continue
914 -
915 -
916 -_load_lang_files()
917 -
918 -def _(key: str, *args, **kwargs) -> str:
919 - """Tłumaczy klucz i formatuje argumenty.
920 -
921 - Dla LANG=pl preferuje wariant „<key>_pl” (np. komunikaty bezpieczeństwa
922 - mają krótkie wersje PL obok bazy EN), potem zwykły klucz, potem EN/klicz.
923 - """
924 - if LANG == "pl":
925 - _pl = T.get("pl", {})
926 - msg = _pl.get(key + "_pl") or _pl.get(key) or T["en"].get(key, key)
927 - else:
928 - msg = T.get(LANG, T["en"]).get(key, T["en"].get(key, key))
929 - if args or kwargs:
930 - return msg.format(*args, **kwargs)
931 - return msg
932 -
933 -
934 -def _ask_confirm() -> bool:
935 - """Pytanie potwierdzające (T/n). PAG_YES=1 → zawsze tak.
936 -
937 - EOF/brak terminala (stdin zamknięty, np. ssh bez TTY, cron, subprocess
938 - panelu webowego) → NIE – anuluj, nie wykonuj operacji bez potwierdzenia
939 - (inaczej input() rzuca EOFError i pag pada tracebackiem).
940 - Enter → tak (domyślne Y/n).
941 - """
942 - if os.environ.get("PAG_YES", "") == "1":
943 - print(_("continue_q") + " t (--yes)")
944 - return True
945 - try:
946 - ans = input(_("continue_q")).strip().lower()
947 - except (EOFError, KeyboardInterrupt):
948 - print(f"\n ⚠ {_('no_tty')}")
949 - return False
950 - return not ans or ans in ("t", "y")
951 -
952 -
953 -# =============================================================================
954 -# ŚCIEŻKI
955 -# =============================================================================
956 -PAG_ROOT = os.environ.get("PAG_ROOT", "/")
957 -PAG_DB = "/var/lib/pag"
958 -PAG_CACHE = "/var/cache/pag"
959 -PAG_CONF = "/etc/pag"
960 -REPO_CACHE = "/var/cache/pag/repos"
961 -REPOS_CONF = "/etc/pag/repos.conf"
962 -REPOS_DIR = PAG_CONF + "/repos" # drop-in: /etc/pag/repos/<nazwa>.conf
963 -INSTALLED_DB = "/var/lib/pag/installed.json"
964 -FILES_DB_SQL = "/var/lib/pag/files.db" # SQLite!
965 -WORLD_FILE = "/var/lib/pag/world"
966 -PINNED_FILE = "/var/lib/pag/pinned.json"
967 -HISTORY_FILE = "/var/lib/pag/history.json"
968 -LOCK_FILE = "/var/lib/pag/pag.lock"
969 -STAGING_DIR = "/.pag_staging" # na tej samej partycji co / (unikamy EXDEV)
970 -PKG_EXT = ".pag"
971 -REPO_CACHE_TTL = 3600
972 -MAX_PKG_SIZE = 2 * 1024 * 1024 * 1024 # 2 GB – maksymalny rozmiar paczki
973 -BASE_MANIFEST = "/usr/share/pag/base.json" # baza z obrazu ISO (pag base/adopt)
974 -
975 -# ── UPRZYWILEJOWANE PLIKI ────────────────────────────────────────────────────
976 -# Domyślnie pag zdejmuje bit SUID i wymusza właściciela root:root. Niektóre
977 -# programy MUSZĄ jednak zachować setuid/setgid albo grupę inną niż root
978 -# (/usr/bin/sudo, /usr/bin/passwd, /usr/bin/unix_chkpwd,
979 -# /usr/lib/dbus-daemon-launch-helper). Bez tego tracą możliwość działania
980 -# po aktualizacji przez pag (np. użytkownik nie zmieni hasła).
981 -#
982 -# Bezpieczeństwo: zawartość pakietu jest uwierzytelniona (podpis GPG repo +
983 -# przypięty fingerprint + SHA256 całego pakietu), więc metadane w nim są
984 -# zaufane tak samo jak same pliki. Zachowujemy uprawnienia WYŁĄCZNIE dla
985 -# ścieżek z tej listy (albo z pola `privileged:` receptury, które pagbuild
986 -# zapisuje w metadata.json).
987 -PRIVILEGED_PATHS = frozenset({
988 - "/usr/bin/cdda2wav", "/usr/bin/cdrecord",
989 - "/usr/bin/chage", "/usr/bin/expiry",
990 - "/usr/bin/fcrondyn", "/usr/bin/fcronsighup", "/usr/bin/fcrontab",
991 - "/usr/bin/firejail", "/usr/bin/fping",
992 - "/usr/bin/fusermount", "/usr/bin/fusermount3",
993 - "/usr/bin/gpasswd", "/usr/bin/ksu", "/usr/bin/lockfile",
994 - "/usr/bin/mount", "/usr/bin/mount.nfs",
995 - "/usr/bin/newgidmap", "/usr/bin/newuidmap",
996 - "/usr/bin/passwd", "/usr/bin/ping", "/usr/bin/ping6",
997 - "/usr/bin/procmail", "/usr/bin/readcd", "/usr/bin/rscsi",
998 - "/usr/bin/screen", "/usr/bin/screen-5.0.2",
999 - "/usr/bin/sg", "/usr/bin/su", "/usr/bin/sudo", "/usr/bin/traceroute",
1000 - "/usr/bin/umount", "/usr/bin/unix_chkpwd", "/usr/bin/wall",
1001 - "/usr/lib/dbus-daemon-launch-helper",
1002 - "/usr/lib/httpd/suexec",
1003 - "/usr/lib/utempter/utempter",
1004 - "/usr/lib/xscreensaver/xscreensaver-auth",
1005 - "/usr/libexec/libgtop_server2",
1006 - "/usr/libexec/qemu-bridge-helper",
1007 - "/usr/libexec/ssh-keysign",
1008 - "/usr/libexec/xf86-video-intel-backlight-helper",
1009 - "/opt/google/chrome/chrome-sandbox",
1010 - "/opt/gitkraken/chrome-sandbox",
1011 - "/opt/VirtualBox/VBoxHeadless", "/opt/VirtualBox/VBoxNetAdpCtl",
1012 - "/opt/VirtualBox/VBoxNetDHCP", "/opt/VirtualBox/VBoxVolInfo",
1013 - "/opt/VirtualBox/VirtualBoxVM",
1014 -})
1015 -ALLOWED_PKG_RE = re.compile(r'^[a-zA-Z0-9][a-zA-Z0-9._+@-]*$')
1016 -
1017 -# Bezpieczeństwo / audyt
1018 -AUDIT_LOG = "/var/log/pag/audit.log" # dziennik operacji krytycznych (hooki, self-update)
1019 -TRUST_DB = "/etc/pag/trusted.json" # mapa repo_url → fingerprint klucza podpisującego
1020 -HOOK_API_VERSION = "1" # wersjonowane API hooków (env PKG_HOOK_API)
1021 -
1022 -# =============================================================================
1023 -# IMMUTABLE OS – DEPLOYMENTY
1024 -# =============================================================================
1025 -# Model: zamiast mutować /, każda operacja tworzy NOWY deployment.
1026 -# /var, /etc, /home są współdzielone między deploymentami.
1027 -#
1028 -# STRUKTURA:
1029 -# /.deployments/
1030 -# active → 20260723T120000 (symlink do aktywnego)
1031 -# 20260723T120000/
1032 -# usr/ bin/ lib/ lib64/ ... (pełny system)
1033 -# var → /var (symlink do współdzielonego)
1034 -# etc → /etc
1035 -# home → /home
1036 -# ...
1037 -#
1038 -# Jak to działa:
1039 -# 1. pag install → kopiuje active → nowy deployment + nakłada zmiany → switch symlinka
1040 -# 2. pag remove → kopiuje active → nowy deployment - usuwa pliki → switch symlinka
1041 -# 3. pag deploy-rollback → przełącza active symlink na poprzedni deployment
1042 -# 4. Przy starcie systemu: initrd montuje /.deployments/active jako /
1043 -# =============================================================================
1044 -
1045 -DEPLOYMENTS_DIR = "/.deployments"
1046 -ACTIVE_LINK = "/.deployments/active"
1047 -DEPLOYMENTS_DB = "/var/lib/pag/deployments.json"
1048 -
1049 -# Snapshoty systemu (CoW). Na btrfs każdy snapshot jest osobnym subwolumenem,
1050 -# więc zajmuje tylko zmienione bloki, a GRUB potrafi uruchomić system z wybranej
1051 -# migawki (rootflags=subvol=...). Na ext4/xfs nie ma snapshotów CoW – zostaje
1052 -# atomowy staging + backup nadpisywanych plików.
1053 -SNAPSHOTS_DIR = "/.pag_snapshots"
1054 -SNAPSHOTS_DB = "/var/lib/pag/snapshots.json"
1055 -GRUB_SNAPSHOT_SCRIPT = "/etc/grub.d/40_pagan_snapshots"
1056 -
1057 -# Ścieżki współdzielone – NIE wchodzą do deploymentu (są symlinkami do /...)
1058 -SHARED_PATHS = {
1059 - "/var", "/etc", "/home", "/root", "/tmp", "/run",
1060 - "/dev", "/proc", "/sys", "/mnt", "/media", "/srv",
1061 - # /boot współdzielone: jądro + initramfs są wspólne dla wszystkich
1062 - # deploymentów (inaczej każdy trzyma własną ~50-100 MB kopię). GRUB
1063 - # wskazuje na /.deployments/<id>/boot → symlink do /boot.
1064 - "/boot",
1065 - "/.deployments", "/.pag_staging",
1066 -}
1067 -
1068 -def _is_shared_path(rel: str) -> bool:
1069 - """Sprawdza czy ścieżka należy do katalogów współdzielonych (poza deploymentem)."""
1070 - for sp in SHARED_PATHS:
1071 - if rel == sp or rel.startswith(sp + "/"):
1072 - return True
1073 - return False
1074 -
1075 -def _is_config_path(rel: str) -> bool:
1076 - """Czy ścieżka to plik konfiguracyjny (/etc/...)?
1077 -
1078 - Dla takich plików stosujemy .pacnew/.pacsave (zachowanie zmian użytkownika)
1079 - zamiast bezwarunkowego nadpisania/usunięcia."""
1080 - p = rel.lstrip("/")
1081 - return p == "etc" or p.startswith("etc/")
1082 -
1083 -# Wrażliwa konfiguracja auth/systemowa – NIGDY nie nadpisujemy jej po cichu.
1084 -# Nadpisanie /etc/pam.d/system-* przez pakiet (np. shadow) potrafi zablokować
1085 -# logowanie/sudo („account validation failure”); dla tych ścieżek zawsze robimy
1086 -# .pacnew, gdy treść na dysku różni się od tej z pakietu.
1087 -_SENSITIVE_CONFIG_RE = re.compile(
1088 - r'^(pam\.d/|security/|sudoers$|sudoers\.d/|shadow$|gshadow$|passwd$|group$|'
1089 - r'login\.defs$|nsswitch\.conf$|default/useradd$)')
1090 -
1091 -def _is_sensitive_config(rel: str) -> bool:
1092 - """Czy rel to wrażliwy plik /etc (PAM, sudoers, shadow, login.defs…)?"""
1093 - p = rel.lstrip("/")
1094 - if not p.startswith("etc/"):
1095 - return False
1096 - return bool(_SENSITIVE_CONFIG_RE.match(p[4:]))
1097 -
1098 -def _get_deployment_root() -> str:
1099 - """Zwraca ścieżkę do aktywnego deploymentu, lub PAG_ROOT jeśli tryb niemutowalny wyłączony."""
1100 - if os.environ.get("PAG_IMMUTABLE", "") in ("0", "no", "false", ""):
1101 - return PAG_ROOT
1102 - if os.path.islink(ACTIVE_LINK):
1103 - return os.readlink(ACTIVE_LINK)
1104 - if os.path.isdir(ACTIVE_LINK):
1105 - return ACTIVE_LINK
1106 - # Brak deploymentów – użyj /
1107 - return PAG_ROOT
1108 -
1109 -def _load_deployments() -> List[dict]:
1110 - """Wczytuje historię deploymentów."""
1111 - if not os.path.exists(DEPLOYMENTS_DB):
1112 - return []
1113 - try:
1114 - return json.load(open(DEPLOYMENTS_DB))
1115 - except Exception:
1116 - return []
1117 -
1118 -def _save_deployments(deployments: List[dict]):
1119 - os.makedirs(os.path.dirname(DEPLOYMENTS_DB), exist_ok=True)
1120 - json.dump(deployments, open(DEPLOYMENTS_DB, "w"), indent=2)
1121 -
1122 -def _create_deployment(pkg_names: List[str], action: str) -> Tuple[str, str]:
1123 - """
1124 - Tworzy nowy deployment przez skopiowanie aktywnego (CoW) i zwraca jego ścieżkę.
1125 - Zwraca (deployment_dir, deployment_id).
1126 - """
1127 - deploy_id = datetime.now().strftime("%Y%m%dT%H%M%S")
1128 - deploy_dir = os.path.join(DEPLOYMENTS_DIR, deploy_id)
1129 - os.makedirs(DEPLOYMENTS_DIR, exist_ok=True)
1130 -
1131 - active = _get_deployment_root()
1132 -
1133 - if os.path.isdir(active) and active != PAG_ROOT:
1134 - # Trójstopniowa strategia kopiowania deploymentu:
1135 - # 1. reflink (CoW – btrfs, xfs) → 0 MB kopiowane
1136 - # 2. hardlink (linki twarde) → 0 MB kopiowane, tylko inody
1137 - # 3. zwykłe cp (ostateczność) → pełna kopia
1138 - print(f" ⚡ Kopiowanie aktywnego deploymentu...")
1139 - copied = False
1140 - for method, cmd, label in [
1141 - ("reflink", ["cp", "--reflink=auto", "-a", active + "/.", deploy_dir + "/"], "CoW (reflink)"),
1142 - ("hardlink", ["cp", "-al", active + "/.", deploy_dir + "/"], "hardlinki"),
1143 - ("copy", ["cp", "-a", active + "/.", deploy_dir + "/"], "pełna kopia"),
1144 - ]:
1145 - try:
1146 - subprocess.run(cmd, check=True, timeout=600, capture_output=True)
1147 - print(f" ✅ Deployment: {deploy_id} ({label})")
1148 - copied = True
1149 - break
1150 - except subprocess.CalledProcessError:
1151 - if method == "copy":
1152 - raise # ostatnia deska – niech leci wyjątek
1153 - continue
1154 - if not copied:
1155 - raise RuntimeError("Nie udało się skopiować deploymentu żadną metodą")
1156 - else:
1157 - # Pierwszy deployment – tylko katalogi szkieletowe
1158 - # /boot celowo POMINIĘTE – jest współdzielone (SHARED_PATHS); poniższa
1159 - # pętla utworzy w deploymencie symlink boot → /boot.
1160 - for d in ["/usr", "/lib", "/lib64", "/bin", "/sbin", "/opt"]:
1161 - if os.path.isdir(d):
1162 - dest = os.path.join(deploy_dir, d.lstrip("/"))
1163 - os.makedirs(dest, exist_ok=True)
1164 - print(f" ✅ Pierwszy deployment: {deploy_id}")
1165 -
1166 - # Utwórz symlinki do współdzielonych katalogów
1167 - for sp in SHARED_PATHS:
1168 - link_dst = os.path.join(deploy_dir, sp.lstrip("/"))
1169 - if not os.path.lexists(link_dst) and os.path.isdir(sp):
1170 - os.symlink(sp, link_dst)
1171 -
1172 - # Zapisz w bazie deploymentów
1173 - deployments = _load_deployments()
1174 - deployments.append({
1175 - "id": deploy_id,
1176 - "action": action,
1177 - "packages": pkg_names,
1178 - "timestamp": datetime.now().isoformat(),
1179 - "active": True,
1180 - })
1181 - # Oznacz poprzednie jako nieaktywne
1182 - for d in deployments[:-1]:
1183 - d["active"] = False
1184 - _save_deployments(deployments)
1185 -
1186 - return deploy_dir, deploy_id
1187 -
1188 -def _switch_deployment(deploy_dir: str) -> bool:
1189 - """Atomowo przełącza aktywny deployment przez podmianę symlinka."""
1190 - tmp_link = ACTIVE_LINK + ".new"
1191 - if os.path.lexists(tmp_link):
1192 - os.remove(tmp_link)
1193 - os.symlink(deploy_dir, tmp_link)
1194 - os.rename(tmp_link, ACTIVE_LINK) # atomowe na tym samym FS
1195 - return True
1196 -
1197 -# =============================================================================
1198 -# SNAPSHOTY SYSTEMU (CoW – btrfs)
1199 -# =============================================================================
1200 -# Snapshot powstaje PRZED transakcją. Na btrfs to subwolumen (kilka KB
1201 -# metadanych, reszta to współdzielone bloki), więc nie kopiujemy całego
1202 -# systemu. Wpis GRUB pozwala uruchomić system z wybranej migawki.
1203 -# Na ext4/xfs nie ma CoW – instalacja nadal jest atomowa dzięki stagingowi,
1204 -# a rollback opiera się na backupie nadpisywanych plików.
1205 -
1206 -def _btrfs_bin() -> str:
1207 - """Ścieżka do btrfs (PATH bywa okrojony w chroocie/instalatorze)."""
1208 - found = shutil.which("btrfs")
1209 - if found:
1210 - return found
1211 - for cand in ("/usr/bin/btrfs", "/usr/sbin/btrfs", "/sbin/btrfs", "/bin/btrfs"):
1212 - if os.path.exists(cand):
1213 - return cand
1214 - return ""
1215 -
1216 -
1217 -def _root_fstype() -> str:
1218 - try:
1219 - r = subprocess.run(["findmnt", "-n", "-o", "FSTYPE", "/"],
1220 - capture_output=True, text=True, timeout=5)
1221 - fs = r.stdout.strip().splitlines()[0].strip() if r.stdout.strip() else ""
1222 - if fs:
1223 - return fs
1224 - except Exception:
1225 - pass
1226 - try:
1227 - r = subprocess.run(["stat", "-f", "-c", "%T", "/"],
1228 - capture_output=True, text=True, timeout=5)
1229 - return r.stdout.strip()
1230 - except Exception:
1231 - return ""
1232 -
1233 -
1234 -def _btrfs_root_path() -> str:
1235 - """Ścieżka aktywnego subwolumenu root względem top-level btrfs."""
1236 - btrfs = _btrfs_bin()
1237 - if btrfs:
1238 - try:
1239 - r = subprocess.run([btrfs, "subvolume", "show", "/"],
1240 - capture_output=True, text=True, timeout=5)
1241 - if r.returncode == 0:
1242 - for line in r.stdout.splitlines():
1243 - line = line.strip()
1244 - if line.lower().startswith("path:"):
1245 - p = line.split(":", 1)[1].strip()
1246 - if p in ("", "/"):
1247 - return "/"
1248 - return p.strip("/")
1249 - except Exception:
1250 - pass
1251 - try:
1252 - r = subprocess.run(["findmnt", "-n", "-o", "FSROOT", "/"],
1253 - capture_output=True, text=True, timeout=5)
1254 - p = r.stdout.strip()
1255 - if p and p != "/":
1256 - return p.strip("/")
1257 - except Exception:
1258 - pass
1259 - return "/"
1260 -
1261 -
1262 -def _snapshot_support() -> Tuple[bool, str]:
1263 - fs = _root_fstype()
1264 - if fs != "btrfs":
1265 - return False, (f"root jest na {fs or 'nieznanym systemie plików'} – "
1266 - f"snapshoty CoW wymagają btrfs")
1267 - if not _btrfs_bin():
1268 - return False, "brak narzędzia btrfs (zainstaluj pakiet btrfs-progs)"
1269 - return True, ""
1270 -
1271 -
1272 -def _load_snapshots() -> List[dict]:
1273 - if not os.path.exists(SNAPSHOTS_DB):
1274 - return []
1275 - try:
1276 - data = load_json(SNAPSHOTS_DB)
1277 - return data if isinstance(data, list) else []
1278 - except Exception:
1279 - return []
1280 -
1281 -
1282 -def _save_snapshots(items: List[dict]):
1283 - os.makedirs(os.path.dirname(SNAPSHOTS_DB), exist_ok=True)
1284 - save_json(SNAPSHOTS_DB, items)
1285 -
1286 -
1287 -def _snapshot_label(snap: dict) -> str:
1288 - """Czytelna etykieta GRUB (bez znaków, które psują menu)."""
1289 - pkgs = list(snap.get("packages") or [])
1290 - p = ", ".join(pkgs[:3])
1291 - if len(pkgs) > 3:
1292 - p += f" +{len(pkgs) - 3}"
1293 - base = f"Pagan Linux snapshot {snap.get('id', '?')}"
1294 - if snap.get("label"):
1295 - base += f" - {snap['label']}"
1296 - if p:
1297 - base += f" - {p}"
1298 - # GRUB: usuń apostrofy i znaki kontrolne.
1299 - return re.sub(r"[\x00-\x1f']", "", base)[:120]
1300 -
1301 -
1302 -def _root_boot_arg() -> str:
1303 - """`root=UUID=...` dla wpisu GRUB (stabilne po zmianie nazw urządzeń)."""
1304 - dev = _detect_root_device()
1305 - if not dev:
1306 - return ""
1307 - if dev.startswith(("UUID=", "PARTUUID=", "LABEL=", "PARTLABEL=")):
1308 - return f" root={dev}"
1309 - uuid = ""
1310 - try:
1311 - r = subprocess.run(["blkid", "-s", "UUID", "-o", "value", dev],
1312 - capture_output=True, text=True, timeout=5)
1313 - uuid = r.stdout.strip().splitlines()[0].strip() if r.stdout.strip() else ""
1314 - except Exception:
1315 - uuid = ""
1316 - return f" root=UUID={uuid}" if uuid else f" root={dev}"
1317 -
1318 -
1319 -def _initrd_for_kernel(boot_dir: str, kernel: str) -> str:
1320 - """Nazwa initramfs pasująca do jądra (initramfs.img / initramfs-<ver>.img…)."""
1321 - if not kernel or not os.path.isdir(boot_dir):
1322 - return ""
1323 - ver = kernel[len("vmlinuz-"):] if kernel.startswith("vmlinuz-") else ""
1324 - candidates = []
1325 - if ver:
1326 - candidates += [f"initramfs-{ver}.img", f"initrd.img-{ver}"]
1327 - candidates += ["initramfs.img", "initrd.img"]
1328 - for c in candidates:
1329 - if os.path.isfile(os.path.join(boot_dir, c)):
1330 - return c
1331 - for f in sorted(os.listdir(boot_dir)):
1332 - if f.startswith(("initramfs", "initrd")):
1333 - return f
1334 - return ""
1335 -
1336 -
1337 -def _pick_kernel_initrd(boot_dir: str) -> Tuple[str, str]:
1338 - kernels = sorted(
1339 - [f for f in os.listdir(boot_dir) if f.startswith("vmlinuz-")],
1340 - reverse=True,
1341 - ) if os.path.isdir(boot_dir) else []
1342 - if not kernels:
1343 - return "", ""
1344 - k = kernels[0]
1345 - return k, _initrd_for_kernel(boot_dir, k)
1346 -
1347 -
1348 -def _grub_snapshot_entries() -> List[str]:
1349 - """Wpisy menu GRUB dla snapshotów (dla `_update_grub_config` i grub.d)."""
1350 - snaps = _load_snapshots()
1351 - if not snaps:
1352 - return []
1353 -
1354 - root_arg = _root_boot_arg()
1355 - try:
1356 - separate_boot = os.path.isdir("/boot") and os.path.ismount("/boot")
1357 - except OSError:
1358 - separate_boot = False
1359 - bp = _boot_prefix()
1360 -
1361 - lines: List[str] = []
1362 - for snap in reversed(snaps):
1363 - path = snap.get("path") or ""
1364 - if not path or not os.path.isdir(path):
1365 - continue
1366 -
1367 - if separate_boot:
1368 - # Osobne /boot jest współdzielone: użyj jądra ZAPISANEGO przy
1369 - # tworzeniu snapshotu (o ile nadal leży w /boot), a nie zawsze
1370 - # najnowszego – nowe jądro mogło być właśnie przyczyną problemu.
1371 - kname = snap.get("kernel") or ""
1372 - if not kname or not os.path.isfile(os.path.join("/boot", kname)):
1373 - kname, _ = _pick_kernel_initrd("/boot")
1374 - iname = _initrd_for_kernel("/boot", kname) if kname else ""
1375 - kernel = f"{bp}/{kname}" if kname else ""
1376 - initrd = f"{bp}/{iname}" if iname else ""
1377 - else:
1378 - snap_boot = os.path.join(path, "boot")
1379 - kname, iname = _pick_kernel_initrd(snap_boot)
1380 - # Kopia zapasowa: jądro z bieżącego /boot (np. gdy /boot nie
1381 - # było częścią snapshotu lub jest to bardzo stara migawka).
1382 - if not kname:
1383 - kname, iname = _pick_kernel_initrd("/boot")
1384 - kernel = f"{bp}/{kname}" if kname else ""
1385 - initrd = f"{bp}/{iname}" if iname else ""
1386 - else:
1387 - kernel = f"{path}/boot/{kname}"
1388 - initrd = f"{path}/boot/{iname}" if iname else ""
1389 -
1390 - if not kernel:
1391 - continue
1392 -
1393 - subvol = snap.get("subvol") or ""
1394 - flags = f" rootflags=subvol={subvol} rootfstype=btrfs" if subvol else ""
1395 - label = _snapshot_label(snap)
1396 -
1397 - lines.append(f"menuentry '{label}' --class pagan --class gnu-linux --class os {{")
1398 - lines.append(f" linux {kernel}{root_arg}{flags} rw quiet")
1399 - if initrd:
1400 - lines.append(f" initrd {initrd}")
1401 - lines.append("}")
1402 - lines.append("")
1403 - return lines
1404 -
1405 -
1406 -def _ensure_snapshot_grub_script() -> bool:
1407 - """Instaluje /etc/grub.d/40_pagan_snapshots (integracja z grub-mkconfig)."""
1408 - if not os.path.isdir("/etc/grub.d"):
1409 - return False
1410 - # Preferuj BIEŻĄCĄ binarkę (np. testy z repo), a nie starszy /usr/bin/pag:
1411 - # stary pag nie zna `snapshot-grub` i uruchomiłby smart-search.
1412 - _self = os.path.abspath(sys.argv[0]) if sys.argv[0] else ""
1413 - exe = _self if _self and os.path.isfile(_self) else (shutil.which("pag") or "/usr/bin/pag")
1414 - if not exe or not os.path.exists(exe):
1415 - exe = "/usr/bin/pag"
1416 - quoted = exe.replace("'", "'\\''")
1417 - script = (
1418 - "#!/bin/sh\n"
1419 - "# Pagan Linux – wpisy GRUB dla snapshotów systemu (wygenerowane przez pag)\n"
1420 - "# Usuń ten plik, aby ukryć snapshoty w menu GRUB.\n"
1421 - f"PAG_BIN='{quoted}'\n"
1422 - 'if [ ! -x "$PAG_BIN" ]; then\n'
1423 - ' PAG_BIN="$(command -v pag 2>/dev/null || true)"\n'
1424 - "fi\n"
1425 - '[ -x "$PAG_BIN" ] || exit 0\n'
1426 - '# Tylko pag >= 4.1 zna komendę snapshot-grub (starszy zrobiłby\n'
1427 - '# smart-search i mógłby zawiesić grub-mkconfig na sieci).\n'
1428 - 'case "$("$PAG_BIN" --version 2>/dev/null)" in\n'
1429 - ' "pag 4."[1-9]*|"pag "[5-9]*|"pag "[1-9][0-9]*) ;;\n'
1430 - ' *) exit 0 ;;\n'
1431 - 'esac\n'
1432 - 'exec "$PAG_BIN" snapshot-grub\n'
1433 - )
1434 - try:
1435 - with open(GRUB_SNAPSHOT_SCRIPT, "w", encoding="utf-8") as fh:
1436 - fh.write(script)
1437 - os.chmod(GRUB_SNAPSHOT_SCRIPT, 0o755)
1438 - return True
1439 - except OSError:
1440 - return False
1441 -
1442 -
1443 -def _create_system_snapshot(packages: List[str], action: str,
1444 - label: str = "") -> Optional[dict]:
1445 - """Tworzy snapshot root (btrfs) i zapisuje go w bazie.
1446 -
1447 - Zwraca dict snapshotu albo None. Nie przerywa instalacji – o tym decyduje
1448 - wywołujący (tryb --snapshot wymaga sukcesu, tryb auto tylko ostrzega).
1449 - """
1450 - ok, why = _snapshot_support()
1451 - if not ok:
1452 - return None
1453 - btrfs = _btrfs_bin()
1454 - try:
1455 - os.makedirs(SNAPSHOTS_DIR, exist_ok=True)
1456 - except OSError as e:
1457 - print(f" ⚠ Nie mogę utworzyć {SNAPSHOTS_DIR}: {e}", file=sys.stderr)
1458 - return None
1459 -
1460 - base_id = datetime.now().strftime("%Y%m%dT%H%M%S")
1461 - snap_id = base_id
1462 - n = 1
1463 - while os.path.lexists(os.path.join(SNAPSHOTS_DIR, snap_id)):
1464 - snap_id = f"{base_id}-{n}"
1465 - n += 1
1466 - snap_path = os.path.join(SNAPSHOTS_DIR, snap_id)
1467 -
1468 - try:
1469 - r = subprocess.run([btrfs, "subvolume", "snapshot", "/", snap_path],
1470 - capture_output=True, text=True, timeout=600)
1471 - except Exception as e:
1472 - print(f" ⚠ Nie udało się utworzyć snapshotu: {e}", file=sys.stderr)
1473 - return None
1474 - if r.returncode != 0:
1475 - msg = (r.stderr or r.stdout or "").strip().splitlines()
1476 - print(f" ⚠ btrfs snapshot nie udał się: {msg[-1] if msg else r.returncode}",
1477 - file=sys.stderr)
1478 - return None
1479 -
1480 - rootp = _btrfs_root_path()
1481 - if rootp in ("", "/"):
1482 - subvol = f"/.pag_snapshots/{snap_id}"
1483 - else:
1484 - subvol = f"{rootp}/.pag_snapshots/{snap_id}"
1485 -
1486 - # Zapamiętaj jądro/initramfs z chwili snapshotu – przy osobnym /boot
1487 - # dzięki temu uruchomimy migawkę ze STARYM (działającym) jądrem.
1488 - _kn, _ir = _pick_kernel_initrd("/boot")
1489 - snap = {
1490 - "id": snap_id,
1491 - "path": snap_path,
1492 - "subvol": subvol,
1493 - "created": datetime.now().isoformat(),
1494 - "action": action,
1495 - "label": label,
1496 - "packages": list(packages)[:100],
1497 - "kernel": _kn,
1498 - "initrd": _ir,
1499 - }
1500 - items = _load_snapshots()
1501 - items.append(snap)
1502 - _save_snapshots(items)
1503 - _ensure_snapshot_grub_script()
1504 - print(f" 📸 Snapshot systemu: {snap_id} (subvol={subvol})")
1505 - return snap
1506 -
1507 -
1508 -def _find_snapshot(snap_id: str) -> Optional[dict]:
1509 - items = _load_snapshots()
1510 - if not snap_id:
1511 - return items[-1] if items else None
1512 - for s in items:
1513 - if s.get("id") == snap_id:
1514 - return s
1515 - for s in items:
1516 - if str(s.get("id", "")).startswith(snap_id):
1517 - return s
1518 - return None
1519 -
1520 -
1521 -def cmd_snapshot_list():
1522 - items = _load_snapshots()
1523 - if not items:
1524 - print(_("snapshot_none"))
1525 - return 0
1526 - print(_("snapshot_list", len(items)))
1527 - for s in reversed(items):
1528 - pkgs = list(s.get("packages") or [])
1529 - listed = ", ".join(pkgs[:4])
1530 - if len(pkgs) > 4:
1531 - listed += f" +{len(pkgs) - 4}"
1532 - print(f" {s.get('id', '?')} [{s.get('action', '')}]")
1533 - if listed:
1534 - print(f" {listed}")
1535 - print(f" {s.get('created', '')}")
1536 - print(f" {s.get('path', '')}")
1537 - return 0
1538 -
1539 -
1540 -def cmd_snapshot_grub():
1541 - """Wypisuje menuentry dla grub-mkconfig (wywoływane z 40_pagan_snapshots)."""
1542 - for line in _grub_snapshot_entries():
1543 - print(line)
1544 - return 0
1545 -
1546 -
1547 -def cmd_snapshot_create(label: str = ""):
1548 - ok, why = _snapshot_support()
1549 - if not ok:
1550 - print(f" ❌ {_('snapshot_unsupported', why)}")
1551 - return 1
1552 - snap = _create_system_snapshot([], "manual", label=label)
1553 - if not snap:
1554 - return 1
1555 - _ensure_snapshot_grub_script()
1556 - _refresh_bootloader()
1557 - print(f" ✅ {_('snapshot_created', snap['id'])}")
1558 - return 0
1559 -
1560 -
1561 -def cmd_snapshot_delete(snap_id: str):
1562 - snap = _find_snapshot(snap_id)
1563 - if not snap:
1564 - print(f" ❌ {_('snapshot_not_found', snap_id)}")
1565 - return 1
1566 - path = snap.get("path") or ""
1567 - if not path.startswith(SNAPSHOTS_DIR + "/"):
1568 - print(" ❌ Nieprawidłowa ścieżka snapshotu – odmawiam usunięcia.")
1569 - return 1
1570 - if os.path.isdir(path):
1571 - btrfs = _btrfs_bin()
1572 - if not btrfs:
1573 - print(f" ❌ {_('snapshot_unsupported', 'brak btrfs')}")
1574 - return 1
1575 - r = subprocess.run([btrfs, "subvolume", "delete", path],
1576 - capture_output=True, text=True, timeout=120)
1577 - if r.returncode != 0:
1578 - print(f" ❌ btrfs: {(r.stderr or '').strip()[:200]}")
1579 - return 1
1580 - _save_snapshots([s for s in _load_snapshots() if s.get("id") != snap.get("id")])
1581 - _refresh_bootloader()
1582 - print(f" ✅ {_('snapshot_deleted', snap.get('id', ''))}")
1583 - return 0
1584 -
1585 -
1586 -def cmd_snapshot_rollback(snap_id: str = ""):
1587 - """Ustawia snapshot jako następny start (albo pokazuje wybór w GRUB)."""
1588 - snap = _find_snapshot(snap_id)
1589 - if not snap:
1590 - print(f" ❌ {_('snapshot_not_found', snap_id or '(brak)' )}")
1591 - return 1
1592 - if not os.path.isdir(snap.get("path") or ""):
1593 - print(f" ❌ {_('snapshot_not_found', snap.get('id', ''))}")
1594 - return 1
1595 -
1596 - label = _snapshot_label(snap)
1597 - print(f" ⏪ Snapshot: {snap.get('id', '')}")
1598 - print(f" {snap.get('created', '')}")
1599 - pkgs = list(snap.get("packages") or [])
1600 - if pkgs:
1601 - print(f" {', '.join(pkgs[:8])}{' …' if len(pkgs) > 8 else ''}")
1602 - if not _ask_confirm():
1603 - return 0
1604 -
1605 - _ensure_snapshot_grub_script()
1606 - _refresh_bootloader()
1607 -
1608 - grub_reboot = shutil.which("grub-reboot") or shutil.which("grub2-reboot")
1609 - if grub_reboot:
1610 - r = subprocess.run([grub_reboot, label], capture_output=True, text=True)
1611 - if r.returncode == 0:
1612 - print(f" ✅ {_('snapshot_rollback_next', label)}")
1613 - print(" 💡 Zrestartuj system – GRUB uruchomi wybrany snapshot.")
1614 - return 0
1615 - print(f" ℹ {_('snapshot_rollback_hint', label)}")
1616 - print(" 💡 Przy starcie wybierz wpis w menu GRUB (sekcja snapshotów).")
1617 - return 0
1618 -
1619 -
1620 -DEFAULT_REPOS = [
1621 - "https://repo.paganlinux.eu/stable/",
1622 -]
1623 -
1624 -# =============================================================================
1625 -# INICJALIZACJA
1626 -# =============================================================================
1627 -
1628 -def ensure_dirs():
1629 - for d in [PAG_DB, PAG_CACHE, PAG_CONF, REPO_CACHE, REPOS_DIR, STAGING_DIR, DEPLOYMENTS_DIR]:
1630 - os.makedirs(d, exist_ok=True)
1631 - for f, default in [
1632 - (REPOS_CONF, "\n".join(DEFAULT_REPOS) + "\n"),
1633 - (INSTALLED_DB, "{}"),
1634 - (PINNED_FILE, "{}"),
1635 - (HISTORY_FILE, "[]"),
1636 - ]:
1637 - if not os.path.exists(f):
1638 - with open(f, "w") as fh: fh.write(default)
1639 - if not os.path.exists(WORLD_FILE):
1640 - Path(WORLD_FILE).touch()
1641 - if not os.path.exists(GPG_HOME):
1642 - os.makedirs(GPG_HOME, exist_ok=True)
1643 - os.chmod(GPG_HOME, 0o700)
1644 - _gpg_run("--list-keys", capture_output=True)
1645 - # Inicjalizuj SQLite
1646 - _db_init()
1647 - # Wyczyść staging po poprzednim przerwanym buildzie/instalacji
1648 - if os.path.isdir(STAGING_DIR):
1649 - for entry in os.listdir(STAGING_DIR):
1650 - if entry == "backups":
1651 - continue # backupy starych wersji – potrzebne do `pag rollback`
1652 - path = os.path.join(STAGING_DIR, entry)
1653 - try:
1654 - if os.path.isfile(path) or os.path.islink(path):
1655 - os.unlink(path)
1656 - elif os.path.isdir(path):
1657 - shutil.rmtree(path, ignore_errors=True)
1658 - except OSError:
1659 - pass
1660 -
1661 -# =============================================================================
1662 -# SQLITE – BAZA PLIKÓW (poprawne zarządzanie połączeniami)
1663 -# =============================================================================
1664 -
1665 -from contextlib import contextmanager
1666 -
1667 -@contextmanager
1668 -def _db_session(readonly: Optional[bool] = None):
1669 - """Context manager – gwarantuje zamknięcie połączenia.
1670 -
1671 - Gdy katalog bazy nie jest zapisywalny (np. komenda read-only uruchomiona
1672 - jako zwykły user), otwieramy połączenie w trybie read-only. Inaczej
1673 - `PRAGMA journal_mode=WAL` próbuje pisać i kończy się błędem
1674 - „attempt to write a readonly database” zamiast zwrócić wynik.
1675 - """
1676 - if readonly is None:
1677 - readonly = not os.access(os.path.dirname(FILES_DB_SQL) or ".", os.W_OK)
1678 - if readonly:
1679 - # Katalog bazy nie jest zapisywalny (np. komenda read-only uruchomiona
1680 - # jako zwykły user). Baza jest w trybie WAL, więc SQLite przy `mode=ro`
1681 - # próbuje utworzyć plik `-shm` w katalogu – bez prawa zapisu kończy się
1682 - # to błędem „attempt to write a readonly database” nawet przy SELECT.
1683 - # Dlatego próbujemy zwykłego `mode=ro`, a gdy zawiedzie, otwieramy z
1684 - # `immutable=1` (SQLite pomija wtedy WAL/SHM i czyta ostatni
1685 - # checkpoint). Przy równoległym zapisie roota odczyt może być chwilowo
1686 - # nieaktualny – dla komend diagnostycznych (files/list/verify) to OK.
1687 - conn = sqlite3.connect(f"file:{FILES_DB_SQL}?mode=ro", uri=True, timeout=15)
1688 - try:
1689 - conn.execute("SELECT 1 FROM sqlite_master LIMIT 1")
1690 - except sqlite3.OperationalError:
1691 - conn.close()
1692 - conn = sqlite3.connect(
1693 - f"file:{FILES_DB_SQL}?mode=ro&immutable=1", uri=True, timeout=15)
1694 - else:
1695 - conn = sqlite3.connect(FILES_DB_SQL, timeout=15)
1696 - conn.execute("PRAGMA journal_mode=WAL")
1697 - conn.execute("PRAGMA synchronous=NORMAL")
1698 - conn.execute("PRAGMA foreign_keys=ON")
1699 - conn.execute("PRAGMA busy_timeout=15000")
1700 - conn.row_factory = sqlite3.Row
1701 - try:
1702 - yield conn
1703 - if not readonly:
1704 - conn.commit()
1705 - except Exception:
1706 - if not readonly:
1707 - conn.rollback()
1708 - raise
1709 - finally:
1710 - conn.close()
1711 -
1712 -
1713 -def _db_init():
1714 - """Tworzy tabele SQLite jeśli nie istnieją."""
1715 - with _db_session() as db:
1716 - db.execute("""
1717 - CREATE TABLE IF NOT EXISTS files (
1718 - id INTEGER PRIMARY KEY AUTOINCREMENT,
1719 - path TEXT NOT NULL,
1720 - package TEXT NOT NULL,
1721 - sha256 TEXT,
1722 - size INTEGER,
1723 - is_symlink INTEGER DEFAULT 0,
1724 - symlink_target TEXT,
1725 - UNIQUE(path, package)
1726 - )
1727 - """)
1728 - db.execute("CREATE INDEX IF NOT EXISTS idx_files_path ON files(path)")
1729 - db.execute("CREATE INDEX IF NOT EXISTS idx_files_pkg ON files(package)")
1730 - db.execute("""
1731 - CREATE TABLE IF NOT EXISTS file_checksums (
1732 - path TEXT PRIMARY KEY,
1733 - sha256 TEXT NOT NULL,
1734 - installed_at TEXT
1735 - )
1736 - """)
1737 - db.commit()
1738 -
1739 -def _db_record_files(pkg_name: str, files: List[dict]):
1740 - """Zapisuje pliki do SQLite (obsługuje symlinki)."""
1741 - with _db_session() as db:
1742 - # Jawna transakcja – atomowość obu zapisów i szybsze wykrycie blokady
1743 - try:
1744 - db.execute("BEGIN IMMEDIATE")
1745 - except sqlite3.OperationalError:
1746 - pass # transakcja już otwarta (implicit)
1747 - db.executemany(
1748 - "INSERT OR REPLACE INTO files (path, package, sha256, size, is_symlink, symlink_target) "
1749 - "VALUES (?,?,?,?,?,?)",
1750 - [(f["path"], pkg_name, f.get("sha256",""), f.get("size",0),
1751 - f.get("is_symlink", 0), f.get("symlink_target", ""))
1752 - for f in files]
1753 - )
1754 - db.executemany(
1755 - "INSERT OR REPLACE INTO file_checksums (path, sha256, installed_at) VALUES (?,?,?)",
1756 - [(f["path"], f.get("sha256",""), datetime.now().isoformat())
1757 - for f in files if f.get("sha256")]
1758 - )
1759 -
1760 -def _db_get_package_files(pkg_name: str) -> List[str]:
1761 - with _db_session() as db:
1762 - return [r["path"] for r in db.execute(
1763 - "SELECT DISTINCT path FROM files WHERE package=?", (pkg_name,)
1764 - )]
1765 -
1766 -def _db_get_file_owners(filepath: str) -> List[str]:
1767 - """Zwraca listę pakietów będących właścicielami pliku."""
1768 - with _db_session() as db:
1769 - return [r["package"] for r in db.execute(
1770 - "SELECT package FROM files WHERE path=?", (filepath,)
1771 - )]
1772 -
1773 -def _db_remove_package_files(pkg_name: str):
1774 - with _db_session() as db:
1775 - db.execute("DELETE FROM files WHERE package=?", (pkg_name,))
1776 - db.commit()
1777 -
1778 -def _db_get_all_file_checksums() -> Dict[str, str]:
1779 - with _db_session() as db:
1780 - return {r["path"]: r["sha256"] for r in db.execute("SELECT path, sha256 FROM file_checksums")}
1781 -
1782 -def _db_get_package_checksums(pkg_name: str) -> Dict[str, str]:
1783 - """Sumy SHA256 zapisane dla plików należących do pakietu.
1784 -
1785 - Używane do wykrycia, czy użytkownik zmodyfikował plik konfiguracyjny
1786 - (porównanie z sumą z chwili instalacji) – serce mechanizmu .pacnew/.pacsave.
1787 - """
1788 - with _db_session() as db:
1789 - return {r["path"]: r["sha256"] for r in db.execute(
1790 - "SELECT fc.path AS path, fc.sha256 AS sha256 FROM file_checksums fc "
1791 - "JOIN files f ON f.path = fc.path WHERE f.package=?", (pkg_name,))}
1792 -
1793 -
1794 -def _db_count_files() -> int:
1795 - with _db_session() as db:
1796 - return db.execute("SELECT COUNT(*) FROM files").fetchone()[0]
1797 -
1798 -# =============================================================================
1799 -# BLOKADA
1800 -# =============================================================================
1801 -
1802 -class DatabaseLock:
1803 - """Blokada plikowa (flock) – jądro zwalnia ją AUTOMATYCZNIE, gdy proces
1804 - ginie (kill -9, twardy reset). Stary PID-file miał race condition: po
1805 - śmierci pag PID mógł zostać przydzielony obcemu procesowi (PID reuse)
1806 - i pag odmawiał działania na zawsze („baza zablokowana”).
1807 - """
1808 - def __init__(self):
1809 - self._f = None
1810 - def __enter__(self):
1811 - os.makedirs(os.path.dirname(LOCK_FILE), exist_ok=True)
1812 - self._f = open(LOCK_FILE, "w")
1813 - try:
1814 - # LOCK_NB: rzuca wyjątek zamiast czekać w nieskończoność
1815 - fcntl.flock(self._f, fcntl.LOCK_EX | fcntl.LOCK_NB)
1816 - except BlockingIOError:
1817 - print(f"❌ {_('db_locked')}", file=sys.stderr)
1818 - print(f" {_('db_lock_hint', LOCK_FILE)}", file=sys.stderr)
1819 - sys.exit(1)
1820 - self._f.write(str(os.getpid()))
1821 - self._f.flush()
1822 - return self
1823 - def __exit__(self, *args):
1824 - if self._f:
1825 - try:
1826 - fcntl.flock(self._f, fcntl.LOCK_UN)
1827 - except OSError:
1828 - pass
1829 - self._f.close()
1830 - self._f = None
1831 - # Uwaga: NIE usuwamy pliku blokady. Stały plik + flock na inode to jedyny
1832 - # bezpieczny wzorzec – os.remove(), gdy inny proces trzyma blokadę na starym
1833 - # inode, otwiera wyścig (nowy proces blokowałby nowo utworzony inode).
1834 -
1835 -
1836 -class SelfUpdateLock:
1837 - """Blokada podmiany binarki pag podczas self-update.
1838 -
1839 - Niezależna od DatabaseLock (inny plik) – cmd_self_update może zostać
1840 - wywołane poza globalną blokadą (np. z zewnętrznego skryptu), a dwie
1841 - równoległe aktualizacje pisałyby do tego samego `dst.new`; `os.replace`
1842 - mógłby wtedy podmienić plik w trakcie wykonywania (uszkodzony pag).
1843 - """
1844 - def __init__(self):
1845 - self._f = None
1846 -
1847 - def __enter__(self):
1848 - lock_path = LOCK_FILE + ".self-update"
1849 - os.makedirs(os.path.dirname(lock_path), exist_ok=True)
1850 - self._f = open(lock_path, "w")
1851 - try:
1852 - fcntl.flock(self._f, fcntl.LOCK_EX | fcntl.LOCK_NB)
1853 - except BlockingIOError:
1854 - self._f.close()
1855 - self._f = None
1856 - print("❌ Inna aktualizacja pag jest w toku – spróbuj ponownie później.",
1857 - file=sys.stderr)
1858 - sys.exit(1)
1859 - self._f.write(str(os.getpid()))
1860 - self._f.flush()
1861 - return self
1862 -
1863 - def __exit__(self, *args):
1864 - if self._f:
1865 - try:
1866 - fcntl.flock(self._f, fcntl.LOCK_UN)
1867 - except OSError:
1868 - pass
1869 - self._f.close()
1870 - self._f = None
1871 -
1872 -# =============================================================================
1873 -# POMOCNICZE
1874 -# =============================================================================
1875 -
1876 -
1877 -_ALLOWED_PREFIXES = ("/usr/", "/etc/", "/var/", "/opt/",
1878 - "/boot/", "/lib/", "/run/", # kernel: vmlinuz/System.map + moduły (usrmerge: lib→usr/lib)
1879 - # Pliki wewnętrzne paczki .pkg.tar.xz
1880 - "metadata.json", "data.tar.xz", "hooks/",
1881 - "sums.json")
1882 -
1883 -def _check_path_safety(name: str) -> bool:
1884 - # Normalizuj – usuń leading ./
1885 - if name.startswith("./"):
1886 - name = name[2:]
1887 - if name in (".", ""):
1888 - return True
1889 - # Porównuj z prefiksami BEZ wiodącego '/', by zarówno "/usr/bin/ls", jak i
1890 - # wewnętrzne pliki pakietu ("hooks/pre-install", "data.tar.xz") przechodziły.
1891 - norm = name.lstrip("/")
1892 - for prefix in _ALLOWED_PREFIXES:
1893 - p = prefix.lstrip("/").rstrip("/")
1894 - if norm == p or norm.startswith(p + "/"):
1895 - return True
1896 - return False
1897 -
1898 -
1899 -def _validate_pkg_name(name):
1900 - return bool(ALLOWED_PKG_RE.match(name))
1901 -
1902 -
1903 -
1904 -def _audit(msg):
1905 - from datetime import datetime, timezone
1906 - os.makedirs(os.path.dirname(AUDIT_LOG), exist_ok=True)
1907 - with open(AUDIT_LOG, "a") as f:
1908 - f.write(datetime.now(timezone.utc).isoformat() + " " + msg + "\n")
1909 -
1910 -def _strip_suid(path):
1911 - try:
1912 - st = os.stat(path)
1913 - if st.st_mode & 0o4000:
1914 - os.chmod(path, st.st_mode & ~0o4000)
1915 - print(f" {_("sec_suid", path=path)}")
1916 - except OSError:
1917 - pass
1918 -
1919 -def _check_downgrade(pkg_name, new_ver, installed_db):
1920 - if pkg_name in installed_db:
1921 - old = installed_db[pkg_name].get("version", "0")
1922 - if new_ver < old:
1923 - print(f" {_("sec_downgrade", pkg=pkg_name, new=new_ver, old=old)}")
1924 - return False
1925 - return True
1926 -
1927 -def _safe_extractall(tar: tarfile.TarFile, dest: str, *, preserve_perms: bool = True,
1928 - privileged=frozenset()):
1929 - """
1930 - Bezpieczne rozpakowanie archiwum tar z ochroną przed Directory Traversal.
1931 -
1932 - Działa na Python < 3.12 (gdzie parametr 'filter' w extractall nie istnieje)
1933 - oraz na Python 3.12+. W przeciwieństwie do filtra 'data' z Pythona 3.12,
1934 - zachowuje bity uprawnień POSIX (SUID, SGID, sticky) – preserve_perms=True.
1935 -
1936 - Ochrona oparta jest na FINALNEJ ścieżce (os.path.realpath), nie tylko na
1937 - prostym sprawdzaniu stringa:
1938 - - Blokuje ścieżki absolutne i z '..' (path traversal)
1939 - - Blokuje symlinki/hardlinki, których cel wychodzi poza dest
1940 - - Blokuje zapis "przez" złośliwy symlink, który został wcześniej
1941 - rozpakowany (np. katalog → /etc, potem zapis katalog/plik)
1942 - - Zachowuje oryginalne uprawnienia plików
1943 - """
1944 - dest_real = os.path.realpath(dest)
1945 - os.makedirs(dest_real, exist_ok=True)
1946 -
1947 - def _target_within(path: str) -> bool:
1948 - try:
1949 - return os.path.commonpath([dest_real, os.path.realpath(path)]) == dest_real
1950 - except ValueError:
1951 - # różne napędy / ścieżki nie da się wspólnie porównać → odrzuć
1952 - return False
1953 -
1954 - for member in tar.getmembers():
1955 - name = member.name
1956 -
1957 - # --- Ochrona przed Directory Traversal (szybkie string-checki) ---
1958 - if name.startswith('/'):
1959 - continue
1960 - if '..' in name.split('/'):
1961 - continue
1962 - # Zablokuj bajt NUL i backslash (bugi/obejścia tarfile na niektórych platformach)
1963 - if '\x00' in name or '\\' in name:
1964 - continue
1965 - if not _check_path_safety(name):
1966 - print(f" BLOCKED: {name}")
1967 - continue
1968 -
1969 - target = os.path.join(dest, name)
1970 -
1971 - # --- Ochrona na podstawie finalnej ścieżki ---
1972 - # Jeśli którykolwiek komponent nadrzędny jest (złośliwym) symlinkiem
1973 - # wskazującym poza dest, realpath to wykryje – zablokuj zapis.
1974 - if not _target_within(target):
1975 - print(f" BLOCKED (escape): {name}")
1976 - continue
1977 -
1978 - # --- Ochrona dla symlinków i hardlinków ---
1979 - if member.issym() or member.islnk():
1980 - link = member.linkname
1981 - # Szybkie odrzucenie linków absolutnych / z '..'
1982 - if link.startswith('/') or '..' in link.split('/'):
1983 - continue
1984 - # Sprawdź, gdzie realnie prowadzi cel linku (względem katalogu linku)
1985 - link_target = os.path.join(os.path.dirname(target), link)
1986 - if not _target_within(link_target):
1987 - print(f" BLOCKED (link escape): {name} -> {link}")
1988 - continue
1989 -
1990 - # Rozpakuj z zachowaniem metadanych. Python 3.12+ wymaga jawnego
1991 - # `filter=` (inaczej DeprecationWarning, a w 3.14+ błąd).
1992 - # UWAGA: 'fully_trusted' CELOWO pomija wbudowane filtry bezpieczeństwa
1993 - # Pythona – to nie przeoczenie. Nasza walidacja powyżej (path traversal,
1994 - # NUL/backslash, escape przez symlink, linki wychodzące poza dest) jest
1995 - # równoważna lub ostrzejsza, a 'fully_trusted' pozwala zachować bity
1996 - # SUID/SGID/sticky, które filtr 'data' by usunął (np. /usr/bin/sudo).
1997 - # SUID jest i tak zdejmowany przez _strip_suid() tuż po rozpakowaniu.
1998 - try:
1999 - if hasattr(tarfile, 'data_filter'):
2000 - # Python 3.12+
2001 - tar.extract(member, dest, set_attrs=preserve_perms, numeric_owner=False,
2002 - filter='fully_trusted')
2003 - else:
2004 - tar.extract(member, dest, set_attrs=preserve_perms, numeric_owner=False)
2005 - except Exception as e:
2006 - print(f" ⚠ Nie rozpakowano {name}: {e}")
2007 - continue
2008 - # Pliki z listy uprzywilejowanej zachowują SUID/SGID; reszta jest
2009 - # czyszczona (ochrona przed SUID niespodziewanym w pakiecie).
2010 - if "/" + os.path.relpath(target, dest_real) not in privileged:
2011 - _strip_suid(target)
2012 -
2013 -
2014 -def _sha256_file(path: str) -> str:
2015 - """SHA256 pliku. Na Python ≥3.11 używa hashlib.file_digest (pętla w C);
2016 - starsze wersje mają fallback z pętlą chunków."""
2017 - with open(path, "rb") as f:
2018 - if hasattr(hashlib, "file_digest"):
2019 - return hashlib.file_digest(f, "sha256").hexdigest()
2020 - h = hashlib.sha256()
2021 - for chunk in iter(lambda: f.read(65536), b""):
2022 - h.update(chunk)
2023 - return h.hexdigest()
2024 -
2025 -def _split_version(v: str):
2026 - """Rozdziela wersję na (release_parts, prerelease_parts).
2027 -
2028 - Przykład: '1.2.0-rc1' → ([1,2,0], ['rc','1']).
2029 - """
2030 - v = v.strip().lower().lstrip("v")
2031 - # build metadata po '+' jest ignorowane przy porównywaniu (semver)
2032 - v = v.split("+", 1)[0]
2033 - # prerelease po '-' lub '_' (np. 1.2.0-rc1, 1.2.0_rc1)
2034 - if "-" in v:
2035 - rel, pre = v.split("-", 1)
2036 - elif "_" in v:
2037 - rel, pre = v.split("_", 1)
2038 - else:
2039 - rel, pre = v, ""
2040 - nums = []
2041 - for part in rel.split("."):
2042 - m = re.match(r"(\d+)", part)
2043 - nums.append(int(m.group(1)) if m else 0)
2044 - pre_parts = [p for p in pre.split(".") if p]
2045 - return nums, pre_parts
2046 -
2047 -
2048 -def _cmp_pre(a, b):
2049 - """Porównuje ciągi identyfikatorów prerelease (reguły semver)."""
2050 - for i in range(max(len(a), len(b))):
2051 - if i >= len(a):
2052 - return -1 # krótszy prerelease jest niższy
2053 - if i >= len(b):
2054 - return 1
2055 - ia, ib = a[i], b[i]
2056 - if ia == ib:
2057 - continue
2058 - na, nb = ia.isdigit(), ib.isdigit()
2059 - if na and nb:
2060 - return 1 if int(ia) > int(ib) else -1
2061 - if na != nb:
2062 - return -1 if na else 1 # identyfikator liczbowy < alfanumeryczny
2063 - return 1 if ia > ib else -1
2064 - return 0
2065 -
2066 -
2067 -def _cmp_version(a: str, b: str) -> int:
2068 - """Porównuje dwie wersje; zwraca -1/0/1. Obsługuje prerelease (rc1, beta...)."""
2069 - a_rel, a_pre = _split_version(a)
2070 - b_rel, b_pre = _split_version(b)
2071 - # Porównaj część release (brakujące komponenty traktuj jako 0)
2072 - for i in range(max(len(a_rel), len(b_rel))):
2073 - xa = a_rel[i] if i < len(a_rel) else 0
2074 - xb = b_rel[i] if i < len(b_rel) else 0
2075 - if xa != xb:
2076 - return 1 if xa > xb else -1
2077 - # Część release równa → decyduje prerelease.
2078 - # Wersja finalna (bez prerelease) jest ZAWSZE nowsza od prerelease.
2079 - if not a_pre and not b_pre:
2080 - return 0
2081 - if not a_pre:
2082 - return 1
2083 - if not b_pre:
2084 - return -1
2085 - return _cmp_pre(a_pre, b_pre)
2086 -
2087 -
2088 -def _version_newer(a: str, b: str) -> bool:
2089 - """True gdy wersja a jest nowsza od b (z poprawną obsługą prerelease)."""
2090 - try:
2091 - return _cmp_version(a, b) > 0
2092 - except Exception:
2093 - return a != b
2094 -
2095 -def load_json(path):
2096 - try:
2097 - with open(path) as f:
2098 - return json.load(f)
2099 - except (FileNotFoundError, json.JSONDecodeError):
2100 - return {}
2101 -
2102 -def save_json(path, data):
2103 - with open(path, "w") as f:
2104 - json.dump(data, f, indent=2)
2105 -
2106 -class PackageInfo:
2107 - __slots__ = ("name","version","release","description","dependencies",
2108 - "optdepends","size_bytes","sha256","gpg_fp","repo_url","filename",
2109 - "provides","license","provides_so","requires_so","privileged")
2110 - def __init__(self, d, repo=""):
2111 - self.name = d.get("name","?")
2112 - self.version = d.get("version","0")
2113 - self.release = d.get("release", 1)
2114 - self.description = d.get("description","")
2115 - self.dependencies = d.get("dependencies", d.get("depends", []))
2116 - # Opcjonalne zależności (flatpak, btrfs-progs, grub, ...) – tylko
2117 - # informacyjne; `pag install` NIE instaluje ich automatycznie.
2118 - self.optdepends = d.get("optdepends", []) or []
2119 - self.size_bytes = d.get("size",0)
2120 - self.sha256 = d.get("sha256","")
2121 - self.gpg_fp = d.get("gpg_fingerprint","")
2122 - self.repo_url = repo
2123 - self.filename = d.get("filename", f"{self.name}-{self.version}{PKG_EXT}")
2124 - self.provides = d.get("provides", []) or []
2125 - self.license = d.get("license", []) or []
2126 - self.provides_so = d.get("provides_so", []) or []
2127 - self.requires_so = d.get("requires_so", []) or []
2128 - # Ścieżki, którym wolno zachować setuid/setgid i grupę (z receptury).
2129 - self.privileged = d.get("privileged", []) or []
2130 -
2131 -# =============================================================================
2132 -# REPOZYTORIA (cache, ETag, GPG)
2133 -# =============================================================================
2134 -
2135 -def _parse_repos_config():
2136 - """Parsuje repozytoria z /etc/pag/repos.conf oraz /etc/pag/repos/*.conf.
2137 -
2138 - Format linii: <url> [fingerprint]
2139 - Opcjonalny `fingerprint` (40 znaków hex) pozwala przypiąć klucz
2140 - podpisujący repo do konkretnego adresu – wtedy TOFU (auto-zaufanie przy
2141 - pierwszym użyciu) nie jest potrzebne, a zmiana klucza = błąd bezpieczeństwa.
2142 -
2143 - Drop-iny (np. stable.conf) są czytane alfabetycznie – pozwalają na
2144 - wygodne dodawanie repo bez dotykania głównego repos.conf
2145 - (np. `echo 'https://repo.paganlinux.eu/stable' > /etc/pag/repos/stable.conf`).
2146 - """
2147 - entries = []
2148 -
2149 - def _read_lines(path):
2150 - if not os.path.exists(path):
2151 - return
2152 - for line in open(path):
2153 - line = line.strip()
2154 - if not line or line.startswith("#"):
2155 - continue
2156 - parts = line.split()
2157 - url = parts[0].rstrip("/")
2158 - fp = parts[1].lower() if len(parts) > 1 else ""
2159 - entries.append({"url": url, "fingerprint": fp or None})
2160 -
2161 - # 1) Legacy: pojedynczy plik /etc/pag/repos.conf
2162 - _read_lines(REPOS_CONF)
2163 - # 2) Drop-in: /etc/pag/repos/<nazwa>.conf (sortowane, stabilna kolejność)
2164 - if os.path.isdir(REPOS_DIR):
2165 - for drop in sorted(os.listdir(REPOS_DIR)):
2166 - if drop.endswith(".conf"):
2167 - _read_lines(os.path.join(REPOS_DIR, drop))
2168 -
2169 - # Dedupe po URL (zachowaj pierwszy wpis – może mieć fingerprint)
2170 - seen, unique = set(), []
2171 - for e in entries:
2172 - if e["url"] not in seen:
2173 - seen.add(e["url"])
2174 - unique.append(e)
2175 -
2176 - if not unique:
2177 - for url in DEFAULT_REPOS:
2178 - # rstrip: get_repos()/_repo_pinned_fp() kluczują URL-e bez ukośnika
2179 - unique.append({"url": url.rstrip("/"), "fingerprint": None})
2180 - return unique
2181 -
2182 -
2183 -def get_repos():
2184 - return [e["url"] for e in _parse_repos_config()]
2185 -
2186 -
2187 -def _repo_pinned_fp(repo_url):
2188 - """Zwraca przypięty fingerprint klucza dla repo (z konfiguracji lub trust DB)."""
2189 - # Normalizacja ukośnika: _parse_repos_config() i trust DB kluczują URL-e BEZ
2190 - # końcowego „/”, a wywołujący podają często DEFAULT_REPOS[0] Z ukośnikiem.
2191 - # Bez tego przypięty klucz nie był znajdowany i lokalny .pag dostawał
2192 - # fałszywe „Brak przypiętego klucza repo” mimo poprawnego wpisu w trusted.json.
2193 - repo_url = repo_url.rstrip("/")
2194 - by_url = {e["url"]: e["fingerprint"] for e in _parse_repos_config()}
2195 - if by_url.get(repo_url):
2196 - return by_url[repo_url]
2197 - db = _load_trust_db()
2198 - fp = db.get(repo_url)
2199 - return fp.lower() if fp else None
2200 -
2201 -def _repo_cache_path(url):
2202 - return os.path.join(REPO_CACHE, url.replace("://","_").replace("/","_").replace(".","_") + ".json")
2203 -
2204 -def _repo_etag_path(url): return _repo_cache_path(url) + ".etag"
2205 -def _repo_ts_path(url): return _repo_cache_path(url) + ".ts"
2206 -
2207 -# Informacja (raz na uruchomienie), gdy cache repozytoriów jest tylko-do-odczytu –
2208 -# np. komendy read-only (`pag info`, `pag search`…) jako zwykły user: nie ma sensu
2209 -# ani prawa odświeżać /var/cache/pag/repos, więc używamy lokalnej kopii indeksu.
2210 -_cache_ro_notice_done = False
2211 -
2212 -def _cache_ro_notice():
2213 - global _cache_ro_notice_done
2214 - if _cache_ro_notice_done:
2215 - return
2216 - _cache_ro_notice_done = True
2217 - print(f" ⚠ {_('cache_ro', cache=REPO_CACHE)}", file=sys.stderr)
2218 -
2219 -def _load_repo_cache(cp: str) -> Optional[list]:
2220 - """Wczytuje cache indeksu repo; zwraca None gdy brak albo uszkodzony.
2221 -
2222 - Partial write (crash w trakcie zapisu) mógł zostawić obcięty JSON. Zamiast
2223 - zwracać pustą listę pakietów (użytkownik myśli, że repo jest puste)
2224 - sygnalizujemy None – wywołujący ponowi pobranie albo pokaże ostrzeżenie."""
2225 - if not os.path.exists(cp):
2226 - return None
2227 - try:
2228 - with open(cp, "r", encoding="utf-8") as fh:
2229 - data = json.load(fh)
2230 - pkgs = data.get("packages")
2231 - if not isinstance(pkgs, list):
2232 - raise ValueError("brak listy 'packages'")
2233 - return pkgs
2234 - except (OSError, ValueError) as e:
2235 - print(f" ⚠ Uszkodzony cache indeksu {cp}: {e}", file=sys.stderr)
2236 - return None
2237 -
2238 -
2239 -def fetch_repo_index(repo_url, force=False):
2240 - cp = _repo_cache_path(repo_url)
2241 - ep = _repo_etag_path(repo_url)
2242 - tp = _repo_ts_path(repo_url)
2243 -
2244 - if not force and os.path.exists(cp) and os.path.exists(tp):
2245 - try:
2246 - if time.time() - float(open(tp).read().strip()) < REPO_CACHE_TTL:
2247 - cached = _load_repo_cache(cp)
2248 - if cached is not None:
2249 - return cached
2250 - # uszkodzony cache – spróbuj odświeżyć z sieci
2251 - except (OSError, ValueError):
2252 - pass
2253 -
2254 - # --- Cache tylko-do-odczytu (np. `pag info` jako zwykły user) ---
2255 - # /var/cache/pag/repos należy do roota. Nie próbuj odświeżać ani pisać –
2256 - # zwykły user i tak nie zapisze indeksu; użyj lokalnej kopii (może być
2257 - # nieaktualna). Pełne odświeżenie indeksu: sudo pag sync
2258 - if not (os.path.isdir(REPO_CACHE) and os.access(REPO_CACHE, os.W_OK)):
2259 - if force:
2260 - print(f" ❌ {repo_url}: nie można odświeżyć indeksu – {REPO_CACHE} jest tylko-do-odczytu",
2261 - file=sys.stderr)
2262 - return None
2263 - _cache_ro_notice()
2264 - cached = _load_repo_cache(cp)
2265 - if cached is not None:
2266 - return cached
2267 - return None
2268 -
2269 - headers = {"User-Agent": "pag/3.0"}
2270 - if os.path.exists(tp) and not force:
2271 - try:
2272 - lm = datetime.fromtimestamp(float(open(tp).read().strip()), tz=timezone.utc)
2273 - # Wymuś lokalizację C/POSIX dla nagłówków HTTP, aby unikać problemów z nazwami dni/miesięcy
2274 - try:
2275 - old_locale = locale.setlocale(locale.LC_TIME)
2276 - locale.setlocale(locale.LC_TIME, 'C')
2277 - headers["If-Modified-Since"] = lm.strftime("%a, %d %b %Y %H:%M:%S GMT")
2278 - locale.setlocale(locale.LC_TIME, old_locale)
2279 - except (locale.Error, ValueError):
2280 - # Jeśli ustawienie lokalizacji się nie powiedzie, użyj domyślnej
2281 - headers["If-Modified-Since"] = lm.strftime("%a, %d %b %Y %H:%M:%S GMT")
2282 - except: pass
2283 - if os.path.exists(ep) and not force:
2284 - try: headers["If-None-Match"] = open(ep).read().strip()
2285 - except: pass
2286 -
2287 - # --- Pobranie indeksu (błędy SIECI nie są błędami zapisu cache) ---
2288 - try:
2289 - req = Request(f"{repo_url}/repo.json", headers=headers)
2290 - with urlopen(req, timeout=30) as resp:
2291 - etag = resp.headers.get("ETag","")
2292 - raw = resp.read()
2293 - data = json.loads(raw.decode())
2294 - except HTTPError as e:
2295 - if e.code == 304:
2296 - # Serwer: indeks bez zmian – odśwież tylko znacznik czasu (best-effort)
2297 - try:
2298 - open(tp,"w").write(str(time.time()))
2299 - except OSError:
2300 - pass
2301 - cached = _load_repo_cache(cp)
2302 - if cached is not None:
2303 - return cached
2304 - # uszkodzona kopia – potraktuj jak brak (ostrzeżenie niżej)
2305 - print(f" ⚠ HTTP {e.code} dla {repo_url}", file=sys.stderr)
2306 - return None
2307 - except Exception as e:
2308 - print(f" ⚠ Błąd pobierania indeksu {repo_url}: {e}", file=sys.stderr)
2309 - return _load_repo_cache(cp)
2310 -
2311 - # Indeks pobrany – zapisz SUROWE bajty (nie re-serializuj! podpis GPG jest
2312 - # nad oryginalnymi bajtami repo.json z serwera) i zweryfikuj podpis.
2313 - # Najpierw zapis tymczasowy + weryfikacja GPG, dopiero potem podmiana cp:
2314 - # błąd zapisu (np. pełny dysk) nie niszczy starej, zweryfikowanej kopii
2315 - # i NIGDY nie zwracamy danych, które nie przeszły weryfikacji.
2316 - tmp_path = cp + ".tmp"
2317 - try:
2318 - with open(tmp_path, "wb") as f:
2319 - f.write(raw)
2320 - if not _verify_repo_sig(repo_url, tmp_path):
2321 - return None # weryfikacja nie powiodła się – stary cache zostaje
2322 - os.replace(tmp_path, cp)
2323 - # przenieś podpis obok docelowego pliku (marker „repo ma podpis")
2324 - for _ext in (".asc", ".sig"):
2325 - if os.path.exists(tmp_path + _ext):
2326 - try:
2327 - os.replace(tmp_path + _ext, cp + _ext)
2328 - except OSError:
2329 - pass
2330 - break
2331 - if etag:
2332 - try:
2333 - open(ep,"w").write(etag)
2334 - except OSError:
2335 - pass
2336 - try:
2337 - open(tp,"w").write(str(time.time()))
2338 - except OSError:
2339 - pass
2340 - return data.get("packages",[])
2341 - except OSError as e:
2342 - print(f" ⚠ Indeks pobrany, ale nie udało się zapisać cache ({REPO_CACHE}): {e}",
2343 - file=sys.stderr)
2344 - # cp nie został podmieniony (podmiana jest po weryfikacji) – lokalna kopia
2345 - # to wciąż stare, zweryfikowane dane
2346 - return _load_repo_cache(cp)
2347 - finally:
2348 - for _p in (tmp_path, tmp_path + ".asc", tmp_path + ".sig"):
2349 - try:
2350 - os.unlink(_p)
2351 - except OSError:
2352 - pass
2353 -
2354 -def _verify_repo_sig(repo_url, cache_path) -> bool:
2355 - """Weryfikuje podpis GPG indeksu repozytorium i przypina fingerprint.
2356 -
2357 - FAIL-CLOSED: brak/nieprawidłowy podpis = False (chyba że PAG_INSECURE=1).
2358 - Zwraca True jeśli indeks jest zaufany, False jeśli należy go odrzucić.
2359 -
2360 - Model zaufania (TOFU + pinning):
2361 - - Pierwszy raz (brak przypiętego fingerprintu) → klucz jest importowany,
2362 - a fingerprint zapisywany w /etc/pag/trusted.json z JAWNYM ostrzeżeniem.
2363 - To świadomy kompromis wygody i bezpieczeństwa.
2364 - - Kolejne uruchomienia: fingerprint jest porównywany z przypiętym.
2365 - Zmiana klucza = ❌ SECURITY ERROR (fail-closed), wymagane ręczne:
2366 - pag key-trust <repo_url> (po weryfikacji nowego klucza)
2367 - """
2368 - insecure = os.environ.get("PAG_INSECURE", "") == "1"
2369 -
2370 - if not os.path.exists(GPG_HOME):
2371 - if insecure:
2372 - return True # brak GPG home – tryb insecure, akceptuj
2373 - print(f" ❌ {repo_url}: brak kluczy GPG – weryfikacja niemożliwa!")
2374 - print(f" Ustaw PAG_INSECURE=1 aby pominąć (niezalecane)")
2375 - os.remove(cache_path)
2376 - return False
2377 -
2378 - sig_path = cache_path + ".sig"
2379 - # Podpisy generowane jako .asc (armored) – próbuj .asc, potem .sig
2380 - sig_data = None
2381 - sig_ext = ""
2382 - for ext in (".asc", ".sig"):
2383 - try:
2384 - req = Request(f"{repo_url}/repo.json{ext}", headers={"User-Agent":"pag/3.0"})
2385 - with urlopen(req, timeout=15) as resp:
2386 - sig_data = resp.read()
2387 - sig_ext = ext
2388 - break
2389 - except Exception:
2390 - continue
2391 - if not sig_data:
2392 - if insecure:
2393 - return True # tryb insecure – akceptuj bez podpisu
2394 - print(f" ❌ {repo_url}: NIE MOŻNA POBRAĆ PODPISU repo.json.asc/.sig!")
2395 - print(f" Ustaw PAG_INSECURE=1 aby pominąć (niezalecane)")
2396 - os.remove(cache_path)
2397 - return False
2398 - sig_path = cache_path + sig_ext
2399 - with open(sig_path, "wb") as f:
2400 - f.write(sig_data)
2401 -
2402 - ok, fingerprint = _gpg_verify_fp(sig_path, cache_path)
2403 - if not ok:
2404 - # Automatyczny import klucza repo przy pierwszym uruchomieniu (TOFU,
2405 - # jak apt) – gdy w keyringu brakuje klucza (No public key).
2406 - res = _gpg_run("--verify", sig_path, cache_path,
2407 - capture_output=True, text=True, timeout=30)
2408 - _stderr = res.stderr.decode(errors="replace") if isinstance(res.stderr, bytes) else (res.stderr or "")
2409 - if "public key" in _stderr.lower() and "no public key" in _stderr.lower():
2410 - try:
2411 - with urlopen(Request(f"{repo_url}/paganos.asc", headers={"User-Agent": "pag/3.0"}), timeout=20) as r:
2412 - keydata = r.read()
2413 - with tempfile.NamedTemporaryFile(delete=False, suffix=".asc") as tmp:
2414 - tmp.write(keydata)
2415 - tmp.flush()
2416 - _gpg_run("--import", tmp.name, capture_output=True, timeout=30)
2417 - os.unlink(tmp.name)
2418 - print(f" 🔑 Importowano klucz repo z {repo_url}/paganos.asc")
2419 - ok, fingerprint = _gpg_verify_fp(sig_path, cache_path)
2420 - except Exception:
2421 - pass
2422 - if not ok:
2423 - if insecure:
2424 - print(f" ⚠ {repo_url}: nieprawidłowy podpis GPG (PAG_INSECURE – ignoruję)")
2425 - return True
2426 - os.remove(cache_path)
2427 - if not shutil.which(GPG_BINARY):
2428 - print(f" ❌ {repo_url}: GPG nie jest zainstalowane – nie można zweryfikować podpisu!")
2429 - print(f" Zainstaluj gnupg lub ustaw PAG_INSECURE=1 (niezalecane)")
2430 - else:
2431 - print(f" ❌ {repo_url}: NIEPRAWIDŁOWY PODPIS GPG indeksu repozytorium!")
2432 - return False
2433 -
2434 - # --- Wymuś przypięty fingerprint (TOFU + pinning) ---
2435 - pinned = _repo_pinned_fp(repo_url)
2436 - if pinned:
2437 - if not fingerprint:
2438 - if insecure:
2439 - print(f" ⚠ {repo_url}: nie można odczytać fingerprintu (PAG_INSECURE – ignoruję)")
2440 - return True
2441 - os.remove(cache_path)
2442 - print(f" ❌ [SECURITY ERROR] {repo_url}: nie można odczytać fingerprintu podpisu!")
2443 - print(f" Przypięty klucz: {pinned} – odrzucam indeks.")
2444 - return False
2445 - if fingerprint != pinned.upper():
2446 - if insecure:
2447 - print(f" ⚠ {repo_url}: ZMIENIONY KLUCZ PODPISU (PAG_INSECURE – ignoruję)")
2448 - return True
2449 - os.remove(cache_path)
2450 - print(f" ❌ [SECURITY ERROR] {repo_url}: Klucz podpisujący repo uległ zmianie!")
2451 - print(f" Oczekiwany: {pinned}")
2452 - print(f" Otrzymany: {fingerprint}")
2453 - print(f" Jeśli to celowa rotacja klucza: pag key-trust {repo_url}")
2454 - return False
2455 - return True
2456 -
2457 - if fingerprint:
2458 - # Brak przypiętego fingerprintu → TOFU: zapisz go w bazie zaufania.
2459 - db = _load_trust_db()
2460 - if db.get(repo_url) != fingerprint:
2461 - _save_trust_db({**db, repo_url: fingerprint})
2462 - print(f" 🔐 Przypięto fingerprint repo {repo_url}: {fingerprint}")
2463 - print(f" (TOFU – pierwsze zaufanie. Gdy klucz się zmieni, pag odmówi aktualizacji.)")
2464 - print(f" Aby uniknąć TOFU, dopisz fingerprint w /etc/pag/repos.conf.")
2465 - return True
2466 -
2467 -def fetch_all_packages(force=False):
2468 - all_pkgs = {}
2469 - for repo_url in get_repos():
2470 - pkgs = fetch_repo_index(repo_url, force)
2471 - if pkgs:
2472 - for pdata in pkgs:
2473 - name = pdata.get("name", pdata.get("filename","?").split("-")[0])
2474 - pkg = PackageInfo(pdata, repo_url)
2475 - if name not in all_pkgs or _version_newer(pkg.version, all_pkgs[name].version):
2476 - all_pkgs[name] = pkg
2477 - return all_pkgs
2478 -
2479 -# =============================================================================
2480 -# GPG
2481 -# =============================================================================
2482 -
2483 -def _verify_pkg_gpg(pkg_path, repo_url=None):
2484 - """Weryfikuje podpis GPG pakietu i (jeśli znamy repo) przypięty fingerprint.
2485 -
2486 - FAIL-CLOSED: brak podpisu = odrzucenie (chyba że PAG_INSECURE=1).
2487 - Zwraca (passed: bool, message: str).
2488 - """
2489 - insecure = os.environ.get("PAG_INSECURE", "") == "1"
2490 - # Brak gnupg = weryfikacja niemożliwa. Bez tej gałęzi użytkownik dostawał
2491 - # mylące „NIEPRAWIDŁOWY PODPIS GPG”, mimo że paczka i podpis są w porządku.
2492 - if not shutil.which(GPG_BINARY):
2493 - if insecure:
2494 - return True, "(gpg missing – PAG_INSECURE)"
2495 - return False, _("gpg_missing")
2496 - sig_path = pkg_path + ".sig"
2497 - if not os.path.exists(sig_path) and os.path.exists(pkg_path + ".asc"):
2498 - sig_path = pkg_path + ".asc"
2499 -
2500 - if not os.path.exists(sig_path):
2501 - if insecure:
2502 - return True, "(no signature – PAG_INSECURE)"
2503 - return False, "BRAK PODPISU – pakiet odrzucony (ustaw PAG_INSECURE=1 aby pominąć)"
2504 -
2505 - ok, fp = _gpg_verify_fp(sig_path, pkg_path)
2506 - if not ok:
2507 - if insecure:
2508 - return True, "(invalid signature – PAG_INSECURE)"
2509 - return False, "NIEPRAWIDŁOWY PODPIS GPG"
2510 -
2511 - # Opcjonalnie: sprawdź, czy podpis pochodzi od klucza przypiętego dla repo.
2512 - if repo_url:
2513 - pinned = _repo_pinned_fp(repo_url)
2514 - if pinned and fp and fp != pinned.upper():
2515 - if insecure:
2516 - return True, "(pkg signer mismatch – PAG_INSECURE)"
2517 - return False, f"PAKIET PODPISANY INNYM KLUCZEM niż repo (oczekiwano {pinned})"
2518 -
2519 - return True, "GPG verified"
2520 -
2521 -def cmd_key_add(source):
2522 - ensure_dirs()
2523 - if not shutil.which(GPG_BINARY):
2524 - print(f"❌ {_('gpg_missing')}"); return 1
2525 - if source.startswith("http"):
2526 - try:
2527 - with urlopen(Request(source, headers={"User-Agent":"pag/3.0"}), timeout=30) as resp:
2528 - keydata = resp.read()
2529 - with tempfile.NamedTemporaryFile(delete=False, suffix=".gpg") as tmp:
2530 - tmp.write(keydata); tmp.flush()
2531 - res = _gpg_run("--import", tmp.name, capture_output=True, timeout=30)
2532 - os.unlink(tmp.name)
2533 - if res.returncode != 0:
2534 - print(f"❌ {_('key_add_failed')}"); return 1
2535 - except Exception as e:
2536 - print(f"❌ Download error: {e}"); return 1
2537 - else:
2538 - res = _gpg_run("--import", source, capture_output=True, timeout=30)
2539 - if res.returncode != 0:
2540 - print(f"❌ {_('key_add_failed')}"); return 1
2541 - print(f"✅ {_('key_imported')}")
2542 -
2543 -def cmd_key_list():
2544 - if not shutil.which(GPG_BINARY):
2545 - print(f"❌ {_('gpg_missing')}"); return
2546 - if not os.path.exists(GPG_HOME):
2547 - print(_("no_keys")); return
2548 - result = _gpg_run("--list-keys", "--keyid-format", "LONG",
2549 - capture_output=True, text=True, timeout=30)
2550 - if result.returncode != 0:
2551 - print(f"❌ {_('gpg_missing')}"); return
2552 - print(result.stdout or _("no_keys"))
2553 -
2554 -def cmd_key_remove(key_id):
2555 - _gpg_run("--batch", "--yes", "--delete-key", key_id,
2556 - capture_output=True, timeout=30)
2557 - print(f"✅ {_('key_removed', key_id)}")
2558 -
2559 -def _repo_signer_fp(repo_url):
2560 - """Pobiera repo.json + podpis i zwraca fingerprint podpisującego (bez pinningu)."""
2561 - repo_url = repo_url.rstrip("/")
2562 - try:
2563 - with urlopen(Request(f"{repo_url}/repo.json", headers={"User-Agent":"pag/3.0"}), timeout=30) as r:
2564 - data = r.read()
2565 - except Exception:
2566 - return None
2567 - sig = None
2568 - sig_ext = ".asc"
2569 - for ext in (".asc", ".sig"):
2570 - try:
2571 - with urlopen(Request(f"{repo_url}/repo.json{ext}", headers={"User-Agent":"pag/3.0"}), timeout=20) as r:
2572 - sig = r.read()
2573 - sig_ext = ext
2574 - break
2575 - except Exception:
2576 - continue
2577 - if not sig:
2578 - return None
2579 - with tempfile.NamedTemporaryFile(delete=False, suffix=".json") as tf:
2580 - tf.write(data); tf.flush()
2581 - data_path = tf.name
2582 - sig_path = data_path + sig_ext
2583 - try:
2584 - with open(sig_path, "wb") as f:
2585 - f.write(sig)
2586 - ok, fp = _gpg_verify_fp(sig_path, data_path)
2587 - finally:
2588 - for p in (data_path, sig_path):
2589 - try: os.unlink(p)
2590 - except OSError: pass
2591 - return fp if ok else None
2592 -
2593 -
2594 -def cmd_key_trust(repo_url):
2595 - """Przypina fingerprint klucza podpisującego repo (koniec z TOFU dla tego repo)."""
2596 - repo_url = repo_url.rstrip("/")
2597 - print(f"🔐 Przypinam klucz repo {repo_url}...")
2598 - fp = _repo_signer_fp(repo_url)
2599 - if not fp:
2600 - print(" ❌ Nie można odczytać fingerprintu podpisu (brak/nieudany).")
2601 - print(" Upewnij się, że klucz repo jest w keyringu (pag key-add <url|file>).")
2602 - return 1
2603 - db = _load_trust_db()
2604 - _save_trust_db({**db, repo_url: fp})
2605 - print(f" ✅ Przypięto {fp} dla {repo_url}")
2606 - print(" Od teraz zmiana klucza zostanie zgłoszona jako SECURITY ERROR.")
2607 - return 0
2608 -
2609 -
2610 -def cmd_key_untrust(repo_url):
2611 - """Usuwa przypięcie fingerprintu dla repo (wraca do TOFU)."""
2612 - repo_url = repo_url.rstrip("/")
2613 - db = _load_trust_db()
2614 - if repo_url not in db:
2615 - print(f" ℹ {repo_url} nie ma przypiętego fingerprintu.")
2616 - return 0
2617 - del db[repo_url]
2618 - _save_trust_db(db)
2619 - print(f" ✅ Usunięto przypięcie dla {repo_url}.")
2620 - return 0
2621 -
2622 -
2623 -def cmd_key_trusted():
2624 - """Listuje przypięte fingerprinty repozytoriów."""
2625 - db = _load_trust_db()
2626 - if not db:
2627 - print(_("no_keys"))
2628 - return
2629 - for url, fp in sorted(db.items()):
2630 - print(f" {url}\n {fp}")
2631 -
2632 -# =============================================================================
2633 -# ATOMOWA INSTALACJA (STAGING)
2634 -# =============================================================================
2635 -
2636 -def _safe_rename(src: str, dst: str) -> bool:
2637 - """
2638 - Atomowe przeniesienie pliku. Jeśli src i dst są na różnych
2639 - systemach plików (EXDEV), kopiuje + usuwa źródło.
2640 - """
2641 - try:
2642 - os.rename(src, dst)
2643 - return True
2644 - except OSError as e:
2645 - if e.errno == 18: # EXDEV – cross-device link
2646 - shutil.copy2(src, dst)
2647 - os.remove(src)
2648 - return True
2649 - raise
2650 -
2651 -
2652 -def _install_file(src: str, rel: str, data_staging: str, sums: dict,
2653 - staging: str, journal: list, installed_files: list,
2654 - deploy_dir: str = "", backup_dir: str = "",
2655 - backup_journal: Optional[list] = None,
2656 - old_checksums: Optional[dict] = None,
2657 - privileged=frozenset()) -> bool:
2658 - """
2659 - Instaluje pojedynczy plik (zwykły lub symlink).
2660 - Obsługuje: cross-device rename, symlinki, weryfikację SHA256.
2661 -
2662 - Jeśli deploy_dir jest podany (tryb immutable), pliki systemowe trafiają
2663 - do deploymentu, a współdzielone (/var, /etc, ...) bezpośrednio do /.
2664 -
2665 - Jeśli backup_dir jest podany, a pod dst istnieje już plik (upgrade/reinstall),
2666 - stara wersja jest przenoszona do backup_dir, by rollback mógł ją przywrócić.
2667 -
2668 - old_checksums: {ścieżka: sha256 z chwili instalacji}. Gdy podane i plik /etc
2669 - został zmodyfikowany przez użytkownika, nowa wersja ląduje jako .pacnew
2670 - (stary plik NIE jest ruszany) – wzorzec jak w pacmanie.
2671 - """
2672 - # W trybie immutable: pliki współdzielone idą do /, reszta do deploymentu
2673 - if deploy_dir and _is_shared_path("/" + rel):
2674 - dst_root = PAG_ROOT
2675 - elif deploy_dir:
2676 - dst_root = deploy_dir
2677 - else:
2678 - dst_root = PAG_ROOT
2679 -
2680 - dst = os.path.join(dst_root, rel)
2681 -
2682 - # --- SYMLINK ---
2683 - if os.path.islink(src):
2684 - link_target = os.readlink(src)
2685 - # Weryfikuj sums.json dla symlinka (hash ścieżki docelowej)
2686 - expected = sums.get("/" + rel, "")
2687 - if expected:
2688 - link_hash = hashlib.sha256(link_target.encode()).hexdigest()
2689 - if expected and link_hash != expected:
2690 - return False
2691 -
2692 - os.makedirs(os.path.dirname(dst), exist_ok=True)
2693 - # Backup istniejącego symlinka (upgrade) – dla poprawnego rollbacku
2694 - if backup_dir and backup_journal is not None and os.path.lexists(dst):
2695 - try:
2696 - backup_path = os.path.join(backup_dir, rel)
2697 - os.makedirs(os.path.dirname(backup_path), exist_ok=True)
2698 - os.replace(dst, backup_path)
2699 - backup_journal.append((backup_path, "/" + rel))
2700 - journal.append(("backup", backup_path, dst))
2701 - except OSError:
2702 - pass
2703 - # Jeśli docelowy symlink już istnieje, usuń go
2704 - if os.path.islink(dst) or os.path.exists(dst):
2705 - os.remove(dst)
2706 - os.symlink(link_target, dst)
2707 - journal.append(("symlink", "", dst))
2708 - installed_files.append({
2709 - "path": "/" + rel,
2710 - "sha256": hashlib.sha256(link_target.encode()).hexdigest(),
2711 - "size": len(link_target),
2712 - "is_symlink": True,
2713 - "symlink_target": link_target,
2714 - })
2715 - return True
2716 -
2717 - # --- ZWYKŁY PLIK ---
2718 - # Oblicz SHA256
2719 - try:
2720 - file_sha = _sha256_file(src)
2721 - except Exception:
2722 - file_sha = ""
2723 -
2724 - # Weryfikuj sums.json
2725 - expected = sums.get("/" + rel, "")
2726 - if expected and file_sha and file_sha != expected:
2727 - return False
2728 -
2729 - # --- .pacnew: NIE nadpisuj pliku konfiguracyjnego, którego nie wolno zgubić ---
2730 - # Robimy `<plik>.pacnew`, gdy:
2731 - # a) plik jest śledzony i użytkownik go zmodyfikował (hash != zapisanej sumy),
2732 - # b) to wrażliwa konfiguracja (/etc/pam.d, /etc/security, sudoers, shadow…),
2733 - # a treść na dysku różni się od tej z pakietu – chroni auth przed
2734 - # cichym nadpisaniem przez `install`/`upgrade` (np. przez shadow).
2735 - # NIE robimy .pacnew, jeśli plik na dysku jest identyczny z nowym albo był
2736 - # niezmieniony od instalacji (wtedy nadpisanie jest bezpieczne).
2737 - old_sha = (old_checksums or {}).get("/" + rel, "")
2738 - if file_sha and _is_config_path(rel) and os.path.isfile(dst) and not os.path.islink(dst):
2739 - tracked_modified = bool(old_sha) and file_sha != old_sha
2740 - if tracked_modified or _is_sensitive_config(rel):
2741 - try:
2742 - cur_sha = _sha256_file(dst)
2743 - except OSError:
2744 - cur_sha = ""
2745 - if cur_sha and cur_sha != file_sha and not (old_sha and cur_sha == old_sha):
2746 - pacnew = dst + ".pacnew"
2747 - try:
2748 - _safe_rename(src, pacnew)
2749 - try:
2750 - os.chown(pacnew, 0, 0)
2751 - except (OSError, PermissionError):
2752 - pass
2753 - # Journal (do cofnięcia przy nieudanej transakcji) – ale NIE
2754 - # zapisujemy .pacnew w bazie plików: to artefakt użytkownika.
2755 - journal.append(("file", src, pacnew))
2756 - print(f" ⚠ {_('conf_pacnew', path=pacnew)}")
2757 - return True
2758 - except OSError:
2759 - pass # nie udało się – kontynuuj normalną instalację
2760 -
2761 - # Utwórz katalog docelowy
2762 - os.makedirs(os.path.dirname(dst), exist_ok=True)
2763 -
2764 - # Backup istniejącego pliku (upgrade) – dla poprawnego rollbacku
2765 - if backup_dir and backup_journal is not None and os.path.lexists(dst):
2766 - try:
2767 - backup_path = os.path.join(backup_dir, rel)
2768 - os.makedirs(os.path.dirname(backup_path), exist_ok=True)
2769 - os.replace(dst, backup_path)
2770 - backup_journal.append((backup_path, "/" + rel))
2771 - journal.append(("backup", backup_path, dst))
2772 - except OSError:
2773 - pass
2774 -
2775 - # Atomowe przeniesienie (z fallbackiem dla cross-device).
2776 - # Zachowuje bity uprawnień (SUID/SGID/sticky) – NIE używamy filter='data'.
2777 - _safe_rename(src, dst)
2778 -
2779 - if "/" + rel in privileged:
2780 - # Plik uprzywilejowany: zostaw właściciela, grupę i bity z pakietu
2781 - # (np. sudo 4755 root:root, qemu-bridge-helper 4750 root:kvm).
2782 - try:
2783 - st = os.stat(dst)
2784 - if st.st_mode & 0o6000:
2785 - _audit(f"privileged {dst} mode={oct(st.st_mode & 0o7777)} "
2786 - f"uid={st.st_uid} gid={st.st_gid}")
2787 - except OSError:
2788 - pass
2789 - else:
2790 - # Wymuś właściciela root:root. UWAGA: os.chown() NIE czyści bitów SUID/SGID.
2791 - try:
2792 - os.chown(dst, 0, 0)
2793 - except (OSError, PermissionError):
2794 - # Na niektórych systemach plików (tmpfs, fat) chown może się nie powieść
2795 - pass
2796 -
2797 - journal.append(("file", src, dst))
2798 - installed_files.append({
2799 - "path": "/" + rel,
2800 - "sha256": file_sha,
2801 - "size": os.path.getsize(dst),
2802 - "is_symlink": False,
2803 - })
2804 - return True
2805 -
2806 -
2807 -
2808 -def _stage_package(pkg_path: str, pkg: PackageInfo) -> Optional[dict]:
2809 - """Rozpakowuje pakiet do stagingu, NIE dotykając systemu.
2810 -
2811 - Zwraca dict: staging, data, sums, hooks. None przy błędzie.
2812 -
2813 - To pierwsza faza transakcji grupowej: najpierw przygotowujemy WSZYSTKIE
2814 - pakiety (np. całe GNOME – 50 paczek). Dopiero gdy każda się rozpakuje i
2815 - przejdzie weryfikację SHA256, przechodzimy do fazy commit. Błąd jednej
2816 - paczki nie zostawia więc systemu w połowie instalacji.
2817 - """
2818 - staging = tempfile.mkdtemp(dir=STAGING_DIR, prefix=f".stage-{pkg.name}-")
2819 - try:
2820 - with tarfile.open(pkg_path, "r:xz") as tf:
2821 - _safe_extractall(tf, staging)
2822 -
2823 - data_tar = os.path.join(staging, "data.tar.xz")
2824 - if not os.path.exists(data_tar):
2825 - raise RuntimeError("brak data.tar.xz w pakiecie")
2826 -
2827 - data_staging = os.path.join(staging, "data")
2828 - os.makedirs(data_staging, exist_ok=True)
2829 - priv = PRIVILEGED_PATHS | frozenset(pkg.privileged or ())
2830 - with tarfile.open(data_tar, "r:xz") as tf:
2831 - _safe_extractall(tf, data_staging, privileged=priv)
2832 -
2833 - sums_path = os.path.join(data_staging, "sums.json")
2834 - sums = json.load(open(sums_path)) if os.path.exists(sums_path) else {}
2835 -
2836 - # Weryfikacja SHA256 JUŻ w stagingu – uszkodzona paczka nie dojdzie
2837 - # do fazy commit, więc nie zdąży nadpisać żadnego pliku w systemie.
2838 - _bad: List[str] = []
2839 - for _root, _dirs, _files in os.walk(data_staging):
2840 - for _name in list(_dirs) + _files:
2841 - if _name == "sums.json":
2842 - continue
2843 - _fp = os.path.join(_root, _name)
2844 - _rel = "/" + os.path.relpath(_fp, data_staging)
2845 - _expected = sums.get(_rel, "")
2846 - if not _expected:
2847 - continue
2848 - try:
2849 - if os.path.islink(_fp):
2850 - _actual = hashlib.sha256(
2851 - os.readlink(_fp).encode()).hexdigest()
2852 - elif os.path.isfile(_fp):
2853 - _actual = _sha256_file(_fp)
2854 - else:
2855 - continue
2856 - except OSError:
2857 - _actual = ""
2858 - if _actual != _expected:
2859 - _bad.append(_rel)
2860 - if len(_bad) >= 5:
2861 - break
2862 - if len(_bad) >= 5:
2863 - break
2864 - if _bad:
2865 - raise RuntimeError(
2866 - "niezgodność SHA256: " + ", ".join(_bad[:5]))
2867 -
2868 - return {
2869 - "staging": staging,
2870 - "data": data_staging,
2871 - "sums": sums,
2872 - "hooks": os.path.join(staging, "hooks"),
2873 - }
2874 - except Exception as e:
2875 - shutil.rmtree(staging, ignore_errors=True)
2876 - print(f" ❌ {pkg.name}: etap przygotowania nieudany ({e})")
2877 - return None
2878 -
2879 -
2880 -def _discard_staged(staged: Optional[dict]):
2881 - """Usuwa katalog stagingu przygotowanego pakietu (bez zmian w systemie)."""
2882 - if staged and staged.get("staging"):
2883 - shutil.rmtree(staged["staging"], ignore_errors=True)
2884 -
2885 -
2886 -def _apply_staged_package(staged: dict, pkg: PackageInfo, deploy_dir: str = "",
2887 - backup_dir: str = "",
2888 - old_checksums: Optional[dict] = None
2889 - ) -> Tuple[bool, List[dict], List[Tuple[str, str]]]:
2890 - """Faza commit: przenosi przygotowany pakiet do systemu.
2891 -
2892 - Hooki pre/post-install uruchamiane są tutaj – dopiero po tym, jak cała
2893 - grupa pakietów została poprawnie rozpakowana w stagingu.
2894 - """
2895 - staging = staged["staging"]
2896 - data_staging = staged["data"]
2897 - sums = staged["sums"]
2898 - hooks_dir = staged["hooks"]
2899 - priv = PRIVILEGED_PATHS | frozenset(pkg.privileged or ())
2900 - journal: List[tuple] = []
2901 - installed_files: List[dict] = []
2902 - backup_journal: List[Tuple[str, str]] = []
2903 -
2904 - try:
2905 - # Hook pre-install (przed przeniesieniem plików do systemu)
2906 - _run_hook(hooks_dir, "pre-install", pkg)
2907 -
2908 - # Przenieś pliki: staging/data/* → /
2909 - for root, dirs, files in os.walk(data_staging):
2910 - # Symlink do katalogu (np. /lib → usr/lib) os.walk zwraca w `dirs`.
2911 - # Nie wolno tworzyć z niego prawdziwego katalogu – przekieruj do
2912 - # pętli plików, gdzie _install_file odtworzy symlink.
2913 - for _d in list(dirs):
2914 - if os.path.islink(os.path.join(root, _d)):
2915 - dirs.remove(_d)
2916 - files.append(_d)
2917 -
2918 - # Odtwórz katalogi z pakietu – w tym PUSTE (np. /etc/pulse/default.pa.d).
2919 - for d in dirs:
2920 - src_dir = os.path.join(root, d)
2921 - rel_dir = os.path.relpath(src_dir, data_staging)
2922 - if deploy_dir and _is_shared_path("/" + rel_dir):
2923 - dst_root = PAG_ROOT
2924 - elif deploy_dir:
2925 - dst_root = deploy_dir
2926 - else:
2927 - dst_root = PAG_ROOT
2928 - dst_dir = os.path.join(dst_root, rel_dir)
2929 - if not os.path.isdir(dst_dir):
2930 - try:
2931 - os.makedirs(dst_dir, exist_ok=True)
2932 - except OSError:
2933 - pass
2934 - for fname in files:
2935 - if fname == "sums.json":
2936 - continue
2937 - src = os.path.join(root, fname)
2938 - rel = os.path.relpath(src, data_staging)
2939 -
2940 - ok = _install_file(src, rel, data_staging, sums,
2941 - staging, journal, installed_files, deploy_dir,
2942 - backup_dir, backup_journal,
2943 - old_checksums=old_checksums,
2944 - privileged=priv)
2945 - if not ok:
2946 - # Cofnij wszystkie operacje
2947 - _rollback_journal(journal, staging)
2948 - return False, [], backup_journal
2949 -
2950 - # Odbuduj cache ikon GTK dla motywów dotkniętych instalacją.
2951 - _icon_dirs = set()
2952 - for f in installed_files:
2953 - fp = f.get("path", "") or ""
2954 - if fp.startswith("/usr/share/icons/"):
2955 - _rest = fp[len("/usr/share/icons/"):]
2956 - _theme = _rest.split("/", 1)[0]
2957 - if _theme:
2958 - _icon_dirs.add(os.path.join(PAG_ROOT, "usr/share/icons", _theme))
2959 - if _icon_dirs:
2960 - try:
2961 - subprocess.run(["gtk-update-icon-cache", "--version"],
2962 - capture_output=True, timeout=10)
2963 - for _d in sorted(_icon_dirs):
2964 - if os.path.isdir(_d):
2965 - subprocess.run(["gtk-update-icon-cache", "-f", "-q", _d],
2966 - capture_output=True, timeout=300)
2967 - except Exception:
2968 - pass
2969 -
2970 - # Uruchom hooki post-install
2971 - _run_hook(hooks_dir, "post-install", pkg)
2972 -
2973 - # Zachowaj hooki na wypadek usunięcia pakietu (pre/post-remove)
2974 - try:
2975 - if os.path.isdir(hooks_dir):
2976 - persisted = os.path.join(PAG_DB, "hooks", pkg.name)
2977 - shutil.rmtree(persisted, ignore_errors=True)
2978 - shutil.copytree(hooks_dir, persisted)
2979 - except Exception:
2980 - pass
2981 -
2982 - # Zapisz do SQLite
2983 - _db_record_files(pkg.name, installed_files)
2984 -
2985 - shutil.rmtree(staging, ignore_errors=True)
2986 - return True, installed_files, backup_journal
2987 -
2988 - except Exception as e:
2989 - _rollback_journal(journal, staging)
2990 - print(f" ❌ {pkg.name}: błąd commit – {e}")
2991 - return False, [], backup_journal
2992 -
2993 -
2994 -def _atomic_install(pkg_path: str, pkg: PackageInfo, deploy_dir: str = "",
2995 - backup_dir: str = "",
2996 - old_checksums: Optional[dict] = None
2997 - ) -> Tuple[bool, List[dict], List[Tuple[str, str]]]:
2998 - """Instaluje pojedynczy pakiet dwufazowo: staging → commit.
2999 -
3000 - Zachowane jako publiczny wrapper dla instalacji pojedynczych plików
3001 - lokalnych; transakcja grupowa w cmd_install przygotowuje staging dla
3002 - całej grupy i wywołuje _apply_staged_package bezpośrednio.
3003 - """
3004 - staged = _stage_package(pkg_path, pkg)
3005 - if not staged:
3006 - return False, [], []
3007 - return _apply_staged_package(staged, pkg, deploy_dir, backup_dir, old_checksums)
3008 -
3009 -def _refresh_dynamic_linker_cache(deploy_dir: str = "") -> bool:
3010 - """Odświeża cache ld.so po udanej instalacji pakietów."""
3011 - ldconfig = shutil.which("ldconfig")
3012 - if not ldconfig:
3013 - print(" ⚠ Nie znaleziono ldconfig — cache linkera nie został odświeżony.",
3014 - file=sys.stderr)
3015 - return False
3016 -
3017 - target_root = deploy_dir or PAG_ROOT
3018 - command = [ldconfig]
3019 - if target_root != "/":
3020 - command.extend(["-r", target_root])
3021 -
3022 - try:
3023 - subprocess.run(command, check=True, timeout=60,
3024 - stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
3025 - text=True)
3026 - return True
3027 - except (OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc:
3028 - detail = getattr(exc, "stderr", None) or str(exc)
3029 - print(f" ⚠ Nie udało się odświeżyć cache'a ld.so: {detail.strip()}",
3030 - file=sys.stderr)
3031 - return False
3032 -
3033 -
3034 -def _rollback_journal(journal: list, staging_path: str):
3035 - """Cofa wszystkie operacje z journala (odwrotna kolejność)."""
3036 - for entry in reversed(journal):
3037 - op = entry[0]
3038 - if op == "file":
3039 - _, src, dst = entry
3040 - try:
3041 - if os.path.exists(dst) or os.path.islink(dst):
3042 - _safe_rename(dst, src)
3043 - except Exception:
3044 - pass
3045 - elif op == "symlink":
3046 - _, _, dst = entry
3047 - try:
3048 - if os.path.islink(dst) or os.path.exists(dst):
3049 - os.remove(dst)
3050 - except Exception:
3051 - pass
3052 - elif op == "backup":
3053 - # Przywróć starą wersję pliku z backupu (upgrade)
3054 - _, bpath, dst = entry
3055 - try:
3056 - if os.path.lexists(bpath):
3057 - os.replace(bpath, dst)
3058 - except Exception:
3059 - pass
3060 - shutil.rmtree(staging_path, ignore_errors=True)
3061 -
3062 -# =============================================================================
3063 -# BEZPIECZNE USUWANIE
3064 -# =============================================================================
3065 -
3066 -def _safe_remove_files(pkg_name: str, installed_db: dict) -> Tuple[int, List[str]]:
3067 - """
3068 - Usuwa pliki pakietu, ale tylko jeśli NIE są współdzielone z innym pakietem.
3069 - Zwraca (liczba usuniętych, [lista usuniętych ścieżek]).
3070 - """
3071 - pkg_files = _db_get_package_files(pkg_name)
3072 - recorded = _db_get_package_checksums(pkg_name)
3073 - removed = []
3074 - skipped_shared = []
3075 - skipped_sensitive = []
3076 -
3077 - for fpath in pkg_files:
3078 - owners = _db_get_file_owners(fpath)
3079 - # Sprawdź czy inny ZAINSTALOWANY pakiet też jest właścicielem
3080 - other_owners = [o for o in owners if o != pkg_name and o in installed_db]
3081 -
3082 - if other_owners:
3083 - # Plik współdzielony – tylko usuń wpis w DB, nie kasuj pliku
3084 - skipped_shared.append(fpath)
3085 - continue
3086 -
3087 - full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
3088 - if os.path.isfile(full) or os.path.islink(full):
3089 - # Wrażliwej konfiguracji systemowej (/etc/pam.d, sudoers, shadow…)
3090 - # NIE kasujemy przy `remove` – jej brak potrafi zablokować logowanie
3091 - # i sudo (np. usunięcie system-auth/system-account). Zostaje wpis w bazie.
3092 - if _is_sensitive_config(fpath):
3093 - skipped_sensitive.append(fpath)
3094 - continue
3095 - # .pacsave: zachowaj ZMIENIONY plik konfiguracyjny zamiast kasować
3096 - # (porównanie z sumą z chwili instalacji), wzorzec jak w pacmanie.
3097 - if not os.path.islink(full) and _is_config_path(fpath):
3098 - old_sha = recorded.get(fpath, "")
3099 - if old_sha:
3100 - try:
3101 - cur_sha = _sha256_file(full)
3102 - except OSError:
3103 - cur_sha = ""
3104 - if cur_sha and cur_sha != old_sha:
3105 - pacsave = full + ".pacsave"
3106 - try:
3107 - os.replace(full, pacsave)
3108 - print(f" ⚠ {_('conf_pacsave', path=pacsave)}")
3109 - removed.append(fpath)
3110 - continue
3111 - except OSError:
3112 - pass
3113 - os.remove(full)
3114 - removed.append(fpath)
3115 -
3116 - # Usuń puste katalogi (od najgłębszych)
3117 - dirs = set()
3118 - for fpath in removed + skipped_shared:
3119 - parent = os.path.dirname(fpath)
3120 - while parent and parent != "/":
3121 - dirs.add(parent)
3122 - parent = os.path.dirname(parent)
3123 -
3124 - for d in sorted(dirs, key=len, reverse=True):
3125 - full_d = os.path.join(PAG_ROOT, d.lstrip("/"))
3126 - if os.path.isdir(full_d):
3127 - try:
3128 - os.rmdir(full_d)
3129 - except OSError:
3130 - pass # nie jest pusty – OK
3131 -
3132 - # Usuń z SQLite
3133 - _db_remove_package_files(pkg_name)
3134 -
3135 - if skipped_shared:
3136 - print(f" ⚠ {len(skipped_shared)} plików współdzielonych zachowanych")
3137 - if skipped_sensitive:
3138 - print(f" ⚠ {len(skipped_sensitive)} wrażliwych plików systemowych zachowanych")
3139 -
3140 - return len(removed) + len(skipped_shared) + len(skipped_sensitive), removed
3141 -
3142 -
3143 -def _remove_stale_files(pkg_name: str, old_files: List[str], new_paths: List[str],
3144 - installed_db: dict, deploy_dir: str = "",
3145 - backup_dir: str = "", backup_journal: Optional[list] = None) -> Tuple[int, List[str]]:
3146 - """
3147 - Po upgrade usuwa pliki starej wersji, których nie ma w nowej.
3148 -
3149 - - Pliki współdzielone z innym zainstalowanym pakietem są ZACHOWYWANE
3150 - (usuwany jest tylko wpis z bazy `files` dla tego pakietu).
3151 - - Sprząta puste katalogi i wpisy SQLite starej wersji.
3152 - Zwraca (liczba usuniętych, [usunięte ścieżki]).
3153 - """
3154 - new_set = set(new_paths)
3155 - # Warianty /usr/lib <-> /usr/lib64: plik obecny w nowej wersji pod równoważną
3156 - # ścieżką NIE jest przestarzały. Bez tego upgrade kasował właśnie
3157 - # zainstalowany plik, gdy stara i nowa wersja używały różnych libdir
3158 - # (kolizja lib/lib64).
3159 - new_effective = set()
3160 - for _p in new_set:
3161 - new_effective.add(_p)
3162 - if _p.startswith("/usr/lib64/"):
3163 - new_effective.add("/usr/lib/" + _p[len("/usr/lib64/"):])
3164 - elif _p.startswith("/usr/lib/"):
3165 - new_effective.add("/usr/lib64/" + _p[len("/usr/lib/"):])
3166 - stale = [f for f in old_files if f not in new_effective]
3167 - if not stale:
3168 - return 0, []
3169 -
3170 - root = deploy_dir or PAG_ROOT
3171 - removed = []
3172 - skipped = 0
3173 - for fpath in stale:
3174 - owners = _db_get_file_owners(fpath)
3175 - other_owners = [o for o in owners if o != pkg_name and o in installed_db]
3176 - if other_owners:
3177 - # Współdzielony z innym pakietem – tylko usuń wpis z DB dla tego pakietu
3178 - skipped += 1
3179 - else:
3180 - # Wrażliwych plików systemowych NIE kasujemy, gdy nowy pakiet ich już
3181 - # nie dostarcza (np. shadow przestaje pakować system-*). Ich brak
3182 - # blokuje login/sudo; usuwamy więc tylko wpis w bazie.
3183 - if _is_sensitive_config(fpath):
3184 - skipped += 1
3185 - else:
3186 - # Gdy nowa wersja pliku /etc trafiła do .pacnew, plik użytkownika
3187 - # MUSI zostać – nie jest „przestarzały”. Zachowujemy też wpis w bazie
3188 - # (stara suma), by kolejny upgrade dalej wykrywał zmiany użytkownika.
3189 - if _is_config_path(fpath):
3190 - _cfg_full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
3191 - if os.path.lexists(_cfg_full + ".pacnew"):
3192 - skipped += 1
3193 - continue
3194 - full = os.path.join(root, fpath.lstrip("/"))
3195 - if os.path.isfile(full) or os.path.islink(full):
3196 - try:
3197 - if backup_dir and backup_journal is not None:
3198 - backup_path = os.path.join(backup_dir, fpath.lstrip("/"))
3199 - os.makedirs(os.path.dirname(backup_path), exist_ok=True)
3200 - os.replace(full, backup_path) # przenieś do backupu (rollback)
3201 - backup_journal.append((backup_path, fpath))
3202 - else:
3203 - os.remove(full)
3204 - removed.append(fpath)
3205 - except OSError:
3206 - pass
3207 - # Usuń wpis `files` dla tego pakietu (stara wersja już go nie zawiera)
3208 - with _db_session() as db:
3209 - db.execute("DELETE FROM files WHERE package=? AND path=?", (pkg_name, fpath))
3210 -
3211 - # Usuń puste katalogi (od najgłębszych)
3212 - dirs = set()
3213 - for fpath in removed:
3214 - parent = os.path.dirname(fpath)
3215 - while parent and parent != "/":
3216 - dirs.add(parent)
3217 - parent = os.path.dirname(parent)
3218 - for d in sorted(dirs, key=len, reverse=True):
3219 - full_d = os.path.join(root, d.lstrip("/"))
3220 - if os.path.isdir(full_d):
3221 - try:
3222 - os.rmdir(full_d)
3223 - except OSError:
3224 - pass # nie jest pusty – OK
3225 -
3226 - if removed:
3227 - print(f" 🧹 Usunięto {len(removed)} nieaktualnych plików ({pkg_name})")
3228 - if skipped:
3229 - print(f" ⚠ {skipped} plików współdzielonych zachowanych")
3230 -
3231 - return len(removed), removed
3232 -
3233 -
3234 -def _new_transaction_backup_root() -> str:
3235 - """Katalog na backupy NADPISYWANYCH plików dla bieżącej transakcji.
3236 -
3237 - Tworzony dla KAŻDEJ transakcji, nie tylko upgrade: „świeża” instalacja
3238 - pakietu też potrafi nadpisać pliki spoza bazy pag (baza rootfs/ISO).
3239 - Gdy transakcja padnie, rollback MUSI mieć co przywrócić – inaczej kasuje
3240 - te pliki (tak zniknął m.in. libpam.so.0 i przestał działać sudo)."""
3241 - txn = datetime.now().strftime("%Y%m%dT%H%M%S") + "-" + str(os.getpid())
3242 - root = os.path.join(STAGING_DIR, "backups", txn)
3243 - os.makedirs(root, exist_ok=True)
3244 - return root
3245 -
3246 -
3247 -def _purge_old_backups(keep_root: str = ""):
3248 - """Usuwa backupy starszych transakcji (zostawia bieżący – dla `pag rollback`)."""
3249 - base = os.path.join(STAGING_DIR, "backups")
3250 - if not os.path.isdir(base):
3251 - return
3252 - for entry in os.listdir(base):
3253 - p = os.path.join(base, entry)
3254 - if p != keep_root and os.path.isdir(p):
3255 - shutil.rmtree(p, ignore_errors=True)
3256 -
3257 -
3258 -def _recover_interrupted_transactions(verbose=True) -> int:
3259 - """Przywraca pliki po transakcji PRZERWANEJ w polowie (crash / kill -9).
3260 -
3261 - Backup transakcji (/.pag_staging/backups/<txn>) powstaje, ZANIM pliki zostana
3262 - podmienione. Jesli pag zginie w trakcie, czesc plikow jest juz przeniesiona do
3263 - backupu, a nowych jeszcze nie ma -> system zostaje bez pliku.
3264 -
3265 - Dla kazdego katalogu backupu, ktory NIE jest zapisany w historii jako UDANA
3266 - transakcja (`upgrade_backup_root` przy `success=true`; takie zostawiamy dla
3267 - `pag rollback`), przywracamy pliki nieobecne w systemie. Potem odswiezamy
3268 - cache linkera.
3269 - """
3270 - base = os.path.join(STAGING_DIR, "backups")
3271 - if not os.path.isdir(base):
3272 - return 0
3273 - try:
3274 - history = load_json(HISTORY_FILE) or []
3275 - except Exception:
3276 - history = []
3277 - done_roots = {
3278 - e.get("upgrade_backup_root") for e in history
3279 - if isinstance(e, dict) and e.get("success") and e.get("upgrade_backup_root")
3280 - }
3281 - restored = 0
3282 - for txn in sorted(os.listdir(base)):
3283 - root = os.path.join(base, txn)
3284 - if not os.path.isdir(root) or root in done_roots:
3285 - continue
3286 - for dirpath, _dirs, files in os.walk(root):
3287 - for fn in files:
3288 - src = os.path.join(dirpath, fn)
3289 - rel = os.path.relpath(src, root)
3290 - dst = os.path.join(PAG_ROOT, rel)
3291 - if os.path.lexists(dst):
3292 - continue
3293 - try:
3294 - os.makedirs(os.path.dirname(dst), exist_ok=True)
3295 - if os.path.islink(src):
3296 - os.symlink(os.readlink(src), dst)
3297 - else:
3298 - shutil.copy2(src, dst)
3299 - restored += 1
3300 - except OSError:
3301 - pass
3302 - if restored:
3303 - try:
3304 - subprocess.run(["ldconfig"], capture_output=True, timeout=120)
3305 - except Exception:
3306 - pass
3307 - if verbose:
3308 - print(f" 🛠 Wykryto przerwana transakcje – przywrocono {restored} brakujacych plikow.")
3309 - return restored
3310 -
3311 -
3312 -# =============================================================================
3313 -# HOOKI
3314 -# =============================================================================
3315 -# Hooki uruchamiają dowolny plik z pakietu jako root — to naturalna cecha
3316 -# menedżera pakietów (apt/pacman też tak mają), dlatego MUSISZ ufać repozytorium.
3317 -# Aby ograniczyć ryzyko:
3318 -# - hook dostaje minimalne, "czyste" środowisko (bez LD_PRELOAD, BASH_ENV itp.)
3319 -# - hooki można wyłączyć (PAG_NO_HOOKS=1) i ustawić timeout (PAG_HOOK_TIMEOUT)
3320 -# - każde uruchomienie jest logowane do /var/log/pag/audit.log
3321 -# - hook ma wersjonowane API (PKG_HOOK_API)
3322 -# =============================================================================
3323 -
3324 -# Lista wykonanych hooków — trafia do wpisu transakcji (informacja w rejestrze).
3325 -_HOOKS_RUN: List[str] = []
3326 -
3327 -
3328 -def _hook_env(pkg: PackageInfo, hook_name: str) -> dict:
3329 - """Buduje minimalne środowisko dla hooka (bez niebezpiecznych zmiennych)."""
3330 - return {
3331 - "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
3332 - "HOME": "/root",
3333 - "LANG": "C.UTF-8",
3334 - "LC_ALL": "C.UTF-8",
3335 - "PKG_NAME": pkg.name,
3336 - "PKG_VERSION": pkg.version,
3337 - "PKG_ACTION": hook_name,
3338 - "PKG_HOOK_API": HOOK_API_VERSION,
3339 - }
3340 -
3341 -
3342 -def _hook_timeout() -> int:
3343 - try:
3344 - return max(1, int(os.environ.get("PAG_HOOK_TIMEOUT", "60")))
3345 - except Exception:
3346 - return 60
3347 -
3348 -
3349 -def _run_hook(hooks_dir: str, hook_name: str, pkg: PackageInfo) -> bool:
3350 - """Uruchamia skrypt hooka jeśli istnieje.
3351 -
3352 - Zwraca True jeśli hook został WYKONANY (istniał i uruchomiono go), False w
3353 - pozostałych przypadkach (brak pliku, wyłączone hooki, błąd). Obsługuje
3354 - ograniczone środowisko, timeout, logowanie do audytu i rejestr w transakcji.
3355 - """
3356 - hook_path = os.path.join(hooks_dir, hook_name)
3357 - if not os.path.exists(hook_path):
3358 - return False
3359 -
3360 - if os.environ.get("PAG_NO_HOOKS", "") == "1":
3361 - print(f" ⚠ Hook pominięty (PAG_NO_HOOKS=1): {hook_name} dla {pkg.name}")
3362 - _audit(f"hook SKIP {hook_name} {pkg.name}-{pkg.version} (PAG_NO_HOOKS=1)")
3363 - return False
3364 -
3365 - os.chmod(hook_path, 0o755)
3366 - env = _hook_env(pkg, hook_name)
3367 - tag = f"{hook_name} {pkg.name}-{pkg.version}"
3368 - try:
3369 - result = subprocess.run([hook_path], env=env, timeout=_hook_timeout(),
3370 - check=False, capture_output=True, text=True,
3371 - cwd="/")
3372 - _HOOKS_RUN.append(tag)
3373 - if result.returncode != 0:
3374 - print(f" ⚠ Hook {hook_name} dla {pkg.name} zakończony z kodem {result.returncode}")
3375 - if result.stderr:
3376 - print(f" {result.stderr.strip()[-200:]}")
3377 - _audit(f"hook FAIL {tag} rc={result.returncode}")
3378 - else:
3379 - _audit(f"hook OK {tag}")
3380 - return True
3381 - except subprocess.TimeoutExpired:
3382 - print(f" ⚠ Hook {hook_name} dla {pkg.name} przekroczył timeout ({_hook_timeout()}s)")
3383 - _audit(f"hook TIMEOUT {tag}")
3384 - return False
3385 - except Exception as e:
3386 - print(f" ⚠ Hook {hook_name} dla {pkg.name}: {e}")
3387 - _audit(f"hook ERROR {tag}: {e}")
3388 - return False
3389 -
3390 -# =============================================================================
3391 -# TRANSAKCJE I ROLLBACK
3392 -# =============================================================================
3393 -
3394 -def _record_transaction(action, packages, success, snapshot, file_journal=None, hooks=None,
3395 - upgrade_backups=None, upgrade_backup_root="", snapshot_id=""):
3396 - history = load_json(HISTORY_FILE) if os.path.exists(HISTORY_FILE) else []
3397 - # Rejestr wykonanych hooków – informacja o tym, że uruchomiono kod pakietu
3398 - # jako root. Trafia do historii, by dało się później sprawdzić, co się działo.
3399 - executed_hooks = list(_HOOKS_RUN) if hooks is None else hooks
3400 - _HOOKS_RUN.clear()
3401 - entry = {
3402 - "action": action, "packages": packages, "success": success,
3403 - "timestamp": datetime.now().isoformat(),
3404 - "snapshot": snapshot,
3405 - "file_journal": file_journal, # lista plików do wycofania
3406 - "hooks": executed_hooks, # wykonane hooki (pre/post-install/remove)
3407 - }
3408 - if snapshot_id:
3409 - # Snapshot systemu (btrfs) z chwili PRZED transakcją – można z niego
3410 - # uruchomić system z menu GRUB albo podejrzeć `pag snapshot-list`.
3411 - entry["snapshot_id"] = snapshot_id
3412 - if upgrade_backups:
3413 - entry["upgrade_backups"] = upgrade_backups # {dst: backup_path}
3414 - entry["upgrade_backup_root"] = upgrade_backup_root
3415 - history.append(entry)
3416 - if len(history) > 50:
3417 - history = history[-50:]
3418 - save_json(HISTORY_FILE, history)
3419 -
3420 -def cmd_history():
3421 - if not os.path.exists(HISTORY_FILE):
3422 - print(_("no_history")); return
3423 - history = load_json(HISTORY_FILE)
3424 - if not history:
3425 - print(_("no_history")); return
3426 - print(f"Ostatnie transakcje ({len(history)}):")
3427 - for i, e in enumerate(reversed(history), 1):
3428 - icon = "✅" if e["success"] else "❌"
3429 - pkgs = ", ".join(e["packages"][:5])
3430 - if len(e["packages"]) > 5: pkgs += f" (+{len(e['packages'])-5})"
3431 - print(f" {i}. {icon} {e['action']}: {pkgs}")
3432 - print(f" {e['timestamp']}")
3433 -
3434 -def cmd_rollback():
3435 - if not os.path.exists(HISTORY_FILE):
3436 - print(_("no_history")); return 1
3437 - history = load_json(HISTORY_FILE)
3438 - if not history:
3439 - print(_("no_history")); return 1
3440 -
3441 - last = None
3442 - for e in reversed(history):
3443 - if e["success"] and e.get("snapshot"):
3444 - last = e; break
3445 -
3446 - if not last:
3447 - print("❌ No snapshot to restore."); return 1
3448 -
3449 - print(f"⏪ Rolling back: {last['action']} ({last['timestamp']})")
3450 - print(f" Packages: {', '.join(last['packages'][:10])}")
3451 -
3452 - if not _ask_confirm():
3453 - return 0
3454 -
3455 - # Przywróć installed.json
3456 - save_json(INSTALLED_DB, last["snapshot"])
3457 -
3458 - # Wycofaj fizyczne pliki (jeśli zapisano journal)
3459 - # Deduplikacja: pakiet może zgłosić ten sam plik więcej niż raz (np. przez
3460 - # `provides` lub wspólną ścieżkę), a journal z historii mógł zostać zapisany
3461 - # przed dodaniem deduplikacji.
3462 - file_journal = list(dict.fromkeys(last.get("file_journal", [])))
3463 - upgrade_backups = last.get("upgrade_backups", {}) or {}
3464 - backup_root = last.get("upgrade_backup_root", "")
3465 -
3466 - # Przywróć stare wersje z backupów (upgrade) – nadpisane i usunięte stale pliki
3467 - for dst, bpath in upgrade_backups.items():
3468 - full = os.path.join(PAG_ROOT, dst.lstrip("/"))
3469 - if bpath and os.path.lexists(bpath):
3470 - try:
3471 - os.makedirs(os.path.dirname(full), exist_ok=True)
3472 - os.replace(bpath, full)
3473 - except OSError:
3474 - pass
3475 -
3476 - # Usuń nowe pliki (które nie miały poprzedniej wersji)
3477 - backed = set(upgrade_backups)
3478 - if file_journal:
3479 - for fpath in reversed(file_journal):
3480 - if fpath in backed:
3481 - continue
3482 - full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
3483 - if os.path.exists(full) or os.path.islink(full):
3484 - os.remove(full)
3485 - print(f" {_('rollback_files', len(file_journal))}")
3486 -
3487 - # Sprzątanie pustych katalogów + katalogu backupów
3488 - dirs = set()
3489 - for fpath in file_journal:
3490 - parent = os.path.dirname(fpath)
3491 - while parent and parent != "/":
3492 - dirs.add(parent)
3493 - parent = os.path.dirname(parent)
3494 - for d in sorted(dirs, key=len, reverse=True):
3495 - full_d = os.path.join(PAG_ROOT, d.lstrip("/"))
3496 - if os.path.isdir(full_d):
3497 - try:
3498 - os.rmdir(full_d)
3499 - except OSError:
3500 - pass
3501 - if backup_root:
3502 - shutil.rmtree(backup_root, ignore_errors=True)
3503 -
3504 - print(f"✅ {_('rollback_restored')}")
3505 - _record_transaction("rollback", last["packages"], True, None)
3506 - return 0
3507 -
3508 -# =============================================================================
3509 -# INSTALACJA
3510 -# =============================================================================
3511 -
3512 -def _install_local_pkg_files(paths, install_succeeded):
3513 - """Instaluje lokalne pliki .pag (bez repozytorium).
3514 -
3515 - Najpierw przygotowuje WSZYSTKIE paczki w stagingu, potem je nakłada.
3516 - Dzięki temu uszkodzony plik w środku grupy nie zostawia systemu
3517 - w połowie instalacji. Zwraca (failed_count, installed_files).
3518 - """
3519 - failed = 0
3520 - prepared = []
3521 - for p in paths:
3522 - p = os.path.abspath(p)
3523 - if not os.path.isfile(p):
3524 - print(f" ❌ Nie znaleziono pakietu: {p}")
3525 - failed += 1
3526 - break
3527 - if not _verify_local_pkg_signature(p):
3528 - failed += 1
3529 - break
3530 - try:
3531 - with tarfile.open(p, "r:xz") as tf:
3532 - meta = tf.extractfile("metadata.json")
3533 - if meta is None:
3534 - print(f" ❌ {p}: brak metadata.json")
3535 - failed += 1
3536 - break
3537 - data = json.loads(meta.read())
3538 - except Exception as e:
3539 - print(f" ❌ {p}: nie udało się odczytać pakietu ({e})")
3540 - failed += 1
3541 - break
3542 - pkg = PackageInfo(data, repo="local")
3543 - staged = _stage_package(p, pkg)
3544 - if not staged:
3545 - failed += 1
3546 - break
3547 - prepared.append((pkg, staged))
3548 -
3549 - if failed:
3550 - for _pkg, _st in prepared:
3551 - _discard_staged(_st)
3552 - print(" ↩ Etap przygotowania nieudany – system NIE został zmieniony.")
3553 - return failed, []
3554 -
3555 - all_files = []
3556 - for pkg, staged in prepared:
3557 - print(f" ↓ {pkg.name}-{pkg.version} (lokalny) ... ", end="", flush=True)
3558 - ok, files, _ = _apply_staged_package(staged, pkg)
3559 - if ok:
3560 - install_succeeded(pkg, files)
3561 - all_files.extend(f["path"] for f in files)
3562 - print("✅")
3563 - else:
3564 - print("❌")
3565 - failed += 1
3566 - return failed, all_files
3567 -
3568 -
3569 -def _preflight_disk(total_bytes: int) -> bool:
3570 - """Pre-flight przed transakcją: wolne miejsce + mount read-only.
3571 -
3572 - Zwraca False (przerywa instalację) gdy na partycji docelowej brakuje
3573 - miejsca na pakiety albo katalog stagingu jest zamontowany read-only
3574 - (inaczej instalacja rwałaby się w połowie, zostawiając uszkodzony system).
3575 - """
3576 - target = PAG_ROOT or "/"
3577 - try:
3578 - st = os.statvfs(target)
3579 - free = st.f_bavail * st.f_frsize
3580 - except OSError:
3581 - return True # nie da się sprawdzić – nie blokuj
3582 - need_mb = total_bytes // 1048576
3583 - free_mb = free // 1048576
3584 - if free < total_bytes:
3585 - print(f" ❌ Za mało miejsca na dysku: potrzeba ~{need_mb} MB, "
3586 - f"wolne {free_mb} MB ({target})")
3587 - return False
3588 - if free < total_bytes * 3:
3589 - print(f" ⚠ Mało miejsca na dysku: wolne {free_mb} MB, "
3590 - f"pakiety ~{need_mb} MB (rozpakowane zajmą więcej)")
3591 - # Wykryj mount read-only (test zapisu w stagingu)
3592 - try:
3593 - probe = os.path.join(STAGING_DIR, ".pag-probe")
3594 - with open(probe, "w") as f:
3595 - f.write("x")
3596 - os.remove(probe)
3597 - except OSError:
3598 - print(f" ❌ {target} jest zamontowane tylko-do-odczytu – nie można instalować.")
3599 - return False
3600 - return True
3601 -
3602 -
3603 -def cmd_install(package_names, as_dep=False, upgrade=False):
3604 - ensure_dirs()
3605 - installed_db = load_json(INSTALLED_DB)
3606 - world = load_world()
3607 - pinned = load_json(PINNED_FILE)
3608 -
3609 - # Obsługa lokalnych plików .pkg.tar.xz (zbudowanych przez pagbuild) –
3610 - # nie wymaga repozytorium ani GPG.
3611 - local_files = [p for p in package_names if p.endswith(PKG_EXT) or
3612 - (os.sep in p and os.path.isfile(os.path.abspath(p)))]
3613 - if local_files:
3614 - _local_need = sum(
3615 - os.path.getsize(os.path.abspath(p))
3616 - for p in local_files if os.path.isfile(os.path.abspath(p))
3617 - )
3618 - if not _preflight_disk(_local_need):
3619 - return 1
3620 -
3621 - def _ok(pkg, files):
3622 - installed_db[pkg.name] = {
3623 - "version": pkg.version, "release": pkg.release, "description": pkg.description,
3624 - "dependencies": pkg.dependencies, "size_bytes": pkg.size_bytes,
3625 - "sha256": pkg.sha256, "installed_at": datetime.now().isoformat(),
3626 - "repo": "local",
3627 - "provides": getattr(pkg, "provides", None) or [],
3628 - "provides_so": getattr(pkg, "provides_so", None) or [],
3629 - "requires_so": getattr(pkg, "requires_so", None) or [],
3630 - }
3631 - world.add(pkg.name)
3632 - failed_local, _fl = _install_local_pkg_files(local_files, _ok)
3633 - save_json(INSTALLED_DB, installed_db)
3634 - save_world(world)
3635 - if failed_local:
3636 - return 1
3637 - _refresh_dynamic_linker_cache()
3638 - package_names = [n for n in package_names if n not in
3639 - [os.path.abspath(x) for x in local_files] and
3640 - n not in local_files]
3641 - to_install = []
3642 - if not package_names:
3643 - return 0
3644 - # pozostałe argumenty to nazwy pakietów z repo – kontynuuj
3645 -
3646 - repo_pkgs = fetch_all_packages()
3647 -
3648 - if not repo_pkgs:
3649 - print(f"❌ {_('no_index')}"); return 1
3650 -
3651 - for name in list(package_names):
3652 - if name in pinned:
3653 - print(f"⚠ {name} {_('pinned_to')} {pinned[name]} – skipping")
3654 - package_names.remove(name)
3655 -
3656 - to_install, missing_deps = _resolve_deps(package_names, repo_pkgs, installed_db)
3657 -
3658 - # ── Pakiety, których NIE MA w repo ani nie są zainstalowane ──
3659 - # Zgłoś od razu zamiast mylącego „Do zainstalowania: N (0.00 MB)”
3660 - # i prośby o potwierdzenie (np. `pag install steam` gdy steam nie istnieje).
3661 - not_found = []
3662 - for n in package_names:
3663 - real = _resolve_provides(n, repo_pkgs, installed_db)
3664 - if real not in repo_pkgs and real not in installed_db \
3665 - and not os.path.exists(os.path.abspath(n)):
3666 - not_found.append(n)
3667 - if not_found:
3668 - print(f"\n ❌ {_('pkg_not_found', ', '.join(not_found))}")
3669 - print(f" {_('not_found_hint')}")
3670 - return 1
3671 -
3672 - # --- Tryb upgrade: pakiety już zainstalowane MUSZĄ zostać ponownie
3673 - # zainstalowane z nowszej wersji (zastąpienie w tej samej transakcji).
3674 - if upgrade:
3675 - # `pag update` przekazuje tu tylko pakiety z NOWSZĄ wersją (już
3676 - # przefiltrowane w _pending_updates), a `pag install -f` wymusza
3677 - # reinstalację nawet tej SAMEJ wersji – dlatego nie filtrujemy po
3678 - # _version_newer.
3679 - upgrade_targets = [
3680 - name for name in package_names
3681 - if name in repo_pkgs
3682 - and name in installed_db
3683 - and name not in pinned
3684 - ]
3685 - for name in upgrade_targets:
3686 - if name not in to_install:
3687 - to_install.append(name)
3688 -
3689 - if not to_install and not missing_deps:
3690 - print(f"✅ {_('all_installed')}"); return 0
3691 -
3692 - # ── WERYFIKACJA ZALEŻNOŚCI ──────────────────────────────────────────
3693 - fatal_missing = _verify_dependencies(to_install, repo_pkgs, installed_db)
3694 -
3695 - if fatal_missing > 0:
3696 - print(f"❌ Nie można kontynuować – {fatal_missing} brakujących zależności.")
3697 - print(f" Zainstaluj brakujące pakiety lub dodaj repozytoria.")
3698 - return 1
3699 -
3700 - so_missing = _verify_so_deps(to_install, repo_pkgs, installed_db)
3701 - if so_missing > 0:
3702 - print(" Zainstaluj dostawcę biblioteki lub zaktualizuj repozytorium.")
3703 - return 1
3704 -
3705 - if not to_install:
3706 - print(f"✅ {_('all_installed')}"); return 0
3707 -
3708 - MAX_MB = MAX_PKG_SIZE // 1048576
3709 - for n in to_install:
3710 - if not _validate_pkg_name(n):
3711 - print(f" {_("sec_badname", name=n)}")
3712 - return 1
3713 - sz = repo_pkgs[n].size_bytes if n in repo_pkgs else 0
3714 - if sz > MAX_PKG_SIZE:
3715 - mb = sz // 1048576
3716 - print(f" {_("sec_toobig", size_mb=mb, max_mb=MAX_MB)}")
3717 - return 1
3718 - total_size = sum(repo_pkgs[n].size_bytes for n in to_install if n in repo_pkgs)
3719 - if not _preflight_disk(total_size):
3720 - return 1
3721 - print(f"\n📦 {_('to_install', len(to_install), total_size/1048576)}")
3722 - for name in to_install:
3723 - p = repo_pkgs.get(name)
3724 - if p:
3725 - if name in installed_db:
3726 - marker = " [upgrade]" if upgrade else ""
3727 - else:
3728 - marker = f" [{_('new')}]"
3729 - print(f" {name}-{p.version}{marker}")
3730 -
3731 - # Pakiet z bazy obrazu ISO (nie w installed.json) → ostrzeż, że pliki z ISO
3732 - # zostaną zastąpione pakietem z repo (kopia do `pag rollback`).
3733 - _base_warn_overwrite(to_install)
3734 -
3735 - if not as_dep and not upgrade:
3736 - if not _ask_confirm():
3737 - print(_("cancelled")); return 0
3738 -
3739 - # `--dry-run`: pokaż plan i wyjdź. Nic nie jest pobierane, rozpakowywane
3740 - # ani zmieniane – bezpieczne sprawdzenie, co zrobiłaby transakcja.
3741 - if os.environ.get("PAG_DRY_RUN", "") == "1":
3742 - print(f"\n 🧪 {_('dry_run_plan')}")
3743 - for _n in to_install:
3744 - _p = repo_pkgs.get(_n)
3745 - if _p:
3746 - _mark = " [upgrade]" if _n in installed_db else f" [{_('new')}]"
3747 - print(f" {_n}-{_p.version}{_mark}")
3748 - print(f" {_('dry_run_done')}")
3749 - return 0
3750 -
3751 - snapshot = copy.deepcopy(installed_db)
3752 - all_installed_files = []
3753 - failed = []
3754 - # Pary (pkg, stare_pliki, nowe_pliki) do usunięcia martwych plików po upgrade
3755 - stale_candidates = []
3756 - # Katalog backupów nadpisywanych plików – dla poprawnego rollbacku.
3757 - # Dla KAŻDEJ transakcji: instalacja „nowego” pakietu także nadpisuje pliki
3758 - # spoza bazy pag (baza rootfs/ISO), a rollback bez backupu by je skasował.
3759 - backup_root = ""
3760 - all_backups: List[Tuple[str, str]] = [] # (backup_path, dst)
3761 - if to_install:
3762 - backup_root = _new_transaction_backup_root()
3763 -
3764 - # --- Dziennik transakcji (dla pełnej atomowości) ---
3765 - # Jeśli którykolwiek pakiet zawiedzie, cofamy WSZYSTKIE zainstalowane
3766 - # w tej transakcji przez _rollback_transaction().
3767 - transaction_journal: List[Tuple[str, str, str]] = [] # (op, src, dst)
3768 -
3769 - # --- Tryb immutable: utwórz nowy deployment ---
3770 - immutable = os.environ.get("PAG_IMMUTABLE", "") == "1"
3771 - deploy_dir = ""
3772 - deploy_id = ""
3773 - if immutable:
3774 - print(f"\n 🏗️ Tworzenie nowego deploymentu...")
3775 - deploy_dir, deploy_id = _create_deployment(to_install, "upgrade" if upgrade else "install")
3776 - target_root = deploy_dir
3777 - else:
3778 - target_root = ""
3779 -
3780 - # --- Faza 1: Równoległe pobieranie wszystkich pakietów ---
3781 - to_download = [repo_pkgs[name] for name in to_install if name in repo_pkgs]
3782 - if len(to_download) > 1:
3783 - print(f"\n ⏬ Pobieranie {len(to_download)} pakietów równolegle...")
3784 - downloaded = _download_packages_parallel(to_download)
3785 - else:
3786 - downloaded = {}
3787 -
3788 - # --- Faza 1b: WERYFIKACJA WSZYSTKICH paczek PRZED instalacją ---
3789 - # KLUCZOWE: GPG i SHA256 sprawdzamy dla WSZYSTKICH paczek, ZANIM
3790 - # zainstalujemy choćby jedną. Inaczej instalowany pakiet może podmienić
3791 - # bibliotekę używaną przez sam gpg (np. libassuan 3.0.1 zmienił namespace
3792 - # symboli LIBASSUAN_1.0 -> LIBASSUAN_2.0) i wtedy weryfikacja kolejnych
3793 - # paczek w tej samej transakcji pada, dając fałszywe
3794 - # „NIEPRAWIDŁOWY PODPIS GPG".
3795 - verified = {}
3796 - _vfail = []
3797 - for _name in to_install:
3798 - _pkg = repo_pkgs.get(_name)
3799 - if not _pkg:
3800 - _vfail.append((_name, _('not_found')))
3801 - continue
3802 - _pp = downloaded.get(_name)
3803 - if not _pp:
3804 - _pp = _download_pkg(_pkg)
3805 - if not _pp:
3806 - _vfail.append((_name, _('download_fail')))
3807 - continue
3808 - _gok, _gmsg = _verify_pkg_gpg(_pp, repo_url=_pkg.repo_url)
3809 - if not _gok:
3810 - _vfail.append((_name, f"{_('gpg_fail')}: {_gmsg[:60]}"))
3811 - continue
3812 - if _pkg.sha256 and _sha256_file(_pp) != _pkg.sha256:
3813 - _vfail.append((_name, _('sha256_mismatch')))
3814 - continue
3815 - verified[_name] = _pp
3816 - if _vfail:
3817 - for _n, _m in _vfail:
3818 - print(f" ❌ {_n}: {_m}")
3819 - print(" ↩ Przerwano PRZED instalacją – żadna paczka nie została zmieniona.")
3820 - return 1
3821 -
3822 - # --- Snapshot systemu PRZED transakcją (btrfs CoW) ---
3823 - # Tworzymy go PO pobraniu i weryfikacji paczek, ale PRZED rozpakowaniem
3824 - # czegokolwiek do systemu. Domyślnie `auto`: tylko na btrfs. `--snapshot`
3825 - # wymusza migawkę (i przerywa, gdy się nie uda), `--no-snapshot` wyłącza.
3826 - snapshot_mode = (os.environ.get("PAG_SNAPSHOT") or "auto").strip().lower()
3827 - sys_snap: Optional[dict] = None
3828 - if to_install and snapshot_mode not in ("never", "no", "0", "off"):
3829 - _snap_ok, _snap_why = _snapshot_support()
3830 - if _snap_ok:
3831 - sys_snap = _create_system_snapshot(
3832 - to_install, "upgrade" if upgrade else "install")
3833 - if sys_snap:
3834 - _refresh_bootloader()
3835 - elif snapshot_mode in ("always", "require", "1", "yes"):
3836 - print(" ❌ Nie udało się utworzyć snapshotu (tryb --snapshot) – przerywam.")
3837 - return 1
3838 - elif snapshot_mode in ("always", "require", "1", "yes"):
3839 - print(f" ❌ {_('snapshot_unsupported', _snap_why)}")
3840 - return 1
3841 - else:
3842 - print(f" ℹ {_('snapshot_unsupported', _snap_why)}")
3843 -
3844 - # --- Faza 1c: PRZYGOTOWANIE CAŁEJ GRUPY W STAGINGU ---
3845 - # Rozpakowujemy WSZYSTKIE pakiety do `/.pag_staging/.stage-*`, zanim
3846 - # dotkniemy systemu. Jeśli jedna z 50 paczek (np. GNOME) jest uszkodzona,
3847 - # transakcja kończy się tutaj – na dysku nie ma żadnych zmian.
3848 - atomic = os.environ.get("PAG_ATOMIC", "1") != "0"
3849 - staged_pkgs: List[Tuple[str, PackageInfo, Optional[dict]]] = []
3850 - if atomic and to_install:
3851 - print(f"\n 🧰 {_('staging_prepare', len(to_install))}")
3852 - _sbar = _StepBar(len(to_install), icon="🧰 ", width=25)
3853 - _stage_failed: List[str] = []
3854 - for _si, _name in enumerate(to_install, 1):
3855 - _pkg = repo_pkgs.get(_name)
3856 - _pp = verified.get(_name)
3857 - if not _pkg or not _pp:
3858 - _stage_failed.append(_name)
3859 - break
3860 - _sbar.step(_si, f"{_name}-{_pkg.version}")
3861 - _st = _stage_package(_pp, _pkg)
3862 - if not _st:
3863 - _stage_failed.append(_name)
3864 - break
3865 - staged_pkgs.append((_name, _pkg, _st))
3866 - _sbar.end()
3867 - if _stage_failed:
3868 - for _n, _p, _st in staged_pkgs:
3869 - _discard_staged(_st)
3870 - print(f" ↩ {_('staging_failed')}")
3871 - if backup_root:
3872 - shutil.rmtree(backup_root, ignore_errors=True)
3873 - _record_transaction("upgrade" if upgrade else "install", to_install, False,
3874 - snapshot,
3875 - snapshot_id=sys_snap["id"] if sys_snap else "")
3876 - return 1
3877 - print(f" ✅ {_('staging_commit')}")
3878 - elif to_install:
3879 - staged_pkgs = [(n, repo_pkgs[n], None) for n in to_install]
3880 -
3881 - # --- Faza 2: Instalacja – JEDNA nadpisywana linia postępu (jak przy
3882 - # pobieraniu), bez ściany tekstu na każdy pakiet. W trybie
3883 - # nieinteraktywnym (logi, netinstall instalatora) wypisujemy linię na
3884 - # pakiet – tam to pożądane do logu.
3885 - t0 = time.time()
3886 - stdout_tty = sys.stdout.isatty()
3887 -
3888 - # Animowany pasek postępu („drakkar”) – jedna nadpisywana linia; morze
3889 - # faluje nawet wtedy, gdy pojedynczy pakiet instaluje się długo.
3890 - _pbar = _StepBar(len(to_install), icon="📦 ", width=25)
3891 -
3892 - def _bar_draw(idx: int, name: str) -> None:
3893 - _pbar.step(idx, name)
3894 -
3895 - def _bar_end() -> None:
3896 - _pbar.end()
3897 -
3898 - for _pkg_i, (name, pkg, _staged) in enumerate(staged_pkgs, 1):
3899 - if not pkg:
3900 - _bar_end()
3901 - print(f" ❌ {name}: {_('not_found')}")
3902 - failed.append(name)
3903 - break
3904 -
3905 - _bar_draw(_pkg_i, f"{name}-{pkg.version}")
3906 -
3907 - # Przed instalacją zapamiętaj pliki starej wersji (potrzebne w upgrade)
3908 - old_files = _db_get_package_files(name) if name in installed_db else []
3909 - # Stare sumy SHA256 – do wykrycia zmian użytkownika w plikach /etc (.pacnew)
3910 - old_checksums = _db_get_package_checksums(name) if name in installed_db else None
3911 -
3912 - # Commit przygotowanego pakietu (w upgrade backupuje nadpisywane pliki).
3913 - # Tryb `PAG_ATOMIC=0` zachowuje starą ścieżkę pojedynczą (staging per pakiet).
3914 - if _staged is not None:
3915 - ok, files, backup_j = _apply_staged_package(
3916 - _staged, pkg, deploy_dir,
3917 - backup_dir=backup_root,
3918 - old_checksums=old_checksums)
3919 - else:
3920 - # Ścieżka pobrana i ZWERYFIKOWANA w fazie 1b.
3921 - pkg_path = verified.get(name)
3922 - if not pkg_path:
3923 - _bar_end()
3924 - print(f" ❌ {name}: {_('download_fail')}")
3925 - failed.append(name)
3926 - break # przerwij transakcję
3927 - ok, files, backup_j = _atomic_install(
3928 - pkg_path, pkg, deploy_dir,
3929 - backup_dir=backup_root,
3930 - old_checksums=old_checksums)
3931 - if ok:
3932 - installed_db[name] = {
3933 - "version": pkg.version, "release": pkg.release, "description": pkg.description,
3934 - "dependencies": pkg.dependencies, "size_bytes": pkg.size_bytes,
3935 - "sha256": pkg.sha256, "installed_at": datetime.now().isoformat(),
3936 - "repo": pkg.repo_url,
3937 - "provides": getattr(pkg, "provides", None) or [],
3938 - "provides_so": getattr(pkg, "provides_so", None) or [],
3939 - "requires_so": getattr(pkg, "requires_so", None) or [],
3940 - }
3941 - if not as_dep and name in package_names:
3942 - world.add(name)
3943 - if not stdout_tty:
3944 - print(f" ✓ {name}-{pkg.version}", flush=True)
3945 - all_installed_files.extend(f["path"] for f in files)
3946 - all_backups.extend(backup_j)
3947 -
3948 - # Upgrade: zapamiętaj stare pliki, by po sukcesie usunąć te,
3949 - # których nie ma już w nowej wersji.
3950 - if upgrade and old_files:
3951 - stale_candidates.append((name, old_files, [f["path"] for f in files]))
3952 -
3953 - # Po instalacji kernela – przebuduj initramfs
3954 - if _is_kernel_package(name):
3955 - _rebuild_initramfs(deploy_dir)
3956 - else:
3957 - _bar_end()
3958 - print(f" ❌ {name}: {_('install_failed')}")
3959 - failed.append(name)
3960 - break # PRZERWIJ – błąd instalacji
3961 -
3962 - # Deduplikacja journalu – ten sam plik może trafić tu dwukrotnie (np. przez
3963 - # `provides`); rollback i historia nie potrzebują duplikatów.
3964 - all_installed_files = list(dict.fromkeys(all_installed_files))
3965 -
3966 - # --- Rollback całej transakcji jeśli cokolwiek zawiodło ---
3967 - if failed:
3968 - _bar_end()
3969 - print(f"\n ↩ Cofanie transakcji ({len(failed)} błędów)...")
3970 - for _n, _p, _st in staged_pkgs:
3971 - _discard_staged(_st)
3972 - _rollback_transaction(installed_db, snapshot, all_installed_files,
3973 - deploy_dir, immutable, backups=all_backups)
3974 - if backup_root:
3975 - shutil.rmtree(backup_root, ignore_errors=True)
3976 - _record_transaction("upgrade" if upgrade else "install", to_install, False,
3977 - snapshot,
3978 - snapshot_id=sys_snap["id"] if sys_snap else "")
3979 - return 1
3980 -
3981 - save_json(INSTALLED_DB, installed_db)
3982 - save_world(world)
3983 -
3984 - # --- Po ZAPISANIU bazy: usuń nieaktualne pliki starych wersji (upgrade).
3985 - # Kolejność ma znaczenie: najpierw utrwalamy stan nowej wersji w bazie, a
3986 - # dopiero potem kasujemy pliki, których nowa wersja nie zawiera. Odwrotna
3987 - # kolejność (kasowanie przed zapisem) przy przerwaniu zostawiała system bez
3988 - # plików. Usunięte pliki trafiają do backupu, aby `pag rollback` mógł je
3989 - # przywrócić.
3990 - for pkg_name, old_files, new_paths in stale_candidates:
3991 - _remove_stale_files(pkg_name, old_files, new_paths, installed_db, deploy_dir,
3992 - backup_root, all_backups)
3993 - _record_transaction("upgrade" if upgrade else "install", to_install, True, snapshot,
3994 - file_journal=all_installed_files,
3995 - upgrade_backups={dst: bp for bp, dst in all_backups} if all_backups else None,
3996 - upgrade_backup_root=backup_root,
3997 - snapshot_id=sys_snap["id"] if sys_snap else "")
3998 -
3999 - # Zachowaj backupy bieżącej transakcji (dla `pag rollback`), usuń starsze.
4000 - if backup_root:
4001 - _purge_old_backups(keep_root=backup_root)
4002 -
4003 - _bar_end()
4004 -
4005 - # --- Tryb immutable: przełącz na nowy deployment ---
4006 - if immutable and not failed:
4007 - _refresh_dynamic_linker_cache(deploy_dir)
4008 - print(f"\n 🔄 Przełączanie na deployment {deploy_id}...")
4009 - _switch_deployment(deploy_dir)
4010 - print(f" ✅ Aktywny deployment: {deploy_id}")
4011 - _update_grub_config()
4012 - cmd_deploy_cleanup(keep=5) # Zostawia 5 najnowszych deploymentów
4013 - print(f" 💡 Restart wymagany do przeładowania systemu.")
4014 - else:
4015 - _refresh_dynamic_linker_cache()
4016 - # Hooki zbiorcze – raz na transakcję (fc-cache itp.), tylko gdy pliki
4017 - # trafiły do realnego systemu (nie do deploymentu).
4018 - _process_triggers(all_installed_files)
4019 - # Jądro zmienione na ZWYKŁEJ instalacji → odśwież GRUB (hook pakietu
4020 - # nie może: trzymany lock PAG-a). Bez tego menu zostaje przy starym jądrze.
4021 - if any(_is_kernel_package(_n) for _n in to_install):
4022 - _post_kernel_hooks()
4023 - elif sys_snap:
4024 - # Snapshot istnieje, ale nie było zmiany jądra – odśwież menu GRUB,
4025 - # żeby wpis migawki był widoczny przy najbliższym starcie.
4026 - _ensure_snapshot_grub_script()
4027 - _refresh_bootloader()
4028 -
4029 - print(f"\n✅ {_('installed', len(to_install))} ({(time.time()-t0):.0f}s)")
4030 - return 0
4031 -
4032 -
4033 -def _rollback_transaction(installed_db: dict, snapshot: dict,
4034 - installed_files: List[str],
4035 - deploy_dir: str, is_immutable: bool,
4036 - backups: Optional[List[Tuple[str, str]]] = None):
4037 - """
4038 - Cofa WSZYSTKIE pakiety zainstalowane w bieżącej transakcji.
4039 - Przywraca installed_db do stanu sprzed transakcji.
4040 - Usuwa fizyczne pliki z systemu (lub deploymentu w trybie immutable).
4041 - Jeśli podano `backups` (upgrade) – przywraca stare wersje nadpisanych plików.
4042 - """
4043 - # Przywróć installed_db
4044 - installed_db.clear()
4045 - installed_db.update(snapshot)
4046 -
4047 - root = deploy_dir if is_immutable else PAG_ROOT
4048 - backup_map = {dst: src for src, dst in (backups or [])}
4049 -
4050 - # Przywróć stare wersje z backupów (upgrade)
4051 - for dst, bpath in backup_map.items():
4052 - full = os.path.join(root, dst.lstrip("/"))
4053 - if os.path.lexists(bpath):
4054 - try:
4055 - os.makedirs(os.path.dirname(full), exist_ok=True)
4056 - os.replace(bpath, full)
4057 - except OSError:
4058 - pass
4059 -
4060 - # Usuń nowe pliki (które nie miały poprzedniej wersji)
4061 - for fpath in reversed(installed_files):
4062 - if fpath in backup_map:
4063 - continue
4064 - full = os.path.join(root, fpath.lstrip("/"))
4065 - if os.path.isfile(full) or os.path.islink(full):
4066 - try:
4067 - os.remove(full)
4068 - except OSError:
4069 - pass
4070 -
4071 - # Wyczyść puste katalogi
4072 - dirs_to_check = set()
4073 - for fpath in installed_files:
4074 - parent = os.path.dirname(fpath)
4075 - while parent and parent != "/":
4076 - dirs_to_check.add(parent)
4077 - parent = os.path.dirname(parent)
4078 - for d in sorted(dirs_to_check, key=len, reverse=True):
4079 - full_d = os.path.join(root, d.lstrip("/"))
4080 - if os.path.isdir(full_d):
4081 - try:
4082 - os.rmdir(full_d)
4083 - except OSError:
4084 - pass
4085 -
4086 - # W trybie immutable: usuń nieudany deployment
4087 - if is_immutable and deploy_dir:
4088 - shutil.rmtree(deploy_dir, ignore_errors=True)
4089 -
4090 - save_json(INSTALLED_DB, snapshot)
4091 -
4092 -
4093 -# =============================================================================
4094 -# USUWANIE
4095 -# =============================================================================
4096 -
4097 -def cmd_remove(package_names):
4098 - installed_db = load_json(INSTALLED_DB)
4099 - world = load_world()
4100 - snapshot = copy.deepcopy(installed_db)
4101 - removed = []
4102 - removed_files = []
4103 -
4104 - total = len(package_names)
4105 - for i, name in enumerate(package_names, 1):
4106 - if name not in installed_db:
4107 - print(f" ⚠ {name}: not installed"); continue
4108 -
4109 - # Pasek postępu (animowany „drakkar” na TTY)
4110 - pct = (i - 1) / total * 100
4111 - bar = _pagan_bar(pct, 25, time.time(), animated=sys.stderr.isatty())
4112 - print(f" 🗑 [{bar}] {i}/{total} ({pct:.0f}%) ", end="\r", file=sys.stderr, flush=True)
4113 -
4114 - print(f"🗑 {name}-{installed_db[name]['version']} ...", end=" ", flush=True)
4115 -
4116 - # Pre-remove hook (jeśli dostępny w staging)
4117 - _run_hook_for_installed(name, "pre-remove")
4118 -
4119 - count, rm_files = _safe_remove_files(name, installed_db)
4120 - del installed_db[name]
4121 - world.discard(name)
4122 - removed.append(name)
4123 - removed_files.extend(rm_files)
4124 - print(f"✅ ({count} files)")
4125 -
4126 - # Post-remove hook + sprzątanie zapisanych hooków
4127 - _run_hook_for_installed(name, "post-remove")
4128 - shutil.rmtree(os.path.join(PAG_DB, "hooks", name), ignore_errors=True)
4129 -
4130 - save_json(INSTALLED_DB, installed_db)
4131 - save_world(world)
4132 - _record_transaction("remove", removed, True, snapshot)
4133 -
4134 - print(file=sys.stderr) # wyczyść linię paska postępu
4135 -
4136 - if not removed: return 0
4137 - print(f"\n✅ Removed {len(removed)}.")
4138 - _process_triggers(removed_files)
4139 -
4140 - orphans = _find_orphans(installed_db, world)
4141 - if orphans:
4142 - print(f"\n💡 {_('orphans_found', len(orphans), ', '.join(sorted(orphans)[:10]))}")
4143 - print(" 'pag remove-orphans' to clean up.")
4144 - return 0
4145 -
4146 -def _run_hook_for_installed(pkg_name, hook_name):
4147 - """Próbuje uruchomić hook z katalogu pakietu (jeśli został zapisany)."""
4148 - hook_dir = os.path.join(PAG_DB, "hooks", pkg_name)
4149 - if os.path.isdir(hook_dir):
4150 - ver = load_json(INSTALLED_DB).get(pkg_name, {}).get("version", "")
4151 - _run_hook(hook_dir, hook_name, PackageInfo({"name": pkg_name, "version": ver}))
4152 -
4153 -
4154 -# =============================================================================
4155 -# TRIGGERS – hooki zbiorcze (raz na transakcję, nie per pakiet)
4156 -# =============================================================================
4157 -# Wzorem pacman/dpkg: pakiet/administrator deklaruje zainteresowanie ścieżkami,
4158 -# a pasujący trigger uruchamia się DOKŁADNIE RAZ na końcu transakcji
4159 -# (np. fc-cache, glib-compile-schemas, update-desktop-database) zamiast po
4160 -# każdym pakiecie z osobna.
4161 -
4162 -TRIGGERS_DIR = PAG_CONF + "/triggers"
4163 -
4164 -DEFAULT_TRIGGERS = [
4165 - {"name": "font-cache", "paths": ["/usr/share/fonts/", "/usr/local/share/fonts/"],
4166 - "run": "fc-cache -fs"},
4167 - {"name": "glib-schemas", "paths": ["/usr/share/glib-2.0/schemas/"],
4168 - "run": "glib-compile-schemas /usr/share/glib-2.0/schemas"},
4169 - {"name": "desktop-database", "paths": ["/usr/share/applications/"],
4170 - "run": "update-desktop-database -q /usr/share/applications"},
4171 - {"name": "mime-database", "paths": ["/usr/share/mime/"],
4172 - "run": "update-mime-database /usr/share/mime"},
4173 - {"name": "systemd-daemon-reload", "paths": ["/usr/lib/systemd/system/"],
4174 - "run": "systemctl daemon-reload"},
4175 - {"name": "systemd-user-daemon-reload", "paths": ["/usr/lib/systemd/user/"],
4176 - "run": "systemctl --global daemon-reload"},
4177 - {"name": "udev-reload", "paths": ["/usr/lib/udev/rules.d/"],
4178 - "run": "udevadm control --reload-rules"},
4179 -]
4180 -
4181 -def _load_triggers() -> List[dict]:
4182 - """Ładuje triggery: domyślne (tylko gdy binarka istnieje) + /etc/pag/triggers/*.json."""
4183 - out = []
4184 - for t in DEFAULT_TRIGGERS:
4185 - bin_name = t["run"].split()[0]
4186 - if shutil.which(bin_name):
4187 - out.append(dict(t))
4188 - if os.path.isdir(TRIGGERS_DIR):
4189 - for fn in sorted(os.listdir(TRIGGERS_DIR)):
4190 - if not fn.endswith(".json"):
4191 - continue
4192 - try:
4193 - with open(os.path.join(TRIGGERS_DIR, fn)) as f:
4194 - data = json.load(f)
4195 - except (OSError, json.JSONDecodeError):
4196 - continue
4197 - if isinstance(data, dict):
4198 - data = [data]
4199 - for t in data:
4200 - if isinstance(t, dict) and t.get("name") and t.get("paths") and t.get("run"):
4201 - out.append(t)
4202 - return out
4203 -
4204 -def _reload_user_media_services(touched_paths: List[str]) -> None:
4205 - """Po aktualizacji multimediow przeladuj uslugi UZYTKOWNIKA (pipewire/wireplumber).
4206 -
4207 - Nowe binarki/moduly sa juz na dysku, ale dzialajace sesje maja stare w
4208 - pamieci i probuja ladowac nieistniejace wersje modulow. Best-effort:
4209 - `systemctl --global daemon-reload` + try-restart w kazdej aktywnej sesji.
4210 - """
4211 - if os.environ.get("PAG_NO_HOOKS", "") == "1":
4212 - return
4213 - _pfx = ("/usr/lib/systemd/user/pipewire", "/usr/lib/systemd/user/wireplumber",
4214 - "/usr/bin/pipewire", "/usr/bin/wireplumber",
4215 - "/usr/lib/pipewire-0.3/", "/usr/lib64/pipewire-0.3/",
4216 - "/usr/lib/wireplumber-0.5/", "/usr/lib64/wireplumber-0.5/")
4217 - if not any(_p.startswith(_x) for _x in _pfx for _p in touched_paths):
4218 - return
4219 - try:
4220 - subprocess.run(["systemctl", "--global", "daemon-reload"],
4221 - capture_output=True, timeout=60)
4222 - except Exception:
4223 - pass
4224 - try:
4225 - _r = subprocess.run(["loginctl", "list-users", "--no-legend"],
4226 - capture_output=True, text=True, timeout=30)
4227 - _users = [ln.split()[1] for ln in (_r.stdout or "").splitlines()
4228 - if len(ln.split()) >= 2]
4229 - except Exception:
4230 - _users = []
4231 - _done = []
4232 - for _u in _users:
4233 - try:
4234 - _rr = subprocess.run(
4235 - ["su", "-", _u, "-c",
4236 - "systemctl --user try-restart pipewire.socket pipewire.service "
4237 - "wireplumber.service"],
4238 - capture_output=True, timeout=60)
4239 - if _rr.returncode == 0:
4240 - _done.append(_u)
4241 - except Exception:
4242 - pass
4243 - if _done:
4244 - print(" \u26a1 przeladowano uslugi audio dla sesji: "
4245 - + ", ".join(sorted(set(_done))))
4246 -
4247 -def _process_triggers(touched_paths: List[str]):
4248 - """Uruchamia pasujące triggery RAZ na końcu transakcji (best-effort)."""
4249 - if not touched_paths:
4250 - return
4251 - if os.environ.get("PAG_NO_HOOKS", "") == "1":
4252 - return
4253 - import shlex as _shlex
4254 - matched = []
4255 - for trig in _load_triggers():
4256 - if any(path.startswith(p) for p in trig["paths"] for path in touched_paths):
4257 - matched.append(trig)
4258 - for trig in matched:
4259 - run = trig["run"]
4260 - print(f" ⚡ Trigger: {trig['name']} ({run})")
4261 - try:
4262 - r = subprocess.run(_shlex.split(run), capture_output=True, text=True, timeout=120)
4263 - _audit(f"TRIGGER {trig['name']}: {run} rc={r.returncode}")
4264 - if r.returncode != 0:
4265 - print(f" ⚠ rc={r.returncode}: {(r.stderr or r.stdout or '').strip()[:160]}")
4266 - except subprocess.TimeoutExpired:
4267 - print(f" ⚠ trigger {trig['name']} przekroczył limit czasu (120 s)")
4268 - _audit(f"TRIGGER {trig['name']} TIMEOUT")
4269 - except Exception as e:
4270 - print(f" ⚠ trigger {trig['name']}: {e}")
4271 - _reload_user_media_services(touched_paths)
4272 -
4273 -
4274 -# =============================================================================
4275 -# UPDATE / UPGRADE / LIST / SEARCH / INFO / VERIFY
4276 -# =============================================================================
4277 -
4278 -def _cleanup_tmp_files(*paths):
4279 - """Usuwa tymczasowe pliki (np. .pag.new) po nieudanej operacji."""
4280 - for p in paths:
4281 - try:
4282 - if os.path.isfile(p):
4283 - os.remove(p)
4284 - except OSError:
4285 - pass
4286 -
4287 -
4288 -def cmd_self_update():
4289 - """Aktualizuje samego klienta pag z repo (podpisany /stable/pag).
4290 -
4291 - Kolejność: pobierz → weryfikacja GPG (+ fingerprint repo) → SHA256 →
4292 - kontrola składni (compile) → backup → atomowe os.replace.
4293 -
4294 - Podmieniamy plik, z którego pag ZOSTAŁ URUCHOMIONY (a nie hardkodowane
4295 - /usr/local/bin/pag): gdy pakiet instaluje /usr/bin/pag, a self-update
4296 - pisał do /usr/local/bin/pag, powstawały DWIE kopie o różnych wersjach
4297 - i zależnie od PATH `pag --version` pokazywał raz jedną, raz drugą."""
4298 - # Dedykowana blokada – patrz SelfUpdateLock. Chroni zapis dst.new oraz
4299 - # os.replace przed równoległą aktualizacją (np. cron + ręcznie).
4300 - with SelfUpdateLock():
4301 - return _self_update_impl()
4302 -
4303 -
4304 -def _self_update_impl():
4305 - repos = get_repos()
4306 - if not repos:
4307 - print("❌ Brak repozytoriów w konfiguracji.")
4308 - return 1
4309 - # Aktualizuj bieżący plik (Python ≥3.9 ustawia __file__ jako ścieżkę
4310 - # bezwzględną). Poza /usr|/usr/local (np. uruchomienie z checkoutu)
4311 - # nie nadpisujemy niczego – wracamy do domyślnej lokalizacji instalacji.
4312 - dst = "/usr/local/bin/pag"
4313 - try:
4314 - cand = os.path.realpath(__file__)
4315 - if cand.startswith(("/usr/", "/usr/local/")):
4316 - dst = cand
4317 - except Exception:
4318 - pass
4319 - base = repos[0]
4320 - dst_new = dst + ".new"
4321 - dst_bak = dst + ".bak"
4322 - print(f"🔄 Sprawdzam aktualizację pag z {base}...")
4323 - try:
4324 - with urlopen(Request(f"{base}/pag", headers={"User-Agent": "pag/3.0"}), timeout=20) as r:
4325 - data = r.read()
4326 - with urlopen(Request(f"{base}/pag.asc", headers={"User-Agent": "pag/3.0"}), timeout=20) as r:
4327 - sig = r.read()
4328 - except Exception as e:
4329 - print(f" ❌ Nie można pobrać pag: {e}")
4330 - return 1
4331 -
4332 - # Zapisz nową wersję w katalogu docelowym (ta sama partycja → atomowy rename)
4333 - with open(dst_new, "wb") as f:
4334 - f.write(data)
4335 - with open(dst_new + ".asc", "wb") as f:
4336 - f.write(sig)
4337 -
4338 - # --- 1. Weryfikacja podpisu GPG – bez tego nie instalujemy ---
4339 - insecure = os.environ.get("PAG_INSECURE", "") == "1"
4340 - ok, fp = _gpg_verify_fp(dst_new + ".asc", dst_new)
4341 - if not ok:
4342 - # Automatyczny import klucza (TOFU) – jak w _verify_repo_sig
4343 - res = _gpg_run("--verify", dst_new + ".asc", dst_new,
4344 - capture_output=True, text=True)
4345 - _stderr = res.stderr.decode(errors="replace") if isinstance(res.stderr, bytes) else (res.stderr or "")
4346 - if "public key" in _stderr.lower() and "no public key" in _stderr.lower():
4347 - try:
4348 - with urlopen(Request(f"{base}/paganos.asc", headers={"User-Agent": "pag/3.0"}), timeout=20) as r:
4349 - keydata = r.read()
4350 - with tempfile.NamedTemporaryFile(delete=False, suffix=".asc") as tmp:
4351 - tmp.write(keydata); tmp.flush()
4352 - _gpg_run("--import", tmp.name, capture_output=True, timeout=30)
4353 - os.unlink(tmp.name)
4354 - print(f" 🔑 Importowano klucz repo z {base}/paganos.asc")
4355 - ok, fp = _gpg_verify_fp(dst_new + ".asc", dst_new)
4356 - except Exception:
4357 - pass
4358 - if not ok:
4359 - if insecure:
4360 - print(" ⚠ Nieprawidłowy podpis aktualizacji (PAG_INSECURE – ignoruję)")
4361 - else:
4362 - print(" ❌ Nieprawidłowy podpis aktualizacji – nie aktualizuję.")
4363 - _cleanup_tmp_files(dst_new, dst_new + ".asc")
4364 - return 1
4365 - # Sprawdź fingerprint względem przypiętego klucza repo
4366 - pinned = _repo_pinned_fp(base)
4367 - if pinned:
4368 - if not fp:
4369 - print(" ❌ Nie można potwierdzić fingerprintu podpisu aktualizacji.")
4370 - _cleanup_tmp_files(dst_new, dst_new + ".asc")
4371 - return 1
4372 - if fp != pinned.upper():
4373 - if insecure:
4374 - print(" ⚠ Podpis aktualizacji innym kluczem (PAG_INSECURE – ignoruję)")
4375 - else:
4376 - print(" ❌ [SECURITY ERROR] Podpis aktualizacji innym kluczem niż repo!")
4377 - print(f" Oczekiwany: {pinned}, Otrzymany: {fp}")
4378 - _cleanup_tmp_files(dst_new, dst_new + ".asc")
4379 - return 1
4380 -
4381 - # --- 2. Weryfikacja SHA256 (jeśli repo publikuje pag.sha256) ---
4382 - try:
4383 - with urlopen(Request(f"{base}/pag.sha256", headers={"User-Agent": "pag/3.0"}), timeout=15) as r:
4384 - sha = r.read().decode().strip().split()[0]
4385 - if sha:
4386 - actual = hashlib.sha256(data).hexdigest()
4387 - if actual.lower() != sha.lower():
4388 - print(f" ❌ SHA256 niezgodny! Oczekiwano {sha}, jest {actual}")
4389 - _cleanup_tmp_files(dst_new, dst_new + ".asc")
4390 - return 1
4391 - print(" ✅ SHA256 zgodny")
4392 - except Exception:
4393 - # Brak pag.sha256 w repo – opcjonalne; nie blokuj aktualizacji.
4394 - pass
4395 -
4396 - # --- 3. Kontrola składni (nie uruchamiaj uszkodzonego/poddanego edycji pliku) ---
4397 - try:
4398 - compile(data, "pag", "exec")
4399 - except SyntaxError as e:
4400 - print(f" ❌ Błąd składni w nowym pag: {e}")
4401 - _cleanup_tmp_files(dst_new, dst_new + ".asc")
4402 - return 1
4403 -
4404 - m = (re.search(rb'PAG_VERSION\s*=\s*"(\d+\.\d+\.\d+[a-z]?)"', data[:3000])
4405 - or re.search(rb"v(\d+\.\d+\.\d+[a-z]?)", data[:3000]))
4406 - new_ver = m.group(1).decode() if m else "?"
4407 - print(f" ✅ Pobrano pag {new_ver} (obecny {PAG_VERSION}), podpis zweryfikowany")
4408 -
4409 - # --- 4. Backup + atomowa podmiana ---
4410 - if os.path.exists(dst):
4411 - shutil.copy2(dst, dst_bak)
4412 - os.chmod(dst_new, 0o755)
4413 - os.replace(dst_new, dst) # atomowe na tym samym FS
4414 - try:
4415 - if os.path.exists(dst_new + ".asc"):
4416 - os.remove(dst_new + ".asc")
4417 - except OSError:
4418 - pass
4419 - print(f" ✅ Zainstalowano nowy pag. Stary zachowany jako {dst_bak}")
4420 - # Ostrzeż, gdy w PATH pierwsza jest INNA kopia `pag` – inaczej
4421 - # `pag --version` dalej pokaże starą wersję i wygląda to jak brak update.
4422 - other = shutil.which("pag")
4423 - if other and os.path.realpath(other) != os.path.realpath(dst):
4424 - print(f" ⚠ W PATH pierwszy jest inny pag: {other} (zaktualizowano {dst})")
4425 - print(f" Usuń starą kopię: sudo rm {other}")
4426 - print(" Uruchom ponownie pag, aby użyć nowej wersji.")
4427 - return 0
4428 -
4429 -
4430 -def _candidate_newer(rp, inst):
4431 - """Czy pakiet z repo jest nowszy od zainstalowanego.
4432 - Porównuje (version, release): sam bump pkgrel (np. auto-rebuild modułów
4433 - po aktualizacji jądra: nvidia-kernel-618 610.57.04-1 -> -2) też musi być
4434 - widziany przez `pag update`. Stare rekordy instalacji (bez pola release)
4435 - traktujemy jak release=1 – nie generują churnu, dopóki nie wrócą do
4436 - reinstalacji/zmiany wersji."""
4437 - rv = getattr(rp, "version", "0")
4438 - iv = inst.get("version", "0")
4439 - if _version_newer(rv, iv):
4440 - return True
4441 - if rv != iv:
4442 - return False
4443 - rr = int(getattr(rp, "release", 1) or 1)
4444 - ir = int(inst.get("release", 1) or 1)
4445 - return rr > ir
4446 -
4447 -
4448 -def _pending_updates() -> List[str]:
4449 - """Zainstalowane pakiety z nowszą wersją/release w repo (bez przypiętych)."""
4450 - installed = load_json(INSTALLED_DB)
4451 - pinned = load_json(PINNED_FILE)
4452 - repo = fetch_all_packages()
4453 - if not repo:
4454 - return []
4455 - return [n for n, i in installed.items()
4456 - if n not in pinned and (rp := repo.get(n)) and _candidate_newer(rp, i)]
4457 -
4458 -# =============================================================================
4459 -# BAZA Z OBRAZU ISO → REPO (`pag base`) – pełny rolling
4460 -# =============================================================================
4461 -# ISO jest zbudowane ZE ŹRÓDEŁ (glibc, gcc, gtk, XFCE, …) – pag tych pakietów
4462 -# nie instalował, więc nie ma ich w installed.json/files.db. Skutki:
4463 -# • `pag upgrade` ich NIE dotyka (nie ma o nich pojęcia),
4464 -# • mimo to `pag install <nazwa>` je NADPISZE – pag robi kopię plików spoza
4465 -# swojej bazy (patrz _new_transaction_backup_root), więc nie są nietykalne.
4466 -#
4467 -# /usr/share/pag/base.json (wypalany przez build-pagan.sh) mówi, co jest w bazie
4468 -# obrazu i w jakiej wersji. `pag base` pokazuje stan, a `pag base adopt` dogrywa
4469 -# te pakiety z repo – po tym zabiegu pag zarządza nimi normalnie, więc
4470 -# `pag upgrade` aktualizuje CAŁY system (rolling), a nie tylko to, co sam
4471 -# wcześniej zainstalował.
4472 -#
4473 -# Nazwy z buildera różnią się od nazw pakietów w repo (builder buduje „libX11”,
4474 -# repo ma pakiet „xorg-libx11”), stąd aliasy poniżej. Nazwy bez odpowiednika
4475 -# w repo zostają w wersji z obrazu – raport mówi o tym wprost, zamiast udawać,
4476 -# że są aktualne.
4477 -BASE_NAME_ALIASES = {
4478 - "atk": "at-spi2-core",
4479 - "dejavu-fonts": "dejavu-ttf",
4480 - "fontconfig": "xorg-fontconfig",
4481 - "gtk": "gtk3",
4482 - "iceauth": "xorg-iceauth",
4483 - "libX11": "xorg-libx11",
4484 - "libXau": "xorg-libxau",
4485 - "libXdmcp": "xorg-libxdmcp",
4486 - "libXext": "xorg-libxext",
4487 - "libXft": "xorg-libxft",
4488 - "libdrm": "xorg-libdrm",
4489 - "libnspr": "nspr",
4490 - "libxkbfile": "xorg-libxkbfile",
4491 - "libxklavier": "xorg-libxklavier",
4492 - "linux-pam": "pam",
4493 - "pixman": "xorg-pixman",
4494 - "sdl2": "sdl",
4495 - "setxkbmap": "xorg-setxkbmap",
4496 - "xauth": "xorg-xauth",
4497 - "xf86-input-libinput": "xorg-xf86-input-libinput",
4498 - "xf86-video-fbdev": "xorg-xf86-video-fbdev",
4499 - "xinit": "xorg-xinit",
4500 - "xkbcomp": "xorg-xkbcomp",
4501 - "xkeyboard-config": "xorg-xkeyboard-config",
4502 - # Builder buduje wpa_supplicant (z podkreślnikiem), a repo ma wpa-supplicant
4503 - # (z myślnikiem) – bez tego aliasu pakiet nie dostawał aktualizacji z repo,
4504 - # mimo że repo.json zna DOKŁADNIE tę samą wersję.
4505 - "wpa_supplicant": "wpa-supplicant",
4506 -}
4507 -
4508 -
4509 -def _base_manifest() -> dict:
4510 - """Manifest bazy z obrazu ({} gdy obraz go nie dostarcza)."""
4511 - _d = load_json(os.path.join(PAG_ROOT, BASE_MANIFEST.lstrip("/")))
4512 - return _d if isinstance(_d, dict) else {}
4513 -
4514 -
4515 -def _base_entries() -> list:
4516 - """[(nazwa_z_buildera, wersja_z_obrazu), ...] z manifestu."""
4517 - _out = []
4518 - for _e in (_base_manifest().get("packages") or []):
4519 - if isinstance(_e, str):
4520 - if _e:
4521 - _out.append((_e, "?"))
4522 - elif isinstance(_e, dict) and _e.get("name"):
4523 - _out.append((str(_e["name"]), str(_e.get("version") or "?")))
4524 - return _out
4525 -
4526 -
4527 -def _base_repo_name(name: str, repo: dict, installed: dict) -> str:
4528 - """Nazwa pakietu w repo dla nazwy z buildera (alias → provides → brak)."""
4529 - if name in repo:
4530 - return name
4531 - _alias = BASE_NAME_ALIASES.get(name)
4532 - if _alias and _alias in repo:
4533 - return _alias
4534 - _real = _resolve_provides(name, repo, installed)
4535 - return _real if _real in repo else ""
4536 -
4537 -
4538 -def _base_summary(repo: Optional[dict] = None) -> dict:
4539 - """Klasyfikacja pakietów bazy z obrazu wobec repo.
4540 -
4541 - repo=None → pobiera indeks repo (potrzebny do listy „do adoptowania”).
4542 - repo={} → bez sieci: rozpoznaje tylko to, czym pag już zarządza.
4543 - """
4544 - _entries = _base_entries()
4545 - if not _entries:
4546 - return {"total": 0, "tracked": 0, "adoptable": [], "unmatched": []}
4547 - if repo is None:
4548 - repo = fetch_all_packages()
4549 - installed = load_json(INSTALLED_DB)
4550 - tracked, adoptable, unmatched = 0, [], []
4551 - for _n, _v in _entries:
4552 - _real = _base_repo_name(_n, repo, installed)
4553 - if _n in installed or (_real and _real in installed):
4554 - tracked += 1
4555 - elif _real:
4556 - adoptable.append((_n, _real, _v))
4557 - else:
4558 - unmatched.append(_n)
4559 - return {"total": len(_entries), "tracked": tracked,
4560 - "adoptable": adoptable, "unmatched": unmatched}
4561 -
4562 -
4563 -def _base_hint_unmanaged() -> None:
4564 - """Jednozdaniowa informacja dla `pag sync/update/upgrade`."""
4565 - try:
4566 - _s = _base_summary()
4567 - except Exception:
4568 - return
4569 - if _s["adoptable"]:
4570 - print(f"\n ℹ {_('base_unmanaged_hint', len(_s['adoptable']))}")
4571 -
4572 -
4573 -def _base_warn_overwrite(names) -> None:
4574 - """Ostrzeżenie w `pag install`, gdy pakiet pochodzi z bazy obrazu ISO."""
4575 - _entries = _base_entries()
4576 - if not _entries:
4577 - return
4578 - _known = set()
4579 - for _n, _v in _entries:
4580 - _known.add(_n)
4581 - _al = BASE_NAME_ALIASES.get(_n)
4582 - if _al:
4583 - _known.add(_al)
4584 - _hit = [n for n in names if n in _known]
4585 - if _hit:
4586 - _listed = ", ".join(_hit[:5]) + (" …" if len(_hit) > 5 else "")
4587 - print(f" ℹ {_('base_overwrite', _listed)}")
4588 -
4589 -
4590 -def cmd_base_status():
4591 - """`pag base` / `pag base status` – co w systemie pochodzi z obrazu,
4592 - czym pag już zarządza i co da się zaadoptować z repo."""
4593 - _man = _base_manifest()
4594 - if not _man:
4595 - print(f" ℹ {_('base_no_manifest')}")
4596 - return 0
4597 - _s = _base_summary()
4598 - print(f"\n {_c('bold', _('base_title'))}")
4599 - print(f" {'─' * 46}")
4600 - _de = _man.get("de") or ""
4601 - print(f" {_('base_iso_version'):<34} {_man.get('iso_version', '?')}" + (f" ({_de})" if _de else ""))
4602 - print(f" {_('base_total'):<34} {_s['total']}")
4603 - print(f" {_('base_tracked'):<34} {_s['tracked']}")
4604 - print(f" {_('base_adoptable'):<34} {len(_s['adoptable'])}")
4605 - print(f" {_('base_unmatched'):<34} {len(_s['unmatched'])}")
4606 - if _s["adoptable"]:
4607 - print(f"\n {_('base_adopt_hint')}")
4608 - for _iso_n, _real, _v in _s["adoptable"][:10]:
4609 - _m = "" if _iso_n == _real else f" ({_iso_n})"
4610 - print(f" {_real}-{_v}{_m}")
4611 - if len(_s["adoptable"]) > 10:
4612 - print(f" … {len(_s['adoptable']) - 10} {_('base_more')}")
4613 - if _s["unmatched"]:
4614 - print(f"\n {_('base_unmatched_hint')}")
4615 - print(" " + ", ".join(_s["unmatched"][:12])
4616 - + (f" … +{len(_s['unmatched']) - 12}" if len(_s["unmatched"]) > 12 else ""))
4617 - return 0
4618 -
4619 -
4620 -def cmd_base_adopt(args):
4621 - """`pag base adopt [pkg...] [--dry-run]` – dograj bazę z obrazu z repo.
4622 -
4623 - Pakiety bazy nie ma w installed.json, więc pag traktuje je jak NOWĄ
4624 - instalację: pliki z obrazu trafiają do kopii transakcji (działa
4625 - `pag rollback`), a po sukcesie pag zarządza nimi jak każdym innym pakietem.
4626 - """
4627 - if not _base_manifest():
4628 - print(f" ℹ {_('base_no_manifest')}")
4629 - return 1
4630 - repo = fetch_all_packages()
4631 - if not repo:
4632 - print(f"❌ {_('no_index')}")
4633 - return 1
4634 - _want = [a for a in args if not a.startswith("-") and a != "adopt"]
4635 - _s = _base_summary(repo)
4636 - plan = _s["adoptable"]
4637 - if _want:
4638 - _sel = set(_want)
4639 - plan = [p for p in plan if p[0] in _sel or p[1] in _sel]
4640 - if not plan:
4641 - print(f" ℹ {_('base_nothing_selected')}")
4642 - return 0
4643 - if not plan:
4644 - print(f"✅ {_('base_all_managed')}")
4645 - return 0
4646 - _size = sum(repo[r].size_bytes for _i, r, _v in plan if r in repo)
4647 - print(f"\n {_('base_adopt_plan', len(plan), _size / 1048576)}")
4648 - for _iso_n, _real, _v in plan[:20]:
4649 - _p = repo.get(_real)
4650 - _rv = _p.version if _p else "?"
4651 - _rr = (getattr(_p, "release", "") or "") if _p else ""
4652 - _rvr = f"{_rv}-{_rr}" if _rr else _rv
4653 - _m = "" if _iso_n == _real else f" ({_iso_n} → {_real})"
4654 - print(f" {_real}: {_v} → {_rvr}{_m}")
4655 - if len(plan) > 20:
4656 - print(f" … {len(plan) - 20} {_('base_more')}")
4657 - if "-n" in args or "--dry-run" in args:
4658 - print(f" {_('base_dry_run')}")
4659 - return 0
4660 - _rc = cmd_install([r for _i, r, _v in plan])
4661 - if _rc == 0:
4662 - # Wymienione biblioteki/narzędzia (glibc, gcc, GTK…) są już nowe na dysku,
4663 - # ale działające procesy wciąż mają stare w pamięci – restart domyka.
4664 - print(f"\n ℹ {_('base_reboot_hint')}")
4665 - return _rc
4666 -
4667 -
4668 -def _base_cached_index() -> dict:
4669 - """Indeks repo TYLKO z lokalnego cache (zero sieci) – do mapowania nazw.
4670 -
4671 - Potrzebne dla `pag base register`: rejestracja bazy obrazu nie może zależeć
4672 - od sieci (odpala się w buildzie, w chroocie, bez DNS). Cache indeksu powstaje
4673 - przy okazji `pag sync`/`pag install` i po nim wystarcza.
4674 - """
4675 - _out = {}
4676 - try:
4677 - for _r in get_repos():
4678 - _cp = _repo_cache_path(_r)
4679 - if not os.path.exists(_cp):
4680 - continue
4681 - for _pdata in (_load_repo_cache(_cp) or []):
4682 - _n = _pdata.get("name") or _pdata.get("filename", "?").split("-")[0]
4683 - _pkg = PackageInfo(_pdata, _r)
4684 - if _n not in _out or _version_newer(_pkg.version, _out[_n].version):
4685 - _out[_n] = _pkg
4686 - except Exception:
4687 - return _out
4688 - return _out
4689 -
4690 -
4691 -def cmd_base_register(args):
4692 - """`pag base register [--force] [--dry-run]` – wpisz bazę obrazu do installed.json.
4693 -
4694 - PO CO: pakietów zbudowanych przez builder (glibc, gcc, GTK, XFCE…) nie ma
4695 - w installed.json, więc `pag upgrade` ich NIE widzi i system nie da się
4696 - prowadzić w trybie rolling – trzeba by najpierw `pag base adopt`, czyli
4697 - ponownie ŚCIĄGNĄĆ całą bazę z repo. Rejestracja zamiast tego zapisuje je
4698 - jako zainstalowane **z wersją z obrazu** (to ona leży na dysku), więc
4699 - `pag upgrade` porówna ją z repo i podniesie tylko to, co nowsze.
4700 -
4701 - Offline: nic nie pobiera. Cache indeksu repo (jeśli jest) służy WYŁĄCZNIE do
4702 - mapowania nazw builder → repo (BASE_NAME_ALIASES/provides) i metadanych
4703 - (release/opis/zależności). Nazwy bez odpowiednika w repo zostają jak są.
4704 -
4705 - OGRANICZENIE: rejestracja nie zna listy plików pakietu (files.db), więc
4706 - dopóki pakiet nie zostanie zaktualizowany z repo, `pag verify`/`pag remove`
4707 - go nie obejmą (`pag base adopt` nadal jest drogą do pełnego przejęcia).
4708 - """
4709 - _force = "-f" in args or "--force" in args
4710 - _dry = "-n" in args or "--dry-run" in args
4711 -
4712 - _entries = _base_entries()
4713 - if not _entries:
4714 - print(f" ℹ {_('base_no_manifest')}")
4715 - return 1
4716 -
4717 - _repo = _base_cached_index()
4718 - installed = load_json(INSTALLED_DB)
4719 - world = load_world()
4720 - _now = datetime.now().isoformat()
4721 -
4722 - added, skipped, renamed = [], 0, 0
4723 - for _n, _v in _entries:
4724 - _real = _base_repo_name(_n, _repo, installed) if _repo else ""
4725 - _key = _real or _n
4726 - if _real and _real != _n:
4727 - renamed += 1
4728 - if _key in installed and not _force:
4729 - skipped += 1
4730 - continue
4731 - _pkg = _repo.get(_key)
4732 - installed[_key] = {
4733 - "version": _v or (getattr(_pkg, "version", "") or "?"),
4734 - "release": getattr(_pkg, "release", "") or "1",
4735 - "description": (getattr(_pkg, "description", "") or "")
4736 - or "Pagan Linux – pakiet bazy obrazu",
4737 - "dependencies": list(getattr(_pkg, "dependencies", []) or []),
4738 - "size_bytes": getattr(_pkg, "size_bytes", 0) or 0,
4739 - "sha256": "",
4740 - "installed_at": _now,
4741 - "repo": "base",
4742 - "provides": list(getattr(_pkg, "provides", []) or []),
4743 - "provides_so": list(getattr(_pkg, "provides_so", []) or []),
4744 - "requires_so": list(getattr(_pkg, "requires_so", []) or []),
4745 - }
4746 - world.add(_key)
4747 - added.append(_key)
4748 -
4749 - if _dry:
4750 - print(f" ℹ {_('base_register_plan', len(added))}")
4751 - return 0
4752 - if added:
4753 - save_json(INSTALLED_DB, installed)
4754 - save_world(world)
4755 - print(f" ✅ {_('base_register_ok', len(added), skipped)}")
4756 - if renamed:
4757 - print(f" ℹ {_('base_register_renamed', renamed)}")
4758 - if not _repo:
4759 - print(f" ℹ {_('base_register_nocache')}")
4760 - return 0
4761 -
4762 -
4763 -def cmd_update(do_upgrade: bool = False):
4764 - """`pag sync` / `pag update` – odświeżenie indeksów + raport aktualizacji.
4765 -
4766 - sync → tylko odświeżenie indeksów + info: „jest X pakietów do
4767 - zaktualizowania – wpisz: pag update".
4768 - update → odświeżenie indeksów + AKTUALIZACJA PAKIETÓW (pakiety, nie system).
4769 - Pomijamy cache TTL (inaczej nowe pakiety/aktualizacje są niewidoczne nawet
4770 - przez godzinę). Pełne pobranie + weryfikacja GPG przy każdym odświeżeniu.
4771 - """
4772 - force = True
4773 - print("🔄 Refreshing indexes...")
4774 - for repo_url in get_repos():
4775 - pkgs = fetch_repo_index(repo_url, force=force)
4776 - cp = _repo_cache_path(repo_url)
4777 - has_sig = os.path.exists(cp + ".sig")
4778 - print(f" {'✅' if pkgs is not None else '❌'} {repo_url}: {len(pkgs or [])} pkgs {'🔐' if has_sig else '⚠'}")
4779 - print(f"✅ {_('indexes_refreshed')}")
4780 -
4781 - # Powiadomienie o nowszej wersji pag (repo.json["pag_version"])
4782 - try:
4783 - for r in get_repos():
4784 - cp = _repo_cache_path(r)
4785 - if os.path.exists(cp):
4786 - d = json.load(open(cp))
4787 - rv = d.get("pag_version", "")
4788 - if rv and rv != PAG_VERSION:
4789 - print(f" ⚠ Nowa wersja pag {rv} dostępna – uruchom: pag self-update")
4790 - except Exception:
4791 - pass
4792 -
4793 - # Raport: pakiety do aktualizacji
4794 - pending = _kernel_group_updates(_pending_updates())
4795 - if not pending:
4796 - print(f"✅ {_('all_up_to_date')}")
4797 - _base_hint_unmanaged()
4798 - return 0
4799 - print(f"{_('updates_available', len(pending))}")
4800 - installed = load_json(INSTALLED_DB)
4801 - repo = fetch_all_packages()
4802 - for n in pending:
4803 - _i = installed.get(n, {})
4804 - _ir = _i.get("release")
4805 - _nr = getattr(repo[n], "release", "") or ""
4806 - _old = f"{_i.get('version', '?')}-{_ir}" if _ir else _i.get("version", "?")
4807 - _new = f"{repo[n].version}-{_nr}" if _nr else repo[n].version
4808 - print(f" {n}: {_old} → {_new}")
4809 - if not do_upgrade:
4810 - _base_hint_unmanaged()
4811 - return 0 # sync: tylko informacja
4812 - if not _ask_confirm():
4813 - return 0
4814 - _rc = cmd_install(pending, upgrade=True)
4815 - _base_hint_unmanaged()
4816 - return _rc
4817 -
4818 -def _initramfs_stale() -> bool:
4819 - """Czy initramfs jest starszy niż najnowsze jądro (wymaga przebudowy)."""
4820 - try:
4821 - kernels = [k for k in os.listdir("/boot") if k.startswith("vmlinuz-")] if os.path.isdir("/boot") else []
4822 - if not kernels:
4823 - return False
4824 - newest = max(os.path.getmtime(os.path.join("/boot", k)) for k in kernels)
4825 - initrd = "/boot/initramfs.img"
4826 - return (not os.path.exists(initrd)) or os.path.getmtime(initrd) < newest
4827 - except Exception:
4828 - return False
4829 -
4830 -def cmd_upgrade():
4831 - """`pag upgrade` – aktualizacja SYSTEMU: pakiety + kernel/initramfs/GRUB."""
4832 - rc = cmd_update(do_upgrade=True)
4833 - if rc != 0:
4834 - return rc
4835 - # System: dopilnuj initramfs (gdyby kernel był nowszy) + GRUB.
4836 - if _initramfs_stale():
4837 - print(" 🐧 Przebudowa initramfs (nowsze jądro)...")
4838 - _rebuild_initramfs()
4839 - _refresh_bootloader()
4840 - return 0
4841 -
4842 -def cmd_list(installed_only=False):
4843 - if installed_only:
4844 - db = load_json(INSTALLED_DB)
4845 - pinned = load_json(PINNED_FILE)
4846 - if not db: print("No packages installed."); return
4847 - print(f"Installed ({len(db)}):")
4848 - for n, i in sorted(db.items()):
4849 - pin = " 📌" if n in pinned else ""
4850 - print(f" {n}-{i['version']}{pin} – {i.get('description','')}")
4851 - else:
4852 - pkgs = fetch_all_packages()
4853 - installed = load_json(INSTALLED_DB)
4854 - pinned = load_json(PINNED_FILE)
4855 - print(f"Available ({len(pkgs)}):")
4856 - for n, p in sorted(pkgs.items()):
4857 - m = "✓" if n in installed else " "
4858 - extra = f" [installed: {installed[n]['version']}]" if n in installed else ""
4859 - if n in pinned: extra += " 📌"
4860 - print(f" [{m}] {n}-{p.version} – {p.description}{extra}")
4861 -
4862 -def cmd_search(query):
4863 - pkgs = fetch_all_packages()
4864 - results = [(n,p) for n,p in pkgs.items() if query.lower() in n.lower() or query.lower() in p.description.lower()]
4865 - if not results: print(f"❌ No results for: {query}"); return
4866 - installed = load_json(INSTALLED_DB)
4867 - print(f"Results for '{query}' ({len(results)}):")
4868 - for n,p in sorted(results):
4869 - print(f" [{'✓' if n in installed else ' '}] {n}-{p.version}")
4870 - print(f" {p.description}")
4871 -
4872 -
4873 -def _smart_search(query: str) -> int:
4874 - """
4875 - Inteligentne wyszukiwanie: repo PaganOS + Flathub.
4876 - Uruchamiane gdy użytkownik wpisze `pag <nazwa>` zamiast `pag install <nazwa>`.
4877 - Pokazuje dostępne źródła i sugeruje komendy instalacji.
4878 - """
4879 - # 1. Repo PaganOS
4880 - try:
4881 - pkgs = fetch_all_packages()
4882 - except Exception:
4883 - pkgs = {}
4884 - repo_lower = [(n, p) for n, p in pkgs.items()
4885 - if query.lower() in n.lower() or query.lower() in p.description.lower()]
4886 -
4887 - # 2. Flathub (jeśli dostępny)
4888 - flat = _flatpak_search_raw(query) if _check_flatpak(quiet=True) else []
4889 -
4890 - if not repo_lower and not flat:
4891 - print(f"\n ❌ '{query}' — nie znaleziono.")
4892 - print(f" Repo PaganOS: pag search {query}")
4893 - if _check_flatpak(quiet=True):
4894 - print(f" Flathub: pag flatpak search {query}")
4895 - print(f" Dodaj repo: pag repo-add <url>")
4896 - return 1
4897 -
4898 - installed = load_json(INSTALLED_DB)
4899 -
4900 - # ── Repo PaganOS ──
4901 - if repo_lower:
4902 - exact = [(n, p) for n, p in repo_lower if n.lower() == query.lower()]
4903 - show = (exact or repo_lower)[:6]
4904 - print(f"\n 📦 PaganOS — '{query}':")
4905 - for n, p in sorted(show):
4906 - mark = "✓" if n in installed else " "
4907 - desc = p.description[:70] if len(p.description) > 75 else p.description
4908 - print(f" [{mark}] {n}-{p.version}")
4909 - if desc:
4910 - print(f" {desc}")
4911 - if len(repo_lower) > 6:
4912 - print(f" ... i {len(repo_lower) - 6} więcej (pag search {query})")
4913 -
4914 - # ── Flathub ──
4915 - if flat:
4916 - print(f"\n 📦 Flathub — '{query}':")
4917 - for r in flat[:5]:
4918 - mark = "✓" if r.get("installed") else " "
4919 - name = r.get("name") or r.get("application", "?")
4920 - desc = (r.get("description") or "")[:65]
4921 - print(f" [{mark}] {name}")
4922 - if desc:
4923 - print(f" {desc}")
4924 - if len(flat) > 5:
4925 - print(f" ... i {len(flat) - 5} więcej (pag flatpak search {query})")
4926 -
4927 - # ── Sugestie instalacji ──
4928 - print()
4929 - if repo_lower:
4930 - 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]
4931 - if best in installed:
4932 - print(f" ✓ {best} jest już zainstalowany ({installed[best]['version']})")
4933 - else:
4934 - print(f" 💡 sudo pag install {best}")
4935 - if flat:
4936 - best_fp = flat[0].get("application") or flat[0].get("name", query)
4937 - print(f" 💡 pag flatpak install {best_fp}")
4938 -
4939 - return 0
4940 -
4941 -def cmd_info(name):
4942 - pkgs = fetch_all_packages()
4943 - p = pkgs.get(name)
4944 - info = load_json(INSTALLED_DB).get(name)
4945 - if not p and not info: print(f"❌ '{name}' not found."); return 1
4946 - print(f"📦 {name}")
4947 - if p:
4948 - print(f" Version (repo): {p.version}")
4949 - print(f" Description: {p.description}")
4950 - print(f" Size: {p.size_bytes/1048576:.1f} MB")
4951 - print(f" SHA256: {p.sha256[:32]}...")
4952 - print(f" GPG: {p.gpg_fp or 'none'}")
4953 - print(f" Dependencies: {', '.join(p.dependencies) if p.dependencies else '(none)'}")
4954 - if p.optdepends:
4955 - print(f" {_('optional_deps')}")
4956 - for _od in p.optdepends:
4957 - print(f" - {_od}")
4958 - if info:
4959 - print(f" Installed: {info['version']} ({info.get('installed_at','?')})")
4960 -
4961 -def cmd_files(name):
4962 - if name not in load_json(INSTALLED_DB):
4963 - print(f"❌ '{name}' not installed."); return 1
4964 - files = _db_get_package_files(name)
4965 - print(f"Files in {name} ({len(files)}):")
4966 - for f in sorted(files): print(f" {f}")
4967 -
4968 -def cmd_repair(dry_run=False):
4969 - """Naprawia system: reinstaluje pakiety, ktorych pliki zginely.
4970 -
4971 - Przechodzi po bazie plikow (jak `verify`), zbiera pakiety z brakujacymi
4972 - plikami i dla kazdego robi REINSTALACJE z repozytorium (staging + GPG).
4973 - Reinstalacja nie rusza konfiguracji uzytkownika (.pacnew), a przywraca
4974 - brakujace pliki pakietu (np. qt6-declarative, accountsservice).
4975 - """
4976 - installed = load_json(INSTALLED_DB)
4977 - if not installed:
4978 - print("Nic do naprawy (brak zainstalowanych pakietow).")
4979 - return 0
4980 - missing = {}
4981 - for name in installed:
4982 - cnt = 0
4983 - for fpath in _db_get_package_files(name):
4984 - full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
4985 - if not (os.path.exists(full) or os.path.islink(full)):
4986 - cnt += 1
4987 - if cnt:
4988 - missing[name] = cnt
4989 - if not missing:
4990 - print("✅ Wszystkie pliki na miejscu – nic do naprawy.")
4991 - return 0
4992 - total = sum(missing.values())
4993 - print(f"🔧 Pakiety z brakujacymi plikami: {len(missing)} (lacznie {total} plikow)")
4994 - for n, c in sorted(missing.items(), key=lambda kv: (-kv[1], kv[0])):
4995 - print(f" {n}: {c}")
4996 - if dry_run:
4997 - print("\n(--dry-run: nic nie zmieniam)")
4998 - return 0
4999 - if not _ask_confirm():
5000 - print(_("cancelled")); return 0
5001 - # Jedna migawka na całą naprawę – nie tworzymy snapshotu per pakiet.
5002 - _snap_ok, _ = _snapshot_support()
5003 - if _snap_ok:
5004 - _create_system_snapshot(list(missing), "repair")
5005 - _refresh_bootloader()
5006 - _prev_snap = os.environ.get("PAG_SNAPSHOT")
5007 - os.environ["PAG_SNAPSHOT"] = "never"
5008 - failed = []
5009 - try:
5010 - for n in sorted(missing, key=lambda x: (-missing[x], x)):
5011 - print(f"\n🔧 repair: {n}")
5012 - try:
5013 - rc = cmd_install([n], upgrade=True)
5014 - except SystemExit as e:
5015 - rc = e.code
5016 - except Exception as e:
5017 - print(f" ❌ {n}: {e}")
5018 - rc = 1
5019 - if rc:
5020 - failed.append(n)
5021 - finally:
5022 - if _prev_snap is None:
5023 - os.environ.pop("PAG_SNAPSHOT", None)
5024 - else:
5025 - os.environ["PAG_SNAPSHOT"] = _prev_snap
5026 - print()
5027 - ok = len(missing) - len(failed)
5028 - if failed:
5029 - print(f"⚠ Naprawiono {ok}/{len(missing)}. Nie udalo sie: {', '.join(failed)}")
5030 - return 1
5031 - print(f"✅ Naprawiono {ok} pakietow.")
5032 - return 0
5033 -
5034 -
5035 -def cmd_verify(deep=False):
5036 - installed = load_json(INSTALLED_DB)
5037 - if not installed: print("Nothing to verify."); return
5038 - errors = []
5039 -
5040 - # Wczytaj WSZYSTKIE sumy RAZ (nie w pętli!) – przy 50k plików wywołanie
5041 - # _db_get_all_file_checksums() per-plik dawało O(n²) i godziny zamiast sekund.
5042 - all_checksums = _db_get_all_file_checksums() if deep else {}
5043 - for name in installed:
5044 - for fpath in _db_get_package_files(name):
5045 - full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
5046 - if not (os.path.exists(full) or os.path.islink(full)):
5047 - errors.append(f" ❌ {name}: missing {fpath}")
5048 - elif deep:
5049 - expected = all_checksums.get(fpath, "")
5050 - if expected:
5051 - actual = _sha256_file(full)
5052 - if actual != expected:
5053 - errors.append(f" ❌ {name}: SHA256 mismatch {fpath}")
5054 -
5055 - if errors:
5056 - print(f"❌ {_('verify_errors', len(errors))}")
5057 - for e in errors: print(e)
5058 - return 1
5059 - total = _db_count_files()
5060 - print(f"✅ {_('verify_ok', total)}")
5061 -
5062 -# =============================================================================
5063 -# PINNING / CLEAN / ORPHANS / REPO / FLATPAK
5064 -# =============================================================================
5065 -
5066 -def cmd_pin(name, version=""):
5067 - pinned = load_json(PINNED_FILE)
5068 - if version:
5069 - pinned[name] = version
5070 - else:
5071 - info = load_json(INSTALLED_DB).get(name, {})
5072 - pinned[name] = info.get("version", "?")
5073 - save_json(PINNED_FILE, pinned)
5074 - print(f"📌 {name} {_('pinned_to')} {pinned[name]}")
5075 -
5076 -def cmd_unpin(name):
5077 - pinned = load_json(PINNED_FILE)
5078 - if name in pinned:
5079 - del pinned[name]; save_json(PINNED_FILE, pinned)
5080 - print(f"🔓 {name} {_('unpinned')}")
5081 - else:
5082 - print(f"⚠ {name} {_('not_pinned')}")
5083 -
5084 -def cmd_pinned():
5085 - pinned = load_json(PINNED_FILE)
5086 - if not pinned: print(_("no_pinned")); return
5087 - print(_("pinned_list", len(pinned)))
5088 - for n,v in sorted(pinned.items()): print(f" 📌 {n} = {v}")
5089 -
5090 -def cmd_clean():
5091 - if os.path.isdir(PAG_CACHE):
5092 - count = size = 0
5093 - for f in os.listdir(PAG_CACHE):
5094 - fp = os.path.join(PAG_CACHE, f)
5095 - if os.path.isfile(fp):
5096 - size += os.path.getsize(fp); os.remove(fp); count += 1
5097 - print(f"✅ {_('cache_cleared', count, size/1048576)}")
5098 -
5099 -def cmd_remove_orphans():
5100 - installed = load_json(INSTALLED_DB)
5101 - world = load_world()
5102 - orphans = _find_orphans(installed, world)
5103 - if not orphans: print("✅ No orphans."); return
5104 - print(f"Orphans ({len(orphans)}):")
5105 - for n in sorted(orphans): print(f" {n}-{installed[n]['version']}")
5106 - if not _ask_confirm():
5107 - return
5108 - cmd_remove(list(orphans))
5109 -
5110 -
5111 -# =============================================================================
5112 -# PROVIDES – PAKIETY WIRTUALNE
5113 -# =============================================================================
5114 -
5115 -PROVIDES_MAP = {
5116 - "pkgconfig(glib-2.0)": "glib",
5117 - "pkgconfig(gobject-introspection-1.0)": "gobject-introspection",
5118 - "pkgconfig(gtk+-3.0)": "gtk",
5119 - "pkgconfig(gtk4)": "gtk",
5120 - "pkgconfig(zlib)": "zlib",
5121 - "pkgconfig(libffi)": "libffi",
5122 - "pkgconfig(expat)": "expat",
5123 - "pkgconfig(libsystemd)": "systemd",
5124 - "pkgconfig(dbus-1)": "dbus",
5125 - "pkgconfig(mount)": "util-linux",
5126 - "pkgconfig(blkid)": "util-linux",
5127 - "pkgconfig(libcap)": "libcap",
5128 - "pkgconfig(liblzma)": "xz",
5129 - "pkgconfig(libzstd)": "zstd",
5130 - "pkgconfig(bzip2)": "bzip2",
5131 - "pkgconfig(libcurl)": "curl",
5132 - "pkgconfig(openssl)": "openssl",
5133 - "pkgconfig(libpcre2-8)": "pcre2",
5134 - "pkgconfig(libxml-2.0)": "libxml2",
5135 - "pkgconfig(libxslt)": "libxslt",
5136 - "pkgconfig(freetype2)": "freetype",
5137 - "pkgconfig(fontconfig)": "fontconfig",
5138 - "pkgconfig(harfbuzz)": "harfbuzz",
5139 - "pkgconfig(cairo)": "cairo",
5140 - "pkgconfig(pango)": "pango",
5141 - "pkgconfig(xt)": "xorg-libxt",
5142 - "pkgconfig(xmu)": "xorg-libxmu",
5143 - "pkgconfig(ice)": "xorg-libice",
5144 - "pkgconfig(sm)": "xorg-libsm",
5145 - "pkgconfig(x11)": "xorg-libx11",
5146 - "pkgconfig(xext)": "xorg-libxext",
5147 - "pkgconfig(xrandr)": "xorg-libxrandr",
5148 - "pkgconfig(xfixes)": "xorg-libxfixes",
5149 - "pkgconfig(xcursor)": "xorg-libxcursor",
5150 - "pkgconfig(xinerama)": "xorg-libxinerama",
5151 - "pkgconfig(xrender)": "xorg-libxrender",
5152 - "pkgconfig(xau)": "xorg-libxau",
5153 - "pkgconfig(xcb)": "xorg-libxcb",
5154 - "pkgconfig(xdamage)": "xorg-libxdamage",
5155 - "pkgconfig(xcomposite)": "xorg-libxcomposite",
5156 - "pkgconfig(xft)": "xorg-libxft",
5157 - "pkgconfig(xss)": "xorg-libxss",
5158 - "pkgconfig(libsoup-3.0)": "libsoup3",
5159 - "pkgconfig(libsoup-2.4)": "libsoup2",
5160 - "pkgconfig(gdk-pixbuf-2.0)": "gdk-pixbuf2",
5161 - "pkgconfig(libpng)": "libpng",
5162 - "pkgconfig(libjpeg)": "libjpeg-turbo",
5163 - "pkgconfig(libtiff-4)": "libtiff",
5164 - "pkgconfig(ffi)": "libffi",
5165 - # ── system / baza ──
5166 - "pkgconfig(libcrypto)": "openssl",
5167 - "pkgconfig(libssl)": "openssl",
5168 - "pkgconfig(libudev)": "systemd",
5169 - "pkgconfig(libmount)": "util-linux",
5170 - "pkgconfig(libblkid)": "util-linux",
5171 - "pkgconfig(uuid)": "util-linux",
5172 - "pkgconfig(libexpat)": "expat",
5173 - "pkgconfig(libpcre)": "pcre",
5174 - "pkgconfig(ncursesw)": "ncurses",
5175 - "pkgconfig(tinfo)": "ncurses",
5176 - "pkgconfig(panel)": "ncurses",
5177 - "pkgconfig(readline)": "readline",
5178 - "pkgconfig(libseccomp)": "libseccomp",
5179 - "pkgconfig(pam)": "linux-pam",
5180 - "pkgconfig(libxcrypt)": "libxcrypt",
5181 - "pkgconfig(libcrypt)": "libxcrypt",
5182 - "pkgconfig(libnsl)": "libnsl",
5183 - "pkgconfig(liblz4)": "lz4",
5184 - "pkgconfig(libevent)": "libevent",
5185 - "pkgconfig(libarchive)": "libarchive",
5186 - "pkgconfig(sqlite3)": "sqlite",
5187 - "pkgconfig(libpq)": "postgresql",
5188 - "pkgconfig(mysqlclient)": "mariadb",
5189 - "pkgconfig(json-c)": "json-c",
5190 - "pkgconfig(json-glib-1.0)": "json-glib",
5191 - "pkgconfig(libunistring)": "libunistring",
5192 - "pkgconfig(libidn2)": "libidn2",
5193 - "pkgconfig(libpsl)": "libpsl",
5194 - "pkgconfig(icu-uc)": "icu",
5195 - "pkgconfig(icu-i18n)": "icu",
5196 - "pkgconfig(icu-io)": "icu",
5197 - "pkgconfig(gnutls)": "gnutls",
5198 - "pkgconfig(nettle)": "nettle",
5199 - "pkgconfig(hogweed)": "nettle",
5200 - "pkgconfig(libgcrypt)": "libgcrypt",
5201 - "pkgconfig(libgpg-error)": "libgpg-error",
5202 - "pkgconfig(libassuan)": "libassuan",
5203 - "pkgconfig(libusb-1.0)": "libusb",
5204 - "pkgconfig(libusb)": "libusb",
5205 - "pkgconfig(libgudev-1.0)": "libgudev",
5206 - "pkgconfig(gudev-1.0)": "libgudev",
5207 - "pkgconfig(polkit-gobject-1)": "polkit",
5208 - "pkgconfig(polkit-agent-1)": "polkit",
5209 - "pkgconfig(libpciaccess)": "libpciaccess",
5210 - "pkgconfig(pixman-1)": "pixman",
5211 - "pkgconfig(libdrm)": "libdrm",
5212 - "pkgconfig(libva)": "libva",
5213 - "pkgconfig(libva-drm)": "libva",
5214 - "pkgconfig(libva-x11)": "libva",
5215 - "pkgconfig(libva-wayland)": "libva",
5216 - "pkgconfig(vdpau)": "libvdpau",
5217 - "pkgconfig(libvdpau)": "libvdpau",
5218 - "pkgconfig(libinput)": "libinput",
5219 - "pkgconfig(libevdev)": "libevdev",
5220 - "pkgconfig(mtdev)": "mtdev",
5221 - # ── grafika / GL / multimedia ──
5222 - "pkgconfig(gbm)": "mesa",
5223 - "pkgconfig(gl)": "libglvnd",
5224 - "pkgconfig(egl)": "libglvnd",
5225 - "pkgconfig(glesv2)": "libglvnd",
5226 - "pkgconfig(glx)": "libglvnd",
5227 - "pkgconfig(vulkan)": "vulkan-loader",
5228 - "pkgconfig(libxkbcommon)": "libxkbcommon",
5229 - "pkgconfig(xkbcommon)": "libxkbcommon",
5230 - "pkgconfig(xkbcommon-x11)": "libxkbcommon",
5231 - "pkgconfig(xcb)": "xorg-libxcb",
5232 - "pkgconfig(xcb-util)": "xcb-util",
5233 - "pkgconfig(xcb-keysyms)": "xcb-util-keysyms",
5234 - "pkgconfig(xcb-icccm)": "xcb-util-wm",
5235 - "pkgconfig(xcb-cursor)": "xcb-util-cursor",
5236 - "pkgconfig(xcb-renderutil)": "xcb-util-renderutil",
5237 - "pkgconfig(xcb-image)": "xcb-util-image",
5238 - "pkgconfig(xcb-errors)": "xcb-util-errors",
5239 - "pkgconfig(wayland-client)": "wayland",
5240 - "pkgconfig(wayland-server)": "wayland",
5241 - "pkgconfig(wayland-cursor)": "wayland",
5242 - "pkgconfig(wayland-egl)": "wayland",
5243 - "pkgconfig(wayland-protocols)": "wayland-protocols",
5244 - "pkgconfig(gstreamer-1.0)": "gstreamer",
5245 - "pkgconfig(gstreamer-base-1.0)": "gstreamer",
5246 - "pkgconfig(gstreamer-check-1.0)": "gstreamer",
5247 - "pkgconfig(gstreamer-controller-1.0)": "gstreamer",
5248 - "pkgconfig(gstreamer-app-1.0)": "gst-plugins-base",
5249 - "pkgconfig(gstreamer-video-1.0)": "gst-plugins-base",
5250 - "pkgconfig(gstreamer-audio-1.0)": "gst-plugins-base",
5251 - "pkgconfig(gstreamer-pbutils-1.0)": "gst-plugins-base",
5252 - "pkgconfig(gstreamer-fft-1.0)": "gst-plugins-base",
5253 - "pkgconfig(gstreamer-riff-1.0)": "gst-plugins-base",
5254 - "pkgconfig(gstreamer-rtp-1.0)": "gst-plugins-base",
5255 - "pkgconfig(gstreamer-rtsp-1.0)": "gst-plugins-base",
5256 - "pkgconfig(gstreamer-sdp-1.0)": "gst-plugins-base",
5257 - "pkgconfig(gstreamer-net-1.0)": "gst-plugins-base",
5258 - "pkgconfig(gstreamer-gl-1.0)": "gst-plugins-base",
5259 - "pkgconfig(libpulse)": "libpulse",
5260 - "pkgconfig(libpulse-simple)": "libpulse",
5261 - "pkgconfig(libpulse-mainloop-glib)": "libpulse",
5262 - "pkgconfig(alsa)": "alsa-lib",
5263 - "pkgconfig(jack)": "jack2",
5264 - "pkgconfig(libsamplerate)": "libsamplerate",
5265 - "pkgconfig(sndfile)": "libsndfile",
5266 - "pkgconfig(libavcodec)": "ffmpeg",
5267 - "pkgconfig(libavformat)": "ffmpeg",
5268 - "pkgconfig(libavutil)": "ffmpeg",
5269 - "pkgconfig(libavfilter)": "ffmpeg",
5270 - "pkgconfig(libswscale)": "ffmpeg",
5271 - "pkgconfig(libswresample)": "ffmpeg",
5272 - "pkgconfig(libpostproc)": "ffmpeg",
5273 - "pkgconfig(SDL2)": "sdl2",
5274 - "pkgconfig(SDL)": "sdl",
5275 - "pkgconfig(SDL2_image)": "sdl2-image",
5276 - "pkgconfig(SDL2_ttf)": "sdl2-ttf",
5277 - "pkgconfig(SDL2_mixer)": "sdl2-mixer",
5278 - "pkgconfig(SDL2_net)": "sdl2-net",
5279 - "pkgconfig(libpng16)": "libpng",
5280 - "pkgconfig(libwebp)": "libwebp",
5281 - "pkgconfig(libwebpmux)": "libwebp",
5282 - "pkgconfig(libwebpdemux)": "libwebp",
5283 - "pkgconfig(libopenjp2)": "openjpeg2",
5284 - "pkgconfig(lcms2)": "lcms2",
5285 - "pkgconfig(libheif)": "libheif",
5286 - "pkgconfig(libde265)": "libde265",
5287 - "pkgconfig(x264)": "x264",
5288 - "pkgconfig(x265)": "x265",
5289 - # ── glib / gio ──
5290 - "pkgconfig(gio-unix-2.0)": "glib",
5291 - "pkgconfig(gmodule-2.0)": "glib",
5292 - "pkgconfig(gthread-2.0)": "glib",
5293 - "pkgconfig(girepository-2.0)": "gobject-introspection",
5294 - "pkgconfig(girepository-1.0)": "gobject-introspection",
5295 - "pkgconfig(libglib-2.0)": "glib",
5296 - "pkgconfig(libgobject-2.0)": "glib",
5297 -}
5298 -
5299 -# Ostrzeżenia o wielu dostawcach tej samej wirtualnej nazwy – raz na proces.
5300 -_PROVIDES_WARNED = set()
5301 -# Cache indeksu provides dla danego obiektu repo: (repo_obj, {virtual: [pkg,...]}).
5302 -# Trzymamy referencję do repo, by uniknąć pomyłki przy ponownym użyciu id().
5303 -_provides_cache = (None, {})
5304 -
5305 -def _provides_index(repo: dict) -> dict:
5306 - """Buduje (i cache’uje) mapę wirtualna nazwa → lista dostawców w repo.
5307 -
5308 - Pozwala wybrać dostawcę DETERMINISTYCZNIE (posortowanego) zamiast zależeć
5309 - od kolejności wstawiania w repo.json, oraz ostrzec o konflikcie provides."""
5310 - global _provides_cache
5311 - cached_repo, idx = _provides_cache
5312 - if cached_repo is repo:
5313 - return idx
5314 - idx = {}
5315 - for _pn, _p in repo.items():
5316 - for _prov in (getattr(_p, "provides", None) or []):
5317 - idx.setdefault(_prov, []).append(_pn)
5318 - for _prov, _pns in idx.items():
5319 - if len(_pns) > 1 and _prov not in _PROVIDES_WARNED:
5320 - _PROVIDES_WARNED.add(_prov)
5321 - _sorted = sorted(_pns)
5322 - print(f" ⚠ {_('provides_conflict', name=_prov, providers=', '.join(_sorted), chosen=_sorted[0])}",
5323 - file=sys.stderr)
5324 - _provides_cache = (repo, idx)
5325 - return idx
5326 -
5327 -
5328 -def _resolve_provides(name: str, repo: dict, installed: Optional[dict] = None) -> str:
5329 - """Rozwija wirtualną nazwę pakietu do rzeczywistej nazwy.
5330 -
5331 - Kolejność: repo → PROVIDES_MAP → wzorce → provides z repo.json →
5332 - provides ZAINSTALOWANYCH pakietów (lokalnie zbudowane poza repo też
5333 - dostarczają wirtualne zależności) → fallback pkgconfig (czyszczenie nazwy).
5334 - """
5335 - if name in repo:
5336 - return name
5337 - if name in PROVIDES_MAP:
5338 - real = PROVIDES_MAP[name]
5339 - if real in repo:
5340 - return real
5341 - # Wzorce: moduły Qt (Qt5Core/Qt6Widgets) i GStreamer (gstreamer-video-1.0)
5342 - if name.startswith("pkgconfig(Qt5"):
5343 - real = "qt5"
5344 - if real in repo:
5345 - return real
5346 - if name.startswith("pkgconfig(Qt6"):
5347 - real = "qt6"
5348 - if real in repo:
5349 - return real
5350 - if name.startswith("pkgconfig(gstreamer-") and name.endswith("-1.0)"):
5351 - real = "gstreamer"
5352 - if real in repo:
5353 - return real
5354 - if name.startswith("pkgconfig(gst-"):
5355 - real = "gst-plugins-base"
5356 - if real in repo:
5357 - return real
5358 - # Dynamiczne provides z repo.json (sekcja provides: w PAGBUILD.yaml)
5359 - # Determinizm: przy wielu dostawcach wybieramy posortowanego pierwszego
5360 - # (i ostrzegamy raz), zamiast zależeć od kolejności w repo.json.
5361 - _idx = _provides_index(repo)
5362 - if name in _idx:
5363 - return min(_idx[name])
5364 - # provides ZAINSTALOWANYCH pakietów – lokalnie zbudowane (pagbuild, poza
5365 - # repo) też dostarczają wirtualne zależności i muszą być rozpoznawane.
5366 - if installed:
5367 - _inst_cands = [pn for pn, meta in installed.items()
5368 - if isinstance(meta, dict) and name in (meta.get("provides") or [])]
5369 - if _inst_cands:
5370 - return min(_inst_cands)
5371 - clean = name
5372 - if name.startswith("pkgconfig(") and ")" in name:
5373 - clean = name.split("(", 1)[1].rstrip(")")
5374 - elif name.startswith("pkgconfig32(") and ")" in name:
5375 - clean = name.split("(", 1)[1].rstrip(")")
5376 - if clean != name and clean in repo:
5377 - return clean
5378 - return name
5379 -
5380 -
5381 -def cmd_why(pkg_name: str):
5382 - """Pokazuje dlaczego pakiet jest zainstalowany."""
5383 - installed = load_json(INSTALLED_DB)
5384 - world = load_world()
5385 - if pkg_name not in installed:
5386 - print(f" {pkg_name}: {_('why_not_installed')}"); return 1
5387 - if pkg_name in world:
5388 - print(f" {pkg_name}-{installed[pkg_name]['version']}: {_('why_explicit')}")
5389 - return 0
5390 - parents = set()
5391 - for w in world:
5392 - _find_dep_path(w, pkg_name, installed, set(), [], parents)
5393 - if parents:
5394 - for pp in sorted(parents):
5395 - print(f" {pkg_name}: {_('why_dependency')} {' → '.join(pp)}")
5396 - else:
5397 - print(f" {pkg_name}: {_('why_dependency')} (unknown/orphan)")
5398 - return 0
5399 -
5400 -
5401 -def _find_dep_path(cur, target, installed, visited, path, results):
5402 - if cur in visited: return
5403 - visited.add(cur); path.append(cur)
5404 - if cur == target:
5405 - results.add(tuple(path))
5406 - else:
5407 - for dep in installed.get(cur, {}).get("dependencies", []):
5408 - _find_dep_path(dep, target, installed, visited, path, results)
5409 - path.pop(); visited.discard(cur)
5410 -
5411 -
5412 -def cmd_rdepends(pkg_name: str):
5413 - """Pokazuje które pakiety zależą od danego pakietu (reverse dependencies).
5414 -
5415 - Odwrotność `pag why`: dla każdego zainstalowanego pakietu sprawdza, czy
5416 - któraś z jego zależności (także wirtualna, przez provides) wskazuje na
5417 - pkg_name. Przydatne przed `pag remove` – pokazuje, co przestanie działać.
5418 - """
5419 - installed = load_json(INSTALLED_DB)
5420 - if pkg_name not in installed:
5421 - print(f" {pkg_name}: {_('why_not_installed')}"); return 1
5422 - world = load_world()
5423 - # Nazwy, które zależą od pkg_name – sama nazwa plus jej wirtualne provides.
5424 - provided = {pkg_name} | set(installed[pkg_name].get("provides") or [])
5425 - rev = []
5426 - for name, meta in installed.items():
5427 - if name == pkg_name:
5428 - continue
5429 - for dep in (meta.get("dependencies") or []):
5430 - if dep in provided or _resolve_provides(dep, {}, installed) == pkg_name:
5431 - rev.append(name); break
5432 - if not rev:
5433 - print(f" {pkg_name}: {_('rdepends_none')}")
5434 - return 0
5435 - print(f"🔗 {_('rdepends_title', pkg_name, len(rev))}")
5436 - for n in sorted(rev):
5437 - kind = _("why_explicit") if n in world else _("why_dependency")
5438 - print(f" {n}-{installed[n].get('version', '?')} ({kind})")
5439 - return 0
5440 -
5441 -
5442 -def cmd_autoremove():
5443 - """Automatycznie usuwa osierocone zależności bez pytania."""
5444 - installed = load_json(INSTALLED_DB)
5445 - world = load_world()
5446 - orphans = _find_orphans(installed, world)
5447 - if not orphans: print(f"✅ {_('autoremove_none')}"); return 0
5448 - print(f"🗑 {_('orphans_found', len(orphans), ', '.join(sorted(orphans)[:10]))}")
5449 - return cmd_remove(list(orphans))
5450 -
5451 -
5452 -def cmd_download(package_names):
5453 - """Pobiera pakiety do cache bez instalowania."""
5454 - ensure_dirs()
5455 - repo = fetch_all_packages()
5456 - if not repo: print(f"❌ {_('no_index')}"); return 1
5457 - total_size = 0; downloaded = []
5458 - for name in package_names:
5459 - pkg = repo.get(name)
5460 - if not pkg:
5461 - print(f" ❌ {name}: {_('not_found')}"); continue
5462 - print(f" ↓ {name}-{pkg.version} ...", end=" ", flush=True)
5463 - path = _download_pkg(pkg)
5464 - if path:
5465 - total_size += os.path.getsize(path)
5466 - downloaded.append(name)
5467 - print(_c("green", "✓"))
5468 - else:
5469 - print(_c("red", "✗"))
5470 - if downloaded:
5471 - print(f"\n✅ {_('downloaded', len(downloaded), total_size/1048576)}")
5472 - return 0 if len(downloaded) == len(package_names) else 1
5473 -
5474 -
5475 -def cmd_stats():
5476 - """Wyświetla statystyki PAG."""
5477 - installed = load_json(INSTALLED_DB)
5478 - history = load_json(HISTORY_FILE) if os.path.exists(HISTORY_FILE) else []
5479 - total_size = sum(i.get("size_bytes", 0) for i in installed.values())
5480 - total_files = _db_count_files()
5481 - cache_size = sum(
5482 - os.path.getsize(os.path.join(PAG_CACHE, f))
5483 - for f in os.listdir(PAG_CACHE)
5484 - if os.path.isfile(os.path.join(PAG_CACHE, f))
5485 - ) if os.path.isdir(PAG_CACHE) else 0
5486 - last_update = "never"
5487 - for e in reversed(history):
5488 - if e.get("action") in ("install", "upgrade") and e.get("success"):
5489 - last_update = e.get("timestamp", "?")[:19]; break
5490 - print(f"\n {_c('bold', _('stats_title'))}")
5491 - print(f" {'─' * 40}")
5492 - print(f" {_('stats_packages'):<30} {len(installed)}")
5493 - print(f" {_('stats_files'):<30} {total_files}")
5494 - print(f" {_('stats_size'):<30} {total_size/1048576:.1f} MB")
5495 - print(f" {_('stats_cache'):<30} {cache_size/1048576:.1f} MB")
5496 - print(f" {_('stats_history'):<30} {len(history)}")
5497 - print(f" {_('stats_last_update'):<30} {last_update}")
5498 - _bs = _base_summary(repo={}) # bez sieci – tylko stan zarządzania bazą
5499 - if _bs["total"]:
5500 - _bt = f"{_bs['tracked']}/{_bs['total']}"
5501 - if _bs["tracked"] < _bs["total"]:
5502 - _bt += " (sudo pag base adopt)"
5503 - print(f" {_('stats_base'):<30} {_bt}")
5504 - by_size = sorted(installed.items(), key=lambda x: x[1].get("size_bytes", 0), reverse=True)[:5]
5505 - if by_size:
5506 - print(f"\n {_c('dim', 'Top 5:')}")
5507 - for n, i in by_size:
5508 - print(f" {n}-{i['version']} {i.get('size_bytes',0)/1048576:.1f} MB")
5509 - return 0
5510 -
5511 -
5512 -def cmd_repo_add(url, name=None):
5513 - if not url.startswith("https://") and not os.environ.get("PAG_INSECURE"):
5514 - print(f" {_('sec_https')}"); return 1
5515 - ensure_dirs()
5516 - url = url.rstrip("/")
5517 - repos = get_repos()
5518 - if url in repos: print(f"⚠ {_('repo_exists', url)}"); return
5519 - if name:
5520 - # Drop-in: /etc/pag/repos/<nazwa>.conf (jak `echo url > .../stable.conf`)
5521 - os.makedirs(REPOS_DIR, exist_ok=True)
5522 - target = os.path.join(REPOS_DIR, name.rstrip("/").replace("/", "_") + ".conf")
5523 - with open(target, "w") as f: f.write(f"{url}\n")
5524 - print(f"✅ {_('repo_added', url)} → {target}")
5525 - return
5526 - with open(REPOS_CONF, "a") as f: f.write(f"{url}\n")
5527 - print(f"✅ {_('repo_added', url)}")
5528 -
5529 -def cmd_repo_list():
5530 - for i, url in enumerate(get_repos(), 1): print(f" {i}. {url}")
5531 -
5532 -FLATPAK_REMOTE_URL = "https://flathub.org/repo/flathub.flatpakrepo"
5533 -
5534 -def _check_flatpak(quiet: bool = False):
5535 - if not shutil.which("flatpak"):
5536 - if not quiet:
5537 - print(f"❌ {_('flatpak_missing')}")
5538 - return False
5539 - r = subprocess.run(["flatpak", "remotes"], capture_output=True, text=True)
5540 - if "flathub" not in r.stdout:
5541 - print(f"⚠ {_('flatpak_adding')}")
5542 - # Jako root dodajemy remote systemowy; bez roota – w instalacji użytkownika,
5543 - # żeby remote i miejsce instalacji były spójne (patrz _flatpak_do_install).
5544 - add = ["flatpak", "remote-add", "--if-not-exists"]
5545 - if os.geteuid() != 0:
5546 - add.append("--user")
5547 - subprocess.run(add + ["flathub", FLATPAK_REMOTE_URL], check=False)
5548 - return True
5549 -
5550 -def _spinner(msg: str):
5551 - """Prosty spinner „myślenia” w osobnym wątku. Zwraca funkcję stop()."""
5552 - stop = threading.Event()
5553 - def _spin():
5554 - for c in itertools.cycle("|/-\\"):
5555 - if stop.is_set():
5556 - break
5557 - sys.stdout.write(f"\r {msg} {c}")
5558 - sys.stdout.flush()
5559 - time.sleep(0.1)
5560 - t = threading.Thread(target=_spin, daemon=True)
5561 - t.start()
5562 - def _stop():
5563 - stop.set()
5564 - t.join(timeout=0.3)
5565 - sys.stdout.write("\r" + " " * (len(msg) + 4) + "\r")
5566 - sys.stdout.flush()
5567 - return _stop
5568 -
5569 -
5570 -def _flatpak_search_raw(query: str) -> List[dict]:
5571 - """Szuka we Flathub i zwraca listę wyników jako słowniki."""
5572 - if not _check_flatpak():
5573 - return []
5574 - stop = _spinner("Szukam we Flathub...")
5575 - try:
5576 - try:
5577 - r = subprocess.run(
5578 - ["flatpak", "search", "--columns=name,description,application,version,branch,remotes", query],
5579 - capture_output=True, text=True, timeout=120
5580 - )
5581 - finally:
5582 - stop()
5583 - if r.returncode != 0 and "No matches found" not in r.stdout and not r.stdout.strip():
5584 - print(f" ⚠ flatpak search: {r.stderr.strip()[:150]}")
5585 - results = []
5586 - for line in r.stdout.strip().split("\n"):
5587 - parts = line.split("\t")
5588 - if len(parts) >= 3:
5589 - results.append({
5590 - "name": parts[0].strip(),
5591 - "description": parts[1].strip() if len(parts) > 1 else "",
5592 - "app_id": parts[2].strip() if len(parts) > 2 else "",
5593 - "version": parts[3].strip() if len(parts) > 3 else "",
5594 - "branch": parts[4].strip() if len(parts) > 4 else "stable",
5595 - "origin": parts[5].strip() if len(parts) > 5 else "flathub",
5596 - })
5597 - return results
5598 - except Exception as e:
5599 - print(f" ⚠ Błąd wyszukiwania: {e}", file=sys.stderr)
5600 - return []
5601 -
5602 -def _flatpak_find_best(query: str) -> Optional[dict]:
5603 - """
5604 - Szuka we Flathub i próbuje znaleźć najlepsze dopasowanie.
5605 - - Jeśli query dokładnie pasuje do app_id → zwraca od razu
5606 - - Jeśli query pasuje do nazwy → zwraca pierwsze
5607 - - Jeśli wiele wyników → wyświetla listę i pyta użytkownika
5608 - - Jeśli brak → zwraca None
5609 - """
5610 - results = _flatpak_search_raw(query)
5611 - if not results:
5612 - return None
5613 -
5614 - # Dokładne dopasowanie app_id
5615 - exact = [r for r in results if r["app_id"].lower() == query.lower()]
5616 - if exact:
5617 - return exact[0]
5618 -
5619 - # Dokładne dopasowanie nazwy
5620 - exact_name = [r for r in results if r["name"].lower() == query.lower()]
5621 - if exact_name:
5622 - return exact_name[0]
5623 -
5624 - # Jednoznaczne dopasowanie (tylko 1 wynik)
5625 - if len(results) == 1:
5626 - return results[0]
5627 -
5628 - # Wiele wyników – pokaż użytkownikowi
5629 - print(f"\n {_('flatpak_found', len(results))}")
5630 - for i, r in enumerate(results):
5631 - print(f" {i+1}. {_c('bold', r['name'])} ({r['app_id']})")
5632 - if r["version"]:
5633 - print(f" {_('flatpak_info_version')}: {r['version']}")
5634 - if r["description"]:
5635 - desc = r["description"][:80] + ("..." if len(r["description"]) > 80 else "")
5636 - print(f" {desc}")
5637 -
5638 - try:
5639 - choice = input(f"\n Wybierz numer (1-{len(results)}) lub Enter aby anulować: ").strip()
5640 - if not choice:
5641 - return None
5642 - idx = int(choice) - 1
5643 - if 0 <= idx < len(results):
5644 - return results[idx]
5645 - except (EOFError, ValueError, IndexError):
5646 - pass
5647 - return None
5648 -
5649 -def _flatpak_get_installed_info(app_id: str) -> Optional[dict]:
5650 - """Zwraca info o zainstalowanym flatpaku lub None."""
5651 - try:
5652 - r = subprocess.run(
5653 - ["flatpak", "info", "--columns=name,version,branch,origin,installed-size,description", app_id],
5654 - capture_output=True, text=True, timeout=10
5655 - )
5656 - if r.returncode != 0:
5657 - return None
5658 - parts = r.stdout.strip().split("\t")
5659 - if len(parts) < 3:
5660 - return None
5661 - return {
5662 - "name": parts[0].strip(),
5663 - "version": parts[1].strip() if len(parts) > 1 else "",
5664 - "branch": parts[2].strip() if len(parts) > 2 else "",
5665 - "origin": parts[3].strip() if len(parts) > 3 else "",
5666 - "size": parts[4].strip() if len(parts) > 4 else "",
5667 - "description": parts[5].strip() if len(parts) > 5 else "",
5668 - }
5669 - except Exception:
5670 - return None
5671 -
5672 -def _flatpak_is_installed(app_id: str) -> bool:
5673 - """Sprawdza czy flatpak o danym ID jest zainstalowany."""
5674 - try:
5675 - r = subprocess.run(
5676 - ["flatpak", "info", app_id],
5677 - capture_output=True, text=True, timeout=10
5678 - )
5679 - return r.returncode == 0
5680 - except Exception:
5681 - return False
5682 -
5683 -# =============================================================================
5684 -# FLATPAK – KOMENDY GŁÓWNE (zunifikowany interfejs)
5685 -# =============================================================================
5686 -# pag flatpak <query> → szuka i proponuje instalację (jeśli nie zainstalowany)
5687 -# pag flatpak search <query> → tylko szuka
5688 -# pag flatpak install <query> → instaluje
5689 -# pag flatpak remove <id> → usuwa
5690 -# pag flatpak list → lista zainstalowanych
5691 -# pag flatpak update → aktualizuje wszystkie
5692 -# pag flatpak info <id> → szczegóły flatpaka
5693 -
5694 -def cmd_flatpak(args: list):
5695 - """
5696 - Główna komenda flatpak – inteligentnie rozpoznaje intencję:
5697 - pag flatpak firefox → szuka i instaluje (jeśli nieznaleziony → szuka)
5698 - pag flatpak search firefox → tylko wyszukiwanie
5699 - pag flatpak install ... → bezpośrednia instalacja
5700 - pag flatpak remove ... → odinstalowanie
5701 - pag flatpak list → lista
5702 - pag flatpak update → aktualizacja
5703 - pag flatpak info ... → szczegóły
5704 - """
5705 - if not _check_flatpak():
5706 - return 1
5707 -
5708 - if not args:
5709 - # Bez argumentów – domyślnie lista
5710 - return cmd_flatpak_list()
5711 -
5712 - subcmd = args[0].lower()
5713 - rest = args[1:]
5714 -
5715 - # ── Podkomendy jawne ────────────────────────────────────────────────
5716 - if subcmd == "search":
5717 - if not rest:
5718 - print(_("flatpak_usage")); return 1
5719 - return cmd_flatpak_search(" ".join(rest))
5720 -
5721 - elif subcmd == "install":
5722 - if not rest:
5723 - print(_("flatpak_usage")); return 1
5724 - return _flatpak_smart_install(rest)
5725 -
5726 - elif subcmd == "remove" or subcmd == "uninstall":
5727 - if not rest:
5728 - print(_("flatpak_usage")); return 1
5729 - return _flatpak_smart_remove(rest)
5730 -
5731 - elif subcmd == "list":
5732 - return cmd_flatpak_list()
5733 -
5734 - elif subcmd == "update":
5735 - return cmd_flatpak_update()
5736 -
5737 - elif subcmd == "info":
5738 - if not rest:
5739 - print(_("flatpak_usage")); return 1
5740 - return cmd_flatpak_info(rest[0])
5741 -
5742 - else:
5743 - # ── Inteligentne wykrywanie: pag flatpak <nazwa> ────────────────
5744 - # Sprawdź czy to zainstalowany flatpak → pokaż info
5745 - # Jeśli nie → szukaj i zaproponuj instalację
5746 - query = " ".join(args)
5747 -
5748 - # Najpierw sprawdź czy już zainstalowany
5749 - if _flatpak_is_installed(query):
5750 - print(f" 📦 {_c('green', query)} – already installed (use 'pag flatpak info {query}' for details)")
5751 - return cmd_flatpak_info(query)
5752 -
5753 - # Szukaj we Flathub
5754 - print(f" {_('flatpak_searching', query)}")
5755 - best = _flatpak_find_best(query)
5756 - if not best:
5757 - print(f" ❌ '{query}' – {_('flatpak_not_found')}")
5758 - return 1
5759 -
5760 - print(f"\n {_c('cyan', best['name'])} ({best['app_id']})")
5761 - if best["version"]:
5762 - print(f" {_('flatpak_info_version')}: {best['version']}")
5763 - if best["description"]:
5764 - print(f" {best['description']}")
5765 -
5766 - try:
5767 - ans = input(f"\n {_('flatpak_install_prompt', best['name'])}").strip().lower()
5768 - except (EOFError, KeyboardInterrupt):
5769 - print(f"\n ⚠ {_('no_tty')}")
5770 - return 0
5771 - if ans and ans not in ("t", "y"):
5772 - print(_("cancelled"))
5773 - return 0
5774 -
5775 - return _flatpak_do_install(best["app_id"])
5776 -
5777 -def _flatpak_smart_install(names: list) -> int:
5778 - """Instaluje flatpaki – obsługuje nazwy częściowe (wyszukuje przed instalacją)."""
5779 - failed = 0
5780 - for name in names:
5781 - if "." in name and "/" not in name:
5782 - # Wygląda na pełne app_id (np. org.mozilla.firefox)
5783 - app_id = name
5784 - else:
5785 - # Szukaj najlepszego dopasowania
5786 - best = _flatpak_find_best(name)
5787 - if not best:
5788 - print(f" ❌ '{name}' – {_('flatpak_not_found')}")
5789 - failed += 1
5790 - continue
5791 - app_id = best["app_id"]
5792 - print(f" → {best['name']} ({app_id})")
5793 -
5794 - if _flatpak_do_install(app_id) != 0:
5795 - failed += 1
5796 - return 1 if failed else 0
5797 -
5798 -def _flatpak_export_dirs() -> List[str]:
5799 - """Katalogi eksportów Flatpaka (system + użytkownika) obecne na dysku.
5800 -
5801 - Instalacja użytkownika roota (/root/.local/share/flatpak) jest świadomie
5802 - POMIJANA – to wewnętrzny artefakt roota, którego sesja użytkownika nigdy
5803 - nie zobaczy (patrz _flatpak_do_install)."""
5804 - dirs = ["/var/lib/flatpak/exports"]
5805 - home = os.path.expanduser("~")
5806 - if home and home not in ("/root", "/"):
5807 - dirs.append(os.path.join(home, ".local", "share", "flatpak", "exports"))
5808 - return [d for d in dirs if os.path.isdir(d)]
5809 -
5810 -
5811 -def _flatpak_refresh_caches() -> None:
5812 - """Odświeża cache pulpitu i ikon po zmianie w Flatpaku (best-effort).
5813 -
5814 - Flatpak robi to sam, ale tylko gdy `update-desktop-database` jest w PATH.
5815 - Bez tego nowo zainstalowana aplikacja bywa nieobecna w menu."""
5816 - for exports in _flatpak_export_dirs():
5817 - apps = os.path.join(exports, "share", "applications")
5818 - if os.path.isdir(apps) and shutil.which("update-desktop-database"):
5819 - subprocess.run(["update-desktop-database", apps],
5820 - capture_output=True, check=False, timeout=60)
5821 - icons = os.path.join(exports, "share", "icons", "hicolor")
5822 - if os.path.isdir(icons) and shutil.which("gtk-update-icon-cache"):
5823 - subprocess.run(["gtk-update-icon-cache", "-q", "-t", "-f", icons],
5824 - capture_output=True, check=False, timeout=120)
5825 -
5826 -
5827 -def _flatpak_session_sees_exports() -> bool:
5828 - """Czy bieżąca sesja ma eksporty Flatpaka w XDG_DATA_DIRS."""
5829 - raw = os.environ.get("XDG_DATA_DIRS", "")
5830 - dirs = {d for d in raw.split(":") if d} or {"/usr/local/share", "/usr/share"}
5831 - return any(os.path.join(e, "share") in dirs for e in _flatpak_export_dirs())
5832 -
5833 -
5834 -def _flatpak_warn_if_invisible() -> None:
5835 - """Ostrzega, gdy sesja nie widzi eksportów – inaczej wygląda to jak
5836 - „zainstalowało się, ale nie ma go w menu / na PC”."""
5837 - if not _flatpak_session_sees_exports():
5838 - print(f" ⚠ {_('flatpak_menu_hint')}")
5839 - print(f" {_('flatpak_menu_fix')}")
5840 -
5841 -
5842 -def _flatpak_do_install(app_id: str) -> int:
5843 - """Wykonuje właściwą instalację flatpaka.
5844 -
5845 - Jako root wymuszamy instalację SYSTEMOWĄ (--system). Bez tego `flatpak`
5846 - uruchomiony jako root potrafi zainstalować aplikację w instalacji
5847 - użytkownika roota (/root/.local/share/flatpak) – widocznej dla roota, ale
5848 - nie dla zalogowanego użytkownika. To dokładnie efekt „instaluje, ale nie
5849 - mam tego na PC”. Bez roota próbujemy instalacji systemowej (polkit),
5850 - a w razie niepowodzenia cofamy się do instalacji użytkownika (--user).
5851 -
5852 - Zakres (scope) ma znaczenie: instalacja SYSTEMOWA (--system) jest widoczna
5853 - dla wszystkich użytkowników, a --user tylko dla bieżącego (dla roota:
5854 - /root/.local/... → niewidoczna dla sesji). `flatpak list` bez flag pokazuje
5855 - oba zakresy, więc systemowa instalacja roota jest widoczna też dla
5856 - zwykłego użytkownika."""
5857 - print(f" {_('flatpak_installing', app_id)}")
5858 - if os.geteuid() == 0:
5859 - result = subprocess.run(
5860 - ["flatpak", "install", "-y", "--system", "flathub", app_id],
5861 - check=False, timeout=600)
5862 - else:
5863 - result = subprocess.run(
5864 - ["flatpak", "install", "-y", "flathub", app_id],
5865 - check=False, timeout=600)
5866 - if result.returncode != 0:
5867 - # Flathub tylko dla użytkownika / brak agenta polkit – instalacja
5868 - # lokalna użytkownika jest lepsza niż twardy błąd.
5869 - subprocess.run(
5870 - ["flatpak", "remote-add", "--if-not-exists", "--user",
5871 - "flathub", FLATPAK_REMOTE_URL], check=False, timeout=60)
5872 - result = subprocess.run(
5873 - ["flatpak", "install", "-y", "--user", "flathub", app_id],
5874 - check=False, timeout=600)
5875 - if result.returncode != 0:
5876 - print(f" ❌ {_('download_fail')}: {app_id}")
5877 - return 1
5878 - _flatpak_refresh_caches()
5879 - print(f" ✅ {_('flatpak_installed', app_id)}")
5880 - _flatpak_warn_if_invisible()
5881 - return 0
5882 -
5883 -def _flatpak_smart_remove(names: list) -> int:
5884 - """Usuwa flatpaki – obsługuje nazwy częściowe."""
5885 - # Pobierz listę zainstalowanych
5886 - try:
5887 - r = subprocess.run(
5888 - ["flatpak", "list", "--columns=application,name"],
5889 - capture_output=True, text=True, timeout=10
5890 - )
5891 - installed = {}
5892 - for line in r.stdout.strip().split("\n"):
5893 - parts = line.split("\t")
5894 - if len(parts) >= 2:
5895 - installed[parts[0].strip()] = parts[1].strip()
5896 - except Exception:
5897 - installed = {}
5898 -
5899 - failed = 0
5900 - for name in names:
5901 - app_id = name
5902 -
5903 - # Jeśli nie podano pełnego ID – spróbuj dopasować
5904 - if name not in installed:
5905 - matches = {aid: aname for aid, aname in installed.items()
5906 - if name.lower() in aid.lower() or name.lower() in aname.lower()}
5907 - if len(matches) == 0:
5908 - print(f" ❌ '{name}' – {_('flatpak_not_installed', name)}")
5909 - failed += 1
5910 - continue
5911 - elif len(matches) == 1:
5912 - app_id = list(matches.keys())[0]
5913 - print(f" → {matches[app_id]} ({app_id})")
5914 - else:
5915 - print(f"\n Wiele dopasowań dla '{name}':")
5916 - for i, (aid, aname) in enumerate(sorted(matches.items()), 1):
5917 - print(f" {i}. {aname} ({aid})")
5918 - try:
5919 - choice = input(f"\n Wybierz numer (1-{len(matches)}) lub Enter: ").strip()
5920 - if not choice:
5921 - failed += 1
5922 - continue
5923 - aid_list = sorted(matches.keys())
5924 - app_id = aid_list[int(choice) - 1]
5925 - except (EOFError, ValueError, IndexError):
5926 - failed += 1
5927 - continue
5928 -
5929 - print(f" 🗑 {app_id} ...", end=" ", flush=True)
5930 - result = subprocess.run(
5931 - ["flatpak", "uninstall", "-y", app_id],
5932 - capture_output=True, text=True, timeout=120
5933 - )
5934 - if result.returncode == 0:
5935 - print("✅")
5936 - print(f" {_('flatpak_removed', app_id)}")
5937 - else:
5938 - print("❌")
5939 - failed += 1
5940 - if not failed:
5941 - _flatpak_refresh_caches()
5942 - return 1 if failed else 0
5943 -
5944 -def cmd_flatpak_search(q: str):
5945 - """Wyszukuje we Flathub i wyświetla wyniki (z możliwością wyboru do instalacji)."""
5946 - if not _check_flatpak():
5947 - return 1
5948 - results = _flatpak_search_raw(q)
5949 - if not results:
5950 - print(f" ❌ '{q}' – {_('flatpak_not_found')}")
5951 - return 1
5952 - print(f"\n {_('flatpak_found', len(results))}")
5953 - shown = results[:30] # max 30 wyników
5954 - for i, r in enumerate(shown, 1):
5955 - installed = "📦 " if _flatpak_is_installed(r["app_id"]) else " "
5956 - print(f" {i:>2}. {installed}{_c('bold', r['name'])} ({r['app_id']})")
5957 - if r["version"]:
5958 - print(f" {_('flatpak_info_version')}: {r['version']} | {_('flatpak_info_branch')}: {r['branch']}")
5959 - if r["description"]:
5960 - desc = r["description"][:100] + ("..." if len(r["description"]) > 100 else "")
5961 - print(f" {_c('dim', desc)}")
5962 - if len(results) > 30:
5963 - print(f" ... i {len(results) - 30} więcej. Doprecyzuj zapytanie.")
5964 -
5965 - # Interaktywny wybór – wpisz numer, aby zainstalować (Enter = anuluj)
5966 - try:
5967 - ans = input(f"\n Wybierz numer do zainstalowania (1-{len(shown)}) lub Enter aby anulować: ").strip()
5968 - except (EOFError, KeyboardInterrupt):
5969 - return 0
5970 - if ans:
5971 - try:
5972 - idx = int(ans) - 1
5973 - if 0 <= idx < len(shown):
5974 - return _flatpak_do_install(shown[idx]["app_id"])
5975 - print(_("cancelled"))
5976 - except (ValueError, IndexError):
5977 - print(_("cancelled"))
5978 - return 0
5979 -
5980 -def cmd_flatpak_list():
5981 - """Wyświetla zainstalowane flatpaki."""
5982 - if not _check_flatpak():
5983 - return 1
5984 - r = subprocess.run(
5985 - ["flatpak", "list", "--columns=application,name,version,origin,installation,installed-size"],
5986 - capture_output=True, text=True, timeout=10
5987 - )
5988 - lines = [l for l in r.stdout.strip().split("\n") if l.strip()]
5989 - if not lines:
5990 - print(" (brak zainstalowanych flatpaków)")
5991 - return 0
5992 - print(f" Zainstalowane flatpaki ({len(lines)}):")
5993 - for line in lines:
5994 - parts = line.split("\t")
5995 - if len(parts) >= 3:
5996 - app_id, name, version = parts[0], parts[1], parts[2]
5997 - scope = parts[4] if len(parts) > 4 else ""
5998 - size = parts[5] if len(parts) > 5 else ""
5999 - size_str = f" ({size})" if size else ""
6000 - scope_str = f" [{scope}]" if scope else ""
6001 - print(f" 📦 {_c('bold', name)} {version}{scope_str}{size_str}")
6002 - print(f" {_c('dim', app_id)}")
6003 - return 0
6004 -
6005 -def cmd_flatpak_update():
6006 - """Aktualizuje wszystkie flatpaki."""
6007 - if not _check_flatpak():
6008 - return 1
6009 - print(" 🔄 Aktualizacja flatpaków...")
6010 - result = subprocess.run(["flatpak", "update", "-y"], check=False, timeout=600)
6011 - if result.returncode == 0:
6012 - _flatpak_refresh_caches()
6013 - print(f" ✅ {_('flatpak_updated')}")
6014 - return result.returncode
6015 -
6016 -def cmd_flatpak_info(app_id: str):
6017 - """Wyświetla szczegóły flatpaka (zainstalowanego lub z Flathub)."""
6018 - if not _check_flatpak():
6019 - return 1
6020 -
6021 - # Najpierw sprawdź zainstalowany
6022 - info = _flatpak_get_installed_info(app_id)
6023 - if info:
6024 - print(f"\n 📦 {_c('bold', info['name'])} {_c('green', '[zainstalowany]')}")
6025 - print(f" {'─' * 45}")
6026 - print(f" {_('flatpak_info_id'):<16} {app_id}")
6027 - print(f" {_('flatpak_info_version'):<16} {info['version']}")
6028 - print(f" {_('flatpak_info_branch'):<16} {info['branch']}")
6029 - print(f" {_('flatpak_info_origin'):<16} {info['origin']}")
6030 - if info["size"]:
6031 - print(f" {_('flatpak_info_size'):<16} {info['size']}")
6032 - if info["description"]:
6033 - print(f" {_('flatpak_info_desc'):<16} {info['description']}")
6034 - return 0
6035 -
6036 - # Szukaj we Flathub
6037 - results = _flatpak_search_raw(app_id)
6038 - exact = [r for r in results if r["app_id"].lower() == app_id.lower()]
6039 - if not exact:
6040 - # Spróbuj częściowego dopasowania
6041 - if results:
6042 - exact = [results[0]]
6043 - else:
6044 - print(f" ❌ '{app_id}' – {_('flatpak_not_found')}")
6045 - return 1
6046 -
6047 - r = exact[0]
6048 - print(f"\n 📦 {_c('bold', r['name'])} (Flathub)")
6049 - print(f" {'─' * 45}")
6050 - print(f" {_('flatpak_info_id'):<16} {r['app_id']}")
6051 - print(f" {_('flatpak_info_version'):<16} {r['version']}")
6052 - if r["description"]:
6053 - print(f" {_('flatpak_info_desc'):<16} {r['description']}")
6054 - print(f"\n 💡 Aby zainstalować: pag flatpak install {r['app_id']}")
6055 - return 0
6056 -
6057 -# =============================================================================
6058 -# IMMUTABLE OS – KOMENDY DEPLOYMENTOWE
6059 -# =============================================================================
6060 -
6061 -# Pakiety jądra – po ich instalacji trzeba przebudować initramfs
6062 -KERNEL_PACKAGE_PATTERNS = ["linux", "kernel", "linux-kernel", "linux-lts"]
6063 -
6064 -def _is_kernel_package(name: str) -> bool:
6065 - """Sprawdza czy pakiet to jądro (wymaga przebudowy initramfs)."""
6066 - name_lower = name.lower()
6067 - return any(pattern in name_lower for pattern in KERNEL_PACKAGE_PATTERNS)
6068 -
6069 -# Towarzysze jądra – aktualizowani RAZEM z jądrem, jeśli są zainstalowani,
6070 -# żeby userspace i moduły jądra nie rozjechały się wersjami.
6071 -KERNEL_SIBLINGS = ("linux-headers", "nvidia-dkms", "nvidia-kernel", "dkms",
6072 - "virtualbox-host-modules", "virtualbox-guest-modules")
6073 -
6074 -
6075 -def _kernel_group_updates(pending):
6076 - """Gdy w transakcji jest jądro, dołóż jego towarzyszy (jeśli zainstalowani)."""
6077 - if not any(_is_kernel_package(n) for n in pending):
6078 - return pending
6079 - try:
6080 - installed = load_json(INSTALLED_DB)
6081 - repo = fetch_all_packages()
6082 - except Exception:
6083 - return pending
6084 - out = list(pending)
6085 - for sib in KERNEL_SIBLINGS:
6086 - if sib in installed and sib in repo and sib not in out:
6087 - out.append(sib)
6088 - return out
6089 -
6090 -
6091 -def _post_kernel_hooks():
6092 - """Po zmianie jądra na ZWYKŁEJ instalacji: initramfs + DKMS + GRUB.
6093 -
6094 - Kolejność ma znaczenie: najpierw initramfs dla nowego jądra, potem moduły
6095 - out-of-tree (DKMS) pod to samo jądro, na końcu wpisy GRUB. Bez tego
6096 - aktualizacja jądra zostawia system z „nowymi modułami na starym jądrze”.
6097 - """
6098 - try:
6099 - _rebuild_initramfs()
6100 - except Exception:
6101 - pass
6102 - if shutil.which("dkms"):
6103 - try:
6104 - print(" 🔧 DKMS: przebudowa modułów out-of-tree (nvidia/vbox)...")
6105 - subprocess.run(["dkms", "autoinstall"],
6106 - capture_output=True, text=True, timeout=1800)
6107 - except Exception:
6108 - pass
6109 - _refresh_bootloader()
6110 -
6111 -def _rebuild_initramfs(deploy_dir: str = "") -> bool:
6112 - """
6113 - Przebudowuje initramfs dla aktywnego (lub podanego) deploymentu.
6114 - Używa skryptu pag-initramfs lub ręcznego cpio.
6115 - """
6116 - if deploy_dir:
6117 - root = deploy_dir
6118 - else:
6119 - root = _get_deployment_root()
6120 -
6121 - if root == PAG_ROOT:
6122 - # Zwykły system – NAJPIERW natywne narzędzie PaganOS (per-wersja +
6123 - # root=UUID/PARTUUID/LABEL), potem dracut/mkinitcpio.
6124 - if shutil.which("pagan-initramfs"):
6125 - print(" 🔧 Przebudowa initramfs (pagan-initramfs)...")
6126 - try:
6127 - r = subprocess.run(["pagan-initramfs"], capture_output=True,
6128 - text=True, timeout=600)
6129 - if r.returncode == 0:
6130 - return True
6131 - except Exception:
6132 - pass
6133 - # Zwykły system – użyj dracut jeśli dostępny
6134 - if shutil.which("dracut"):
6135 - print(" 🔧 Przebudowa initramfs (dracut)...")
6136 - result = subprocess.run(
6137 - ["dracut", "--force", "/boot/initramfs.img"],
6138 - capture_output=True, text=True, timeout=120
6139 - )
6140 - return result.returncode == 0
6141 - elif shutil.which("mkinitcpio"):
6142 - print(" 🔧 Przebudowa initramfs (mkinitcpio)...")
6143 - result = subprocess.run(
6144 - ["mkinitcpio", "-g", "/boot/initramfs.img"],
6145 - capture_output=True, text=True, timeout=120
6146 - )
6147 - return result.returncode == 0
6148 - else:
6149 - print(" ⚠ Brak dracut/mkinitcpio – initramfs nie został przebudowany")
6150 - return False
6151 -
6152 - # Tryb immutable – budujemy initramfs dla deploymentu
6153 - print(" 🔧 Budowanie initramfs dla deploymentu...")
6154 -
6155 - # Sprawdź czy mamy nasz skrypt init
6156 - pag_init_script = "/usr/share/pag/initramfs-init"
6157 - if not os.path.exists(pag_init_script):
6158 - # Szukaj w źródłach (developerski fallback)
6159 - alt_paths = [
6160 - os.path.join(os.path.dirname(os.path.abspath(__file__)), "scripts", "initramfs-init"),
6161 - "/usr/share/pag/init",
6162 - ]
6163 - for p in alt_paths:
6164 - if os.path.exists(p):
6165 - pag_init_script = p
6166 - break
6167 -
6168 - if not os.path.exists(pag_init_script):
6169 - print(" ⚠ Nie znaleziono pag-initramfs-init – pomijam budowę initramfs")
6170 - return False
6171 -
6172 - boot_dir = os.path.join(root, "boot")
6173 - os.makedirs(boot_dir, exist_ok=True)
6174 -
6175 - # Znajdź jądro (vmlinuz-*)
6176 - kernels = sorted(
6177 - [f for f in os.listdir(boot_dir) if f.startswith("vmlinuz-")],
6178 - reverse=True
6179 - ) if os.path.exists(boot_dir) else []
6180 - if not kernels:
6181 - print(" ⚠ Nie znaleziono vmlinuz-* w /boot deploymentu")
6182 - return False
6183 -
6184 - kernel_ver = kernels[0].replace("vmlinuz-", "")
6185 - print(f" 🐧 Jądro: {kernel_ver}")
6186 -
6187 - # Buduj initramfs ręcznie (cpio)
6188 - tmpdir = tempfile.mkdtemp(prefix="pag-initramfs-")
6189 - try:
6190 - # Podstawowa struktura
6191 - for d in ["bin", "sbin", "dev", "proc", "sys", "run", "new_root",
6192 - "usr/bin", "usr/sbin", "lib", "lib64", "etc"]:
6193 - os.makedirs(os.path.join(tmpdir, d), exist_ok=True)
6194 -
6195 - # Skopiuj init
6196 - shutil.copy2(pag_init_script, os.path.join(tmpdir, "init"))
6197 - os.chmod(os.path.join(tmpdir, "init"), 0o755)
6198 -
6199 - # Skopiuj niezbędne binaria (busybox lub podstawowe narzędzia)
6200 - busybox_paths = [
6201 - os.path.join(root, "usr/bin/busybox"),
6202 - os.path.join(root, "bin/busybox"),
6203 - "/usr/bin/busybox",
6204 - "/bin/busybox",
6205 - ]
6206 - busybox = None
6207 - for bp in busybox_paths:
6208 - if os.path.exists(bp):
6209 - busybox = bp
6210 - break
6211 -
6212 - if busybox:
6213 - shutil.copy2(busybox, os.path.join(tmpdir, "bin/busybox"))
6214 - # Utwórz symlinki dla podstawowych komend
6215 - for cmd in ["sh", "mount", "umount", "ls", "cat", "echo", "sleep",
6216 - "readlink", "mkdir", "switch_root", "cp", "rm"]:
6217 - link = os.path.join(tmpdir, "bin", cmd)
6218 - if not os.path.exists(link):
6219 - os.symlink("busybox", link)
6220 - # /bin/sh → busybox
6221 - if not os.path.exists(os.path.join(tmpdir, "bin/sh")):
6222 - os.symlink("busybox", os.path.join(tmpdir, "bin/sh"))
6223 - else:
6224 - # Bez busybox – kopiuj podstawowe narzędzia z deploymentu
6225 - for tool in ["bash", "mount", "umount", "readlink", "mkdir", "cat", "sleep", "cp", "rm"]:
6226 - src = os.path.join(root, "usr/bin", tool)
6227 - if not os.path.exists(src):
6228 - src = os.path.join(root, "bin", tool)
6229 - if os.path.exists(src):
6230 - dest = os.path.join(tmpdir, "bin", os.path.basename(tool))
6231 - shutil.copy2(src, dest)
6232 - # Kopiuj zależności .so
6233 - _copy_libs_for_binary(src, tmpdir, root)
6234 -
6235 - # Dodaj moduły jądra (opcjonalnie – dla sterowników dyskowych)
6236 - modules_src = os.path.join(root, "lib/modules", kernel_ver)
6237 - if os.path.isdir(modules_src):
6238 - modules_dst = os.path.join(tmpdir, "lib/modules", kernel_ver)
6239 - # Kopiuj tylko niezbędne (fs, block, drivers/ata, drivers/nvme)
6240 - for sub in ["kernel/fs", "kernel/drivers/ata", "kernel/drivers/nvme",
6241 - "kernel/drivers/scsi", "kernel/drivers/virtio",
6242 - "modules.order", "modules.builtin"]:
6243 - src_sub = os.path.join(modules_src, sub)
6244 - if os.path.exists(src_sub):
6245 - dst_sub = os.path.join(modules_dst, sub)
6246 - os.makedirs(os.path.dirname(dst_sub), exist_ok=True)
6247 - if os.path.isdir(src_sub):
6248 - try:
6249 - shutil.copytree(src_sub, dst_sub, dirs_exist_ok=True, symlinks=True,
6250 - ignore_dangling_symlinks=True)
6251 - except (FileNotFoundError, PermissionError):
6252 - print(f" ⚠ Pomijam niedostępne pliki: {sub}")
6253 - else:
6254 - try:
6255 - shutil.copy2(src_sub, dst_sub)
6256 - except (FileNotFoundError, PermissionError):
6257 - print(f" ⚠ Pomijam niedostępny plik: {sub}")
6258 -
6259 - # Pakuj do initramfs.img
6260 - initramfs_path = os.path.join(boot_dir, "initramfs.img")
6261 - old_cwd = os.getcwd()
6262 - os.chdir(tmpdir)
6263 - try:
6264 - with open(initramfs_path + ".tmp", "wb") as out:
6265 - _run_cpio_pipeline(tmpdir, out)
6266 - os.rename(initramfs_path + ".tmp", initramfs_path)
6267 - finally:
6268 - os.chdir(old_cwd)
6269 -
6270 - size_mb = os.path.getsize(initramfs_path) / 1048576
6271 - print(f" ✅ initramfs.img ({size_mb:.1f} MB) → {initramfs_path}")
6272 - return True
6273 -
6274 - except Exception as e:
6275 - print(f" ❌ Błąd budowy initramfs: {e}")
6276 - return False
6277 - finally:
6278 - shutil.rmtree(tmpdir, ignore_errors=True)
6279 -
6280 -
6281 -def _run_cpio_pipeline(tmpdir: str, out):
6282 - """find . -print0 | cpio --null -oH newc | gzip — bez shell=True.
6283 -
6284 - Buduje pipeline przez subprocess.Popen, unikając pośrednika powłoki
6285 - (brak ryzyka injection i niepotrzebnego procesu sh). Wykonuje się w cwd=tmpdir.
6286 - Separatory NUL (\0): plik/katalog ze znakiem nowej linii w nazwie nie
6287 - rozjeżdża cpio (inaczej uszkodzone archiwum → kernel panic przy rozruchu).
6288 - """
6289 - find = subprocess.Popen(["find", ".", "-print0"], cwd=tmpdir, stdout=subprocess.PIPE)
6290 - cpio = subprocess.Popen(["cpio", "--null", "-oH", "newc"], cwd=tmpdir,
6291 - stdin=find.stdout, stdout=subprocess.PIPE)
6292 - find.stdout.close() # zwolnij uchwyt – cpio dostanie SIGPIPE po zakończeniu find
6293 - gzip = subprocess.Popen(["gzip"], stdin=cpio.stdout, stdout=out)
6294 - cpio.stdout.close()
6295 - try:
6296 - gzip.wait(timeout=120)
6297 - if gzip.returncode != 0:
6298 - raise subprocess.CalledProcessError(gzip.returncode, ["gzip"])
6299 - cpio.wait(timeout=30)
6300 - find.wait(timeout=30)
6301 - except subprocess.TimeoutExpired:
6302 - for p in (gzip, cpio, find):
6303 - p.kill()
6304 - raise
6305 - finally:
6306 - for p in (find, cpio, gzip):
6307 - if p.poll() is None:
6308 - p.kill()
6309 - # Skontroluj też kody procesów pośrednich (cpio/find mogą zawieść, a gzip zwrócić 0)
6310 - if cpio.returncode != 0:
6311 - raise subprocess.CalledProcessError(cpio.returncode, ["cpio"])
6312 - if find.returncode != 0:
6313 - raise subprocess.CalledProcessError(find.returncode, ["find"])
6314 -
6315 -
6316 -def _copy_libs_for_binary(binary: str, dest_dir: str, root: str):
6317 - """Kopiuje zależności .so dla binarki do initramfs (uproszczone ldd)."""
6318 - try:
6319 - result = subprocess.run(
6320 - ["ldd", binary], capture_output=True, text=True, timeout=10
6321 - )
6322 - for line in result.stdout.split("\n"):
6323 - m = re.search(r'=>\s+(/\S+)', line)
6324 - if m:
6325 - lib_path = m.group(1)
6326 - lib_rel = lib_path.lstrip("/")
6327 - lib_dest = os.path.join(dest_dir, lib_rel)
6328 - if not os.path.exists(lib_dest):
6329 - os.makedirs(os.path.dirname(lib_dest), exist_ok=True)
6330 - # Szukaj w deployment root lub systemie
6331 - if os.path.exists(lib_path):
6332 - shutil.copy2(lib_path, lib_dest)
6333 - else:
6334 - alt = os.path.join(root, lib_rel)
6335 - if os.path.exists(alt):
6336 - shutil.copy2(alt, lib_dest)
6337 - except Exception:
6338 - pass
6339 -
6340 -
6341 -def cmd_initramfs_update():
6342 - """Ręcznie przebudowuje initramfs dla bieżącego deploymentu."""
6343 - ensure_dirs()
6344 - deploy_dir = _get_deployment_root()
6345 - if deploy_dir != PAG_ROOT:
6346 - print(f"🏗️ Deployment: {os.path.basename(deploy_dir)}")
6347 - ok = _rebuild_initramfs(deploy_dir)
6348 - if ok:
6349 - print("✅ Initramfs zaktualizowany.")
6350 - # Po initramfs – zaktualizuj też GRUB
6351 - _update_grub_config()
6352 - else:
6353 - print("❌ Błąd aktualizacji initramfs.")
6354 - return 0 if ok else 1
6355 -
6356 -
6357 -def _boot_prefix() -> str:
6358 - """Prefiks ścieżek jądra/initrd w grub.cfg.
6359 -
6360 - Gdy /boot jest OSOBNYM punktem montowania, GRUB ma w `root` partycję
6361 - /boot (tam leży grub.cfg i jądra), więc ścieżki podajemy względem niej:
6362 - "/vmlinuz-…", "/initramfs.img" – BEZ przedrostka /boot. Gdy /boot leży
6363 - na roocie, wymagane jest "/boot/…". Zły przedrostek = "file not found".
6364 - """
6365 - try:
6366 - if os.path.isdir("/boot") and os.path.ismount("/boot"):
6367 - return ""
6368 - except OSError:
6369 - pass
6370 - return "/boot"
6371 -
6372 -
6373 -def _refresh_bootloader():
6374 - """Odświeża wpisy bootloadera po zmianie jądra.
6375 -
6376 - Deploymenty (immutable OS): własny generator _update_grub_config().
6377 - Zwykła instalacja: standardowy `grub-mkconfig` – /etc/grub.d/10_linux
6378 - sam wygeneruje wpisy dla KAŻDEGO /boot/vmlinuz-* wraz z jego własnym
6379 - initrd. Bez tego `pag upgrade kernel` zostawiał w menu STARY wpis:
6380 - system startował ze starym jądrem, a nowe moduły leżały bezużyteczne
6381 - ("moduły 7.2.8 na jądrze 7.2.5" → zawieszenie na starcie).
6382 - """
6383 - try:
6384 - if _load_deployments():
6385 - _update_grub_config()
6386 - return
6387 - except Exception:
6388 - pass
6389 - grub_cfg = "/boot/grub/grub.cfg"
6390 - if not os.path.isdir("/boot/grub"):
6391 - return
6392 - for tool, cmd in ((
6393 - "grub-mkconfig", ["grub-mkconfig", "-o", grub_cfg]), (
6394 - "grub2-mkconfig", ["grub2-mkconfig", "-o", grub_cfg])):
6395 - if shutil.which(tool):
6396 - try:
6397 - print(" 📋 Regeneracja GRUB (grub-mkconfig)...")
6398 - subprocess.run(cmd, capture_output=True, text=True,
6399 - errors="replace", timeout=180)
6400 - except Exception:
6401 - pass
6402 - return
6403 -
6404 -
6405 -def _update_grub_config():
6406 - """
6407 - Generuje wpisy GRUB dla wszystkich deploymentów.
6408 - Każdy deployment dostaje własny wpis – rollback możliwy z bootloadera.
6409 - """
6410 - grub_cfg = "/boot/grub/grub.cfg"
6411 - if not os.path.exists(os.path.dirname(grub_cfg)):
6412 - return # brak GRUB
6413 -
6414 - deployments = _load_deployments()
6415 - root_dev = _detect_root_device()
6416 - if not root_dev:
6417 - print(" ⚠ Nie udało się wykryć partycji root – wpisy GRUB nie dostaną root=.",
6418 - file=sys.stderr)
6419 - print(" Ustaw PAG_ROOT_DEVICE=/dev/... (lub PAG_GRUB_ROOT) i powtórz.",
6420 - file=sys.stderr)
6421 - root_arg = f" root={root_dev}" if root_dev else ""
6422 -
6423 - lines = [
6424 - "# =====================================================================",
6425 - "# Pagan Linux – GRUB config (wygenerowane przez pag grub-update)",
6426 - f"# Data: {datetime.now().isoformat()}",
6427 - "# =====================================================================",
6428 - "",
6429 - ]
6430 -
6431 - # Domyślny – ostatni (najnowszy) deployment
6432 - if deployments:
6433 - latest = deployments[-1]["id"]
6434 - lines.append(f"set default=0")
6435 - lines.append(f"set timeout=5")
6436 - else:
6437 - lines.append("set default=0")
6438 - lines.append("set timeout=5")
6439 - lines.append("")
6440 -
6441 - # Wpisy dla każdego deploymentu (od najnowszego)
6442 - entry_num = 0
6443 - for d in reversed(deployments):
6444 - deploy_dir = os.path.join(DEPLOYMENTS_DIR, d["id"])
6445 - boot_dir = os.path.join(deploy_dir, "boot")
6446 - kernels = sorted(
6447 - [f for f in os.listdir(boot_dir) if f.startswith("vmlinuz-")],
6448 - reverse=True
6449 - ) if os.path.isdir(boot_dir) else []
6450 -
6451 - kernel_path = f"/.deployments/{d['id']}/boot/{kernels[0]}" if kernels else ""
6452 - initrd_path = f"/.deployments/{d['id']}/boot/initramfs.img"
6453 - initrd_line = f"initrd {initrd_path}" if os.path.exists(os.path.join(boot_dir, "initramfs.img")) else ""
6454 -
6455 - active_mark = " [AKTYWNY]" if d.get("active") else ""
6456 - pkg_list = ", ".join(d.get("packages", [])[:3])
6457 - label = f"Pagan Linux – {d['id']}{active_mark}"
6458 -
6459 - lines.append(f"menuentry '{label}' {{")
6460 - if kernel_path:
6461 - lines.append(f" linux {kernel_path}{root_arg} rw quiet")
6462 - else:
6463 - lines.append(f" # Brak jądra w tym deploymencie")
6464 - if initrd_line:
6465 - lines.append(f" {initrd_line}")
6466 - lines.append("}")
6467 - lines.append("")
6468 - entry_num += 1
6469 -
6470 - # Snapshoty systemu (btrfs) – każdy jako osobny wpis do uruchomienia.
6471 - _snap_lines = _grub_snapshot_entries()
6472 - if _snap_lines:
6473 - lines.append("# --- Snapshoty systemu (CoW) ---")
6474 - lines.extend(_snap_lines)
6475 -
6476 - # Wpis fallback: zwykły root (gdyby wszystko padło).
6477 - # Uwaga: GRUB NIE rozwija globów – trzeba podać KONKRETNY plik jądra
6478 - # (wcześniejsze `linux /boot/vmlinuz-*` było niepoprawne).
6479 - fallback_kernels = sorted(
6480 - [f for f in os.listdir("/boot") if f.startswith("vmlinuz-")],
6481 - reverse=True
6482 - ) if os.path.isdir("/boot") else []
6483 - # Osobna partycja /boot => GRUB ma ją w `root`, ścieżki BEZ /boot.
6484 - _bp = _boot_prefix()
6485 - lines.append("menuentry 'Pagan Linux – fallback (zwykły root)' {")
6486 - if fallback_kernels:
6487 - lines.append(f" linux {_bp}/{fallback_kernels[0]}{root_arg} rw quiet")
6488 - _fi = _initrd_for_kernel("/boot", fallback_kernels[0])
6489 - if _fi:
6490 - lines.append(f" initrd {_bp}/{_fi}")
6491 - else:
6492 - lines.append(" # Brak jądra w /boot")
6493 - lines.append("}")
6494 - lines.append("")
6495 -
6496 - # Zapisz
6497 - os.makedirs(os.path.dirname(grub_cfg), exist_ok=True)
6498 - with open(grub_cfg, "w") as f:
6499 - f.write("\n".join(lines))
6500 -
6501 - print(" 📋 GRUB config zaktualizowany – wpisy dla każdego deploymentu")
6502 -
6503 -
6504 -def _root_device_from_fstab(path: str = "/etc/fstab") -> str:
6505 - """Zwraca DEVICE z wpisu dla '/' w fstab (pomija komentarze)."""
6506 - try:
6507 - with open(path, "r", encoding="utf-8", errors="replace") as fh:
6508 - for line in fh:
6509 - line = line.split("#", 1)[0].strip()
6510 - if not line:
6511 - continue
6512 - parts = line.split()
6513 - if len(parts) >= 2 and parts[1] == "/":
6514 - return parts[0]
6515 - except OSError:
6516 - pass
6517 - return ""
6518 -
6519 -
6520 -def _in_chroot() -> bool:
6521 - """Heurystyka: czy działamy w chrocie (build ISO/IMG)?
6522 -
6523 - W chrocie /proc/1/root to root HOSTA – inny system plików niż nasz '/'.
6524 - Na zwykłym systemie PID 1 ma root równy '/'. PAGAN_ROOT ustawiają skrypty
6525 - budujące i jest dziedziczony przez chroot (dodatkowa wskazówka).
6526 - """
6527 - if os.environ.get("PAG_IN_CHROOT") == "1":
6528 - return True
6529 - if os.environ.get("PAGAN_ROOT"):
6530 - return True
6531 - try:
6532 - return os.stat("/").st_dev != os.stat("/proc/1/root").st_dev
6533 - except OSError:
6534 - return False
6535 -
6536 -
6537 -def _detect_root_device() -> str:
6538 - """Wykrywa urządzenie/identyfikator partycji root dla GRUB (root=...).
6539 -
6540 - Kolejność (od najbardziej wiarygodnego w danym kontekście):
6541 - 1) PAG_ROOT_DEVICE / PAG_GRUB_ROOT – jawny override (build ISO/IMG,
6542 - instalator); najpewniejszy, bo nie zgadujemy.
6543 - 2) /etc/fstab TARGETU – w chrocie findmnt '/' zwraca partycję HOSTA,
6544 - a fstab opisuje target (np. root=/dev/sda2 dla obrazu IMG).
6545 - 3) findmnt '/' – na żywym systemie (obsługuje UUID/LUKS/subvol).
6546 - Zwraca "" gdy nie da się ustalić – wtedy GRUB nie dostaje błędnego root=.
6547 - """
6548 - explicit = (os.environ.get("PAG_ROOT_DEVICE")
6549 - or os.environ.get("PAG_GRUB_ROOT") or "").strip()
6550 - if explicit:
6551 - return explicit
6552 -
6553 - fstab_dev = _root_device_from_fstab()
6554 - if _in_chroot() and fstab_dev:
6555 - return fstab_dev
6556 -
6557 - try:
6558 - result = subprocess.run(
6559 - ["findmnt", "-n", "-o", "SOURCE", "/"],
6560 - capture_output=True, text=True, timeout=5
6561 - )
6562 - if result.returncode == 0 and result.stdout.strip():
6563 - return result.stdout.strip()
6564 - except Exception:
6565 - pass
6566 -
6567 - # Ostatnia deska: fstab targetu (lepsze niż hardkodowane /dev/sda1,
6568 - # które na sprzęcie z NVMe dawało niebootowalny system).
6569 - return fstab_dev
6570 -
6571 -
6572 -def cmd_grub_update():
6573 - """Ręcznie regeneruje konfigurację GRUB (deploymenty + snapshoty)."""
6574 - ensure_dirs()
6575 - print("📋 Aktualizacja konfiguracji GRUB...")
6576 - _ensure_snapshot_grub_script()
6577 - # Deploymenty mają własny generator; zwykły system – grub-mkconfig,
6578 - # który uruchomi /etc/grub.d/40_pagan_snapshots i zachowa pozostałe wpisy.
6579 - _refresh_bootloader()
6580 - print("✅ GRUB zaktualizowany.")
6581 - return 0
6582 -
6583 -def cmd_deploy_list():
6584 - """Wyświetla listę wszystkich deploymentów."""
6585 - deployments = _load_deployments()
6586 - if not deployments:
6587 - print(_("no_deployments")); return
6588 -
6589 - print(_("deployments_list", len(deployments)))
6590 - active = os.readlink(ACTIVE_LINK) if os.path.islink(ACTIVE_LINK) else ""
6591 -
6592 - for d in reversed(deployments):
6593 - marker = f" ◀ {_('active_deployment')}" if d.get("active") or d["id"] == os.path.basename(active) else ""
6594 - print(f" {d['id']}{marker}")
6595 - print(f" {d['action']}: {', '.join(d['packages'][:5])}")
6596 - if len(d.get('packages', [])) > 5:
6597 - print(f" +{len(d['packages']) - 5} więcej...")
6598 - print(f" {d['timestamp']}")
6599 -
6600 -
6601 -def cmd_deploy_rollback():
6602 - """Przełącza na poprzedni deployment."""
6603 - deployments = _load_deployments()
6604 - active_indices = [i for i, d in enumerate(deployments) if d.get("active")]
6605 -
6606 - if len(deployments) < 2:
6607 - print(f"❌ {_('deploy_rollback_fail')}"); return 1
6608 -
6609 - current_idx = active_indices[0] if active_indices else len(deployments) - 1
6610 - prev_idx = current_idx - 1 if current_idx > 0 else -1
6611 -
6612 - if prev_idx < 0:
6613 - print(f"❌ {_('deploy_rollback_fail')}"); return 1
6614 -
6615 - prev = deployments[prev_idx]
6616 - prev_dir = os.path.join(DEPLOYMENTS_DIR, prev["id"])
6617 -
6618 - if not os.path.isdir(prev_dir):
6619 - print(f"❌ Deployment {prev['id']} nie istnieje na dysku"); return 1
6620 -
6621 - print(f"⏪ Przywracanie deploymentu: {prev['id']}")
6622 - print(f" {prev['action']}: {', '.join(prev['packages'][:5])}")
6623 -
6624 - if not _ask_confirm():
6625 - return 0
6626 -
6627 - _switch_deployment(prev_dir)
6628 -
6629 - for d in deployments:
6630 - d["active"] = (d["id"] == prev["id"])
6631 - _save_deployments(deployments)
6632 -
6633 - _update_grub_config()
6634 - print(f"✅ {_('deploy_rollback_ok', prev['id'])}")
6635 - print(" 💡 Restart wymagany do przeładowania systemu.")
6636 - return 0
6637 -
6638 -
6639 -def cmd_deploy_cleanup(keep: int = 3):
6640 - """Usuwa stare deploymenty, zachowując ostatnie `keep`."""
6641 - deployments = _load_deployments()
6642 -
6643 - if len(deployments) <= keep:
6644 - print(f"✅ {_('deploy_cleanup_none', keep)}"); return 0
6645 -
6646 - to_remove = deployments[:-keep]
6647 - removed = 0
6648 -
6649 - for d in to_remove:
6650 - deploy_dir = os.path.join(DEPLOYMENTS_DIR, d["id"])
6651 - if os.path.isdir(deploy_dir):
6652 - shutil.rmtree(deploy_dir, ignore_errors=True)
6653 - removed += 1
6654 -
6655 - remaining = deployments[-keep:]
6656 - _save_deployments(remaining)
6657 -
6658 - print(f"✅ {_('deploy_cleanup_ok', removed)}")
6659 - return 0
6660 -
6661 -
6662 -# =============================================================================
6663 -# POMOCNICZE
6664 -# =============================================================================
6665 -
6666 -# Pakiety dostarczane przez bazowy system (zawsze "zainstalowane"). Wchodzą do
6667 -# rootfs z ISO przez data.tar.xz, więc NIE ma ich w repo.json ani w bazie pag –
6668 -# każda zależność od nich (glibc, bash, python3…) wyglądałaby na "brakującą".
6669 -# Współdzielone przez rozwijanie i weryfikację zależności.
6670 -SYSTEM_BASE = {
6671 - "glibc", "libc", "gcc", "g++", "make", "binutils", "coreutils", "bash",
6672 - "linux-api-headers", "kernel-headers", "zlib", "pkg-config", "pkgconf",
6673 - "tar", "gzip", "xz", "bzip2", "findutils", "grep", "sed", "gawk", "awk",
6674 - "diffutils", "patch", "file", "m4", "perl", "python3", "sh",
6675 -}
6676 -
6677 -
6678 -def _resolve_deps(names, repo, installed):
6679 - resolved, visited = [], set()
6680 - missing = [] # zależności których nie ma ani w repo ani zainstalowane
6681 -
6682 - def _is_base(dep):
6683 - """True, gdy zależność dostarcza bazowy system (także przez provides)."""
6684 - return dep in SYSTEM_BASE \
6685 - or _resolve_provides(dep, repo, installed) in SYSTEM_BASE
6686 -
6687 - def visit(name, explicit=False):
6688 - if name in visited: return
6689 -
6690 - # Rozwijanie wirtualnych zależności przez provides
6691 - target = _resolve_provides(name, repo, installed)
6692 -
6693 - # Zależność dostarczana przez bazowy system – nie ma jej w repo ani w
6694 - # bazie pag, więc nie "brakuje" jej i nie próbujemy jej instalować.
6695 - # Wyjątek: nazwa podana wprost przez użytkownika (explicit=True).
6696 - if not explicit and target in SYSTEM_BASE:
6697 - return
6698 -
6699 - if target in visited: return
6700 - visited.add(target)
6701 - if target in repo:
6702 - for dep in repo[target].dependencies:
6703 - real_dep = _resolve_provides(dep, repo, installed)
6704 - real_target = real_dep if real_dep in repo else dep
6705 -
6706 - if _is_base(dep):
6707 - continue
6708 -
6709 - # Sprawdź czy zależność jest dostępna
6710 - if real_target not in installed and real_target not in repo:
6711 - if dep not in missing:
6712 - missing.append(dep)
6713 -
6714 - if dep not in installed:
6715 - visit(real_target)
6716 - elif target not in installed:
6717 - # Pakiet nie istnieje ani w repo ani zainstalowany
6718 - if target not in missing:
6719 - missing.append(target)
6720 -
6721 - if target not in installed and target not in resolved:
6722 - resolved.append(target)
6723 -
6724 - for name in names:
6725 - visit(name, explicit=True)
6726 -
6727 - # Zwróć brakujące (do sprawdzenia przez wywołującego)
6728 - return resolved, missing
6729 -
6730 -def _verify_dependencies(to_install: list, repo: dict, installed: dict) -> int:
6731 - """
6732 - Sprawdza czy wszystkie zależności pakietów do instalacji są spełnione.
6733 - Zwraca liczbę brakujących zależności.
6734 - """
6735 - all_missing = []
6736 - all_warnings = []
6737 -
6738 - for pkg_name in to_install:
6739 - pkg = repo.get(pkg_name)
6740 - if not pkg:
6741 - continue
6742 -
6743 - for dep in pkg.dependencies:
6744 - if dep in SYSTEM_BASE:
6745 - continue # bazowy system dostarcza tę zależność
6746 - real_dep = _resolve_provides(dep, repo, installed)
6747 - # Sprawdź czy zależność jest dostępna (w repo lub już zainstalowana)
6748 - in_repo = real_dep in repo
6749 - in_installed = real_dep in installed
6750 - will_be_installed = real_dep in to_install
6751 -
6752 - if not in_repo and not in_installed and not will_be_installed:
6753 - if dep not in all_missing:
6754 - all_missing.append((pkg_name, dep))
6755 - elif in_repo and not in_installed and not will_be_installed:
6756 - if dep not in [w[1] for w in all_warnings]:
6757 - all_warnings.append((pkg_name, dep, real_dep))
6758 -
6759 - if all_missing:
6760 - print(f"\n❌ {_c('red', 'BRAKUJĄCE ZALEŻNOŚCI')} – nie można zainstalować:")
6761 - for pkg, dep in all_missing:
6762 - print(f" {pkg} → potrzebuje {_c('red', dep)} (brak w repozytoriach)")
6763 - print()
6764 -
6765 - if all_warnings:
6766 - print(f"\n⚠ {_c('yellow', 'NIESPEŁNIONE ZALEŻNOŚCI')} – zostaną doinstalowane:")
6767 - for pkg, dep, real in all_warnings:
6768 - print(f" {pkg} → {dep} ({_c('green', real)} – będzie pobrane)")
6769 - print()
6770 -
6771 - return len(all_missing)
6772 -
6773 -# Biblioteki bazowe (glibc/gcc runtime) – zawsze dostępne, nie wymagają pakietu
6774 -BASE_SO = {
6775 - "libc.so.6", "libm.so.6", "libpthread.so.0", "libdl.so.2", "librt.so.1",
6776 - "libutil.so.1", "libresolv.so.2", "libnsl.so.1", "libcrypt.so.1",
6777 - "ld-linux.so.2", "ld-linux-x86-64.so.2", "ld-linux-aarch64.so.1",
6778 - "libgcc_s.so.1", "linux-vdso.so.1",
6779 -}
6780 -
6781 -def _verify_so_deps(to_install: list, repo: dict, installed: dict) -> int:
6782 - """Sprawdza wymagania ABI (provides_so / requires_so z metadata.json).
6783 -
6784 - Fail-closed TYLKO gdy metadata jawnie deklaruje requires_so, a żaden pakiet
6785 - (bazowy, zainstalowany lub instalowany w tej transakcji) nie dostarcza
6786 - wymaganej wersji biblioteki. Stare pakiety bez tych pól są pomijane.
6787 - """
6788 - provided = set(BASE_SO)
6789 - for n in to_install:
6790 - p = repo.get(n)
6791 - if p:
6792 - provided.update(p.provides_so or [])
6793 - for n, info in installed.items():
6794 - provided.update(info.get("provides_so", []) or [])
6795 -
6796 - # NAPRAWA: soname faktycznie obecne w systemie (ldconfig -p). Metadane
6797 - # starych paczek (zbudowanych przed polem provides_so) ich nie deklaruja,
6798 - # a biblioteki sa na dysku - bez tego fail-closed check blokuje legalne
6799 - # aktualizacje (np. mesa -> libLLVM.so.22.1).
6800 - try:
6801 - import shutil as _sh, subprocess as _sp
6802 - _ld = _sh.which("ldconfig")
6803 - if _ld:
6804 - _o = _sp.run([_ld, "-p"], capture_output=True, text=True).stdout
6805 - for _ln in _o.splitlines():
6806 - _ln = _ln.strip()
6807 - if "=>" in _ln:
6808 - provided.add(_ln.split("=>")[0].strip().split()[0])
6809 - except Exception:
6810 - pass
6811 -
6812 - missing = []
6813 - for n in sorted(to_install):
6814 - p = repo.get(n)
6815 - if not p:
6816 - continue
6817 - for so in (p.requires_so or []):
6818 - if so not in provided:
6819 - missing.append((n, so))
6820 -
6821 - if missing:
6822 - print(f"\n❌ {_c('red', 'BRAK WYMAGANYCH BIBLIOTEK (ABI so-name)')}:")
6823 - for n, so in missing:
6824 - print(f" {n} → wymaga {_c('red', so)} – żaden pakiet nie dostarcza tej wersji")
6825 - print()
6826 - return len(missing)
6827 -
6828 -def _download_pkg(pkg, attempts: int = 3, progress: bool = True):
6829 - """Pobiera pakiet do cache. `progress=False` wycisza pasek (np. gdy
6830 - równoległy pobierający pokazuje własny pasek zbiorczy)."""
6831 - url = f"{pkg.repo_url}/{pkg.filename}"
6832 - dest = os.path.join(PAG_CACHE, pkg.filename)
6833 - if os.path.exists(dest) and (not pkg.sha256 or _sha256_file(dest) == pkg.sha256):
6834 - _download_pkg_sig(pkg, dest) # upewnij się, że sygnatura jest w cache
6835 - return dest
6836 - last_err = None
6837 - for attempt in range(1, attempts + 1):
6838 - try:
6839 - req = Request(url, headers={"User-Agent":"pag/3.0"})
6840 - with urlopen(req, timeout=600) as resp:
6841 - total = int(resp.headers.get("Content-Length", 0))
6842 - bar = DownloadBar(pkg.filename, total) if progress else None
6843 - with open(dest, "wb") as f:
6844 - while True:
6845 - chunk = resp.read(65536)
6846 - if not chunk:
6847 - break
6848 - f.write(chunk)
6849 - if bar is not None:
6850 - bar.update(len(chunk))
6851 - if bar is not None:
6852 - bar.close()
6853 - if pkg.sha256 and _sha256_file(dest) != pkg.sha256:
6854 - last_err = "SHA256 mismatch"
6855 - try:
6856 - os.remove(dest)
6857 - except OSError:
6858 - pass
6859 - if attempt < attempts:
6860 - print(f" ↻ Ponawiam pobieranie {pkg.filename} "
6861 - f"({attempt}/{attempts - 1})...", file=sys.stderr)
6862 - time.sleep(attempt)
6863 - continue
6864 - return None
6865 - _download_pkg_sig(pkg, dest)
6866 - return dest
6867 - except Exception as e:
6868 - last_err = e
6869 - # Usuń częściowy plik – bez tego mógłby zostać użyty jako „cache”
6870 - # (gdy pakiet nie ma sha256) albo mylić kolejną próbę.
6871 - try:
6872 - if os.path.exists(dest):
6873 - os.remove(dest)
6874 - except OSError:
6875 - pass
6876 - if attempt < attempts:
6877 - print(f" ↻ Ponawiam pobieranie {pkg.filename} "
6878 - f"({attempt}/{attempts - 1})...", file=sys.stderr)
6879 - time.sleep(attempt)
6880 - continue
6881 - print(f" ⚠ Błąd pobierania {pkg.filename}: {last_err}", file=sys.stderr)
6882 - return None
6883 -
6884 -def _download_pkg_sig(pkg, dest):
6885 - """Zapewnia AKTUALNY podpis pakietu (.asc, fallback .sig) w cache.
6886 -
6887 - Istniejący podpis jest używany tylko wtedy, gdy faktycznie weryfikuje TĘ
6888 - paczkę. Inaczej po przebudowie tej samej wersji (ten sam plik, nowy sha256)
6889 - stary podpis zostawał obok nowej paczki i weryfikacja dawała fałszywe
6890 - „NIEPRAWIDŁOWY PODPIS GPG”.
6891 - """
6892 - for ext in (".asc", ".sig"):
6893 - sig_dest = dest + ext
6894 - if os.path.exists(sig_dest):
6895 - ok, _fp = _gpg_verify_fp(sig_dest, dest)
6896 - if ok:
6897 - return
6898 - for ext in (".asc", ".sig"):
6899 - sig_dest = dest + ext
6900 - try:
6901 - req = Request(f"{pkg.repo_url}/{pkg.filename}{ext}", headers={"User-Agent":"pag/3.0"})
6902 - with urlopen(req, timeout=30) as resp:
6903 - data = resp.read()
6904 - except Exception:
6905 - continue
6906 - # nie mieszaj rozszerzeń – zostaje tylko ten wariant podpisu
6907 - for other in (".asc", ".sig"):
6908 - if other != ext:
6909 - try:
6910 - os.remove(dest + other)
6911 - except OSError:
6912 - pass
6913 - with open(sig_dest, "wb") as f:
6914 - f.write(data)
6915 - return
6916 - # Nie udało się pobrać podpisu – usuń nieaktualny z cache, żeby weryfikacja
6917 - # nie porównywała paczki z podpisem od innej wersji (czytelny „BRAK PODPISU”).
6918 - for other in (".asc", ".sig"):
6919 - try:
6920 - os.remove(dest + other)
6921 - except OSError:
6922 - pass
6923 -
6924 -def _download_packages_parallel(pkgs: List[PackageInfo], max_workers: int = 4) -> Dict[str, Optional[str]]:
6925 - """
6926 - Równoległe pobieranie wielu pakietów przez ThreadPoolExecutor.
6927 - Znacząco przyspiesza przy dużych aktualizacjach (50+ pakietów).
6928 - Zwraca słownik {nazwa_pakietu: ścieżka_lub_None}.
6929 - """
6930 - results = {}
6931 - total = len(pkgs)
6932 - completed = 0
6933 - with ThreadPoolExecutor(max_workers=max_workers) as executor:
6934 - future_to_pkg = {executor.submit(_download_pkg, pkg, progress=False): pkg for pkg in pkgs}
6935 - for future in as_completed(future_to_pkg):
6936 - pkg = future_to_pkg[future]
6937 - try:
6938 - results[pkg.name] = future.result()
6939 - except Exception:
6940 - results[pkg.name] = None
6941 - completed += 1
6942 - # Pasek postępu (animowany „drakkar” na TTY)
6943 - pct = completed / total * 100
6944 - bar = _pagan_bar(pct, 20, time.time(), animated=sys.stderr.isatty())
6945 - print(f"\r ⏬ [{bar}] {completed}/{total} ({pct:.0f}%)", end="", file=sys.stderr, flush=True)
6946 - print(file=sys.stderr) # nowa linia po zakończeniu
6947 - return results
6948 -
6949 -def load_world():
6950 - if not os.path.exists(WORLD_FILE): return set()
6951 - return {l.strip() for l in open(WORLD_FILE) if l.strip()}
6952 -
6953 -def save_world(w):
6954 - with open(WORLD_FILE,"w") as f:
6955 - for n in sorted(w): f.write(f"{n}\n")
6956 -
6957 -def _find_orphans(installed, world):
6958 - needed = set(world)
6959 - changed = True
6960 - while changed:
6961 - changed = False
6962 - for n in list(needed):
6963 - for dep in installed.get(n,{}).get("dependencies",[]):
6964 - if dep not in needed and dep in installed:
6965 - needed.add(dep); changed = True
6966 - return {n for n in installed if n not in needed}
6967 -
6968 -# =============================================================================
6969 -# MAIN
6970 -# =============================================================================
6971 -
6972 -def cmd_sbom(argv):
6973 - """pag sbom export [spdx|cyclonedx] – manifest SBOM zainstalowanych pakietów.
6974 -
6975 - Wypisuje na stdout JSON (SPDX 2.3 lub CycloneDX 1.5) z listą
6976 - zainstalowanych pakietów, wersji, licencji i sum SHA256.
6977 - """
6978 - fmt = (argv[0] if argv else "spdx").lower()
6979 - if fmt not in ("spdx", "cyclonedx"):
6980 - print("❌ Format: spdx | cyclonedx")
6981 - return 1
6982 - installed = load_json(INSTALLED_DB)
6983 - if not installed:
6984 - print("{}") if fmt == "cyclonedx" else print("{\"packages\": []}")
6985 - return 0
6986 - # metadata repo (licencje) – best-effort
6987 - try:
6988 - repo = fetch_all_packages()
6989 - except Exception:
6990 - repo = {}
6991 - names = sorted(installed)
6992 - created = datetime.now().astimezone().isoformat(timespec="seconds")
6993 -
6994 - def _license_of(name):
6995 - p = repo.get(name)
6996 - lic = getattr(p, "license", None) or []
6997 - if isinstance(lic, list):
6998 - lic = ", ".join(x for x in lic if x)
6999 - return lic or "NOASSERTION"
7000 -
7001 - if fmt == "spdx":
7002 - doc = {
7003 - "spdxVersion": "SPDX-2.3",
7004 - "dataLicense": "CC0-1.0",
7005 - "SPDXID": "SPDXRef-DOCUMENT",
7006 - "name": "PaganOS-installed",
7007 - "documentNamespace": f"https://repo.paganlinux.eu/sbom/installed-{int(time.time())}",
7008 - "creationInfo": {
7009 - "created": created,
7010 - "creators": [f"Tool: pag-{PAG_VERSION}"],
7011 - },
7012 - "packages": [],
7013 - }
7014 - for i, n in enumerate(names):
7015 - info = installed[n]
7016 - doc["packages"].append({
7017 - "SPDXID": f"SPDXRef-Package-{i+1}",
7018 - "name": n,
7019 - "versionInfo": info.get("version", ""),
7020 - "downloadLocation": info.get("repo", "NOASSERTION"),
7021 - "filesAnalyzed": False,
7022 - "licenseConcluded": _license_of(n),
7023 - "checksums": [{"algorithm": "SHA256", "checksumValue": info.get("sha256", "")}],
7024 - })
7025 - else: # cyclonedx
7026 - doc = {
7027 - "bomFormat": "CycloneDX",
7028 - "specVersion": "1.5",
7029 - "serialNumber": f"urn:uuid:{str(uuid.uuid4())}",
7030 - "version": 1,
7031 - "metadata": {
7032 - "timestamp": created,
7033 - "tools": [{"vendor": "PaganOS", "name": "pag", "version": PAG_VERSION}],
7034 - },
7035 - "components": [],
7036 - }
7037 - for n in names:
7038 - info = installed[n]
7039 - lic = _license_of(n)
7040 - comp = {
7041 - "type": "library",
7042 - "name": n,
7043 - "version": info.get("version", ""),
7044 - "hashes": [{"alg": "SHA-256", "content": info.get("sha256", "")}],
7045 - }
7046 - if lic != "NOASSERTION":
7047 - comp["licenses"] = [{"license": {"id": lic}}]
7048 - doc["components"].append(comp)
7049 - print(json.dumps(doc, indent=2, ensure_ascii=False))
7050 - return 0
7051 -
7052 -
7053 -USAGE_EN = """pag v3 – Pagan Linux Package Manager
7054 -
7055 -BASIC:
7056 - pag install <pkg>... Install packages
7057 - pag remove <pkg>... Remove packages
7058 - pag update Update PACKAGES (refreshes indexes first)
7059 - pag sync Refresh indexes + show pending package updates
7060 - pag upgrade Update SYSTEM (packages + kernel/initramfs/GRUB)
7061 - pag list [--installed] List available / installed
7062 - pag search <query> Search packages
7063 - pag info <pkg> Package details
7064 - pag files <pkg> List package files
7065 - pag verify [--deep] Verify integrity (--deep = SHA256 per file)
7066 - pag clean Clear download cache
7067 - pag stats System statistics
7068 - pag download <pkg>... Download packages to cache (offline prep)
7069 -
7070 -ROLLING (base baked into the image):
7071 - pag base [status] Image packages vs. repo (what pag manages)
7072 - pag base adopt [pkg...] Adopt base packages from the repo (--dry-run = preview)
7073 -
7074 -SECURITY:
7075 - pag key-add <url|file> Import GPG key
7076 - pag key-list List trusted keys
7077 - pag key-remove <id> Remove key
7078 - pag key-trust <repo> Pin repo signing key fingerprint (no TOFU)
7079 - pag key-untrust <repo> Forget repo fingerprint (back to TOFU)
7080 - pag key-trusted List pinned repo fingerprints
7081 -
7082 -ADVANCED:
7083 - pag why <pkg> Show why a package is installed
7084 - pag rdepends <pkg> Show which packages depend on a package
7085 - pag autoremove Auto-remove orphaned dependencies
7086 - pag pin <pkg> [ver] Pin package version
7087 - pag unpin <pkg> Unpin
7088 - pag pinned List pinned
7089 - pag history Transaction history
7090 - pag rollback Rollback last transaction
7091 - pag repair [--dry-run] Reinstall packages with missing files
7092 - pag remove-orphans Remove orphaned deps
7093 - pag repo-add <url> [name] Add repository (drop-in /etc/pag/repos/)
7094 - pag repo-list List repositories
7095 - pag sbom export [fmt] SBOM manifest (spdx|cyclonedx)
7096 -
7097 -FLATPAK:
7098 - pag flatpak [<query>] Search & install (smart)
7099 - pag flatpak search <q> Search Flathub
7100 - pag flatpak install <id> Install flatpak
7101 - pag flatpak remove <id> Remove flatpak
7102 - pag flatpak list List installed flatpaks
7103 - pag flatpak update Update all flatpaks
7104 - pag flatpak info <id> Show flatpak details
7105 -
7106 -SNAPSHOTS (btrfs CoW):
7107 - pag snapshot-list List system snapshots
7108 - pag snapshot-create [label] Create a snapshot now
7109 - pag snapshot-rollback [id] Start from snapshot at next boot (GRUB)
7110 - pag snapshot-delete <id> Delete a snapshot
7111 -
7112 -IMMUTABLE OS (PAG_IMMUTABLE=1):
7113 - pag deploy-list List all deployments
7114 - pag deploy-rollback Switch to previous deployment
7115 - pag deploy-cleanup [N] Remove old deployments (keep last N, default 3)
7116 - pag initramfs-update Rebuild initramfs for current kernel/deployment
7117 - pag grub-update Regenerate GRUB entries for all deployments
7118 -"""
7119 -
7120 -USAGE_PL = """pag v3 – Pagan Linux Package Manager
7121 -
7122 -PODSTAWOWE:
7123 - pag install <pkg>... Instalacja pakietów
7124 - pag remove <pkg>... Usuwanie pakietów
7125 - pag update Aktualizacja PAKIETÓW (odświeża indeksy)
7126 - pag sync Odśwież indeksy + info o aktualizacjach
7127 - pag upgrade Aktualizacja SYSTEMU (pakiety + kernel/initramfs/GRUB)
7128 - pag list [--installed] Lista dostępnych / zainstalowanych
7129 - pag search <query> Szukaj pakietów
7130 - pag info <pkg> Szczegóły pakietu
7131 - pag files <pkg> Lista plików pakietu
7132 - pag verify [--deep] Weryfikacja integralności
7133 - pag clean Wyczyść cache pobierania
7134 - pag stats Statystyki systemu
7135 - pag download <pkg>... Pobierz do cache (offline)
7136 -
7137 -ROLLING (baza wypalona w obrazie):
7138 - pag base [status] Pakiety z obrazu vs repo (czym pag zarządza)
7139 - pag base adopt [pkg...] Adoptuj pakiety bazy z repo (--dry-run = podgląd)
7140 -
7141 -BEZPIECZEŃSTWO:
7142 - pag key-add <url|file> Importuj klucz GPG
7143 - pag key-list Lista zaufanych kluczy
7144 - pag key-remove <id> Usuń klucz
7145 - pag key-trust <repo> Przypnij fingerprint klucza repo (bez TOFU)
7146 - pag key-untrust <repo> Zapomnij fingerprint repo (powrót do TOFU)
7147 - pag key-trusted Lista przypiętych fingerprintów repo
7148 -
7149 -ZAAWANSOWANE:
7150 - pag why <pkg> Dlaczego pakiet jest zainstalowany
7151 - pag rdepends <pkg> Które pakiety zależą od pakietu
7152 - pag autoremove Usuń osierocone zależności
7153 - pag pin <pkg> [ver] Przypnij wersję pakietu
7154 - pag unpin <pkg> Odepnij
7155 - pag pinned Lista przypiętych
7156 - pag history Historia transakcji
7157 - pag rollback Cofnij ostatnią transakcję
7158 - pag repair [--dry-run] Napraw brakujące pliki pakietów (reinstalacja)
7159 - pag remove-orphans Usuń osierocone zależności
7160 - pag repo-add <url> [nazwa] Dodaj repozytorium (drop-in w /etc/pag/repos/)
7161 - pag repo-list Lista repozytoriów
7162 - pag sbom export [fmt] Manifest SBOM (spdx|cyclonedx)
7163 -
7164 -FLATPAK:
7165 - pag flatpak [<query>] Szukaj i instaluj
7166 - pag flatpak search <q> Szukaj na Flathub
7167 - pag flatpak install <id> Zainstaluj flatpak
7168 - pag flatpak remove <id> Usuń flatpak
7169 - pag flatpak list Lista zainstalowanych
7170 - pag flatpak update Aktualizuj wszystkie
7171 - pag flatpak info <id> Szczegóły flatpaka
7172 -
7173 -SNAPSHOTY (btrfs CoW):
7174 - pag snapshot-list Lista snapshotów systemu
7175 - pag snapshot-create [opis] Utwórz snapshot teraz
7176 - pag snapshot-rollback [id] Uruchom snapshot przy następnym starcie (GRUB)
7177 - pag snapshot-delete <id> Usuń snapshot
7178 -
7179 -IMMUTABLE OS (PAG_IMMUTABLE=1):
7180 - pag deploy-list Lista wdrożeń
7181 - pag deploy-rollback Przełącz na poprzednie wdrożenie
7182 - pag deploy-cleanup [N] Usuń stare wdrożenia (zachowaj N, domyślnie 3)
7183 - pag initramfs-update Przebuduj initramfs
7184 - pag grub-update Regeneruj wpisy GRUB"""
7185 -
7186 -def _get_usage():
7187 - # Plik językowy może dostarczyć klucz "usage" – wtedy wygrywa z wbudowanym.
7188 - _u = T.get(LANG, {}).get("usage")
7189 - if _u:
7190 - return _u
7191 - if LANG == "pl":
7192 - return USAGE_PL
7193 - return USAGE_EN
7194 -
7195 -
7196 -def _extract_lang(outdir: str) -> int:
7197 - """Eksport wbudowanych tłumaczeń do outdir/{pl,en}.json (+ klucz "usage").
7198 -
7199 - Używane przez recepturę pakietu (pag.pag), żeby tłumaczenia jechały RAZEM
7200 - z wersją paga – po `pag install/upgrade pag` i self-update są zawsze zgodne.
7201 - """
7202 - os.makedirs(outdir, exist_ok=True)
7203 - for _code in ("pl", "en"):
7204 - _d = dict(T.get(_code, {}))
7205 - _u = globals().get(f"USAGE_{_code.upper()}", "")
7206 - if _u:
7207 - _d["usage"] = _u
7208 - _p = os.path.join(outdir, f"{_code}.json")
7209 - with open(_p, "w", encoding="utf-8") as _fh:
7210 - json.dump(_d, _fh, ensure_ascii=False, indent=2, sort_keys=True)
7211 - print(f" ✓ {_p} ({len(_d)} kluczy)")
7212 - return 0
7213 -
7214 -
7215 -def main():
7216 - # Ukryte (używane przy budowie pakietu): eksport tłumaczeń do plików
7217 - if len(sys.argv) >= 3 and sys.argv[1] == "--lang-extract":
7218 - sys.exit(_extract_lang(sys.argv[2]))
7219 - if len(sys.argv) >= 2 and sys.argv[1] in ("--version", "-V", "version"):
7220 - print(f"pag {PAG_VERSION}")
7221 - sys.exit(0)
7222 - if len(sys.argv) == 2 and sys.argv[1] in ("--help", "-h", "help"):
7223 - print(_get_usage()); sys.exit(0)
7224 - if len(sys.argv) < 2:
7225 - print(_get_usage()); sys.exit(0)
7226 -
7227 - cmd = sys.argv[1]
7228 - args = sys.argv[2:]
7229 -
7230 - # Python bez modułu ssl = brak HTTPS w urllib. Powiedz to wprost, zamiast
7231 - # pokazywać mylące „unknown url type: https” przy każdej operacji sieciowej.
7232 - if not _ssl_ok():
7233 - print(f" ⚠ {_('ssl_broken')}", file=sys.stderr)
7234 -
7235 - # `pag repair --dry-run`: diagnostyka bez roota (nic nie zmienia).
7236 - if cmd == "repair" and "--dry-run" in args and os.geteuid() != 0:
7237 - sys.exit(cmd_repair(dry_run=True) or 0)
7238 -
7239 - # --- Komendy TYLKO DO ODCZYTU (nie wymagają roota) ---
7240 - READ_ONLY = {
7241 - "list": lambda: cmd_list("--installed" in args),
7242 - "search": lambda: cmd_search(args[0]) if args else print("Usage: pag search <query>"),
7243 - "info": lambda: cmd_info(args[0]) if args else print("Usage: pag info <pkg>"),
7244 - "files": lambda: cmd_files(args[0]) if args else print("Usage: pag files <pkg>"),
7245 - "verify": lambda: cmd_verify("--deep" in args),
7246 - "why": lambda: cmd_why(args[0]) if args else print("Usage: pag why <pkg>"),
7247 - "rdepends": lambda: cmd_rdepends(args[0]) if args else print("Usage: pag rdepends <pkg>"),
7248 - "stats": cmd_stats,
7249 - "pinned": cmd_pinned,
7250 - "history": cmd_history,
7251 - "repo-list": cmd_repo_list,
7252 - "key-list": cmd_key_list,
7253 - "key-trusted": cmd_key_trusted,
7254 - "flatpak": lambda: cmd_flatpak(args),
7255 - "flatpak-search": lambda: cmd_flatpak_search(args[0]) if args else print("Usage: pag flatpak-search <query>"),
7256 - "flatpak-list": cmd_flatpak_list,
7257 - "flatpak-info": lambda: cmd_flatpak_info(args[0]) if args else print("Usage: pag flatpak-info <id>"),
7258 - "deploy-list": cmd_deploy_list,
7259 - "deploy": cmd_deploy_list,
7260 - "snapshot-list": cmd_snapshot_list,
7261 - "snapshots": cmd_snapshot_list,
7262 - "snapshot-grub": cmd_snapshot_grub,
7263 - "sbom": lambda: cmd_sbom(args),
7264 - }
7265 -
7266 - if cmd in READ_ONLY:
7267 - sys.exit(READ_ONLY[cmd]() or 0)
7268 -
7269 - # --- `pag base` / `pag base status`: tylko odczyt (bez roota i bez locka) ---
7270 - # `pag base adopt` NIE wpada tutaj – idzie ścieżką komend zapisu (roota + lock
7271 - # pilnuje wspólna obsługa niżej), żeby transakcja była bezpieczna.
7272 - if cmd in ("base", "base-status") and not (args and args[0] in ("adopt", "register")):
7273 - sys.exit(cmd_base_status() or 0)
7274 -
7275 - # --- Smart search: `pag <nazwa-pakietu>` → repo + Flathub + sugestie ---
7276 - WRITE_CMDS = {
7277 - "install", "remove", "update", "sync", "upgrade", "clean", "download",
7278 - "autoremove", "remove-orphans", "pin", "unpin", "rollback",
7279 - "repo-add", "key-add", "key-remove", "key-trust", "key-untrust",
7280 - "self-update",
7281 - "flatpak", "flatpak-install", "flatpak-remove", "flatpak-update",
7282 - "deploy-rollback", "deploy-cleanup", "initramfs-update", "grub-update",
7283 - "snapshot-create", "snapshot-delete", "snapshot-rollback",
7284 - "base", "base-adopt", "base-register",
7285 - "repair",
7286 - }
7287 - if cmd not in WRITE_CMDS:
7288 - # Literówka komendy? (np. `pag instal steam` zamiast `pag install`) –
7289 - # zasugeruj poprawną komendę ZAMIAST wpadać w smart search (który
7290 - # potrafi wisieć na `flatpak search` aż do Ctrl-C).
7291 - _known = set(READ_ONLY) | set(WRITE_CMDS)
7292 - _close = difflib.get_close_matches(cmd, _known, n=1, cutoff=0.75)
7293 - if _close:
7294 - print(f"❌ Nieznana komenda: '{cmd}'. Czy chodziło o '{_close[0]}'?")
7295 - print(f" Uruchom 'pag' bez argumentów, aby zobaczyć listę komend.")
7296 - sys.exit(1)
7297 - sys.exit(_smart_search(" ".join([cmd] + args)) or 0)
7298 -
7299 - # Obsługa flag globalnych (-y/--yes oraz transakcji/snapshotów)
7300 - global_args = []
7301 - for a in args:
7302 - if a in ("-y", "--yes"):
7303 - os.environ["PAG_YES"] = "1"
7304 - elif a == "--dry-run":
7305 - os.environ["PAG_DRY_RUN"] = "1"
7306 - global_args.append(a) # `repair`/`base adopt` czytają flagę
7307 - elif a == "--snapshot":
7308 - os.environ["PAG_SNAPSHOT"] = "always"
7309 - elif a == "--no-snapshot":
7310 - os.environ["PAG_SNAPSHOT"] = "never"
7311 - elif a == "--atomic":
7312 - os.environ["PAG_ATOMIC"] = "1"
7313 - elif a == "--no-atomic":
7314 - os.environ["PAG_ATOMIC"] = "0"
7315 - else:
7316 - global_args.append(a)
7317 - args = global_args
7318 -
7319 - # --- Komendy ZAPISU (wymagają roota) ---
7320 - if os.geteuid() != 0:
7321 - print(f"❌ {_('root_required')}", file=sys.stderr); sys.exit(1)
7322 -
7323 - ensure_dirs()
7324 -
7325 - with DatabaseLock():
7326 - # Auto-naprawa: backup z przerwanej transakcji (bez wpisu „success")
7327 - # -> przywróć brakujące pliki, zanim cokolwiek innego zrobimy.
7328 - _recover_interrupted_transactions()
7329 - WRITE_COMMANDS = {
7330 - "install": lambda: cmd_install(
7331 - [a for a in args if a not in (
7332 - "-f", "--force", "--dry-run", "--snapshot", "--no-snapshot",
7333 - "--atomic", "--no-atomic", "--")],
7334 - upgrade=("-f" in args or "--force" in args)),
7335 - "remove": lambda: cmd_remove(args),
7336 - "update": lambda: cmd_update(do_upgrade=True),
7337 - "sync": lambda: cmd_update(do_upgrade=False),
7338 - "upgrade": cmd_upgrade,
7339 - "clean": cmd_clean,
7340 - "download": lambda: cmd_download(args),
7341 - "autoremove": cmd_autoremove,
7342 - "remove-orphans": cmd_remove_orphans,
7343 - "pin": lambda: cmd_pin(args[0], args[1] if len(args)>1 else ""),
7344 - "unpin": lambda: cmd_unpin(args[0]) if args else print("Usage: pag unpin <pkg>"),
7345 - "rollback": cmd_rollback,
7346 - "repair": lambda: cmd_repair(dry_run="--dry-run" in args),
7347 - "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]"),
7348 - "key-add": lambda: cmd_key_add(args[0]) if args else print("Usage: pag key-add <url|file>"),
7349 - "key-remove": lambda: cmd_key_remove(args[0]) if args else print("Usage: pag key-remove <id>"),
7350 - "key-trust": lambda: cmd_key_trust(args[0]) if args else print("Usage: pag key-trust <repo_url>"),
7351 - "key-untrust": lambda: cmd_key_untrust(args[0]) if args else print("Usage: pag key-untrust <repo_url>"),
7352 - "self-update": cmd_self_update,
7353 - "flatpak": lambda: cmd_flatpak(args),
7354 - "flatpak-install": lambda: _flatpak_smart_install(args) if args else print("Usage: pag flatpak-install <app>"),
7355 - "flatpak-remove": lambda: _flatpak_smart_remove(args) if args else print("Usage: pag flatpak-remove <app>"),
7356 - "flatpak-update": cmd_flatpak_update,
7357 - "deploy-rollback": cmd_deploy_rollback,
7358 - "deploy-cleanup": lambda: cmd_deploy_cleanup(int(args[0]) if args else 3),
7359 - "snapshot-create": lambda: cmd_snapshot_create(" ".join(
7360 - a for a in args if not a.startswith("-"))),
7361 - "snapshot-delete": lambda: cmd_snapshot_delete(args[0]) if args else print(
7362 - "Usage: pag snapshot-delete <id>"),
7363 - "snapshot-rollback": lambda: cmd_snapshot_rollback(
7364 - args[0] if args else ""),
7365 - "initramfs-update": cmd_initramfs_update,
7366 - "grub-update": cmd_grub_update,
7367 - "base": lambda: cmd_base_register(args) if (args and args[0] == "register") else cmd_base_adopt(args),
7368 - "base-adopt": lambda: cmd_base_adopt(args),
7369 - "base-register": lambda: cmd_base_register(args),
7370 - }
7371 -
7372 - fn = WRITE_COMMANDS.get(cmd)
7373 - if fn:
7374 - sys.exit(fn() or 0)
7375 - # Should never reach here – _smart_search handles unknowns
7376 - sys.exit(_smart_search(" ".join([cmd] + args)) or 0)
7377 -
7378 -if __name__ == "__main__":
7379 - try:
7380 - main()
7381 - except KeyboardInterrupt:
7382 - # Ctrl-C (np. podczas flatpak search / pobierania) – bez tracebacka
7383 - print("\n ⚠ Przerwano (Ctrl-C).")
2 +"""
3 +╔══════════════════════════════════════════════════════════════════════════════╗
4 +║ PAG - Pagan Linux Package Manager v4.2.0 ║
5 +║ Produkcyjny menedżer pakietów – atomowy, bezpieczny, i18n ║
6 +╚══════════════════════════════════════════════════════════════════════════════╝
7 +
8 +KLUCZOWE CECHY:
9 + - Transakcja grupowa: staging CAŁEJ grupy → commit (błąd paczki nie psuje systemu)
10 + - Snapshoty btrfs przed transakcją + wpisy GRUB (rollback przy starcie)
11 + - Atomowa instalacja przez staging (tmpdir → rename) – brak pół-instalacji
12 + - Bezpieczne usuwanie – sprawdza czy plik nie jest współdzielony
13 + - SQLite dla bazy plików – miliony plików bez problemu
14 + - GPG: weryfikacja repo.json + podpisy pakietów + pinning fingerprintu
15 + - Hooki: pre/post-install, pre/post-remove (piaskownica env, timeout, audit)
16 + - Głęboka weryfikacja SHA256 per-plik
17 + - Pełny rollback – cofa fizyczne pliki
18 + - Blokada flock – tylko jedna instancja
19 + - Transakcje z migawkami + rejestr wykonanych hooków
20 + - Cache HTTP (ETag/If-Modified-Since)
21 + - Wielojęzyczność (i18n) – PL, EN
22 +
23 +FORMAT PAKIETU (.pag):
24 + ├── data.tar.xz – pliki + sums.json (SHA256 per plik)
25 + ├── metadata.json – nazwa, wersja, zależności
26 + └── hooks/ – pre-install, post-install, pre-remove, post-remove
27 +
28 +MODEL ZAUFANIA / BEZPIECZEŃSTWO:
29 + - Repozytorium MUSI być zaufane: podpisy GPG zweryfikowane; fingerprint
30 + klucza przypiętego do repo (TOFU przy pierwszym użyciu, potem pinning).
31 + - Hooki uruchamiają dowolny plik z pakietu jako ROOT (jak apt/pacman).
32 + Ograniczamy je (czyste env, timeout, PAG_NO_HOOKS=1, log do
33 + /var/log/pag/audit.log) i rejestrujemy w transakcji, ale ostatecznie
34 + instalujesz kod, któremu ufasz.
35 + - self-update: weryfikacja podpisu + SHA256 + składnia, atomowa podmiana.
36 +"""
37 +
38 +import os, sys, json, copy, shutil, hashlib, tarfile, tempfile, subprocess, time, fcntl, locale, re, difflib
39 +
40 +def _early(en, pl):
41 + return pl if os.environ.get("LANG", "")[:2] == "pl" else en
42 +
43 +# Twarde moduły Pythona. Zamiast tracebacku dajemy jasny komunikat, bo brak
44 +# tych modułów oznacza zwykle niezadeklarowaną zależność pakietu (sqlite/xz).
45 +try:
46 + import sqlite3
47 +except ImportError:
48 + sys.stderr.write(_early("pag: Python without sqlite3 module – install the sqlite "
49 + "package (libsqlite3) and rebuild python.\n",
50 + "pag: Python bez modułu sqlite3 – zainstaluj pakiet sqlite "
51 + "(libsqlite3) i przebuduj python.\n"))
52 + sys.exit(1)
53 +try:
54 + import lzma # noqa: F401 – potrzebny do paczek .pag (XZ)
55 +except ImportError:
56 + sys.stderr.write(_early("pag: Python without lzma module – install the xz "
57 + "package (liblzma) and rebuild python.\n",
58 + "pag: Python bez modułu lzma – zainstaluj pakiet xz "
59 + "(liblzma) i przebuduj python.\n"))
60 + sys.exit(1)
61 +
62 +# Fix TLS trust inside the Pagan chroot: point Python at the CA bundle that
63 +# pag ships, otherwise urlopen() fails with "unable to get local issuer
64 +# certificate" (no default capath/cafile is resolved in the chroot).
65 +for _cafile in (
66 + "/etc/ssl/certs/ca-certificates.crt",
67 + "/etc/ssl/cert.pem",
68 +):
69 + if os.path.isfile(_cafile):
70 + os.environ["SSL_CERT_FILE"] = _cafile
71 + break
72 +
73 +from pathlib import Path
74 +from datetime import datetime, timezone
75 +from typing import Dict, List, Optional, Tuple, Set
76 +from concurrent.futures import ThreadPoolExecutor, as_completed
77 +from urllib.request import urlopen, Request
78 +import threading, itertools
79 +import uuid # serialNumber SBOM (CycloneDX)
80 +
81 +# Wersja klienta – do porównania z repo.json["pag_version"] (self-update)
82 +PAG_VERSION = "4.2.0"
83 +from urllib.error import URLError, HTTPError
84 +
85 +# =============================================================================
86 +# Pagan progress — animowany pasek „Drakkar” (własny motyw Pagan/Loki)
87 +# -----------------------------------------------------------------------------
88 +# Zamiast statycznego „█” pasek jest animowany: łódź wikingów płynie po
89 +# falującym morzu, a za nią ciągnie się smuga z wędrującym refleksem. Animacja
90 +# jest funkcją czasu, więc „płynie” nawet gdy postęp stoi w miejscu (długa
91 +# instalacja jednego pakietu, przerwa między fragmentami pobierania).
92 +#
93 +# Konfiguracja (zmienne środowiskowe):
94 +# PAG_NO_ANIM=1 – wyłącz animację (zostaje klasyczny statyczny pasek)
95 +# PAG_BAR_STYLE=<styl> – drakkar (domyślnie) | snake | classic
96 +# Poza TTY animacja jest automatycznie wyłączona (czyste logi w plikach).
97 +# =============================================================================
98 +
99 +_PAGAN_ANIM = os.environ.get("PAG_NO_ANIM", "") not in ("1", "true", "yes", "on")
100 +_PAGAN_STYLE = os.environ.get("PAG_BAR_STYLE", "drakkar").strip().lower()
101 +_DRAW_LOCK = threading.Lock() # serializacja zapisów wielu pasków
102 +
103 +# Dwie fazy fali – przesuwane w czasie dają wrażenie ruchu morza.
104 +_WAVE_PHASES = ("~_", "_~")
105 +
106 +# Zapas kolumn przy rysowaniu paska: ostatnia kolumna terminala wywołuje
107 +# „auto-wrap”, a glify szerokie (np. emoji 📦) liczą się jako 1 w `len()`, ale
108 +# zajmują 2 kolumny – margines chroni przed zawinięciem linii.
109 +_BAR_MARGIN = 2
110 +
111 +
112 +def _term_width(stream=None, default: int = 80) -> int:
113 + """Szerokość terminala (w kolumnach) dla strumienia paska.
114 +
115 + Pasek MUSI zmieścić się w jednej linii: gdy jest szerszy niż terminal, ten
116 + sam go zawija i KAŻDA aktualizacja trafia do nowej linii zamiast nadpisywać
117 + poprzednią. Pytamy o rozmiar konkretnego `stream` (pasek pisze na stderr),
118 + a nie domyślnego stdout – inaczej przy przekierowanym stdout dostalibyśmy
119 + fałszywe 80 kolumn.
120 + """
121 + fd = None
122 + if stream is not None:
123 + try:
124 + fd = stream.fileno()
125 + except Exception:
126 + fd = None
127 + if fd is not None:
128 + try:
129 + cols = os.get_terminal_size(fd).columns
130 + if cols > 0:
131 + return cols
132 + except OSError:
133 + pass
134 + try:
135 + cols = shutil.get_terminal_size((default, 24)).columns
136 + except Exception:
137 + cols = default
138 + return cols if cols > 0 else default
139 +
140 +
141 +def _classic_bar(pct: float, width: int) -> str:
142 + """Klasyczny statyczny pasek █/░ (fallback dla logów i PAG_NO_ANIM)."""
143 + filled = int(round(width * max(0.0, min(100.0, pct)) / 100.0))
144 + return "█" * filled + "░" * (width - filled)
145 +
146 +
147 +def _drakkar_bar(pct: float, width: int, t: float, filled: int) -> str:
148 + """Drakkar (łódź wikingów) płynący po falującym morzu.
149 +
150 + - przed łodzią: falujące morze (~ _ przesuwane w czasie),
151 + - dziób łodzi: » (kolumna = bieżący postęp),
152 + - za łodzią: smuga z wędrującym refleksem światła.
153 + """
154 + done = pct >= 100.0
155 + wave = _WAVE_PHASES[int(t * 6) % len(_WAVE_PHASES)]
156 + ship = min(filled, width - 1)
157 + glow = int(t * 10) % ship if ship > 0 else -1
158 + out = []
159 + for i in range(width):
160 + if done:
161 + out.append("»" if i == width - 1 else "█") # łódź zacumowana
162 + elif i < ship:
163 + out.append("█" if i == glow else "▓")
164 + elif i == ship:
165 + out.append("»")
166 + else:
167 + out.append(wave[i & 1])
168 + return "".join(out)
169 +
170 +
171 +def _snake_bar(pct: float, width: int, t: float, filled: int) -> str:
172 + """Jörmungandr – wąż sunący przez pasek (głowa @, łuski o/~, ogon ·)."""
173 + done = pct >= 100.0
174 + head = min(filled, width - 1)
175 + out = []
176 + for i in range(width):
177 + if done:
178 + out.append("@" if i == width - 1 else "o")
179 + elif i < head:
180 + out.append("o" if (i + int(t * 6)) & 1 else "~")
181 + elif i == head:
182 + out.append("@")
183 + else:
184 + out.append("·")
185 + return "".join(out)
186 +
187 +
188 +def _pagan_bar(pct: float, width: int = 30, t: float = 0.0,
189 + style: Optional[str] = None, animated: bool = True) -> str:
190 + """Zwraca jednoliniowy pasek postępu o STAŁEJ szerokości `width`.
191 +
192 + `pct` – postęp 0..100
193 + `t` – czas (s); różne `t` → inna klatka animacji
194 + `animated` – False wymusza klasyczny statyczny pasek (np. brak TTY)
195 + """
196 + width = max(6, int(width))
197 + pct = max(0.0, min(100.0, float(pct)))
198 + style = style or _PAGAN_STYLE
199 + if not animated or not _PAGAN_ANIM or style == "classic":
200 + return _classic_bar(pct, width)
201 + filled = int(round(width * pct / 100.0))
202 + if style == "snake":
203 + return _snake_bar(pct, width, t, filled)
204 + return _drakkar_bar(pct, width, t, filled)
205 +
206 +
207 +class _Bar:
208 + """Baza animowanych pasków: rysują JEDNĄ nadpisywaną linię na `stream`.
209 +
210 + Gdy mamy TTY, wątek w tle odświeża pasek ~10×/s, dzięki czemu morze faluje
211 + także wtedy, gdy postęp chwilowo się nie zmienia.
212 + """
213 + def __init__(self, width: int, stream=None):
214 + self.width = width
215 + self.stream = stream if stream is not None else sys.stderr
216 + self.tty = self.stream.isatty()
217 + self._lock = threading.RLock()
218 + self._last_len = 0
219 + self._stop = threading.Event()
220 + self._thread = None
221 +
222 + # -- wątek animacji -------------------------------------------------------
223 + def _start_anim(self):
224 + if _PAGAN_ANIM and self.tty and self._thread is None:
225 + self._thread = threading.Thread(target=self._anim_loop, daemon=True)
226 + self._thread.start()
227 +
228 + def _anim_loop(self):
229 + while not self._stop.wait(0.1):
230 + with self._lock:
231 + if self._stop.is_set():
232 + break
233 + self._write(self._line())
234 +
235 + def _stop_anim(self):
236 + self._stop.set()
237 + if self._thread is not None:
238 + self._thread.join(timeout=0.3)
239 + self._thread = None
240 +
241 + # -- rysowanie ------------------------------------------------------------
242 + def _cap(self) -> int:
243 + """Maksymalna liczba kolumn jednej linii paska (z zapasem na wrap)."""
244 + return _term_width(self.stream) - _BAR_MARGIN
245 +
246 + def _shrink(self, text: str, fixed: int) -> str:
247 + """Skróć `text` tak, by `text` + `fixed` kolumn zmieściło się w linii."""
248 + room = self._cap() - fixed
249 + if room >= 1 and len(text) > room:
250 + return "…" if room == 1 else text[:room - 1] + "…"
251 + return text
252 +
253 + def _fit(self, line: str) -> str:
254 + """Ostatnia linia obrony: przytnij linię do szerokości terminala.
255 +
256 + Wycinamy ŚRODEK (wielokropek), więc widoczne zostają początek (nazwa)
257 + i koniec (%, prędkość, ETA). Bez tego zawinięta linia = nowa linia przy
258 + każdym odświeżeniu zamiast nadpisywania poprzedniej.
259 + """
260 + cap = self._cap()
261 + if cap <= 0 or len(line) <= cap:
262 + return line
263 + keep = cap - 1 # miejsce na wielokropek „…”
264 + head = (keep + 1) // 2
265 + tail = keep - head
266 + return line[:head] + "…" + (line[-tail:] if tail > 0 else "")
267 +
268 + def _write(self, line: str):
269 + line = self._fit(line)
270 + clear = " " * max(0, self._last_len - len(line))
271 + with _DRAW_LOCK:
272 + self.stream.write(f"\r{line}{clear}")
273 + self.stream.flush()
274 + self._last_len = len(line)
275 +
276 + def _line(self) -> str:
277 + raise NotImplementedError
278 +
279 + def _clear_line(self):
280 + if self.tty and self._last_len:
281 + with _DRAW_LOCK:
282 + self.stream.write("\r" + " " * self._last_len + "\r")
283 + self.stream.flush()
284 + self._last_len = 0
285 +
286 + def _newline(self):
287 + if self.tty and self._last_len:
288 + self.stream.write("\n")
289 + self.stream.flush()
290 + self._last_len = 0
291 +
292 +
293 +class ProgressBar(_Bar):
294 + """Pasek postępu dla N elementów — animowany („drakkar”) na TTY."""
295 + def __init__(self, total: int, desc: str = "", unit: str = "", width: int = 30):
296 + super().__init__(width)
297 + self.total = max(total, 1)
298 + self.desc = desc
299 + self.unit = unit
300 + self.n = 0
301 + self.suffix = ""
302 + self.start = time.time()
303 + self._start_anim()
304 +
305 + def _line(self) -> str:
306 + pct = self.n / self.total * 100
307 + elapsed = time.time() - self.start
308 + speed = self.n / elapsed if elapsed > 0 else 0
309 + if self.n >= self.total:
310 + eta_str = _("done")
311 + elif speed > 0:
312 + eta = (self.total - self.n) / speed
313 + eta_str = f"{eta:.0f}s" if eta < 60 else f"{eta/60:.1f}m"
314 + else:
315 + eta_str = "?..."
316 + bar = _pagan_bar(pct, self.width, time.time(), animated=self.tty)
317 + tail = f" [{bar}] {self.n}/{self.total} ({pct:.0f}%) ETA {eta_str}{self.suffix}"
318 + desc = self._shrink(self.desc, 2 + len(tail))
319 + return f" {desc}{tail}"
320 +
321 + def update(self, n: Optional[int] = None, suffix: str = ""):
322 + with self._lock:
323 + if n is not None:
324 + self.n = n
325 + else:
326 + self.n += 1
327 + self.suffix = suffix
328 + if self.tty:
329 + self._write(self._line())
330 + elif (self.n == 1 or self.n >= self.total
331 + or self.n % max(1, self.total // 10) == 0):
332 + # Bez TTY – tylko kamienie milowe (czysty log)
333 + print(self._line(), file=self.stream)
334 +
335 + def close(self):
336 + self._stop_anim()
337 + with self._lock:
338 + self._newline()
339 +
340 + def __enter__(self):
341 + return self
342 +
343 + def __exit__(self, *args):
344 + self.close()
345 +
346 +
347 +class DownloadBar(_Bar):
348 + """Animowany pasek pobierania (na podstawie Content-Length)."""
349 + def __init__(self, filename: str, total_bytes: int):
350 + super().__init__(25)
351 + self.filename = filename
352 + self.total = total_bytes
353 + self.downloaded = 0
354 + self.start = time.time()
355 + self._start_anim()
356 +
357 + def _line(self) -> str:
358 + pct = self.downloaded / self.total * 100 if self.total > 0 else 0.0
359 + elapsed = time.time() - self.start
360 + speed = self.downloaded / elapsed if elapsed > 0 else 0
361 + if self.total > 0 and speed > 0:
362 + eta = (self.total - self.downloaded) / speed
363 + eta_str = f"{eta:.0f}s" if eta < 60 else f"{eta/60:.1f}m"
364 + else:
365 + eta_str = "?..."
366 + bar = _pagan_bar(pct, self.width, time.time(), animated=self.tty)
367 + sz = self._fmt_size(self.total)
368 + spd = self._fmt_size(int(speed))
369 + tail = f" [{bar}] {pct:.0f}% {sz} {spd}/s ETA {eta_str}"
370 + # Nazwa pliku bywa długa (np. linux-firmware-…-1.pag) i wtedy CAŁA linia
371 + # nie mieści się w terminalu (zawijanie → nowa linia przy każdym %).
372 + # Skracamy WYŁĄCZNIE nazwę – pełny pasek, prędkość i ETA zostają.
373 + name = self._shrink(self.filename, 4 + len(tail)) # prefiks „ ↓ ” = 4 kolumny
374 + return f" ↓ {name}{tail}"
375 +
376 + def update(self, chunk_size: int):
377 + with self._lock:
378 + self.downloaded += chunk_size
379 + if self.tty and self.total > 0:
380 + self._write(self._line())
381 +
382 + def close(self):
383 + self._stop_anim()
384 + with self._lock:
385 + if self.total > 0:
386 + self._newline()
387 +
388 + @staticmethod
389 + def _fmt_size(n: int) -> str:
390 + for unit in ("B", "KB", "MB", "GB"):
391 + if n < 1024:
392 + return f"{n:.1f} {unit}"
393 + n /= 1024
394 + return f"{n:.1f} TB"
395 +
396 +
397 +class _StepBar(_Bar):
398 + """Animowany pasek dla pętli „krok po kroku” (instalacja/aktualizacja).
399 +
400 + Pasek nie skacze skokowo co pakiet – między krokami łagodnie „dopełza”
401 + w stronę kolejnego progu (jak w instalatorach), więc rośnie w sposób
402 + ciągły. Wątek animacji odświeża go ~10×/s.
403 + """
404 + def __init__(self, total: int, icon: str = "", width: int = 25,
405 + creep_tau: float = 3.0):
406 + super().__init__(width)
407 + self.total = max(total, 1)
408 + self.icon = icon
409 + self.creep_tau = creep_tau # „stała czasu” dopełzania (s)
410 + self.idx = 0
411 + self.label = ""
412 + self.t0 = time.time()
413 + self._step_t = time.time() # start bieżącego pakietu
414 + self._start_anim()
415 +
416 + def _frac(self) -> float:
417 + """Ukończona część [0..1]: kroki + wygładzone dopełzanie w bieżącym."""
418 + done = max(0, self.idx - 1)
419 + if done >= self.total:
420 + return 1.0
421 + # 0.5 ** (dt/tau): 0 → ~1 asymptotycznie; cap 0.9, by krok był widoczny
422 + creep = 1.0 - 0.5 ** ((time.time() - self._step_t) / self.creep_tau)
423 + return (done + min(creep, 0.9)) / self.total
424 +
425 + def _line(self) -> str:
426 + pct = self._frac() * 100.0
427 + eta_s = ""
428 + if self.idx > 1:
429 + avg = (time.time() - self.t0) / (self.idx - 1)
430 + rem = avg * (self.total - self.idx + 1)
431 + eta_s = f" ~{rem:.0f}s" if rem < 60 else f" ~{rem/60:.1f}m"
432 + bar = _pagan_bar(pct, self.width, time.time(), animated=self.tty)
433 + tail = f"[{bar}] {self.idx}/{self.total} ({pct:.0f}%) "
434 + label = self._shrink(self.label, 2 + len(self.icon) + len(tail) + len(eta_s))
435 + return f" {self.icon}{tail}{label}{eta_s}"
436 +
437 + def step(self, idx: int, label: str):
438 + with self._lock:
439 + self.idx = idx
440 + self.label = label
441 + self._step_t = time.time()
442 + if self.tty:
443 + self._write(self._line())
444 + else:
445 + print(self._line(), file=self.stream)
446 +
447 + def end(self):
448 + self._stop_anim()
449 + with self._lock:
450 + self._clear_line()
451 +
452 +# =============================================================================
453 +# GPG – BEZPIECZNE WYWOŁYWANIE (odporne na brak binarki gpg)
454 +# =============================================================================
455 +
456 +GPG_BINARY = shutil.which("gpg2") or shutil.which("gpg") or "gpg"
457 +GPG_HOME = "/etc/pag/gpg" # izolowany keyring (działa z keyboxd GPG 2.4+)
458 +
459 +def _ssl_ok() -> bool:
460 + """Czy Python ma działający moduł ssl (HTTPS w urllib).
461 +
462 + Bez niego urllib nie zna schematu https i każda operacja sieciowa kończy
463 + się „unknown url type: https” – myląco, bo wygląda jak błąd adresu.
464 + """
465 + try:
466 + import ssl # noqa: F401
467 + return True
468 + except Exception:
469 + return False
470 +
471 +
472 +def _gpg_run(*args, timeout: int = 30, **kwargs) -> subprocess.CompletedProcess:
473 + """
474 + Bezpieczne wywołanie GPG – przechwytuje FileNotFoundError,
475 + gdyby gpg/gpg2 nie było zainstalowane w minimalnym środowisku.
476 + Wymusza LC_ALL=C aby komunikaty GPG były zawsze po angielsku
477 + (niezależnie od locale systemu) – kluczowe dla parsowania stderr.
478 + """
479 + env = kwargs.pop("env", None) or os.environ.copy()
480 + env["LC_ALL"] = "C"
481 + env["GNUPGHOME"] = GPG_HOME
482 + _text = bool(kwargs.get("text") or kwargs.get("universal_newlines"))
483 + try:
484 + return subprocess.run([GPG_BINARY, *args], timeout=timeout, env=env, **kwargs)
485 + except FileNotFoundError:
486 + # GPG nie jest dostępne – zwróć błąd z komunikatem
487 + # (szanuj text=True – inaczej caller dostaje bytes i może wybuchnąć TypeError)
488 + _text = bool(kwargs.get("text") or kwargs.get("universal_newlines"))
489 + _msg = _("gpg_binary_not_found", GPG_BINARY)
490 + return subprocess.CompletedProcess(
491 + [GPG_BINARY, *args], 127,
492 + stdout=("" if _text else b""),
493 + stderr=(_msg if _text else _msg.encode()),
494 + )
495 + except subprocess.TimeoutExpired:
496 + _msg = _("gpg_timeout")
497 + return subprocess.CompletedProcess(
498 + [GPG_BINARY, *args], 124,
499 + stdout=("" if _text else b""),
500 + stderr=(_msg if _text else _msg.encode())
501 + )
502 +
503 +def _load_trust_db() -> dict:
504 + """Mapa repo_url → fingerprint klucza podpisującego (baza zaufania)."""
505 + try:
506 + with open(TRUST_DB) as f:
507 + return json.load(f)
508 + except (FileNotFoundError, json.JSONDecodeError):
509 + return {}
510 +
511 +
512 +def _save_trust_db(db: dict):
513 + os.makedirs(os.path.dirname(TRUST_DB), exist_ok=True)
514 + with open(TRUST_DB, "w") as f:
515 + json.dump(db, f, indent=2)
516 +
517 +
518 +def _gpg_verify_fp(sig_path: str, data_path: str, timeout: int = 30):
519 + """Weryfikuje podpis i odczytuje fingerprint podpisującego.
520 +
521 + Używa --status-fd=1 i linii VALIDSIG <fingerprint>. Zwraca (ok, fingerprint).
522 +
523 + FAIL-CLOSED: OK tylko gdy GPG zwrócił 0 ORAZ w statusie maszynowym jest
524 + linia VALIDSIG. Nie zakładamy sukcesu na podstawie samego kodu wyjścia –
525 + gdyby format --status-fd się zmienił, wolimy odrzucić podpis niż przyjąć
526 + niezaufany pakiet (wywołujący traktuje fp=None jako brak potwierdzenia).
527 + """
528 + env = os.environ.copy()
529 + res = _gpg_run("--verify", "--status-fd", "1", sig_path, data_path,
530 + capture_output=True, text=True, timeout=timeout, env=env)
531 + out = res.stdout or ""
532 + m = re.search(r"\[GNUPG:\]\s+VALIDSIG\s+([0-9A-Fa-f]{16,})", out)
533 + if not m:
534 + m = re.search(r"\bVALIDSIG\s+([0-9A-Fa-f]{16,})", out)
535 + if res.returncode != 0 or not m:
536 + return False, None
537 + return True, m.group(1).upper()
538 +
539 +
540 +def _verify_local_pkg_signature(pkg_path: str) -> bool:
541 + """Weryfikuje lokalny .pag tym samym kluczem co zaufane repo."""
542 + # PAG_INSECURE=1 – spójnie z _verify_repo_sig() i _verify_pkg_signature().
543 + # Potrzebne w środowisku BUILDA: instalator buduje własne .pag (np. `kernel`)
544 + # lokalnie, nie ma dla nich pliku .asc, a klucza prywatnego repo celowo NIE ma
545 + # na maszynie budującej. Wcześniej ta funkcja jako jedyna ignorowała
546 + # PAG_INSECURE, więc obejście używane przez resztę builda tu nie działało.
547 + if os.environ.get("PAG_INSECURE", "") == "1":
548 + print(_(' ⚠ PAG_INSECURE=1 – skipping local package signature verification'))
549 + return True
550 + sig_path = next((pkg_path + ext for ext in (".asc", ".sig")
551 + if os.path.isfile(pkg_path + ext)), "")
552 + if not sig_path:
553 + print(_(' ❌ No signature for package: {arg1}', arg1=(pkg_path)))
554 + print(_(' A .pag.asc/.pag.sig file from the same source is required.'))
555 + return False
556 + ok, fingerprint = _gpg_verify_fp(sig_path, pkg_path)
557 + if not ok or not fingerprint:
558 + print(_(' ❌ Invalid package signature: {arg1}', arg1=(pkg_path)))
559 + return False
560 + expected = _repo_pinned_fp(DEFAULT_REPOS[0])
561 + if not expected:
562 + print(_(' ❌ No pinned repo key for the local package.'))
563 + print(_(' Run first: sudo pag sync'))
564 + return False
565 + if fingerprint != expected.upper():
566 + print(_(' ❌ [SECURITY ERROR] Package was signed with a different repo key.'))
567 + print(_(' Expected: {arg1}', arg1=(expected)))
568 + print(_(' Received: {arg1}', arg1=(fingerprint)))
569 + return False
570 + print(_(' 🔐 Package signature OK ({arg1})', arg1=(fingerprint)))
571 + return True
572 +
573 +
574 +# =============================================================================
575 +# i18n – WIELOJĘZYCZNOŚĆ
576 +# =============================================================================
577 +
578 +LANG = os.environ.get("LANG", "en_US.UTF-8")[:2] # pl, en, de...
579 +COLOR = os.environ.get("NO_COLOR", "") == "" and sys.stdout.isatty()
580 +
581 +def _c(code: str, text: str) -> str:
582 + """Dodaje kody ANSI jeśli kolor jest włączony."""
583 + if not COLOR:
584 + return text
585 + colors = {
586 + "green": "\033[32m", "red": "\033[31m", "yellow": "\033[33m",
587 + "cyan": "\033[36m", "bold": "\033[1m", "dim": "\033[2m",
588 + "reset": "\033[0m",
589 + }
590 + return f"{colors.get(code,'')}{text}{colors['reset']}"
591 +
592 +T = {
593 + "en": {
594 + "root_required": "pag requires root privileges (sudo).",
595 + "db_locked": "Another pag instance is running.",
596 + "db_lock_hint": "If no other pag process is running, wait a moment and retry.",
597 + "no_index": "Cannot fetch repository indexes. Run 'pag update'.",
598 + "cache_ro": "Repo cache is read-only ({cache}) – using local index (may be outdated).\n Refresh as root: sudo pag sync",
599 + "all_installed": "All packages are already installed.",
600 + "to_install": "To install: {} packages ({:.2f} MB)",
601 + "new": "NEW",
602 + "continue_q": "Continue? [Y/n] ",
603 + "no_tty": "No TTY / stdin closed (EOF) – cancelling.",
604 + "cancelled": "Cancelled.",
605 + "not_found": "not found in repos",
606 + "pkg_not_found": "Package not found: {} (not in any repo)",
607 + "not_found_hint": "Check the spelling or run 'pag search <query>'.",
608 + "downloading": "Downloading",
609 + "download_fail": "download failed",
610 + "gpg_fail": "GPG verification failed",
611 + "sha256_mismatch": "SHA256 mismatch",
612 + "install_failed": "installation failed",
613 + "installed": "Installed {} packages.",
614 + "rollback_restored": "Restored previous state from snapshot.",
615 + "rollback_files": "Rolled back {} files.",
616 + "no_history": "No transaction history.",
617 + "pinned_list": "Pinned packages ({}):",
618 + "no_pinned": "No pinned packages.",
619 + "pinned_to": "pinned to",
620 + "unpinned": "unpinned.",
621 + "not_pinned": "was not pinned.",
622 + "repo_added": "Added repository: {}",
623 + "repo_exists": "Repository already exists: {}",
624 + "updated_done": "Index refresh complete. {} packages cached.",
625 + "indexes_refreshed": "Indexes refreshed.",
626 + "updates_available": "⚠ {} packages have updates – run: pag update",
627 + "upgrading": "Upgrading: {} packages",
628 + "all_up_to_date": "All packages are up to date.",
629 + "removing": "Removing",
630 + "orphans_found": "Orphaned dependencies ({}): {}",
631 + "flatpak_missing": "Flatpak is not installed.",
632 + "flatpak_adding": "Adding Flathub remote...",
633 + "flatpak_searching": "Searching Flathub for '{}'...",
634 + "flatpak_found": "Found {} results:",
635 + "flatpak_not_found": "not found on Flathub",
636 + "flatpak_install_prompt": "Install {}? [Y/n] ",
637 + "flatpak_installing": "Installing {}...",
638 + "flatpak_installed": "Flatpak {} installed.",
639 + "flatpak_removed": "Flatpak {} removed.",
640 + "flatpak_not_installed": "Flatpak {} is not installed.",
641 + "flatpak_info_id": "ID",
642 + "flatpak_info_version": "Version",
643 + "flatpak_info_branch": "Branch",
644 + "flatpak_info_origin": "Origin",
645 + "flatpak_info_size": "Installed size",
646 + "flatpak_info_desc": "Description",
647 + "flatpak_updated": "Flatpaks updated.",
648 + "flatpak_usage": "Usage: pag flatpak <search|install|remove|list|update|info> [args]",
649 + "flatpak_scope": "Installation",
650 + "flatpak_menu_hint": "Installed and verified, but this session may not show it in the menu: Flatpak exports are missing from XDG_DATA_DIRS.",
651 + "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.",
652 + "key_imported": "Key imported successfully.",
653 + "key_removed": "Key removed: {}",
654 + "no_keys": "No trusted GPG keys.",
655 + "gpg_missing": "GNUPG MISSING – install gnupg and retry",
656 + "ssl_broken": "Python has no working ssl module (HTTPS impossible) – fix the python/openssl packages (e.g. sudo pag install -f python).",
657 + "key_add_failed": "Key import failed (gpg error) – key was NOT added.",
658 + "verify_ok": "All {} files intact.",
659 + "verify_errors": "{} problems found:",
660 + "cache_cleared": "{} files ({:.2f} MB) cleared from cache.",
661 + "deployments_list": "Deployments ({}):",
662 + "no_deployments": "No deployments.",
663 + "active_deployment": "ACTIVE",
664 + "deploy_rollback_ok": "Switched to deployment: {}",
665 + "deploy_rollback_fail": "No previous deployment.",
666 + "deploy_cleanup_ok": "Removed {} old deployments.",
667 + "deploy_cleanup_none": "No deployments to clean (minimum {}).",
668 + "snapshot_none": "No system snapshots.",
669 + "snapshot_list": "System snapshots ({}):",
670 + "snapshot_created": "Snapshot created: {}.",
671 + "snapshot_deleted": "Snapshot removed: {}.",
672 + "snapshot_not_found": "Snapshot not found: {}",
673 + "snapshot_unsupported": "Snapshots unavailable: {}",
674 + "snapshot_rollback_next": "Next boot set to snapshot: {}",
675 + "snapshot_rollback_hint": "Select this entry in the GRUB menu: {}",
676 + "staging_prepare": "Preparing {} packages in staging (system unchanged)...",
677 + "staging_failed": "Staging failed – the system was NOT modified.",
678 + "staging_commit": "All packages prepared – applying changes...",
679 + "dry_run_done": "Dry run – nothing was changed.",
680 + "dry_run_plan": "Dry run – transaction plan (no changes):",
681 + "why_explicit": "explicitly installed",
682 + "why_dependency": "dependency of",
683 + "why_not_installed": "not installed",
684 + "rdepends_title": "Reverse dependencies of {} ({}):",
685 + "rdepends_none": "nothing depends on it.",
686 + "optional_deps": "Optional dependencies (not installed automatically):",
687 + "autoremove_ok": "Removed {} orphaned packages.",
688 + "autoremove_none": "No orphaned packages.",
689 + "downloaded": "Downloaded {} to cache ({:.2f} MB).",
690 + "provides_mapped": "{} → {} (provides)",
691 + "stats_title": "PAG Statistics",
692 + "stats_packages": "Installed packages",
693 + "stats_files": "Tracked files",
694 + "stats_size": "Total size",
695 + "stats_cache": "Cache size",
696 + "stats_history": "Transactions",
697 + "stats_last_update": "Last update",
698 + # Komunikaty bezpieczeństwa (baza EN; PL w tabeli "pl" jako sec_*_pl)
699 + "sec_downgrade": "Downgrade blocked: {pkg} {new} < {old}",
700 + "sec_suid": "SUID stripped from {path}",
701 + "sec_https": "HTTPS required for repos",
702 + "sec_badname": "Invalid package name: {name}",
703 + "sec_toobig": "Package too large: {size_mb}MB > {max_mb}MB",
704 + "sec_conflict": "File conflict: {path} owned by {owner}",
705 + "sec_audit": "{pkg} installed by {user}",
706 + "sec_locked": "Another pag process is running",
707 + # Konfiguracja (/etc) – zachowanie zmian użytkownika
708 + "conf_pacnew": "Modified config kept; new version saved as {path}",
709 + "conf_pacsave": "Modified config kept as {path}",
710 + # Zależności wirtualne (provides)
711 + "provides_conflict": "Multiple providers for '{name}' ({providers}) – using '{chosen}'",
712 +
713 + # Base baked into the ISO image (pag base / base adopt)
714 + "base_title": "Base from the ISO image",
715 + "base_no_manifest": "This system carries no base manifest (/usr/share/pag/base.json) – nothing to adopt.",
716 + "base_iso_version": "Image version",
717 + "base_total": "Base packages (from image)",
718 + "base_tracked": "Managed by pag",
719 + "base_adoptable": "Adoptable from repo",
720 + "base_unmatched": "No counterpart in repo",
721 + "base_adopt_hint": "Adopt them (image files get replaced by repo packages): sudo pag base adopt",
722 + "base_unmatched_hint": "These stay at the image version (no such package in repo):",
723 + "base_more": "more",
724 + "base_nothing_selected": "None of the given names is on the adopt list.",
725 + "base_all_managed": "Every base package is already managed by pag.",
726 + "base_adopt_plan": "Adopting {} base packages from the repo (~{:.0f} MB):",
727 + "base_dry_run": "Dry run – nothing was installed.",
728 + "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).",
729 + "base_overwrite": "{} comes from the ISO image – its files will be replaced (backup kept for 'pag rollback').",
730 + "base_reboot_hint": "Base adopted from the repo – reboot before using the new libraries/toolchain.",
731 + "base_register_ok": "Registered {} base packages in the package DB ({} were already tracked).",
732 + "base_register_plan": "Dry run – would register {} base packages.",
733 + "base_register_nocache": "No cached repo index – builder names kept as-is (run 'sudo pag sync' and 'pag base register' again to map them to repo names).",
734 + "base_register_renamed": "{} names were matched to their repo package names.",
735 + "stats_base": "Base (image) managed",
736 + },
737 + "pl": {
738 + "root_required": "pag wymaga uprawnień root (sudo).",
739 + "db_locked": "Inna instancja pag jest uruchomiona.",
740 + "db_lock_hint": "Jeśli żaden inny proces pag nie działa, poczekaj chwilę i spróbuj ponownie.",
741 + "no_index": "Nie można pobrać indeksów repozytoriów. Uruchom 'pag update'.",
742 + "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",
743 + "all_installed": "Wszystkie pakiety są już zainstalowane.",
744 + "to_install": "Do zainstalowania: {} pakietów ({:.2f} MB)",
745 + "new": "NOWY",
746 + "continue_q": "Kontynuować? [T/n] ",
747 + "no_tty": "Brak terminala (EOF) – anuluję.",
748 + "cancelled": "Anulowano.",
749 + "not_found": "brak w repozytoriach",
750 + "pkg_not_found": "Nie znaleziono pakietu: {} (brak w repozytoriach)",
751 + "not_found_hint": "Sprawdź pisownię lub uruchom 'pag search <fraza>'.",
752 + "downloading": "Pobieranie",
753 + "download_fail": "błąd pobierania",
754 + "gpg_fail": "błąd weryfikacji GPG",
755 + "sha256_mismatch": "niezgodność SHA256",
756 + "install_failed": "błąd instalacji",
757 + "installed": "Zainstalowano {} pakietów.",
758 + "rollback_restored": "Przywrócono poprzedni stan z migawki.",
759 + "rollback_files": "Wycofano {} plików.",
760 + "no_history": "Brak historii transakcji.",
761 + "pinned_list": "Przypięte pakiety ({}):",
762 + "no_pinned": "Brak przypiętych pakietów.",
763 + "pinned_to": "przypięty do",
764 + "unpinned": "odpięty.",
765 + "not_pinned": "nie był przypięty.",
766 + "repo_added": "Dodano repozytorium: {}",
767 + "repo_exists": "Repozytorium już istnieje: {}",
768 + "updated_done": "Odświeżanie zakończone. {} pakietów w cache.",
769 + "indexes_refreshed": "Indeksy odświeżone.",
770 + "updates_available": "⚠ jest {} pakietów do zaktualizowania – wpisz: pag update",
771 + "upgrading": "Aktualizacje: {} pakietów",
772 + "all_up_to_date": "Wszystkie pakiety są aktualne.",
773 + "removing": "Usuwanie",
774 + "orphans_found": "Osierocone zależności ({}): {}",
775 + "flatpak_missing": "Flatpak nie jest zainstalowany.",
776 + "flatpak_adding": "Dodaję zdalne repozytorium Flathub...",
777 + "flatpak_searching": "Szukam '{}' we Flathub...",
778 + "flatpak_found": "Znaleziono {} wyników:",
779 + "flatpak_not_found": "nie znaleziono we Flathub",
780 + "flatpak_install_prompt": "Zainstalować {}? [T/n] ",
781 + "flatpak_installing": "Instalowanie {}...",
782 + "flatpak_installed": "Flatpak {} zainstalowany.",
783 + "flatpak_removed": "Flatpak {} usunięty.",
784 + "flatpak_not_installed": "Flatpak {} nie jest zainstalowany.",
785 + "flatpak_info_id": "ID",
786 + "flatpak_info_version": "Wersja",
787 + "flatpak_info_branch": "Gałąź",
788 + "flatpak_info_origin": "Źródło",
789 + "flatpak_info_size": "Rozmiar",
790 + "flatpak_info_desc": "Opis",
791 + "flatpak_updated": "Flapaki zaktualizowane.",
792 + "flatpak_usage": "Użycie: pag flatpak <search|install|remove|list|update|info> [args]",
793 + "flatpak_scope": "Instalacja",
794 + "flatpak_menu_hint": "Zainstalowano i zweryfikowano, ale sesja może jej nie pokazać w menu: brak eksportów Flatpaka w XDG_DATA_DIRS.",
795 + "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.",
796 + "key_imported": "Klucz zaimportowany pomyślnie.",
797 + "key_removed": "Klucz usunięty: {}",
798 + "no_keys": "Brak zaufanych kluczy GPG.",
799 + "gpg_missing": "BRAK GNUPG – zainstaluj gnupg i spróbuj ponownie",
800 + "ssl_broken": "Python bez działającego modułu ssl (HTTPS niemożliwe) – napraw pakiety python/openssl (np. sudo pag install -f python).",
801 + "key_add_failed": "Import klucza nie powiódł się (błąd gpg) – klucz NIE został dodany.",
802 + "verify_ok": "Wszystkie {} plików sprawne.",
803 + "verify_errors": "Znaleziono {} problemów:",
804 + "cache_cleared": "{} plików ({:.2f} MB) usuniętych z cache.",
805 + "deployments_list": "Deploymenty ({}):",
806 + "no_deployments": "Brak deploymentów.",
807 + "active_deployment": "AKTYWNY",
808 + "deploy_rollback_ok": "Przełączono na deployment: {}",
809 + "deploy_rollback_fail": "Brak poprzedniego deploymentu.",
810 + "deploy_cleanup_ok": "Usunięto {} starych deploymentów.",
811 + "deploy_cleanup_none": "Nie ma deploymentów do wyczyszczenia (minimum {}).",
812 + "snapshot_none": "Brak snapshotów systemu.",
813 + "snapshot_list": "Snapshoty systemu ({}):",
814 + "snapshot_created": "Utworzono snapshot: {}.",
815 + "snapshot_deleted": "Usunięto snapshot: {}.",
816 + "snapshot_not_found": "Nie znaleziono snapshotu: {}",
817 + "snapshot_unsupported": "Snapshoty niedostępne: {}",
818 + "snapshot_rollback_next": "Następny start ustawiono na snapshot: {}",
819 + "snapshot_rollback_hint": "Wybierz ten wpis w menu GRUB: {}",
820 + "staging_prepare": "Przygotowuję {} pakietów w stagingu (system bez zmian)...",
821 + "staging_failed": "Etap przygotowania nieudany – system NIE został zmieniony.",
822 + "staging_commit": "Wszystkie pakiety przygotowane – nakładam zmiany...",
823 + "dry_run_done": "Dry-run – nic nie zmieniono.",
824 + "dry_run_plan": "Dry-run – plan transakcji (bez zmian):",
825 + "why_explicit": "zainstalowany jawnie",
826 + "why_dependency": "zależność od",
827 + "why_not_installed": "niezainstalowany",
828 + "rdepends_title": "Odwrotne zależności {} ({}):",
829 + "rdepends_none": "nic od niego nie zależy.",
830 + "optional_deps": "Opcjonalne zależności (nie są instalowane automatycznie):",
831 + "autoremove_ok": "Usunięto {} osieroconych pakietów.",
832 + "autoremove_none": "Brak osieroconych pakietów.",
833 + "downloaded": "Pobrano {} do cache ({:.2f} MB).",
834 + "sec_downgrade": "Downgrade blocked: {pkg} {new} < {old}",
835 + "sec_suid": "SUID stripped from {path}",
836 + "sec_https": "HTTPS required for repos",
837 + "sec_badname": "Invalid package name: {name}",
838 + "sec_toobig": "Package too large: {size_mb}MB > {max_mb}MB",
839 + "sec_conflict": "File conflict: {path} owned by {owner}",
840 + "sec_audit": "{pkg} installed by {user}",
841 + "sec_locked": "Another pag process is running",
842 + "sec_downgrade_pl": "Blokada downgrade: {pkg} {new} < {old}",
843 + "sec_suid_pl": "SUID usuniety z {path}",
844 + "sec_https_pl": "Repozytorium wymaga HTTPS",
845 + "sec_badname_pl": "Nieprawidlowa nazwa pakietu: {name}",
846 + "sec_toobig_pl": "Paczka za duza: {size_mb}MB > {max_mb}MB",
847 + "sec_conflict_pl": "Konflikt plikow: {path} nalezy do {owner}",
848 + "sec_audit_pl": "{pkg} zainstalowany przez {user}",
849 + "sec_locked_pl": "Inny proces pag juz dziala",
850 +
851 + "provides_mapped": "{} → {} (provides)",
852 + "stats_title": "Statystyki PAG",
853 + "stats_packages": "Zainstalowane pakiety",
854 + "stats_files": "Śledzone pliki",
855 + "stats_size": "Całkowity rozmiar",
856 + "stats_cache": "Rozmiar cache",
857 + "stats_history": "Transakcje",
858 + "stats_last_update": "Ostatnia aktualizacja",
859 + "conf_pacnew": "Zmieniony plik konfiguracyjny zachowany; nowa wersja: {path}",
860 + "conf_pacsave": "Zmieniony plik konfiguracyjny zachowany jako {path}",
861 + "provides_conflict": "Wielu dostawców dla '{name}' ({providers}) – używam '{chosen}'",
862 +
863 + # Baza wypalona w obrazie ISO (pag base / base adopt)
864 + "base_title": "Baza z obrazu ISO",
865 + "base_no_manifest": "Ten system nie ma manifestu bazy (/usr/share/pag/base.json) – nie ma czego adoptować.",
866 + "base_iso_version": "Wersja obrazu",
867 + "base_total": "Pakiety bazy (z obrazu)",
868 + "base_tracked": "Zarządzane przez pag",
869 + "base_adoptable": "Do adoptowania z repo",
870 + "base_unmatched": "Bez odpowiednika w repo",
871 + "base_adopt_hint": "Adoptuj (pliki z obrazu zostaną zastąpione pakietami z repo): sudo pag base adopt",
872 + "base_unmatched_hint": "Te zostaną w wersji z obrazu (brak takiego pakietu w repo):",
873 + "base_more": "więcej",
874 + "base_nothing_selected": "Żadna z podanych nazw nie jest na liście do adoptowania.",
875 + "base_all_managed": "Wszystkie pakiety bazy są już zarządzane przez pag.",
876 + "base_adopt_plan": "Adoptowanie {} pakietów bazy z repo (~{:.0f} MB):",
877 + "base_dry_run": "Próba na sucho – nic nie zainstalowano.",
878 + "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).",
879 + "base_overwrite": "{} pochodzi z obrazu ISO – pliki zostaną zastąpione (kopia zapasowa dla 'pag rollback').",
880 + "base_reboot_hint": "Baza zaadoptowana z repo – zrestartuj system, zanim zaczniesz używać nowych bibliotek/narzędzi.",
881 + "base_register_ok": "Zarejestrowano {} pakietów bazy w bazie pakietów ({} już było).",
882 + "base_register_plan": "Dry-run – zarejestrowałbym {} pakietów bazy.",
883 + "base_register_nocache": "Brak cache indeksu repo – zostawiono nazwy z buildera (uruchom 'sudo pag sync' i ponownie 'pag base register', aby je zmapować).",
884 + "base_register_renamed": "{} nazw dopasowano do nazw pakietów w repo.",
885 + "stats_base": "Baza (obraz) zarządzana",
886 + },
887 +}
888 +
889 +# ── i18n: komunikaty CLI (msgid = tekst EN) ─────────────────────────────
890 +_EXTRA_I18N = {
891 + ' ⚠ PAG_INSECURE=1 – skipping local package signature verification': ' ⚠ PAG_INSECURE=1 – pomijam weryfikację podpisu pakietu lokalnego',
892 + ' ❌ No signature for package: {arg1}': ' ❌ Brak podpisu dla pakietu: {arg1}',
893 + ' A .pag.asc/.pag.sig file from the same source is required.': ' Wymagany jest plik .pag.asc/.pag.sig z tego samego źródła.',
894 + ' ❌ Invalid package signature: {arg1}': ' ❌ Nieprawidłowy podpis pakietu: {arg1}',
895 + ' ❌ No pinned repo key for the local package.': ' ❌ Brak przypiętego klucza repo dla lokalnego pakietu.',
896 + ' Run first: sudo pag sync': ' Uruchom najpierw: sudo pag sync',
897 + ' ❌ [SECURITY ERROR] Package was signed with a different repo key.': ' ❌ [SECURITY ERROR] Pakiet podpisano innym kluczem repo.',
898 + ' Expected: {arg1}': ' Oczekiwany: {arg1}',
899 + ' Received: {arg1}': ' Otrzymany: {arg1}',
900 + ' 🔐 Package signature OK ({arg1})': ' 🔐 Podpis pakietu OK ({arg1})',
901 + ' ⚡ Copying the active deployment...': ' ⚡ Kopiowanie aktywnego deploymentu...',
902 + ' ✅ Deployment: {arg1} ({arg2})': ' ✅ Deployment: {arg1} ({arg2})',
903 + ' ✅ First deployment: {arg1}': ' ✅ Pierwszy deployment: {arg1}',
904 + ' ⚠ Cannot create {arg1}: {arg2}': ' ⚠ Nie mogę utworzyć {arg1}: {arg2}',
905 + ' ⚠ Failed to create snapshot: {arg1}': ' ⚠ Nie udało się utworzyć snapshotu: {arg1}',
906 + ' ⚠ btrfs snapshot failed: {arg1}': ' ⚠ btrfs snapshot nie udał się: {arg1}',
907 + ' 📸 System snapshot: {arg1} (subvol={arg2})': ' 📸 Snapshot systemu: {arg1} (subvol={arg2})',
908 + ' ❌ Invalid snapshot path – refusing to delete.': ' ❌ Nieprawidłowa ścieżka snapshotu – odmawiam usunięcia.',
909 + ' ⏪ Snapshot: {arg1}': ' ⏪ Snapshot: {arg1}',
910 + ' 💡 Reboot the system – GRUB will boot the selected snapshot.': ' 💡 Zrestartuj system – GRUB uruchomi wybrany snapshot.',
911 + ' 💡 At boot, choose an entry in the GRUB menu (snapshots section).': ' 💡 Przy starcie wybierz wpis w menu GRUB (sekcja snapshotów).',
912 + '❌ Another pag update is in progress – try again later.': '❌ Inna aktualizacja pag jest w toku – spróbuj ponownie później.',
913 + ' ⚠ Failed to extract {arg1}: {arg2}': ' ⚠ Nie rozpakowano {arg1}: {arg2}',
914 + ' ⚠ Corrupted index cache {arg1}: {arg2}': ' ⚠ Uszkodzony cache indeksu {arg1}: {arg2}',
915 + ' ❌ {arg1}: cannot refresh index – {arg2} is read-only': ' ❌ {arg1}: nie można odświeżyć indeksu – {arg2} jest tylko-do-odczytu',
916 + ' ⚠ HTTP {arg1} for {arg2}': ' ⚠ HTTP {arg1} dla {arg2}',
917 + ' ⚠ Failed to download index {arg1}: {arg2}': ' ⚠ Błąd pobierania indeksu {arg1}: {arg2}',
918 + ' ⚠ Index downloaded, but failed to save cache ({arg1}): {arg2}': ' ⚠ Indeks pobrany, ale nie udało się zapisać cache ({arg1}): {arg2}',
919 + ' ❌ {arg1}: no GPG keys – verification impossible!': ' ❌ {arg1}: brak kluczy GPG – weryfikacja niemożliwa!',
920 + ' Set PAG_INSECURE=1 to skip (not recommended)': ' Ustaw PAG_INSECURE=1 aby pominąć (niezalecane)',
921 + ' ❌ {arg1}: CANNOT DOWNLOAD SIGNATURE repo.json.asc/.sig!': ' ❌ {arg1}: NIE MOŻNA POBRAĆ PODPISU repo.json.asc/.sig!',
922 + ' 🔑 Imported repo key from {arg1}/paganos.asc': ' 🔑 Importowano klucz repo z {arg1}/paganos.asc',
923 + ' ⚠ {arg1}: invalid GPG signature (PAG_INSECURE – ignoring)': ' ⚠ {arg1}: nieprawidłowy podpis GPG (PAG_INSECURE – ignoruję)',
924 + ' ❌ {arg1}: GPG is not installed – cannot verify the signature!': ' ❌ {arg1}: GPG nie jest zainstalowane – nie można zweryfikować podpisu!',
925 + ' Install gnupg or set PAG_INSECURE=1 (not recommended)': ' Zainstaluj gnupg lub ustaw PAG_INSECURE=1 (niezalecane)',
926 + ' ❌ {arg1}: INVALID GPG SIGNATURE of the repository index!': ' ❌ {arg1}: NIEPRAWIDŁOWY PODPIS GPG indeksu repozytorium!',
927 + ' ⚠ {arg1}: cannot read signature fingerprint (PAG_INSECURE – ignoring)': ' ⚠ {arg1}: nie można odczytać fingerprintu (PAG_INSECURE – ignoruję)',
928 + ' ❌ [SECURITY ERROR] {arg1}: cannot read signature fingerprint!': ' ❌ [SECURITY ERROR] {arg1}: nie można odczytać fingerprintu podpisu!',
929 + ' Pinned key: {arg1} – rejecting the index.': ' Przypięty klucz: {arg1} – odrzucam indeks.',
930 + ' ⚠ {arg1}: SIGNING KEY CHANGED (PAG_INSECURE – ignoring)': ' ⚠ {arg1}: ZMIENIONY KLUCZ PODPISU (PAG_INSECURE – ignoruję)',
931 + ' ❌ [SECURITY ERROR] {arg1}: Repository signing key has changed!': ' ❌ [SECURITY ERROR] {arg1}: Klucz podpisujący repo uległ zmianie!',
932 + ' If this is an intentional key rotation: pag key-trust {arg1}': ' Jeśli to celowa rotacja klucza: pag key-trust {arg1}',
933 + ' 🔐 Pinned repo fingerprint {arg1}: {arg2}': ' 🔐 Przypięto fingerprint repo {arg1}: {arg2}',
934 + ' (TOFU – first trust. If the key changes, pag will refuse updates.)': ' (TOFU – pierwsze zaufanie. Gdy klucz się zmieni, pag odmówi aktualizacji.)',
935 + ' To avoid TOFU, add the fingerprint to /etc/pag/repos.conf.': ' Aby uniknąć TOFU, dopisz fingerprint w /etc/pag/repos.conf.',
936 + '❌ Download error: {arg1}': '❌ Błąd pobierania: {arg1}',
937 + '🔐 Pinning repo key {arg1}...': '🔐 Przypinam klucz repo {arg1}...',
938 + ' ❌ Cannot read signature fingerprint (missing/failed).': ' ❌ Nie można odczytać fingerprintu podpisu (brak/nieudany).',
939 + ' Make sure the repo key is in the keyring (pag key-add <url|file>).': ' Upewnij się, że klucz repo jest w keyringu (pag key-add <url|file>).',
940 + ' ✅ Pinned {arg1} for {arg2}': ' ✅ Przypięto {arg1} dla {arg2}',
941 + ' From now on, a key change will be reported as SECURITY ERROR.': ' Od teraz zmiana klucza zostanie zgłoszona jako SECURITY ERROR.',
942 + ' ℹ {arg1} has no pinned fingerprint.': ' ℹ {arg1} nie ma przypiętego fingerprintu.',
943 + ' ✅ Removed pin for {arg1}.': ' ✅ Usunięto przypięcie dla {arg1}.',
944 + ' ❌ {arg1}: preparation stage failed ({arg2})': ' ❌ {arg1}: etap przygotowania nieudany ({arg2})',
945 + ' ❌ {arg1}: commit error – {arg2}': ' ❌ {arg1}: błąd commit – {arg2}',
946 + ' ⚠ ldconfig not found — linker cache was not refreshed.': ' ⚠ Nie znaleziono ldconfig — cache linkera nie został odświeżony.',
947 + ' ⚠ Failed to refresh ld.so cache: {arg1}': " ⚠ Nie udało się odświeżyć cache'a ld.so: {arg1}",
948 + ' ⚠ {arg1} shared files preserved': ' ⚠ {arg1} plików współdzielonych zachowanych',
949 + ' ⚠ {arg1} sensitive system files preserved': ' ⚠ {arg1} wrażliwych plików systemowych zachowanych',
950 + ' 🧹 Removed {arg1} obsolete files ({arg2})': ' 🧹 Usunięto {arg1} nieaktualnych plików ({arg2})',
951 + ' 🛠 Interrupted transaction detected – restored {arg1} missing files.': ' 🛠 Wykryto przerwana transakcje – przywrocono {arg1} brakujacych plikow.',
952 + ' ⚠ Hook skipped (PAG_NO_HOOKS=1): {arg1} for {arg2}': ' ⚠ Hook pominięty (PAG_NO_HOOKS=1): {arg1} dla {arg2}',
953 + ' ⚠ Hook {arg1} for {arg2} exited with code {arg3}': ' ⚠ Hook {arg1} dla {arg2} zakończony z kodem {arg3}',
954 + ' ⚠ Hook {arg1} for {arg2} timed out ({arg3}s)': ' ⚠ Hook {arg1} dla {arg2} przekroczył timeout ({arg3}s)',
955 + ' ⚠ Hook {arg1} for {arg2}: {arg3}': ' ⚠ Hook {arg1} dla {arg2}: {arg3}',
956 + 'Recent transactions ({arg1}):': 'Ostatnie transakcje ({arg1}):',
957 + '❌ No snapshot to restore.': '❌ Brak snapshotu do przywrócenia.',
958 + '⏪ Rolling back: {arg1} ({arg2})': '⏪ Wycofywanie: {arg1} ({arg2})',
959 + ' Packages: {arg1}': ' Pakiety: {arg1}',
960 + ' ❌ Package not found: {arg1}': ' ❌ Nie znaleziono pakietu: {arg1}',
961 + ' ❌ {arg1}: missing metadata.json': ' ❌ {arg1}: brak metadata.json',
962 + ' ❌ {arg1}: failed to read package ({arg2})': ' ❌ {arg1}: nie udało się odczytać pakietu ({arg2})',
963 + ' ↩ Preparation stage failed – the system was NOT changed.': ' ↩ Etap przygotowania nieudany – system NIE został zmieniony.',
964 + ' ↓ {arg1}-{arg2} (local) ... ': ' ↓ {arg1}-{arg2} (lokalny) ... ',
965 + ' ❌ Not enough disk space: need ~{arg1} MB, free {arg2} MB ({arg3})': ' ❌ Za mało miejsca na dysku: potrzeba ~{arg1} MB, wolne {arg2} MB ({arg3})',
966 + ' ⚠ Low disk space: {arg1} MB free, packages ~{arg2} MB (extracted will take more)': ' ⚠ Mało miejsca na dysku: wolne {arg1} MB, pakiety ~{arg2} MB (rozpakowane zajmą więcej)',
967 + ' ❌ {arg1} is mounted read-only – cannot install.': ' ❌ {arg1} jest zamontowane tylko-do-odczytu – nie można instalować.',
968 + '❌ Cannot continue – {arg1} missing dependencies.': '❌ Nie można kontynuować – {arg1} brakujących zależności.',
969 + ' Install the missing packages or add repositories.': ' Zainstaluj brakujące pakiety lub dodaj repozytoria.',
970 + ' Install the library provider or update the repository.': ' Zainstaluj dostawcę biblioteki lub zaktualizuj repozytorium.',
971 + '\n 🏗️ Creating a new deployment...': '\n 🏗️ Tworzenie nowego deploymentu...',
972 + '\n ⏬ Downloading {arg1} packages in parallel...': '\n ⏬ Pobieranie {arg1} pakietów równolegle...',
973 + ' ↩ Aborted BEFORE installation – no package was changed.': ' ↩ Przerwano PRZED instalacją – żadna paczka nie została zmieniona.',
974 + ' ❌ Failed to create snapshot (--snapshot mode) – aborting.': ' ❌ Nie udało się utworzyć snapshotu (tryb --snapshot) – przerywam.',
975 + '\n ↩ Rolling back transaction ({arg1} errors)...': '\n ↩ Cofanie transakcji ({arg1} błędów)...',
976 + '\n 🔄 Switching to deployment {arg1}...': '\n 🔄 Przełączanie na deployment {arg1}...',
977 + ' ✅ Active deployment: {arg1}': ' ✅ Aktywny deployment: {arg1}',
978 + ' 💡 Restart required to reload the system.': ' 💡 Restart wymagany do przeładowania systemu.',
979 + ' ⚠ {arg1}: not installed': ' ⚠ {arg1}: nie zainstalowano',
980 + '✅ ({arg1} files)': '✅ ({arg1} plików)',
981 + '\n✅ Removed {arg1}.': '\n✅ Usunięto {arg1}.',
982 + " 'pag remove-orphans' to clean up.": " Uruchom 'pag remove-orphans', aby posprzątać.",
983 + ' ⚡ Trigger: {arg1} ({arg2})': ' ⚡ Wyzwalacz: {arg1} ({arg2})',
984 + ' ⚠ trigger {arg1} timed out (120 s)': ' ⚠ trigger {arg1} przekroczył limit czasu (120 s)',
985 + ' ⚠ trigger {arg1}: {arg2}': ' ⚠ wyzwalacz {arg1}: {arg2}',
986 + '❌ No repositories configured.': '❌ Brak repozytoriów w konfiguracji.',
987 + '🔄 Checking for pag update from {arg1}...': '🔄 Sprawdzam aktualizację pag z {arg1}...',
988 + ' ❌ Cannot download pag: {arg1}': ' ❌ Nie można pobrać pag: {arg1}',
989 + ' ⚠ Invalid update signature (PAG_INSECURE – ignoring)': ' ⚠ Nieprawidłowy podpis aktualizacji (PAG_INSECURE – ignoruję)',
990 + ' ❌ Invalid update signature – not updating.': ' ❌ Nieprawidłowy podpis aktualizacji – nie aktualizuję.',
991 + ' ❌ Cannot confirm the update signature fingerprint.': ' ❌ Nie można potwierdzić fingerprintu podpisu aktualizacji.',
992 + ' ⚠ Update signed with a different key (PAG_INSECURE – ignoring)': ' ⚠ Podpis aktualizacji innym kluczem (PAG_INSECURE – ignoruję)',
993 + ' ❌ [SECURITY ERROR] Update signed with a different key than the repo!': ' ❌ [SECURITY ERROR] Podpis aktualizacji innym kluczem niż repo!',
994 + ' Expected: {arg1}, received: {arg2}': ' Oczekiwany: {arg1}, Otrzymany: {arg2}',
995 + ' ❌ SHA256 mismatch! Expected {arg1}, got {arg2}': ' ❌ SHA256 niezgodny! Oczekiwano {arg1}, jest {arg2}',
996 + ' ✅ SHA256 matches': ' ✅ SHA256 zgodny',
997 + ' ❌ Syntax error in new pag: {arg1}': ' ❌ Błąd składni w nowym pag: {arg1}',
998 + ' ✅ Downloaded pag {arg1} (current {arg2}), signature verified': ' ✅ Pobrano pag {arg1} (obecny {arg2}), podpis zweryfikowany',
999 + ' ✅ Installed new pag. Old version kept as {arg1}': ' ✅ Zainstalowano nowy pag. Stary zachowany jako {arg1}',
1000 + ' ⚠ A different pag is first in PATH: {arg1} (updated {arg2})': ' ⚠ W PATH pierwszy jest inny pag: {arg1} (zaktualizowano {arg2})',
1001 + ' Remove the old copy: sudo rm {arg1}': ' Usuń starą kopię: sudo rm {arg1}',
1002 + ' Restart pag to use the new version.': ' Uruchom ponownie pag, aby użyć nowej wersji.',
1003 + '🔄 Refreshing indexes...': '🔄 Odświeżanie indeksów...',
1004 + ' {arg1} {arg2}: {arg3} packages {arg4}': ' {arg1} {arg2}: {arg3} pakietów {arg4}',
1005 + ' ⚠ New pag version {arg1} available – run: pag self-update': ' ⚠ Nowa wersja pag {arg1} dostępna – uruchom: pag self-update',
1006 + ' 🐧 Rebuilding initramfs (newer kernel)...': ' 🐧 Przebudowa initramfs (nowsze jądro)...',
1007 + 'No packages installed.': 'Brak zainstalowanych pakietów.',
1008 + 'Installed ({arg1}):': 'Zainstalowane ({arg1}):',
1009 + 'Available ({arg1}):': 'Dostępne ({arg1}):',
1010 + '❌ No results for: {arg1}': '❌ Brak wyników dla: {arg1}',
1011 + "Results for '{arg1}' ({arg2}):": "Wyniki dla '{arg1}' ({arg2}):",
1012 + "\n ❌ '{arg1}' — not found.": "\n ❌ '{arg1}' — nie znaleziono.",
1013 + ' PaganOS repo: pag search {arg1}': ' Repo PaganOS: pag search {arg1}',
1014 + ' Flathub: pag flatpak search {arg1}': ' Flathub: pag flatpak search {arg1}',
1015 + ' Add repo: pag repo-add <url>': ' Dodaj repo: pag repo-add <url>',
1016 + ' ... and {arg1} more (pag search {arg2})': ' ... i {arg1} więcej (pag search {arg2})',
1017 + ' ... and {arg1} more (pag flatpak search {arg2})': ' ... i {arg1} więcej (pag flatpak search {arg2})',
1018 + ' ✓ {arg1} is already installed ({arg2})': ' ✓ {arg1} jest już zainstalowany ({arg2})',
1019 + "❌ '{arg1}' not found.": "❌ Nie znaleziono '{arg1}'.",
1020 + ' Version (repo): {arg1}': ' Wersja (repo): {arg1}',
1021 + ' Description: {arg1}': ' Opis: {arg1}',
1022 + ' Size: {arg1:.1f} MB': ' Rozmiar: {arg1:.1f} MB',
1023 + ' SHA256: {arg1}...': ' SHA256: {arg1}...',
1024 + ' GPG: {arg1}': ' GPG: {arg1}',
1025 + ' Dependencies: {arg1}': ' Zależności: {arg1}',
1026 + ' Installed: {arg1} ({arg2})': ' Zainstalowany: {arg1} ({arg2})',
1027 + "❌ '{arg1}' not installed.": "❌ '{arg1}' nie jest zainstalowany.",
1028 + 'Files in {arg1} ({arg2}):': 'Pliki w {arg1} ({arg2}):',
1029 + 'Nothing to repair (no packages installed).': 'Nic do naprawy (brak zainstalowanych pakietow).',
1030 + '✅ All files are in place – nothing to repair.': '✅ Wszystkie pliki na miejscu – nic do naprawy.',
1031 + '🔧 Packages with missing files: {arg1} (total {arg2} files)': '🔧 Pakiety z brakujacymi plikami: {arg1} (lacznie {arg2} plikow)',
1032 + '\n(--dry-run: nothing is changed)': '\n(--dry-run: nic nie zmieniam)',
1033 + '\n🔧 repair: {arg1}': '\n🔧 naprawa: {arg1}',
1034 + '⚠ Repaired {arg1}/{arg2}. Failed: {arg3}': '⚠ Naprawiono {arg1}/{arg2}. Nie udalo sie: {arg3}',
1035 + '✅ Repaired {arg1} packages.': '✅ Naprawiono {arg1} pakietow.',
1036 + 'Nothing to verify.': 'Nie ma czego weryfikować.',
1037 + '✅ No orphans.': 'Brak osieroconych pakietów.',
1038 + 'Orphans ({arg1}):': 'Osierocone ({arg1}):',
1039 + ' ⚠ Search error: {arg1}': ' ⚠ Błąd wyszukiwania: {arg1}',
1040 + '\n Choose a number (1-{arg1}) or press Enter to cancel:': '\n Wybierz numer (1-{arg1}) lub Enter aby anulować: ',
1041 + " 📦 {arg1} – already installed (use 'pag flatpak info {arg2}' for details)": " 📦 {arg1} – już zainstalowany (szczegóły: 'pag flatpak info {arg2}')",
1042 + "\n Multiple matches for '{arg1}':": "\n Wiele dopasowań dla '{arg1}':",
1043 + '\n Choose a number (1-{arg1}) or press Enter:': '\n Wybierz numer (1-{arg1}) lub Enter: ',
1044 + ' ... and {arg1} more. Refine your query.': ' ... i {arg1} więcej. Doprecyzuj zapytanie.',
1045 + '\n Choose a number to install (1-{arg1}) or press Enter to cancel:': '\n Wybierz numer do zainstalowania (1-{arg1}) lub Enter aby anulować: ',
1046 + ' (no installed flatpaks)': ' (brak zainstalowanych flatpaków)',
1047 + 'Installed flatpaks ({arg1}):': ' Zainstalowane flatpaki ({arg1}):',
1048 + ' 🔄 Updating flatpaks...': ' 🔄 Aktualizacja flatpaków...',
1049 + '\n 💡 To install: pag flatpak install {arg1}': '\n 💡 Aby zainstalować: pag flatpak install {arg1}',
1050 + ' 🔧 DKMS: rebuilding out-of-tree modules (nvidia/vbox)...': ' 🔧 DKMS: przebudowa modułów out-of-tree (nvidia/vbox)...',
1051 + ' 🔧 Rebuilding initramfs (pagan-initramfs)...': ' 🔧 Przebudowa initramfs (pagan-initramfs)...',
1052 + ' 🔧 Rebuilding initramfs (dracut)...': ' 🔧 Przebudowa initramfs (dracut)...',
1053 + ' 🔧 Rebuilding initramfs (mkinitcpio)...': ' 🔧 Przebudowa initramfs (mkinitcpio)...',
1054 + ' ⚠ No dracut/mkinitcpio – initramfs was not rebuilt': ' ⚠ Brak dracut/mkinitcpio – initramfs nie został przebudowany',
1055 + ' 🔧 Building initramfs for the deployment...': ' 🔧 Budowanie initramfs dla deploymentu...',
1056 + ' ⚠ pag-initramfs-init not found – skipping initramfs build': ' ⚠ Nie znaleziono pag-initramfs-init – pomijam budowę initramfs',
1057 + " ⚠ No vmlinuz-* found in the deployment's /boot": ' ⚠ Nie znaleziono vmlinuz-* w /boot deploymentu',
1058 + ' 🐧 Kernel: {arg1}': ' 🐧 Jądro: {arg1}',
1059 + ' ⚠ Skipping unavailable files: {arg1}': ' ⚠ Pomijam niedostępne pliki: {arg1}',
1060 + ' ⚠ Skipping unavailable file: {arg1}': ' ⚠ Pomijam niedostępny plik: {arg1}',
1061 + ' ✅ initramfs.img ({arg1:.1f} MB) → {arg2}': ' ✅ initramfs.img ({arg1:.1f} MB) → {arg2}',
1062 + ' ❌ initramfs build error: {arg1}': ' ❌ Błąd budowy initramfs: {arg1}',
1063 + '🏗️ Deployment: {arg1}': '🏗️ Deployment: {arg1}',
1064 + '✅ Initramfs updated.': '✅ Initramfs zaktualizowany.',
1065 + '❌ Initramfs update failed.': '❌ Błąd aktualizacji initramfs.',
1066 + ' 📋 Regenerating GRUB (grub-mkconfig)...': ' 📋 Regeneracja GRUB (grub-mkconfig)...',
1067 + ' ⚠ Could not detect the root partition – GRUB entries will have no root=.': ' ⚠ Nie udało się wykryć partycji root – wpisy GRUB nie dostaną root=.',
1068 + ' Set PAG_ROOT_DEVICE=/dev/... (or PAG_GRUB_ROOT) and retry.': ' Ustaw PAG_ROOT_DEVICE=/dev/... (lub PAG_GRUB_ROOT) i powtórz.',
1069 + ' 📋 GRUB config updated – entries for each deployment': ' 📋 GRUB config zaktualizowany – wpisy dla każdego deploymentu',
1070 + '📋 Updating GRUB configuration...': '📋 Aktualizacja konfiguracji GRUB...',
1071 + '✅ GRUB updated.': '✅ GRUB zaktualizowany.',
1072 + ' +{arg1} more...': ' +{arg1} więcej...',
1073 + '❌ Deployment {arg1} does not exist on disk': '❌ Deployment {arg1} nie istnieje na dysku',
1074 + '⏪ Restoring deployment: {arg1}': '⏪ Przywracanie deploymentu: {arg1}',
1075 + '\n❌ {arg1} – cannot install:': '\n❌ {arg1} – nie można zainstalować:',
1076 + ' {arg1} → needs {arg2} (missing from repositories)': ' {arg1} → potrzebuje {arg2} (brak w repozytoriach)',
1077 + '\n⚠ {arg1} – will be installed as dependencies:': '\n⚠ {arg1} – zostaną doinstalowane:',
1078 + ' {arg1} → {arg2} ({arg3} – will be downloaded)': ' {arg1} → {arg2} ({arg3} – będzie pobrane)',
1079 + ' {arg1} → requires {arg2} – no package provides this version': ' {arg1} → wymaga {arg2} – żaden pakiet nie dostarcza tej wersji',
1080 + ' ↻ Retrying download of {arg1} ({arg2}/{arg3})...': ' ↻ Ponawiam pobieranie {arg1} ({arg2}/{arg3})...',
1081 + ' ⚠ Download error {arg1}: {arg2}': ' ⚠ Błąd pobierania {arg1}: {arg2}',
1082 + '❌ Format: spdx | cyclonedx': '❌ Format: spdx | cyclonedx',
1083 + ' ✓ {arg1} ({arg2} keys)': ' ✓ {arg1} ({arg2} kluczy)',
1084 + 'Usage: pag search <query>': 'Użycie: pag search <query>',
1085 + 'Usage: pag info <pkg>': 'Użycie: pag info <pkg>',
1086 + 'Usage: pag files <pkg>': 'Użycie: pag files <pkg>',
1087 + 'Usage: pag why <pkg>': 'Użycie: pag why <pkg>',
1088 + 'Usage: pag rdepends <pkg>': 'Użycie: pag rdepends <pkg>',
1089 + 'Usage: pag flatpak-search <query>': 'Użycie: pag flatpak-search <query>',
1090 + 'Usage: pag flatpak-info <id>': 'Użycie: pag flatpak-info <id>',
1091 + "❌ Unknown command: '{arg1}'. Did you mean '{arg2}'?": "❌ Nieznana komenda: '{arg1}'. Czy chodziło o '{arg2}'?",
1092 + " Run 'pag' without arguments to see the command list.": " Uruchom 'pag' bez argumentów, aby zobaczyć listę komend.",
1093 + 'Usage: pag unpin <pkg>': 'Użycie: pag unpin <pkg>',
1094 + 'Usage: pag repo-add <url> [name]': 'Użycie: pag repo-add <url> [name]',
1095 + 'Usage: pag key-add <url|file>': 'Użycie: pag key-add <url|file>',
1096 + 'Usage: pag key-remove <id>': 'Użycie: pag key-remove <id>',
1097 + 'Usage: pag key-trust <repo_url>': 'Użycie: pag key-trust <repo_url>',
1098 + 'Usage: pag key-untrust <repo_url>': 'Użycie: pag key-untrust <repo_url>',
1099 + 'Usage: pag flatpak-install <app>': 'Użycie: pag flatpak-install <app>',
1100 + 'Usage: pag flatpak-remove <app>': 'Użycie: pag flatpak-remove <app>',
1101 + 'Usage: pag snapshot-delete <id>': 'Użycie: pag snapshot-delete <id>',
1102 + '\n ⚠ Interrupted (Ctrl-C).': '\n ⚠ Przerwano (Ctrl-C).',
1103 +}
1104 +for _msgid, _pl in _EXTRA_I18N.items():
1105 + T["en"].setdefault(_msgid, _msgid)
1106 + T["pl"].setdefault(_msgid, _pl)
1107 +
1108 +_AUX_I18N = {
1109 + 'installed_marker': ('installed', 'zainstalowany'),
1110 + 'none_value': ('none', 'brak'),
1111 + 'none_parenthesized': ('(none)', '(brak)'),
1112 + 'stats_top': ('Top 5:', 'Największe 5:'),
1113 + 'never': ('never', 'nigdy'),
1114 + 'action_install': ('install', 'instalacja'),
1115 + 'action_upgrade': ('upgrade', 'aktualizacja'),
1116 + 'action_remove': ('remove', 'usunięcie'),
1117 + 'action_rollback': ('rollback', 'wycofanie'),
1118 + 'action_manual': ('manual', 'ręczny'),
1119 + 'action_repair': ('repair', 'naprawa'),
1120 + 'flatpak_searching_any': ('Searching Flathub...', 'Szukam we Flathub...'),
1121 + 'upgrade_marker': ('[upgrade]', '[aktualizacja]'),
1122 + 'hardlink_method': ('hardlinks', 'hardlinki'),
1123 + 'copy_method': ('full copy', 'pełna kopia'),
1124 + 'reflink_method': ('CoW (reflink)', 'CoW (reflink)'),
1125 + 'verify_missing_file': (' ❌ {}: missing {}', ' ❌ {}: brakuje {}'),
1126 + 'verify_sha_mismatch': (' ❌ {}: SHA256 mismatch {}', ' ❌ {}: niezgodność SHA256 {}'),
1127 + 'gpg_binary_not_found': ('GPG binary not found ({})', 'Nie znaleziono binarki GPG ({})'),
1128 + 'gpg_timeout': ('GPG operation timed out', 'Operacja GPG przekroczyła limit czasu'),
1129 + 'audio_services_reloaded': (' ⚡ audio services reloaded for sessions: {}', ' ⚡ przeładowano usługi audio dla sesji: {}'),
1130 + 'grub_fallback_label': ('Pagan Linux – fallback (plain root)', 'Pagan Linux – fallback (zwykły root)'),
1131 + 'done': ('done', 'gotowe'),
1132 + 'deploy_copy_failed': ('Failed to copy the deployment by any method', 'Nie udało się skopiować deploymentu żadną metodą'),
1133 + 'pkg_missing_data_tar': ('missing data.tar.xz in package', 'brak data.tar.xz w pakiecie'),
1134 + 'pkg_sha_mismatch': ('SHA256 mismatch: {}', 'niezgodność SHA256: {}'),
1135 + 'repo_index_invalid': ("missing 'packages' list", "brak listy 'packages'"),
1136 +}
1137 +for _k, (_en, _pl) in _AUX_I18N.items():
1138 + T["en"].setdefault(_k, _en)
1139 + T["pl"].setdefault(_k, _pl)
1140 +
1141 +# ── Tłumaczenia z PLIKÓW (nadpisują/rozszerzają wbudowane PL/EN) ─────────────
1142 +# Kolejność: PAG_LANG_DIR (env) → /etc/pag/lang → /usr/share/pag/lang →
1143 +# ./pag-lang obok binarki (dev). Brak plików NIE jest błędem – zostaje
1144 +# wbudowany słownik T (fallback), więc pag zawsze działa.
1145 +# Przykład pliku (pag-lang/pl.json): {"app_title": "...", "usage": "..."}.
1146 +def _load_lang_files() -> None:
1147 + # PAG_LANG_NO_FILES=1 → pomiń pliki (używane przy eksporcie --lang-extract,
1148 + # żeby wyeksportować CZYSTE wbudowane słowniki, bez starych nadpisań).
1149 + if os.environ.get("PAG_LANG_NO_FILES") == "1":
1150 + return
1151 + dirs = []
1152 + _env = os.environ.get("PAG_LANG_DIR")
1153 + if _env:
1154 + dirs.append(_env)
1155 + # __file__ bywa niedostępne, gdy moduł jest exec/frozen (np. harness
1156 + # instalacyjny) – liczymy wtedy od ścieżki programu, zamiast wywalać
1157 + # NameError przy samym imporcie.
1158 + _self = globals().get("__file__") or sys.argv[0] or "pag"
1159 + dirs += ["/etc/pag/lang", "/usr/share/pag/lang",
1160 + os.path.join(os.path.dirname(os.path.abspath(_self)), "pag-lang")]
1161 + for _d in dirs:
1162 + for _code in list(T.keys()) + ["pl", "en", "de"]:
1163 + _p = os.path.join(_d, f"{_code}.json")
1164 + try:
1165 + with open(_p, "r", encoding="utf-8") as _fh:
1166 + _data = json.load(_fh)
1167 + if isinstance(_data, dict):
1168 + # Merge (nie replace): klucze nieobecne w pliku zachowują
1169 + # wbudowane tłumaczenie. Puste wartości pomijamy, żeby
1170 + # niekompletny/uszkodzony plik nie wyczyścił komunikatu.
1171 + _clean = {str(k): str(v) for k, v in _data.items()
1172 + if str(v).strip()}
1173 + T.setdefault(_code, {}).update(_clean)
1174 + except (OSError, ValueError):
1175 + continue
1176 +
1177 +
1178 +_load_lang_files()
1179 +
1180 +def _(key: str, *args, **kwargs) -> str:
1181 + """Tłumaczy klucz i formatuje argumenty.
1182 +
1183 + Dla LANG=pl preferuje wariant „<key>_pl” (np. komunikaty bezpieczeństwa
1184 + mają krótkie wersje PL obok bazy EN), potem zwykły klucz, potem EN/klicz.
1185 + """
1186 + if LANG == "pl":
1187 + _pl = T.get("pl", {})
1188 + msg = _pl.get(key + "_pl") or _pl.get(key) or T["en"].get(key, key)
1189 + else:
1190 + msg = T.get(LANG, T["en"]).get(key, T["en"].get(key, key))
1191 + if args or kwargs:
1192 + return msg.format(*args, **kwargs)
1193 + return msg
1194 +
1195 +
1196 +def _ask_confirm() -> bool:
1197 + """Pytanie potwierdzające (T/n). PAG_YES=1 → zawsze tak.
1198 +
1199 + EOF/brak terminala (stdin zamknięty, np. ssh bez TTY, cron, subprocess
1200 + panelu webowego) → NIE – anuluj, nie wykonuj operacji bez potwierdzenia
1201 + (inaczej input() rzuca EOFError i pag pada tracebackiem).
1202 + Enter → tak (domyślne Y/n).
1203 + """
1204 + if os.environ.get("PAG_YES", "") == "1":
1205 + print(_("continue_q") + " t (--yes)")
1206 + return True
1207 + try:
1208 + ans = input(_("continue_q")).strip().lower()
1209 + except (EOFError, KeyboardInterrupt):
1210 + print(f"\n ⚠ {_('no_tty')}")
1211 + return False
1212 + return not ans or ans in ("t", "y")
1213 +
1214 +
1215 +# =============================================================================
1216 +# ŚCIEŻKI
1217 +# =============================================================================
1218 +PAG_ROOT = os.environ.get("PAG_ROOT", "/")
1219 +PAG_DB = "/var/lib/pag"
1220 +PAG_CACHE = "/var/cache/pag"
1221 +PAG_CONF = "/etc/pag"
1222 +REPO_CACHE = "/var/cache/pag/repos"
1223 +REPOS_CONF = "/etc/pag/repos.conf"
1224 +REPOS_DIR = PAG_CONF + "/repos" # drop-in: /etc/pag/repos/<nazwa>.conf
1225 +INSTALLED_DB = "/var/lib/pag/installed.json"
1226 +FILES_DB_SQL = "/var/lib/pag/files.db" # SQLite!
1227 +WORLD_FILE = "/var/lib/pag/world"
1228 +PINNED_FILE = "/var/lib/pag/pinned.json"
1229 +HISTORY_FILE = "/var/lib/pag/history.json"
1230 +LOCK_FILE = "/var/lib/pag/pag.lock"
1231 +STAGING_DIR = "/.pag_staging" # na tej samej partycji co / (unikamy EXDEV)
1232 +PKG_EXT = ".pag"
1233 +REPO_CACHE_TTL = 3600
1234 +MAX_PKG_SIZE = 2 * 1024 * 1024 * 1024 # 2 GB – maksymalny rozmiar paczki
1235 +BASE_MANIFEST = "/usr/share/pag/base.json" # baza z obrazu ISO (pag base/adopt)
1236 +
1237 +# ── UPRZYWILEJOWANE PLIKI ────────────────────────────────────────────────────
1238 +# Domyślnie pag zdejmuje bit SUID i wymusza właściciela root:root. Niektóre
1239 +# programy MUSZĄ jednak zachować setuid/setgid albo grupę inną niż root
1240 +# (/usr/bin/sudo, /usr/bin/passwd, /usr/bin/unix_chkpwd,
1241 +# /usr/lib/dbus-daemon-launch-helper). Bez tego tracą możliwość działania
1242 +# po aktualizacji przez pag (np. użytkownik nie zmieni hasła).
1243 +#
1244 +# Bezpieczeństwo: zawartość pakietu jest uwierzytelniona (podpis GPG repo +
1245 +# przypięty fingerprint + SHA256 całego pakietu), więc metadane w nim są
1246 +# zaufane tak samo jak same pliki. Zachowujemy uprawnienia WYŁĄCZNIE dla
1247 +# ścieżek z tej listy (albo z pola `privileged:` receptury, które pagbuild
1248 +# zapisuje w metadata.json).
1249 +PRIVILEGED_PATHS = frozenset({
1250 + "/usr/bin/cdda2wav", "/usr/bin/cdrecord",
1251 + "/usr/bin/chage", "/usr/bin/expiry",
1252 + "/usr/bin/fcrondyn", "/usr/bin/fcronsighup", "/usr/bin/fcrontab",
1253 + "/usr/bin/firejail", "/usr/bin/fping",
1254 + "/usr/bin/fusermount", "/usr/bin/fusermount3",
1255 + "/usr/bin/gpasswd", "/usr/bin/ksu", "/usr/bin/lockfile",
1256 + "/usr/bin/mount", "/usr/bin/mount.nfs",
1257 + "/usr/bin/newgidmap", "/usr/bin/newuidmap",
1258 + "/usr/bin/passwd", "/usr/bin/ping", "/usr/bin/ping6",
1259 + "/usr/bin/procmail", "/usr/bin/readcd", "/usr/bin/rscsi",
1260 + "/usr/bin/screen", "/usr/bin/screen-5.0.2",
1261 + "/usr/bin/sg", "/usr/bin/su", "/usr/bin/sudo", "/usr/bin/traceroute",
1262 + "/usr/bin/umount", "/usr/bin/unix_chkpwd", "/usr/bin/wall",
1263 + "/usr/lib/dbus-daemon-launch-helper",
1264 + "/usr/lib/httpd/suexec",
1265 + "/usr/lib/utempter/utempter",
1266 + "/usr/lib/xscreensaver/xscreensaver-auth",
1267 + "/usr/libexec/libgtop_server2",
1268 + "/usr/libexec/qemu-bridge-helper",
1269 + "/usr/libexec/ssh-keysign",
1270 + "/usr/libexec/xf86-video-intel-backlight-helper",
1271 + "/opt/google/chrome/chrome-sandbox",
1272 + "/opt/gitkraken/chrome-sandbox",
1273 + "/opt/VirtualBox/VBoxHeadless", "/opt/VirtualBox/VBoxNetAdpCtl",
1274 + "/opt/VirtualBox/VBoxNetDHCP", "/opt/VirtualBox/VBoxVolInfo",
1275 + "/opt/VirtualBox/VirtualBoxVM",
1276 +})
1277 +ALLOWED_PKG_RE = re.compile(r'^[a-zA-Z0-9][a-zA-Z0-9._+@-]*$')
1278 +
1279 +# Bezpieczeństwo / audyt
1280 +AUDIT_LOG = "/var/log/pag/audit.log" # dziennik operacji krytycznych (hooki, self-update)
1281 +TRUST_DB = "/etc/pag/trusted.json" # mapa repo_url → fingerprint klucza podpisującego
1282 +HOOK_API_VERSION = "1" # wersjonowane API hooków (env PKG_HOOK_API)
1283 +
1284 +# =============================================================================
1285 +# IMMUTABLE OS – DEPLOYMENTY
1286 +# =============================================================================
1287 +# Model: zamiast mutować /, każda operacja tworzy NOWY deployment.
1288 +# /var, /etc, /home są współdzielone między deploymentami.
1289 +#
1290 +# STRUKTURA:
1291 +# /.deployments/
1292 +# active → 20260723T120000 (symlink do aktywnego)
1293 +# 20260723T120000/
1294 +# usr/ bin/ lib/ lib64/ ... (pełny system)
1295 +# var → /var (symlink do współdzielonego)
1296 +# etc → /etc
1297 +# home → /home
1298 +# ...
1299 +#
1300 +# Jak to działa:
1301 +# 1. pag install → kopiuje active → nowy deployment + nakłada zmiany → switch symlinka
1302 +# 2. pag remove → kopiuje active → nowy deployment - usuwa pliki → switch symlinka
1303 +# 3. pag deploy-rollback → przełącza active symlink na poprzedni deployment
1304 +# 4. Przy starcie systemu: initrd montuje /.deployments/active jako /
1305 +# =============================================================================
1306 +
1307 +DEPLOYMENTS_DIR = "/.deployments"
1308 +ACTIVE_LINK = "/.deployments/active"
1309 +DEPLOYMENTS_DB = "/var/lib/pag/deployments.json"
1310 +
1311 +# Snapshoty systemu (CoW). Na btrfs każdy snapshot jest osobnym subwolumenem,
1312 +# więc zajmuje tylko zmienione bloki, a GRUB potrafi uruchomić system z wybranej
1313 +# migawki (rootflags=subvol=...). Na ext4/xfs nie ma snapshotów CoW – zostaje
1314 +# atomowy staging + backup nadpisywanych plików.
1315 +SNAPSHOTS_DIR = "/.pag_snapshots"
1316 +SNAPSHOTS_DB = "/var/lib/pag/snapshots.json"
1317 +GRUB_SNAPSHOT_SCRIPT = "/etc/grub.d/40_pagan_snapshots"
1318 +
1319 +# Ścieżki współdzielone – NIE wchodzą do deploymentu (są symlinkami do /...)
1320 +SHARED_PATHS = {
1321 + "/var", "/etc", "/home", "/root", "/tmp", "/run",
1322 + "/dev", "/proc", "/sys", "/mnt", "/media", "/srv",
1323 + # /boot współdzielone: jądro + initramfs są wspólne dla wszystkich
1324 + # deploymentów (inaczej każdy trzyma własną ~50-100 MB kopię). GRUB
1325 + # wskazuje na /.deployments/<id>/boot → symlink do /boot.
1326 + "/boot",
1327 + "/.deployments", "/.pag_staging",
1328 +}
1329 +
1330 +def _is_shared_path(rel: str) -> bool:
1331 + """Sprawdza czy ścieżka należy do katalogów współdzielonych (poza deploymentem)."""
1332 + for sp in SHARED_PATHS:
1333 + if rel == sp or rel.startswith(sp + "/"):
1334 + return True
1335 + return False
1336 +
1337 +def _is_config_path(rel: str) -> bool:
1338 + """Czy ścieżka to plik konfiguracyjny (/etc/...)?
1339 +
1340 + Dla takich plików stosujemy .pacnew/.pacsave (zachowanie zmian użytkownika)
1341 + zamiast bezwarunkowego nadpisania/usunięcia."""
1342 + p = rel.lstrip("/")
1343 + return p == "etc" or p.startswith("etc/")
1344 +
1345 +# Wrażliwa konfiguracja auth/systemowa – NIGDY nie nadpisujemy jej po cichu.
1346 +# Nadpisanie /etc/pam.d/system-* przez pakiet (np. shadow) potrafi zablokować
1347 +# logowanie/sudo („account validation failure”); dla tych ścieżek zawsze robimy
1348 +# .pacnew, gdy treść na dysku różni się od tej z pakietu.
1349 +_SENSITIVE_CONFIG_RE = re.compile(
1350 + r'^(pam\.d/|security/|sudoers$|sudoers\.d/|shadow$|gshadow$|passwd$|group$|'
1351 + r'login\.defs$|nsswitch\.conf$|default/useradd$)')
1352 +
1353 +def _is_sensitive_config(rel: str) -> bool:
1354 + """Czy rel to wrażliwy plik /etc (PAM, sudoers, shadow, login.defs…)?"""
1355 + p = rel.lstrip("/")
1356 + if not p.startswith("etc/"):
1357 + return False
1358 + return bool(_SENSITIVE_CONFIG_RE.match(p[4:]))
1359 +
1360 +def _get_deployment_root() -> str:
1361 + """Zwraca ścieżkę do aktywnego deploymentu, lub PAG_ROOT jeśli tryb niemutowalny wyłączony."""
1362 + if os.environ.get("PAG_IMMUTABLE", "") in ("0", "no", "false", ""):
1363 + return PAG_ROOT
1364 + if os.path.islink(ACTIVE_LINK):
1365 + return os.readlink(ACTIVE_LINK)
1366 + if os.path.isdir(ACTIVE_LINK):
1367 + return ACTIVE_LINK
1368 + # Brak deploymentów – użyj /
1369 + return PAG_ROOT
1370 +
1371 +def _load_deployments() -> List[dict]:
1372 + """Wczytuje historię deploymentów."""
1373 + if not os.path.exists(DEPLOYMENTS_DB):
1374 + return []
1375 + try:
1376 + return json.load(open(DEPLOYMENTS_DB))
1377 + except Exception:
1378 + return []
1379 +
1380 +def _save_deployments(deployments: List[dict]):
1381 + os.makedirs(os.path.dirname(DEPLOYMENTS_DB), exist_ok=True)
1382 + json.dump(deployments, open(DEPLOYMENTS_DB, "w"), indent=2)
1383 +
1384 +def _create_deployment(pkg_names: List[str], action: str) -> Tuple[str, str]:
1385 + """
1386 + Tworzy nowy deployment przez skopiowanie aktywnego (CoW) i zwraca jego ścieżkę.
1387 + Zwraca (deployment_dir, deployment_id).
1388 + """
1389 + deploy_id = datetime.now().strftime("%Y%m%dT%H%M%S")
1390 + deploy_dir = os.path.join(DEPLOYMENTS_DIR, deploy_id)
1391 + os.makedirs(DEPLOYMENTS_DIR, exist_ok=True)
1392 +
1393 + active = _get_deployment_root()
1394 +
1395 + if os.path.isdir(active) and active != PAG_ROOT:
1396 + # Trójstopniowa strategia kopiowania deploymentu:
1397 + # 1. reflink (CoW – btrfs, xfs) → 0 MB kopiowane
1398 + # 2. hardlink (linki twarde) → 0 MB kopiowane, tylko inody
1399 + # 3. zwykłe cp (ostateczność) → pełna kopia
1400 + print(_(' ⚡ Copying the active deployment...'))
1401 + copied = False
1402 + for method, cmd, label in [
1403 + ("reflink", ["cp", "--reflink=auto", "-a", active + "/.", deploy_dir + "/"], _("reflink_method")),
1404 + ("hardlink", ["cp", "-al", active + "/.", deploy_dir + "/"], _("hardlink_method")),
1405 + ("copy", ["cp", "-a", active + "/.", deploy_dir + "/"], _("copy_method")),
1406 + ]:
1407 + try:
1408 + subprocess.run(cmd, check=True, timeout=600, capture_output=True)
1409 + print(_(' ✅ Deployment: {arg1} ({arg2})', arg1=(deploy_id), arg2=(label)))
1410 + copied = True
1411 + break
1412 + except subprocess.CalledProcessError:
1413 + if method == "copy":
1414 + raise # ostatnia deska – niech leci wyjątek
1415 + continue
1416 + if not copied:
1417 + raise RuntimeError(_("deploy_copy_failed"))
1418 + else:
1419 + # Pierwszy deployment – tylko katalogi szkieletowe
1420 + # /boot celowo POMINIĘTE – jest współdzielone (SHARED_PATHS); poniższa
1421 + # pętla utworzy w deploymencie symlink boot → /boot.
1422 + for d in ["/usr", "/lib", "/lib64", "/bin", "/sbin", "/opt"]:
1423 + if os.path.isdir(d):
1424 + dest = os.path.join(deploy_dir, d.lstrip("/"))
1425 + os.makedirs(dest, exist_ok=True)
1426 + print(_(' ✅ First deployment: {arg1}', arg1=(deploy_id)))
1427 +
1428 + # Utwórz symlinki do współdzielonych katalogów
1429 + for sp in SHARED_PATHS:
1430 + link_dst = os.path.join(deploy_dir, sp.lstrip("/"))
1431 + if not os.path.lexists(link_dst) and os.path.isdir(sp):
1432 + os.symlink(sp, link_dst)
1433 +
1434 + # Zapisz w bazie deploymentów
1435 + deployments = _load_deployments()
1436 + deployments.append({
1437 + "id": deploy_id,
1438 + "action": action,
1439 + "packages": pkg_names,
1440 + "timestamp": datetime.now().isoformat(),
1441 + "active": True,
1442 + })
1443 + # Oznacz poprzednie jako nieaktywne
1444 + for d in deployments[:-1]:
1445 + d["active"] = False
1446 + _save_deployments(deployments)
1447 +
1448 + return deploy_dir, deploy_id
1449 +
1450 +def _switch_deployment(deploy_dir: str) -> bool:
1451 + """Atomowo przełącza aktywny deployment przez podmianę symlinka."""
1452 + tmp_link = ACTIVE_LINK + ".new"
1453 + if os.path.lexists(tmp_link):
1454 + os.remove(tmp_link)
1455 + os.symlink(deploy_dir, tmp_link)
1456 + os.rename(tmp_link, ACTIVE_LINK) # atomowe na tym samym FS
1457 + return True
1458 +
1459 +# =============================================================================
1460 +# SNAPSHOTY SYSTEMU (CoW – btrfs)
1461 +# =============================================================================
1462 +# Snapshot powstaje PRZED transakcją. Na btrfs to subwolumen (kilka KB
1463 +# metadanych, reszta to współdzielone bloki), więc nie kopiujemy całego
1464 +# systemu. Wpis GRUB pozwala uruchomić system z wybranej migawki.
1465 +# Na ext4/xfs nie ma CoW – instalacja nadal jest atomowa dzięki stagingowi,
1466 +# a rollback opiera się na backupie nadpisywanych plików.
1467 +
1468 +def _btrfs_bin() -> str:
1469 + """Ścieżka do btrfs (PATH bywa okrojony w chroocie/instalatorze)."""
1470 + found = shutil.which("btrfs")
1471 + if found:
1472 + return found
1473 + for cand in ("/usr/bin/btrfs", "/usr/sbin/btrfs", "/sbin/btrfs", "/bin/btrfs"):
1474 + if os.path.exists(cand):
1475 + return cand
1476 + return ""
1477 +
1478 +
1479 +def _root_fstype() -> str:
1480 + try:
1481 + r = subprocess.run(["findmnt", "-n", "-o", "FSTYPE", "/"],
1482 + capture_output=True, text=True, timeout=5)
1483 + fs = r.stdout.strip().splitlines()[0].strip() if r.stdout.strip() else ""
1484 + if fs:
1485 + return fs
1486 + except Exception:
1487 + pass
1488 + try:
1489 + r = subprocess.run(["stat", "-f", "-c", "%T", "/"],
1490 + capture_output=True, text=True, timeout=5)
1491 + return r.stdout.strip()
1492 + except Exception:
1493 + return ""
1494 +
1495 +
1496 +def _btrfs_root_path() -> str:
1497 + """Ścieżka aktywnego subwolumenu root względem top-level btrfs."""
1498 + btrfs = _btrfs_bin()
1499 + if btrfs:
1500 + try:
1501 + r = subprocess.run([btrfs, "subvolume", "show", "/"],
1502 + capture_output=True, text=True, timeout=5)
1503 + if r.returncode == 0:
1504 + for line in r.stdout.splitlines():
1505 + line = line.strip()
1506 + if line.lower().startswith("path:"):
1507 + p = line.split(":", 1)[1].strip()
1508 + if p in ("", "/"):
1509 + return "/"
1510 + return p.strip("/")
1511 + except Exception:
1512 + pass
1513 + try:
1514 + r = subprocess.run(["findmnt", "-n", "-o", "FSROOT", "/"],
1515 + capture_output=True, text=True, timeout=5)
1516 + p = r.stdout.strip()
1517 + if p and p != "/":
1518 + return p.strip("/")
1519 + except Exception:
1520 + pass
1521 + return "/"
1522 +
1523 +
1524 +def _snapshot_support() -> Tuple[bool, str]:
1525 + fs = _root_fstype()
1526 + if fs != "btrfs":
1527 + return False, (f"root jest na {fs or 'nieznanym systemie plików'} – "
1528 + f"snapshoty CoW wymagają btrfs")
1529 + if not _btrfs_bin():
1530 + return False, "brak narzędzia btrfs (zainstaluj pakiet btrfs-progs)"
1531 + return True, ""
1532 +
1533 +
1534 +def _load_snapshots() -> List[dict]:
1535 + if not os.path.exists(SNAPSHOTS_DB):
1536 + return []
1537 + try:
1538 + data = load_json(SNAPSHOTS_DB)
1539 + return data if isinstance(data, list) else []
1540 + except Exception:
1541 + return []
1542 +
1543 +
1544 +def _save_snapshots(items: List[dict]):
1545 + os.makedirs(os.path.dirname(SNAPSHOTS_DB), exist_ok=True)
1546 + save_json(SNAPSHOTS_DB, items)
1547 +
1548 +
1549 +def _snapshot_label(snap: dict) -> str:
1550 + """Czytelna etykieta GRUB (bez znaków, które psują menu)."""
1551 + pkgs = list(snap.get("packages") or [])
1552 + p = ", ".join(pkgs[:3])
1553 + if len(pkgs) > 3:
1554 + p += f" +{len(pkgs) - 3}"
1555 + base = f"Pagan Linux snapshot {snap.get('id', '?')}"
1556 + if snap.get("label"):
1557 + base += f" - {snap['label']}"
1558 + if p:
1559 + base += f" - {p}"
1560 + # GRUB: usuń apostrofy i znaki kontrolne.
1561 + return re.sub(r"[\x00-\x1f']", "", base)[:120]
1562 +
1563 +
1564 +def _root_boot_arg() -> str:
1565 + """`root=UUID=...` dla wpisu GRUB (stabilne po zmianie nazw urządzeń)."""
1566 + dev = _detect_root_device()
1567 + if not dev:
1568 + return ""
1569 + if dev.startswith(("UUID=", "PARTUUID=", "LABEL=", "PARTLABEL=")):
1570 + return f" root={dev}"
1571 + uuid = ""
1572 + try:
1573 + r = subprocess.run(["blkid", "-s", "UUID", "-o", "value", dev],
1574 + capture_output=True, text=True, timeout=5)
1575 + uuid = r.stdout.strip().splitlines()[0].strip() if r.stdout.strip() else ""
1576 + except Exception:
1577 + uuid = ""
1578 + return f" root=UUID={uuid}" if uuid else f" root={dev}"
1579 +
1580 +
1581 +def _initrd_for_kernel(boot_dir: str, kernel: str) -> str:
1582 + """Nazwa initramfs pasująca do jądra (initramfs.img / initramfs-<ver>.img…)."""
1583 + if not kernel or not os.path.isdir(boot_dir):
1584 + return ""
1585 + ver = kernel[len("vmlinuz-"):] if kernel.startswith("vmlinuz-") else ""
1586 + candidates = []
1587 + if ver:
1588 + candidates += [f"initramfs-{ver}.img", f"initrd.img-{ver}"]
1589 + candidates += ["initramfs.img", "initrd.img"]
1590 + for c in candidates:
1591 + if os.path.isfile(os.path.join(boot_dir, c)):
1592 + return c
1593 + for f in sorted(os.listdir(boot_dir)):
1594 + if f.startswith(("initramfs", "initrd")):
1595 + return f
1596 + return ""
1597 +
1598 +
1599 +def _pick_kernel_initrd(boot_dir: str) -> Tuple[str, str]:
1600 + kernels = sorted(
1601 + [f for f in os.listdir(boot_dir) if f.startswith("vmlinuz-")],
1602 + reverse=True,
1603 + ) if os.path.isdir(boot_dir) else []
1604 + if not kernels:
1605 + return "", ""
1606 + k = kernels[0]
1607 + return k, _initrd_for_kernel(boot_dir, k)
1608 +
1609 +
1610 +def _grub_snapshot_entries() -> List[str]:
1611 + """Wpisy menu GRUB dla snapshotów (dla `_update_grub_config` i grub.d)."""
1612 + snaps = _load_snapshots()
1613 + if not snaps:
1614 + return []
1615 +
1616 + root_arg = _root_boot_arg()
1617 + try:
1618 + separate_boot = os.path.isdir("/boot") and os.path.ismount("/boot")
1619 + except OSError:
1620 + separate_boot = False
1621 + bp = _boot_prefix()
1622 +
1623 + lines: List[str] = []
1624 + for snap in reversed(snaps):
1625 + path = snap.get("path") or ""
1626 + if not path or not os.path.isdir(path):
1627 + continue
1628 +
1629 + if separate_boot:
1630 + # Osobne /boot jest współdzielone: użyj jądra ZAPISANEGO przy
1631 + # tworzeniu snapshotu (o ile nadal leży w /boot), a nie zawsze
1632 + # najnowszego – nowe jądro mogło być właśnie przyczyną problemu.
1633 + kname = snap.get("kernel") or ""
1634 + if not kname or not os.path.isfile(os.path.join("/boot", kname)):
1635 + kname, _ = _pick_kernel_initrd("/boot")
1636 + iname = _initrd_for_kernel("/boot", kname) if kname else ""
1637 + kernel = f"{bp}/{kname}" if kname else ""
1638 + initrd = f"{bp}/{iname}" if iname else ""
1639 + else:
1640 + snap_boot = os.path.join(path, "boot")
1641 + kname, iname = _pick_kernel_initrd(snap_boot)
1642 + # Kopia zapasowa: jądro z bieżącego /boot (np. gdy /boot nie
1643 + # było częścią snapshotu lub jest to bardzo stara migawka).
1644 + if not kname:
1645 + kname, iname = _pick_kernel_initrd("/boot")
1646 + kernel = f"{bp}/{kname}" if kname else ""
1647 + initrd = f"{bp}/{iname}" if iname else ""
1648 + else:
1649 + kernel = f"{path}/boot/{kname}"
1650 + initrd = f"{path}/boot/{iname}" if iname else ""
1651 +
1652 + if not kernel:
1653 + continue
1654 +
1655 + subvol = snap.get("subvol") or ""
1656 + flags = f" rootflags=subvol={subvol} rootfstype=btrfs" if subvol else ""
1657 + label = _snapshot_label(snap)
1658 +
1659 + lines.append(f"menuentry '{label}' --class pagan --class gnu-linux --class os {{")
1660 + lines.append(f" linux {kernel}{root_arg}{flags} rw quiet")
1661 + if initrd:
1662 + lines.append(f" initrd {initrd}")
1663 + lines.append("}")
1664 + lines.append("")
1665 + return lines
1666 +
1667 +
1668 +def _ensure_snapshot_grub_script() -> bool:
1669 + """Instaluje /etc/grub.d/40_pagan_snapshots (integracja z grub-mkconfig)."""
1670 + if not os.path.isdir("/etc/grub.d"):
1671 + return False
1672 + # Preferuj BIEŻĄCĄ binarkę (np. testy z repo), a nie starszy /usr/bin/pag:
1673 + # stary pag nie zna `snapshot-grub` i uruchomiłby smart-search.
1674 + _self = os.path.abspath(sys.argv[0]) if sys.argv[0] else ""
1675 + exe = _self if _self and os.path.isfile(_self) else (shutil.which("pag") or "/usr/bin/pag")
1676 + if not exe or not os.path.exists(exe):
1677 + exe = "/usr/bin/pag"
1678 + quoted = exe.replace("'", "'\\''")
1679 + script = (
1680 + "#!/bin/sh\n"
1681 + "# Pagan Linux – wpisy GRUB dla snapshotów systemu (wygenerowane przez pag)\n"
1682 + "# Usuń ten plik, aby ukryć snapshoty w menu GRUB.\n"
1683 + f"PAG_BIN='{quoted}'\n"
1684 + 'if [ ! -x "$PAG_BIN" ]; then\n'
1685 + ' PAG_BIN="$(command -v pag 2>/dev/null || true)"\n'
1686 + "fi\n"
1687 + '[ -x "$PAG_BIN" ] || exit 0\n'
1688 + '# Tylko pag >= 4.1 zna komendę snapshot-grub (starszy zrobiłby\n'
1689 + '# smart-search i mógłby zawiesić grub-mkconfig na sieci).\n'
1690 + 'case "$("$PAG_BIN" --version 2>/dev/null)" in\n'
1691 + ' "pag 4."[1-9]*|"pag "[5-9]*|"pag "[1-9][0-9]*) ;;\n'
1692 + ' *) exit 0 ;;\n'
1693 + 'esac\n'
1694 + 'exec "$PAG_BIN" snapshot-grub\n'
1695 + )
1696 + try:
1697 + with open(GRUB_SNAPSHOT_SCRIPT, "w", encoding="utf-8") as fh:
1698 + fh.write(script)
1699 + os.chmod(GRUB_SNAPSHOT_SCRIPT, 0o755)
1700 + return True
1701 + except OSError:
1702 + return False
1703 +
1704 +
1705 +def _create_system_snapshot(packages: List[str], action: str,
1706 + label: str = "") -> Optional[dict]:
1707 + """Tworzy snapshot root (btrfs) i zapisuje go w bazie.
1708 +
1709 + Zwraca dict snapshotu albo None. Nie przerywa instalacji – o tym decyduje
1710 + wywołujący (tryb --snapshot wymaga sukcesu, tryb auto tylko ostrzega).
1711 + """
1712 + ok, why = _snapshot_support()
1713 + if not ok:
1714 + return None
1715 + btrfs = _btrfs_bin()
1716 + try:
1717 + os.makedirs(SNAPSHOTS_DIR, exist_ok=True)
1718 + except OSError as e:
1719 + print(_(' ⚠ Cannot create {arg1}: {arg2}', arg1=(SNAPSHOTS_DIR), arg2=(e)), file=sys.stderr)
1720 + return None
1721 +
1722 + base_id = datetime.now().strftime("%Y%m%dT%H%M%S")
1723 + snap_id = base_id
1724 + n = 1
1725 + while os.path.lexists(os.path.join(SNAPSHOTS_DIR, snap_id)):
1726 + snap_id = f"{base_id}-{n}"
1727 + n += 1
1728 + snap_path = os.path.join(SNAPSHOTS_DIR, snap_id)
1729 +
1730 + try:
1731 + r = subprocess.run([btrfs, "subvolume", "snapshot", "/", snap_path],
1732 + capture_output=True, text=True, timeout=600)
1733 + except Exception as e:
1734 + print(_(' ⚠ Failed to create snapshot: {arg1}', arg1=(e)), file=sys.stderr)
1735 + return None
1736 + if r.returncode != 0:
1737 + msg = (r.stderr or r.stdout or "").strip().splitlines()
1738 + print(_(' ⚠ btrfs snapshot failed: {arg1}', arg1=(msg[-1] if msg else r.returncode)),
1739 + file=sys.stderr)
1740 + return None
1741 +
1742 + rootp = _btrfs_root_path()
1743 + if rootp in ("", "/"):
1744 + subvol = f"/.pag_snapshots/{snap_id}"
1745 + else:
1746 + subvol = f"{rootp}/.pag_snapshots/{snap_id}"
1747 +
1748 + # Zapamiętaj jądro/initramfs z chwili snapshotu – przy osobnym /boot
1749 + # dzięki temu uruchomimy migawkę ze STARYM (działającym) jądrem.
1750 + _kn, _ir = _pick_kernel_initrd("/boot")
1751 + snap = {
1752 + "id": snap_id,
1753 + "path": snap_path,
1754 + "subvol": subvol,
1755 + "created": datetime.now().isoformat(),
1756 + "action": action,
1757 + "label": label,
1758 + "packages": list(packages)[:100],
1759 + "kernel": _kn,
1760 + "initrd": _ir,
1761 + }
1762 + items = _load_snapshots()
1763 + items.append(snap)
1764 + _save_snapshots(items)
1765 + _ensure_snapshot_grub_script()
1766 + print(_(' 📸 System snapshot: {arg1} (subvol={arg2})', arg1=(snap_id), arg2=(subvol)))
1767 + return snap
1768 +
1769 +
1770 +def _find_snapshot(snap_id: str) -> Optional[dict]:
1771 + items = _load_snapshots()
1772 + if not snap_id:
1773 + return items[-1] if items else None
1774 + for s in items:
1775 + if s.get("id") == snap_id:
1776 + return s
1777 + for s in items:
1778 + if str(s.get("id", "")).startswith(snap_id):
1779 + return s
1780 + return None
1781 +
1782 +
1783 +def cmd_snapshot_list():
1784 + items = _load_snapshots()
1785 + if not items:
1786 + print(_("snapshot_none"))
1787 + return 0
1788 + print(_("snapshot_list", len(items)))
1789 + for s in reversed(items):
1790 + pkgs = list(s.get("packages") or [])
1791 + listed = ", ".join(pkgs[:4])
1792 + if len(pkgs) > 4:
1793 + listed += f" +{len(pkgs) - 4}"
1794 + print(f" {s.get('id', '?')} [{_action_label(s.get('action', ''))}]")
1795 + if listed:
1796 + print(f" {listed}")
1797 + print(f" {s.get('created', '')}")
1798 + print(f" {s.get('path', '')}")
1799 + return 0
1800 +
1801 +
1802 +def cmd_snapshot_grub():
1803 + """Wypisuje menuentry dla grub-mkconfig (wywoływane z 40_pagan_snapshots)."""
1804 + for line in _grub_snapshot_entries():
1805 + print(line)
1806 + return 0
1807 +
1808 +
1809 +def cmd_snapshot_create(label: str = ""):
1810 + ok, why = _snapshot_support()
1811 + if not ok:
1812 + print(f" ❌ {_('snapshot_unsupported', why)}")
1813 + return 1
1814 + snap = _create_system_snapshot([], "manual", label=label)
1815 + if not snap:
1816 + return 1
1817 + _ensure_snapshot_grub_script()
1818 + _refresh_bootloader()
1819 + print(f" ✅ {_('snapshot_created', snap['id'])}")
1820 + return 0
1821 +
1822 +
1823 +def cmd_snapshot_delete(snap_id: str):
1824 + snap = _find_snapshot(snap_id)
1825 + if not snap:
1826 + print(f" ❌ {_('snapshot_not_found', snap_id)}")
1827 + return 1
1828 + path = snap.get("path") or ""
1829 + if not path.startswith(SNAPSHOTS_DIR + "/"):
1830 + print(_(' ❌ Invalid snapshot path – refusing to delete.'))
1831 + return 1
1832 + if os.path.isdir(path):
1833 + btrfs = _btrfs_bin()
1834 + if not btrfs:
1835 + print(f" ❌ {_('snapshot_unsupported', 'brak btrfs')}")
1836 + return 1
1837 + r = subprocess.run([btrfs, "subvolume", "delete", path],
1838 + capture_output=True, text=True, timeout=120)
1839 + if r.returncode != 0:
1840 + print(f" ❌ btrfs: {(r.stderr or '').strip()[:200]}")
1841 + return 1
1842 + _save_snapshots([s for s in _load_snapshots() if s.get("id") != snap.get("id")])
1843 + _refresh_bootloader()
1844 + print(f" ✅ {_('snapshot_deleted', snap.get('id', ''))}")
1845 + return 0
1846 +
1847 +
1848 +def cmd_snapshot_rollback(snap_id: str = ""):
1849 + """Ustawia snapshot jako następny start (albo pokazuje wybór w GRUB)."""
1850 + snap = _find_snapshot(snap_id)
1851 + if not snap:
1852 + print(f" ❌ {_('snapshot_not_found', snap_id or '(brak)' )}")
1853 + return 1
1854 + if not os.path.isdir(snap.get("path") or ""):
1855 + print(f" ❌ {_('snapshot_not_found', snap.get('id', ''))}")
1856 + return 1
1857 +
1858 + label = _snapshot_label(snap)
1859 + print(_(' ⏪ Snapshot: {arg1}', arg1=(snap.get('id', ''))))
1860 + print(f" {snap.get('created', '')}")
1861 + pkgs = list(snap.get("packages") or [])
1862 + if pkgs:
1863 + print(f" {', '.join(pkgs[:8])}{' …' if len(pkgs) > 8 else ''}")
1864 + if not _ask_confirm():
1865 + return 0
1866 +
1867 + _ensure_snapshot_grub_script()
1868 + _refresh_bootloader()
1869 +
1870 + grub_reboot = shutil.which("grub-reboot") or shutil.which("grub2-reboot")
1871 + if grub_reboot:
1872 + r = subprocess.run([grub_reboot, label], capture_output=True, text=True)
1873 + if r.returncode == 0:
1874 + print(f" ✅ {_('snapshot_rollback_next', label)}")
1875 + print(_(' 💡 Reboot the system – GRUB will boot the selected snapshot.'))
1876 + return 0
1877 + print(f" ℹ {_('snapshot_rollback_hint', label)}")
1878 + print(_(' 💡 At boot, choose an entry in the GRUB menu (snapshots section).'))
1879 + return 0
1880 +
1881 +
1882 +DEFAULT_REPOS = [
1883 + "https://repo.paganlinux.eu/stable/",
1884 +]
1885 +
1886 +# =============================================================================
1887 +# INICJALIZACJA
1888 +# =============================================================================
1889 +
1890 +def ensure_dirs():
1891 + for d in [PAG_DB, PAG_CACHE, PAG_CONF, REPO_CACHE, REPOS_DIR, STAGING_DIR, DEPLOYMENTS_DIR]:
1892 + os.makedirs(d, exist_ok=True)
1893 + for f, default in [
1894 + (REPOS_CONF, "\n".join(DEFAULT_REPOS) + "\n"),
1895 + (INSTALLED_DB, "{}"),
1896 + (PINNED_FILE, "{}"),
1897 + (HISTORY_FILE, "[]"),
1898 + ]:
1899 + if not os.path.exists(f):
1900 + with open(f, "w") as fh: fh.write(default)
1901 + if not os.path.exists(WORLD_FILE):
1902 + Path(WORLD_FILE).touch()
1903 + if not os.path.exists(GPG_HOME):
1904 + os.makedirs(GPG_HOME, exist_ok=True)
1905 + os.chmod(GPG_HOME, 0o700)
1906 + _gpg_run("--list-keys", capture_output=True)
1907 + # Inicjalizuj SQLite
1908 + _db_init()
1909 + # Wyczyść staging po poprzednim przerwanym buildzie/instalacji
1910 + if os.path.isdir(STAGING_DIR):
1911 + for entry in os.listdir(STAGING_DIR):
1912 + if entry == "backups":
1913 + continue # backupy starych wersji – potrzebne do `pag rollback`
1914 + path = os.path.join(STAGING_DIR, entry)
1915 + try:
1916 + if os.path.isfile(path) or os.path.islink(path):
1917 + os.unlink(path)
1918 + elif os.path.isdir(path):
1919 + shutil.rmtree(path, ignore_errors=True)
1920 + except OSError:
1921 + pass
1922 +
1923 +# =============================================================================
1924 +# SQLITE – BAZA PLIKÓW (poprawne zarządzanie połączeniami)
1925 +# =============================================================================
1926 +
1927 +from contextlib import contextmanager
1928 +
1929 +@contextmanager
1930 +def _db_session(readonly: Optional[bool] = None):
1931 + """Context manager – gwarantuje zamknięcie połączenia.
1932 +
1933 + Gdy katalog bazy nie jest zapisywalny (np. komenda read-only uruchomiona
1934 + jako zwykły user), otwieramy połączenie w trybie read-only. Inaczej
1935 + `PRAGMA journal_mode=WAL` próbuje pisać i kończy się błędem
1936 + „attempt to write a readonly database” zamiast zwrócić wynik.
1937 + """
1938 + if readonly is None:
1939 + readonly = not os.access(os.path.dirname(FILES_DB_SQL) or ".", os.W_OK)
1940 + if readonly:
1941 + # Katalog bazy nie jest zapisywalny (np. komenda read-only uruchomiona
1942 + # jako zwykły user). Baza jest w trybie WAL, więc SQLite przy `mode=ro`
1943 + # próbuje utworzyć plik `-shm` w katalogu – bez prawa zapisu kończy się
1944 + # to błędem „attempt to write a readonly database” nawet przy SELECT.
1945 + # Dlatego próbujemy zwykłego `mode=ro`, a gdy zawiedzie, otwieramy z
1946 + # `immutable=1` (SQLite pomija wtedy WAL/SHM i czyta ostatni
1947 + # checkpoint). Przy równoległym zapisie roota odczyt może być chwilowo
1948 + # nieaktualny – dla komend diagnostycznych (files/list/verify) to OK.
1949 + conn = sqlite3.connect(f"file:{FILES_DB_SQL}?mode=ro", uri=True, timeout=15)
1950 + try:
1951 + conn.execute("SELECT 1 FROM sqlite_master LIMIT 1")
1952 + except sqlite3.OperationalError:
1953 + conn.close()
1954 + conn = sqlite3.connect(
1955 + f"file:{FILES_DB_SQL}?mode=ro&immutable=1", uri=True, timeout=15)
1956 + else:
1957 + conn = sqlite3.connect(FILES_DB_SQL, timeout=15)
1958 + conn.execute("PRAGMA journal_mode=WAL")
1959 + conn.execute("PRAGMA synchronous=NORMAL")
1960 + conn.execute("PRAGMA foreign_keys=ON")
1961 + conn.execute("PRAGMA busy_timeout=15000")
1962 + conn.row_factory = sqlite3.Row
1963 + try:
1964 + yield conn
1965 + if not readonly:
1966 + conn.commit()
1967 + except Exception:
1968 + if not readonly:
1969 + conn.rollback()
1970 + raise
1971 + finally:
1972 + conn.close()
1973 +
1974 +
1975 +def _db_init():
1976 + """Tworzy tabele SQLite jeśli nie istnieją."""
1977 + with _db_session() as db:
1978 + db.execute("""
1979 + CREATE TABLE IF NOT EXISTS files (
1980 + id INTEGER PRIMARY KEY AUTOINCREMENT,
1981 + path TEXT NOT NULL,
1982 + package TEXT NOT NULL,
1983 + sha256 TEXT,
1984 + size INTEGER,
1985 + is_symlink INTEGER DEFAULT 0,
1986 + symlink_target TEXT,
1987 + UNIQUE(path, package)
1988 + )
1989 + """)
1990 + db.execute("CREATE INDEX IF NOT EXISTS idx_files_path ON files(path)")
1991 + db.execute("CREATE INDEX IF NOT EXISTS idx_files_pkg ON files(package)")
1992 + db.execute("""
1993 + CREATE TABLE IF NOT EXISTS file_checksums (
1994 + path TEXT PRIMARY KEY,
1995 + sha256 TEXT NOT NULL,
1996 + installed_at TEXT
1997 + )
1998 + """)
1999 + db.commit()
2000 +
2001 +def _db_record_files(pkg_name: str, files: List[dict]):
2002 + """Zapisuje pliki do SQLite (obsługuje symlinki)."""
2003 + with _db_session() as db:
2004 + # Jawna transakcja – atomowość obu zapisów i szybsze wykrycie blokady
2005 + try:
2006 + db.execute("BEGIN IMMEDIATE")
2007 + except sqlite3.OperationalError:
2008 + pass # transakcja już otwarta (implicit)
2009 + db.executemany(
2010 + "INSERT OR REPLACE INTO files (path, package, sha256, size, is_symlink, symlink_target) "
2011 + "VALUES (?,?,?,?,?,?)",
2012 + [(f["path"], pkg_name, f.get("sha256",""), f.get("size",0),
2013 + f.get("is_symlink", 0), f.get("symlink_target", ""))
2014 + for f in files]
2015 + )
2016 + db.executemany(
2017 + "INSERT OR REPLACE INTO file_checksums (path, sha256, installed_at) VALUES (?,?,?)",
2018 + [(f["path"], f.get("sha256",""), datetime.now().isoformat())
2019 + for f in files if f.get("sha256")]
2020 + )
2021 +
2022 +def _db_get_package_files(pkg_name: str) -> List[str]:
2023 + with _db_session() as db:
2024 + return [r["path"] for r in db.execute(
2025 + "SELECT DISTINCT path FROM files WHERE package=?", (pkg_name,)
2026 + )]
2027 +
2028 +def _db_get_file_owners(filepath: str) -> List[str]:
2029 + """Zwraca listę pakietów będących właścicielami pliku."""
2030 + with _db_session() as db:
2031 + return [r["package"] for r in db.execute(
2032 + "SELECT package FROM files WHERE path=?", (filepath,)
2033 + )]
2034 +
2035 +def _db_remove_package_files(pkg_name: str):
2036 + with _db_session() as db:
2037 + db.execute("DELETE FROM files WHERE package=?", (pkg_name,))
2038 + db.commit()
2039 +
2040 +def _db_get_all_file_checksums() -> Dict[str, str]:
2041 + with _db_session() as db:
2042 + return {r["path"]: r["sha256"] for r in db.execute("SELECT path, sha256 FROM file_checksums")}
2043 +
2044 +def _db_get_package_checksums(pkg_name: str) -> Dict[str, str]:
2045 + """Sumy SHA256 zapisane dla plików należących do pakietu.
2046 +
2047 + Używane do wykrycia, czy użytkownik zmodyfikował plik konfiguracyjny
2048 + (porównanie z sumą z chwili instalacji) – serce mechanizmu .pacnew/.pacsave.
2049 + """
2050 + with _db_session() as db:
2051 + return {r["path"]: r["sha256"] for r in db.execute(
2052 + "SELECT fc.path AS path, fc.sha256 AS sha256 FROM file_checksums fc "
2053 + "JOIN files f ON f.path = fc.path WHERE f.package=?", (pkg_name,))}
2054 +
2055 +
2056 +def _db_count_files() -> int:
2057 + with _db_session() as db:
2058 + return db.execute("SELECT COUNT(*) FROM files").fetchone()[0]
2059 +
2060 +# =============================================================================
2061 +# BLOKADA
2062 +# =============================================================================
2063 +
2064 +class DatabaseLock:
2065 + """Blokada plikowa (flock) – jądro zwalnia ją AUTOMATYCZNIE, gdy proces
2066 + ginie (kill -9, twardy reset). Stary PID-file miał race condition: po
2067 + śmierci pag PID mógł zostać przydzielony obcemu procesowi (PID reuse)
2068 + i pag odmawiał działania na zawsze („baza zablokowana”).
2069 + """
2070 + def __init__(self):
2071 + self._f = None
2072 + def __enter__(self):
2073 + os.makedirs(os.path.dirname(LOCK_FILE), exist_ok=True)
2074 + self._f = open(LOCK_FILE, "w")
2075 + try:
2076 + # LOCK_NB: rzuca wyjątek zamiast czekać w nieskończoność
2077 + fcntl.flock(self._f, fcntl.LOCK_EX | fcntl.LOCK_NB)
2078 + except BlockingIOError:
2079 + print(f"❌ {_('db_locked')}", file=sys.stderr)
2080 + print(f" {_('db_lock_hint', LOCK_FILE)}", file=sys.stderr)
2081 + sys.exit(1)
2082 + self._f.write(str(os.getpid()))
2083 + self._f.flush()
2084 + return self
2085 + def __exit__(self, *args):
2086 + if self._f:
2087 + try:
2088 + fcntl.flock(self._f, fcntl.LOCK_UN)
2089 + except OSError:
2090 + pass
2091 + self._f.close()
2092 + self._f = None
2093 + # Uwaga: NIE usuwamy pliku blokady. Stały plik + flock na inode to jedyny
2094 + # bezpieczny wzorzec – os.remove(), gdy inny proces trzyma blokadę na starym
2095 + # inode, otwiera wyścig (nowy proces blokowałby nowo utworzony inode).
2096 +
2097 +
2098 +class SelfUpdateLock:
2099 + """Blokada podmiany binarki pag podczas self-update.
2100 +
2101 + Niezależna od DatabaseLock (inny plik) – cmd_self_update może zostać
2102 + wywołane poza globalną blokadą (np. z zewnętrznego skryptu), a dwie
2103 + równoległe aktualizacje pisałyby do tego samego `dst.new`; `os.replace`
2104 + mógłby wtedy podmienić plik w trakcie wykonywania (uszkodzony pag).
2105 + """
2106 + def __init__(self):
2107 + self._f = None
2108 +
2109 + def __enter__(self):
2110 + lock_path = LOCK_FILE + ".self-update"
2111 + os.makedirs(os.path.dirname(lock_path), exist_ok=True)
2112 + self._f = open(lock_path, "w")
2113 + try:
2114 + fcntl.flock(self._f, fcntl.LOCK_EX | fcntl.LOCK_NB)
2115 + except BlockingIOError:
2116 + self._f.close()
2117 + self._f = None
2118 + print(_('❌ Another pag update is in progress – try again later.'),
2119 + file=sys.stderr)
2120 + sys.exit(1)
2121 + self._f.write(str(os.getpid()))
2122 + self._f.flush()
2123 + return self
2124 +
2125 + def __exit__(self, *args):
2126 + if self._f:
2127 + try:
2128 + fcntl.flock(self._f, fcntl.LOCK_UN)
2129 + except OSError:
2130 + pass
2131 + self._f.close()
2132 + self._f = None
2133 +
2134 +# =============================================================================
2135 +# POMOCNICZE
2136 +# =============================================================================
2137 +
2138 +
2139 +# Katalogi systemowe. /bin, /sbin i /lib64 to na usrmerge symlinki do
2140 +# /usr/bin, /usr/bin i /usr/lib64 – bez nich pag pomijał CAŁĄ zawartość
2141 +# pakietów, które pakują pliki „starymi” ścieżkami (np. busybox: 386 plików
2142 +# w ./bin/, w tym sam ./bin/busybox → "BLOCKED: ./bin/ls" i spółka).
2143 +_ALLOWED_PREFIXES = ("/usr/", "/etc/", "/var/", "/opt/",
2144 + "/boot/", "/lib/", "/lib64/", "/run/",
2145 + "/bin/", "/sbin/", # usrmerge: bin→usr/bin, sbin→usr/bin
2146 + # Pliki wewnętrzne paczki .pkg.tar.xz
2147 + "metadata.json", "data.tar.xz", "hooks/",
2148 + "sums.json")
2149 +
2150 +def _check_path_safety(name: str) -> bool:
2151 + # Normalizuj – usuń leading ./
2152 + if name.startswith("./"):
2153 + name = name[2:]
2154 + if name in (".", ""):
2155 + return True
2156 + # Porównuj z prefiksami BEZ wiodącego '/', by zarówno "/usr/bin/ls", jak i
2157 + # wewnętrzne pliki pakietu ("hooks/pre-install", "data.tar.xz") przechodziły.
2158 + norm = name.lstrip("/")
2159 + for prefix in _ALLOWED_PREFIXES:
2160 + p = prefix.lstrip("/").rstrip("/")
2161 + if norm == p or norm.startswith(p + "/"):
2162 + return True
2163 + return False
2164 +
2165 +
2166 +def _validate_pkg_name(name):
2167 + return bool(ALLOWED_PKG_RE.match(name))
2168 +
2169 +
2170 +
2171 +def _audit(msg):
2172 + from datetime import datetime, timezone
2173 + os.makedirs(os.path.dirname(AUDIT_LOG), exist_ok=True)
2174 + with open(AUDIT_LOG, "a") as f:
2175 + f.write(datetime.now(timezone.utc).isoformat() + " " + msg + "\n")
2176 +
2177 +def _strip_suid(path):
2178 + try:
2179 + st = os.stat(path)
2180 + if st.st_mode & 0o4000:
2181 + os.chmod(path, st.st_mode & ~0o4000)
2182 + print(f" {_("sec_suid", path=path)}")
2183 + except OSError:
2184 + pass
2185 +
2186 +def _check_downgrade(pkg_name, new_ver, installed_db):
2187 + if pkg_name in installed_db:
2188 + old = installed_db[pkg_name].get("version", "0")
2189 + if new_ver < old:
2190 + print(f" {_("sec_downgrade", pkg=pkg_name, new=new_ver, old=old)}")
2191 + return False
2192 + return True
2193 +
2194 +def _safe_extractall(tar: tarfile.TarFile, dest: str, *, preserve_perms: bool = True,
2195 + privileged=frozenset()):
2196 + """
2197 + Bezpieczne rozpakowanie archiwum tar z ochroną przed Directory Traversal.
2198 +
2199 + Działa na Python < 3.12 (gdzie parametr 'filter' w extractall nie istnieje)
2200 + oraz na Python 3.12+. W przeciwieństwie do filtra 'data' z Pythona 3.12,
2201 + zachowuje bity uprawnień POSIX (SUID, SGID, sticky) – preserve_perms=True.
2202 +
2203 + Ochrona oparta jest na FINALNEJ ścieżce (os.path.realpath), nie tylko na
2204 + prostym sprawdzaniu stringa:
2205 + - Blokuje ścieżki absolutne i z '..' (path traversal)
2206 + - Blokuje symlinki/hardlinki, których cel wychodzi poza dest
2207 + - Blokuje zapis "przez" złośliwy symlink, który został wcześniej
2208 + rozpakowany (np. katalog → /etc, potem zapis katalog/plik)
2209 + - Zachowuje oryginalne uprawnienia plików
2210 + """
2211 + dest_real = os.path.realpath(dest)
2212 + os.makedirs(dest_real, exist_ok=True)
2213 +
2214 + def _target_within(path: str) -> bool:
2215 + try:
2216 + return os.path.commonpath([dest_real, os.path.realpath(path)]) == dest_real
2217 + except ValueError:
2218 + # różne napędy / ścieżki nie da się wspólnie porównać → odrzuć
2219 + return False
2220 +
2221 + for member in tar.getmembers():
2222 + name = member.name
2223 +
2224 + # --- Ochrona przed Directory Traversal (szybkie string-checki) ---
2225 + if name.startswith('/'):
2226 + continue
2227 + if '..' in name.split('/'):
2228 + continue
2229 + # Zablokuj bajt NUL i backslash (bugi/obejścia tarfile na niektórych platformach)
2230 + if '\x00' in name or '\\' in name:
2231 + continue
2232 + if not _check_path_safety(name):
2233 + print(f" BLOCKED: {name}")
2234 + continue
2235 +
2236 + target = os.path.join(dest, name)
2237 +
2238 + # --- Ochrona na podstawie finalnej ścieżki ---
2239 + # Jeśli którykolwiek komponent nadrzędny jest (złośliwym) symlinkiem
2240 + # wskazującym poza dest, realpath to wykryje – zablokuj zapis.
2241 + if not _target_within(target):
2242 + print(f" BLOCKED (escape): {name}")
2243 + continue
2244 +
2245 + # --- Ochrona dla symlinków i hardlinków ---
2246 + if member.issym() or member.islnk():
2247 + link = member.linkname
2248 + # Szybkie odrzucenie linków absolutnych / z '..'
2249 + if link.startswith('/') or '..' in link.split('/'):
2250 + continue
2251 + # Sprawdź, gdzie realnie prowadzi cel linku (względem katalogu linku)
2252 + link_target = os.path.join(os.path.dirname(target), link)
2253 + if not _target_within(link_target):
2254 + print(f" BLOCKED (link escape): {name} -> {link}")
2255 + continue
2256 +
2257 + # Rozpakuj z zachowaniem metadanych. Python 3.12+ wymaga jawnego
2258 + # `filter=` (inaczej DeprecationWarning, a w 3.14+ błąd).
2259 + # UWAGA: 'fully_trusted' CELOWO pomija wbudowane filtry bezpieczeństwa
2260 + # Pythona – to nie przeoczenie. Nasza walidacja powyżej (path traversal,
2261 + # NUL/backslash, escape przez symlink, linki wychodzące poza dest) jest
2262 + # równoważna lub ostrzejsza, a 'fully_trusted' pozwala zachować bity
2263 + # SUID/SGID/sticky, które filtr 'data' by usunął (np. /usr/bin/sudo).
2264 + # SUID jest i tak zdejmowany przez _strip_suid() tuż po rozpakowaniu.
2265 + try:
2266 + if hasattr(tarfile, 'data_filter'):
2267 + # Python 3.12+
2268 + tar.extract(member, dest, set_attrs=preserve_perms, numeric_owner=False,
2269 + filter='fully_trusted')
2270 + else:
2271 + tar.extract(member, dest, set_attrs=preserve_perms, numeric_owner=False)
2272 + except Exception as e:
2273 + print(_(' ⚠ Failed to extract {arg1}: {arg2}', arg1=(name), arg2=(e)))
2274 + continue
2275 + # Pliki z listy uprzywilejowanej zachowują SUID/SGID; reszta jest
2276 + # czyszczona (ochrona przed SUID niespodziewanym w pakiecie).
2277 + if "/" + os.path.relpath(target, dest_real) not in privileged:
2278 + _strip_suid(target)
2279 +
2280 +
2281 +def _sha256_file(path: str) -> str:
2282 + """SHA256 pliku. Na Python ≥3.11 używa hashlib.file_digest (pętla w C);
2283 + starsze wersje mają fallback z pętlą chunków."""
2284 + with open(path, "rb") as f:
2285 + if hasattr(hashlib, "file_digest"):
2286 + return hashlib.file_digest(f, "sha256").hexdigest()
2287 + h = hashlib.sha256()
2288 + for chunk in iter(lambda: f.read(65536), b""):
2289 + h.update(chunk)
2290 + return h.hexdigest()
2291 +
2292 +def _split_version(v: str):
2293 + """Rozdziela wersję na (release_parts, prerelease_parts).
2294 +
2295 + Przykład: '1.2.0-rc1' → ([1,2,0], ['rc','1']).
2296 + """
2297 + v = v.strip().lower().lstrip("v")
2298 + # build metadata po '+' jest ignorowane przy porównywaniu (semver)
2299 + v = v.split("+", 1)[0]
2300 + # prerelease po '-' lub '_' (np. 1.2.0-rc1, 1.2.0_rc1)
2301 + if "-" in v:
2302 + rel, pre = v.split("-", 1)
2303 + elif "_" in v:
2304 + rel, pre = v.split("_", 1)
2305 + else:
2306 + rel, pre = v, ""
2307 + nums = []
2308 + for part in rel.split("."):
2309 + m = re.match(r"(\d+)", part)
2310 + nums.append(int(m.group(1)) if m else 0)
2311 + pre_parts = [p for p in pre.split(".") if p]
2312 + return nums, pre_parts
2313 +
2314 +
2315 +def _cmp_pre(a, b):
2316 + """Porównuje ciągi identyfikatorów prerelease (reguły semver)."""
2317 + for i in range(max(len(a), len(b))):
2318 + if i >= len(a):
2319 + return -1 # krótszy prerelease jest niższy
2320 + if i >= len(b):
2321 + return 1
2322 + ia, ib = a[i], b[i]
2323 + if ia == ib:
2324 + continue
2325 + na, nb = ia.isdigit(), ib.isdigit()
2326 + if na and nb:
2327 + return 1 if int(ia) > int(ib) else -1
2328 + if na != nb:
2329 + return -1 if na else 1 # identyfikator liczbowy < alfanumeryczny
2330 + return 1 if ia > ib else -1
2331 + return 0
2332 +
2333 +
2334 +def _cmp_version(a: str, b: str) -> int:
2335 + """Porównuje dwie wersje; zwraca -1/0/1. Obsługuje prerelease (rc1, beta...)."""
2336 + a_rel, a_pre = _split_version(a)
2337 + b_rel, b_pre = _split_version(b)
2338 + # Porównaj część release (brakujące komponenty traktuj jako 0)
2339 + for i in range(max(len(a_rel), len(b_rel))):
2340 + xa = a_rel[i] if i < len(a_rel) else 0
2341 + xb = b_rel[i] if i < len(b_rel) else 0
2342 + if xa != xb:
2343 + return 1 if xa > xb else -1
2344 + # Część release równa → decyduje prerelease.
2345 + # Wersja finalna (bez prerelease) jest ZAWSZE nowsza od prerelease.
2346 + if not a_pre and not b_pre:
2347 + return 0
2348 + if not a_pre:
2349 + return 1
2350 + if not b_pre:
2351 + return -1
2352 + return _cmp_pre(a_pre, b_pre)
2353 +
2354 +
2355 +def _version_newer(a: str, b: str) -> bool:
2356 + """True gdy wersja a jest nowsza od b (z poprawną obsługą prerelease)."""
2357 + try:
2358 + return _cmp_version(a, b) > 0
2359 + except Exception:
2360 + return a != b
2361 +
2362 +def load_json(path):
2363 + try:
2364 + with open(path) as f:
2365 + return json.load(f)
2366 + except (FileNotFoundError, json.JSONDecodeError):
2367 + return {}
2368 +
2369 +def save_json(path, data):
2370 + with open(path, "w") as f:
2371 + json.dump(data, f, indent=2)
2372 +
2373 +class PackageInfo:
2374 + __slots__ = ("name","version","release","description","dependencies",
2375 + "optdepends","size_bytes","sha256","gpg_fp","repo_url","filename",
2376 + "provides","license","provides_so","requires_so","privileged")
2377 + def __init__(self, d, repo=""):
2378 + self.name = d.get("name","?")
2379 + self.version = d.get("version","0")
2380 + self.release = d.get("release", 1)
2381 + self.description = d.get("description","")
2382 + self.dependencies = d.get("dependencies", d.get("depends", []))
2383 + # Opcjonalne zależności (flatpak, btrfs-progs, grub, ...) – tylko
2384 + # informacyjne; `pag install` NIE instaluje ich automatycznie.
2385 + self.optdepends = d.get("optdepends", []) or []
2386 + self.size_bytes = d.get("size",0)
2387 + self.sha256 = d.get("sha256","")
2388 + self.gpg_fp = d.get("gpg_fingerprint","")
2389 + self.repo_url = repo
2390 + self.filename = d.get("filename", f"{self.name}-{self.version}{PKG_EXT}")
2391 + self.provides = d.get("provides", []) or []
2392 + self.license = d.get("license", []) or []
2393 + self.provides_so = d.get("provides_so", []) or []
2394 + self.requires_so = d.get("requires_so", []) or []
2395 + # Ścieżki, którym wolno zachować setuid/setgid i grupę (z receptury).
2396 + self.privileged = d.get("privileged", []) or []
2397 +
2398 +# =============================================================================
2399 +# REPOZYTORIA (cache, ETag, GPG)
2400 +# =============================================================================
2401 +
2402 +def _parse_repos_config():
2403 + """Parsuje repozytoria z /etc/pag/repos.conf oraz /etc/pag/repos/*.conf.
2404 +
2405 + Format linii: <url> [fingerprint]
2406 + Opcjonalny `fingerprint` (40 znaków hex) pozwala przypiąć klucz
2407 + podpisujący repo do konkretnego adresu – wtedy TOFU (auto-zaufanie przy
2408 + pierwszym użyciu) nie jest potrzebne, a zmiana klucza = błąd bezpieczeństwa.
2409 +
2410 + Drop-iny (np. stable.conf) są czytane alfabetycznie – pozwalają na
2411 + wygodne dodawanie repo bez dotykania głównego repos.conf
2412 + (np. `echo 'https://repo.paganlinux.eu/stable' > /etc/pag/repos/stable.conf`).
2413 + """
2414 + entries = []
2415 +
2416 + def _read_lines(path):
2417 + if not os.path.exists(path):
2418 + return
2419 + for line in open(path):
2420 + line = line.strip()
2421 + if not line or line.startswith("#"):
2422 + continue
2423 + parts = line.split()
2424 + url = parts[0].rstrip("/")
2425 + fp = parts[1].lower() if len(parts) > 1 else ""
2426 + entries.append({"url": url, "fingerprint": fp or None})
2427 +
2428 + # 1) Legacy: pojedynczy plik /etc/pag/repos.conf
2429 + _read_lines(REPOS_CONF)
2430 + # 2) Drop-in: /etc/pag/repos/<nazwa>.conf (sortowane, stabilna kolejność)
2431 + if os.path.isdir(REPOS_DIR):
2432 + for drop in sorted(os.listdir(REPOS_DIR)):
2433 + if drop.endswith(".conf"):
2434 + _read_lines(os.path.join(REPOS_DIR, drop))
2435 +
2436 + # Dedupe po URL (zachowaj pierwszy wpis – może mieć fingerprint)
2437 + seen, unique = set(), []
2438 + for e in entries:
2439 + if e["url"] not in seen:
2440 + seen.add(e["url"])
2441 + unique.append(e)
2442 +
2443 + if not unique:
2444 + for url in DEFAULT_REPOS:
2445 + # rstrip: get_repos()/_repo_pinned_fp() kluczują URL-e bez ukośnika
2446 + unique.append({"url": url.rstrip("/"), "fingerprint": None})
2447 + return unique
2448 +
2449 +
2450 +def get_repos():
2451 + return [e["url"] for e in _parse_repos_config()]
2452 +
2453 +
2454 +def _repo_pinned_fp(repo_url):
2455 + """Zwraca przypięty fingerprint klucza dla repo (z konfiguracji lub trust DB)."""
2456 + # Normalizacja ukośnika: _parse_repos_config() i trust DB kluczują URL-e BEZ
2457 + # końcowego „/”, a wywołujący podają często DEFAULT_REPOS[0] Z ukośnikiem.
2458 + # Bez tego przypięty klucz nie był znajdowany i lokalny .pag dostawał
2459 + # fałszywe „Brak przypiętego klucza repo” mimo poprawnego wpisu w trusted.json.
2460 + repo_url = repo_url.rstrip("/")
2461 + by_url = {e["url"]: e["fingerprint"] for e in _parse_repos_config()}
2462 + if by_url.get(repo_url):
2463 + return by_url[repo_url]
2464 + db = _load_trust_db()
2465 + fp = db.get(repo_url)
2466 + return fp.lower() if fp else None
2467 +
2468 +def _repo_cache_path(url):
2469 + return os.path.join(REPO_CACHE, url.replace("://","_").replace("/","_").replace(".","_") + ".json")
2470 +
2471 +def _repo_etag_path(url): return _repo_cache_path(url) + ".etag"
2472 +def _repo_ts_path(url): return _repo_cache_path(url) + ".ts"
2473 +
2474 +# Informacja (raz na uruchomienie), gdy cache repozytoriów jest tylko-do-odczytu –
2475 +# np. komendy read-only (`pag info`, `pag search`…) jako zwykły user: nie ma sensu
2476 +# ani prawa odświeżać /var/cache/pag/repos, więc używamy lokalnej kopii indeksu.
2477 +_cache_ro_notice_done = False
2478 +
2479 +def _cache_ro_notice():
2480 + global _cache_ro_notice_done
2481 + if _cache_ro_notice_done:
2482 + return
2483 + _cache_ro_notice_done = True
2484 + print(f" ⚠ {_('cache_ro', cache=REPO_CACHE)}", file=sys.stderr)
2485 +
2486 +def _load_repo_cache(cp: str) -> Optional[list]:
2487 + """Wczytuje cache indeksu repo; zwraca None gdy brak albo uszkodzony.
2488 +
2489 + Partial write (crash w trakcie zapisu) mógł zostawić obcięty JSON. Zamiast
2490 + zwracać pustą listę pakietów (użytkownik myśli, że repo jest puste)
2491 + sygnalizujemy None – wywołujący ponowi pobranie albo pokaże ostrzeżenie."""
2492 + if not os.path.exists(cp):
2493 + return None
2494 + try:
2495 + with open(cp, "r", encoding="utf-8") as fh:
2496 + data = json.load(fh)
2497 + pkgs = data.get("packages")
2498 + if not isinstance(pkgs, list):
2499 + raise ValueError(_("repo_index_invalid"))
2500 + return pkgs
2501 + except (OSError, ValueError) as e:
2502 + print(_(' ⚠ Corrupted index cache {arg1}: {arg2}', arg1=(cp), arg2=(e)), file=sys.stderr)
2503 + return None
2504 +
2505 +
2506 +def fetch_repo_index(repo_url, force=False):
2507 + cp = _repo_cache_path(repo_url)
2508 + ep = _repo_etag_path(repo_url)
2509 + tp = _repo_ts_path(repo_url)
2510 +
2511 + if not force and os.path.exists(cp) and os.path.exists(tp):
2512 + try:
2513 + if time.time() - float(open(tp).read().strip()) < REPO_CACHE_TTL:
2514 + cached = _load_repo_cache(cp)
2515 + if cached is not None:
2516 + return cached
2517 + # uszkodzony cache – spróbuj odświeżyć z sieci
2518 + except (OSError, ValueError):
2519 + pass
2520 +
2521 + # --- Cache tylko-do-odczytu (np. `pag info` jako zwykły user) ---
2522 + # /var/cache/pag/repos należy do roota. Nie próbuj odświeżać ani pisać –
2523 + # zwykły user i tak nie zapisze indeksu; użyj lokalnej kopii (może być
2524 + # nieaktualna). Pełne odświeżenie indeksu: sudo pag sync
2525 + if not (os.path.isdir(REPO_CACHE) and os.access(REPO_CACHE, os.W_OK)):
2526 + if force:
2527 + print(_(' ❌ {arg1}: cannot refresh index – {arg2} is read-only', arg1=(repo_url), arg2=(REPO_CACHE)),
2528 + file=sys.stderr)
2529 + return None
2530 + _cache_ro_notice()
2531 + cached = _load_repo_cache(cp)
2532 + if cached is not None:
2533 + return cached
2534 + return None
2535 +
2536 + headers = {"User-Agent": "pag/3.0"}
2537 + if os.path.exists(tp) and not force:
2538 + try:
2539 + lm = datetime.fromtimestamp(float(open(tp).read().strip()), tz=timezone.utc)
2540 + # Wymuś lokalizację C/POSIX dla nagłówków HTTP, aby unikać problemów z nazwami dni/miesięcy
2541 + try:
2542 + old_locale = locale.setlocale(locale.LC_TIME)
2543 + locale.setlocale(locale.LC_TIME, 'C')
2544 + headers["If-Modified-Since"] = lm.strftime("%a, %d %b %Y %H:%M:%S GMT")
2545 + locale.setlocale(locale.LC_TIME, old_locale)
2546 + except (locale.Error, ValueError):
2547 + # Jeśli ustawienie lokalizacji się nie powiedzie, użyj domyślnej
2548 + headers["If-Modified-Since"] = lm.strftime("%a, %d %b %Y %H:%M:%S GMT")
2549 + except: pass
2550 + if os.path.exists(ep) and not force:
2551 + try: headers["If-None-Match"] = open(ep).read().strip()
2552 + except: pass
2553 +
2554 + # --- Pobranie indeksu (błędy SIECI nie są błędami zapisu cache) ---
2555 + try:
2556 + req = Request(f"{repo_url}/repo.json", headers=headers)
2557 + with urlopen(req, timeout=30) as resp:
2558 + etag = resp.headers.get("ETag","")
2559 + raw = resp.read()
2560 + data = json.loads(raw.decode())
2561 + except HTTPError as e:
2562 + if e.code == 304:
2563 + # Serwer: indeks bez zmian – odśwież tylko znacznik czasu (best-effort)
2564 + try:
2565 + open(tp,"w").write(str(time.time()))
2566 + except OSError:
2567 + pass
2568 + cached = _load_repo_cache(cp)
2569 + if cached is not None:
2570 + return cached
2571 + # uszkodzona kopia – potraktuj jak brak (ostrzeżenie niżej)
2572 + print(_(' ⚠ HTTP {arg1} for {arg2}', arg1=(e.code), arg2=(repo_url)), file=sys.stderr)
2573 + return None
2574 + except Exception as e:
2575 + print(_(' ⚠ Failed to download index {arg1}: {arg2}', arg1=(repo_url), arg2=(e)), file=sys.stderr)
2576 + return _load_repo_cache(cp)
2577 +
2578 + # Indeks pobrany – zapisz SUROWE bajty (nie re-serializuj! podpis GPG jest
2579 + # nad oryginalnymi bajtami repo.json z serwera) i zweryfikuj podpis.
2580 + # Najpierw zapis tymczasowy + weryfikacja GPG, dopiero potem podmiana cp:
2581 + # błąd zapisu (np. pełny dysk) nie niszczy starej, zweryfikowanej kopii
2582 + # i NIGDY nie zwracamy danych, które nie przeszły weryfikacji.
2583 + tmp_path = cp + ".tmp"
2584 + try:
2585 + with open(tmp_path, "wb") as f:
2586 + f.write(raw)
2587 + if not _verify_repo_sig(repo_url, tmp_path):
2588 + return None # weryfikacja nie powiodła się – stary cache zostaje
2589 + os.replace(tmp_path, cp)
2590 + # przenieś podpis obok docelowego pliku (marker „repo ma podpis")
2591 + for _ext in (".asc", ".sig"):
2592 + if os.path.exists(tmp_path + _ext):
2593 + try:
2594 + os.replace(tmp_path + _ext, cp + _ext)
2595 + except OSError:
2596 + pass
2597 + break
2598 + if etag:
2599 + try:
2600 + open(ep,"w").write(etag)
2601 + except OSError:
2602 + pass
2603 + try:
2604 + open(tp,"w").write(str(time.time()))
2605 + except OSError:
2606 + pass
2607 + return data.get("packages",[])
2608 + except OSError as e:
2609 + print(_(' ⚠ Index downloaded, but failed to save cache ({arg1}): {arg2}', arg1=(REPO_CACHE), arg2=(e)),
2610 + file=sys.stderr)
2611 + # cp nie został podmieniony (podmiana jest po weryfikacji) – lokalna kopia
2612 + # to wciąż stare, zweryfikowane dane
2613 + return _load_repo_cache(cp)
2614 + finally:
2615 + for _p in (tmp_path, tmp_path + ".asc", tmp_path + ".sig"):
2616 + try:
2617 + os.unlink(_p)
2618 + except OSError:
2619 + pass
2620 +
2621 +def _verify_repo_sig(repo_url, cache_path) -> bool:
2622 + """Weryfikuje podpis GPG indeksu repozytorium i przypina fingerprint.
2623 +
2624 + FAIL-CLOSED: brak/nieprawidłowy podpis = False (chyba że PAG_INSECURE=1).
2625 + Zwraca True jeśli indeks jest zaufany, False jeśli należy go odrzucić.
2626 +
2627 + Model zaufania (TOFU + pinning):
2628 + - Pierwszy raz (brak przypiętego fingerprintu) → klucz jest importowany,
2629 + a fingerprint zapisywany w /etc/pag/trusted.json z JAWNYM ostrzeżeniem.
2630 + To świadomy kompromis wygody i bezpieczeństwa.
2631 + - Kolejne uruchomienia: fingerprint jest porównywany z przypiętym.
2632 + Zmiana klucza = ❌ SECURITY ERROR (fail-closed), wymagane ręczne:
2633 + pag key-trust <repo_url> (po weryfikacji nowego klucza)
2634 + """
2635 + insecure = os.environ.get("PAG_INSECURE", "") == "1"
2636 +
2637 + if not os.path.exists(GPG_HOME):
2638 + if insecure:
2639 + return True # brak GPG home – tryb insecure, akceptuj
2640 + print(_(' ❌ {arg1}: no GPG keys – verification impossible!', arg1=(repo_url)))
2641 + print(_(' Set PAG_INSECURE=1 to skip (not recommended)'))
2642 + os.remove(cache_path)
2643 + return False
2644 +
2645 + sig_path = cache_path + ".sig"
2646 + # Podpisy generowane jako .asc (armored) – próbuj .asc, potem .sig
2647 + sig_data = None
2648 + sig_ext = ""
2649 + for ext in (".asc", ".sig"):
2650 + try:
2651 + req = Request(f"{repo_url}/repo.json{ext}", headers={"User-Agent":"pag/3.0"})
2652 + with urlopen(req, timeout=15) as resp:
2653 + sig_data = resp.read()
2654 + sig_ext = ext
2655 + break
2656 + except Exception:
2657 + continue
2658 + if not sig_data:
2659 + if insecure:
2660 + return True # tryb insecure – akceptuj bez podpisu
2661 + print(_(' ❌ {arg1}: CANNOT DOWNLOAD SIGNATURE repo.json.asc/.sig!', arg1=(repo_url)))
2662 + print(_(' Set PAG_INSECURE=1 to skip (not recommended)'))
2663 + os.remove(cache_path)
2664 + return False
2665 + sig_path = cache_path + sig_ext
2666 + with open(sig_path, "wb") as f:
2667 + f.write(sig_data)
2668 +
2669 + ok, fingerprint = _gpg_verify_fp(sig_path, cache_path)
2670 + if not ok:
2671 + # Automatyczny import klucza repo przy pierwszym uruchomieniu (TOFU,
2672 + # jak apt) – gdy w keyringu brakuje klucza (No public key).
2673 + res = _gpg_run("--verify", sig_path, cache_path,
2674 + capture_output=True, text=True, timeout=30)
2675 + _stderr = res.stderr.decode(errors="replace") if isinstance(res.stderr, bytes) else (res.stderr or "")
2676 + if "public key" in _stderr.lower() and "no public key" in _stderr.lower():
2677 + try:
2678 + with urlopen(Request(f"{repo_url}/paganos.asc", headers={"User-Agent": "pag/3.0"}), timeout=20) as r:
2679 + keydata = r.read()
2680 + with tempfile.NamedTemporaryFile(delete=False, suffix=".asc") as tmp:
2681 + tmp.write(keydata)
2682 + tmp.flush()
2683 + _gpg_run("--import", tmp.name, capture_output=True, timeout=30)
2684 + os.unlink(tmp.name)
2685 + print(_(' 🔑 Imported repo key from {arg1}/paganos.asc', arg1=(repo_url)))
2686 + ok, fingerprint = _gpg_verify_fp(sig_path, cache_path)
2687 + except Exception:
2688 + pass
2689 + if not ok:
2690 + if insecure:
2691 + print(_(' ⚠ {arg1}: invalid GPG signature (PAG_INSECURE – ignoring)', arg1=(repo_url)))
2692 + return True
2693 + os.remove(cache_path)
2694 + if not shutil.which(GPG_BINARY):
2695 + print(_(' ❌ {arg1}: GPG is not installed – cannot verify the signature!', arg1=(repo_url)))
2696 + print(_(' Install gnupg or set PAG_INSECURE=1 (not recommended)'))
2697 + else:
2698 + print(_(' ❌ {arg1}: INVALID GPG SIGNATURE of the repository index!', arg1=(repo_url)))
2699 + return False
2700 +
2701 + # --- Wymuś przypięty fingerprint (TOFU + pinning) ---
2702 + pinned = _repo_pinned_fp(repo_url)
2703 + if pinned:
2704 + if not fingerprint:
2705 + if insecure:
2706 + print(_(' ⚠ {arg1}: cannot read signature fingerprint (PAG_INSECURE – ignoring)', arg1=(repo_url)))
2707 + return True
2708 + os.remove(cache_path)
2709 + print(_(' ❌ [SECURITY ERROR] {arg1}: cannot read signature fingerprint!', arg1=(repo_url)))
2710 + print(_(' Pinned key: {arg1} – rejecting the index.', arg1=(pinned)))
2711 + return False
2712 + if fingerprint != pinned.upper():
2713 + if insecure:
2714 + print(_(' ⚠ {arg1}: SIGNING KEY CHANGED (PAG_INSECURE – ignoring)', arg1=(repo_url)))
2715 + return True
2716 + os.remove(cache_path)
2717 + print(_(' ❌ [SECURITY ERROR] {arg1}: Repository signing key has changed!', arg1=(repo_url)))
2718 + print(_(' Expected: {arg1}', arg1=(pinned)))
2719 + print(_(' Received: {arg1}', arg1=(fingerprint)))
2720 + print(_(' If this is an intentional key rotation: pag key-trust {arg1}', arg1=(repo_url)))
2721 + return False
2722 + return True
2723 +
2724 + if fingerprint:
2725 + # Brak przypiętego fingerprintu → TOFU: zapisz go w bazie zaufania.
2726 + db = _load_trust_db()
2727 + if db.get(repo_url) != fingerprint:
2728 + _save_trust_db({**db, repo_url: fingerprint})
2729 + print(_(' 🔐 Pinned repo fingerprint {arg1}: {arg2}', arg1=(repo_url), arg2=(fingerprint)))
2730 + print(_(' (TOFU – first trust. If the key changes, pag will refuse updates.)'))
2731 + print(_(' To avoid TOFU, add the fingerprint to /etc/pag/repos.conf.'))
2732 + return True
2733 +
2734 +def fetch_all_packages(force=False):
2735 + all_pkgs = {}
2736 + for repo_url in get_repos():
2737 + pkgs = fetch_repo_index(repo_url, force)
2738 + if pkgs:
2739 + for pdata in pkgs:
2740 + name = pdata.get("name", pdata.get("filename","?").split("-")[0])
2741 + pkg = PackageInfo(pdata, repo_url)
2742 + if name not in all_pkgs or _version_newer(pkg.version, all_pkgs[name].version):
2743 + all_pkgs[name] = pkg
2744 + return all_pkgs
2745 +
2746 +# =============================================================================
2747 +# GPG
2748 +# =============================================================================
2749 +
2750 +def _verify_pkg_gpg(pkg_path, repo_url=None):
2751 + """Weryfikuje podpis GPG pakietu i (jeśli znamy repo) przypięty fingerprint.
2752 +
2753 + FAIL-CLOSED: brak podpisu = odrzucenie (chyba że PAG_INSECURE=1).
2754 + Zwraca (passed: bool, message: str).
2755 + """
2756 + insecure = os.environ.get("PAG_INSECURE", "") == "1"
2757 + # Brak gnupg = weryfikacja niemożliwa. Bez tej gałęzi użytkownik dostawał
2758 + # mylące „NIEPRAWIDŁOWY PODPIS GPG”, mimo że paczka i podpis są w porządku.
2759 + if not shutil.which(GPG_BINARY):
2760 + if insecure:
2761 + return True, "(gpg missing – PAG_INSECURE)"
2762 + return False, _("gpg_missing")
2763 + sig_path = pkg_path + ".sig"
2764 + if not os.path.exists(sig_path) and os.path.exists(pkg_path + ".asc"):
2765 + sig_path = pkg_path + ".asc"
2766 +
2767 + if not os.path.exists(sig_path):
2768 + if insecure:
2769 + return True, "(no signature – PAG_INSECURE)"
2770 + return False, "BRAK PODPISU – pakiet odrzucony (ustaw PAG_INSECURE=1 aby pominąć)"
2771 +
2772 + ok, fp = _gpg_verify_fp(sig_path, pkg_path)
2773 + if not ok:
2774 + if insecure:
2775 + return True, "(invalid signature – PAG_INSECURE)"
2776 + return False, "NIEPRAWIDŁOWY PODPIS GPG"
2777 +
2778 + # Opcjonalnie: sprawdź, czy podpis pochodzi od klucza przypiętego dla repo.
2779 + if repo_url:
2780 + pinned = _repo_pinned_fp(repo_url)
2781 + if pinned and fp and fp != pinned.upper():
2782 + if insecure:
2783 + return True, "(pkg signer mismatch – PAG_INSECURE)"
2784 + return False, f"PAKIET PODPISANY INNYM KLUCZEM niż repo (oczekiwano {pinned})"
2785 +
2786 + return True, "GPG verified"
2787 +
2788 +def cmd_key_add(source):
2789 + ensure_dirs()
2790 + if not shutil.which(GPG_BINARY):
2791 + print(f"❌ {_('gpg_missing')}"); return 1
2792 + if source.startswith("http"):
2793 + try:
2794 + with urlopen(Request(source, headers={"User-Agent":"pag/3.0"}), timeout=30) as resp:
2795 + keydata = resp.read()
2796 + with tempfile.NamedTemporaryFile(delete=False, suffix=".gpg") as tmp:
2797 + tmp.write(keydata); tmp.flush()
2798 + res = _gpg_run("--import", tmp.name, capture_output=True, timeout=30)
2799 + os.unlink(tmp.name)
2800 + if res.returncode != 0:
2801 + print(f"❌ {_('key_add_failed')}"); return 1
2802 + except Exception as e:
2803 + print(_('❌ Download error: {arg1}', arg1=(e))); return 1
2804 + else:
2805 + res = _gpg_run("--import", source, capture_output=True, timeout=30)
2806 + if res.returncode != 0:
2807 + print(f"❌ {_('key_add_failed')}"); return 1
2808 + print(f"✅ {_('key_imported')}")
2809 +
2810 +def cmd_key_list():
2811 + if not shutil.which(GPG_BINARY):
2812 + print(f"❌ {_('gpg_missing')}"); return
2813 + if not os.path.exists(GPG_HOME):
2814 + print(_("no_keys")); return
2815 + result = _gpg_run("--list-keys", "--keyid-format", "LONG",
2816 + capture_output=True, text=True, timeout=30)
2817 + if result.returncode != 0:
2818 + print(f"❌ {_('gpg_missing')}"); return
2819 + print(result.stdout or _("no_keys"))
2820 +
2821 +def cmd_key_remove(key_id):
2822 + _gpg_run("--batch", "--yes", "--delete-key", key_id,
2823 + capture_output=True, timeout=30)
2824 + print(f"✅ {_('key_removed', key_id)}")
2825 +
2826 +def _repo_signer_fp(repo_url):
2827 + """Pobiera repo.json + podpis i zwraca fingerprint podpisującego (bez pinningu)."""
2828 + repo_url = repo_url.rstrip("/")
2829 + try:
2830 + with urlopen(Request(f"{repo_url}/repo.json", headers={"User-Agent":"pag/3.0"}), timeout=30) as r:
2831 + data = r.read()
2832 + except Exception:
2833 + return None
2834 + sig = None
2835 + sig_ext = ".asc"
2836 + for ext in (".asc", ".sig"):
2837 + try:
2838 + with urlopen(Request(f"{repo_url}/repo.json{ext}", headers={"User-Agent":"pag/3.0"}), timeout=20) as r:
2839 + sig = r.read()
2840 + sig_ext = ext
2841 + break
2842 + except Exception:
2843 + continue
2844 + if not sig:
2845 + return None
2846 + with tempfile.NamedTemporaryFile(delete=False, suffix=".json") as tf:
2847 + tf.write(data); tf.flush()
2848 + data_path = tf.name
2849 + sig_path = data_path + sig_ext
2850 + try:
2851 + with open(sig_path, "wb") as f:
2852 + f.write(sig)
2853 + ok, fp = _gpg_verify_fp(sig_path, data_path)
2854 + finally:
2855 + for p in (data_path, sig_path):
2856 + try: os.unlink(p)
2857 + except OSError: pass
2858 + return fp if ok else None
2859 +
2860 +
2861 +def cmd_key_trust(repo_url):
2862 + """Przypina fingerprint klucza podpisującego repo (koniec z TOFU dla tego repo)."""
2863 + repo_url = repo_url.rstrip("/")
2864 + print(_('🔐 Pinning repo key {arg1}...', arg1=(repo_url)))
2865 + fp = _repo_signer_fp(repo_url)
2866 + if not fp:
2867 + print(_(' ❌ Cannot read signature fingerprint (missing/failed).'))
2868 + print(_(' Make sure the repo key is in the keyring (pag key-add <url|file>).'))
2869 + return 1
2870 + db = _load_trust_db()
2871 + _save_trust_db({**db, repo_url: fp})
2872 + print(_(' ✅ Pinned {arg1} for {arg2}', arg1=(fp), arg2=(repo_url)))
2873 + print(_(' From now on, a key change will be reported as SECURITY ERROR.'))
2874 + return 0
2875 +
2876 +
2877 +def cmd_key_untrust(repo_url):
2878 + """Usuwa przypięcie fingerprintu dla repo (wraca do TOFU)."""
2879 + repo_url = repo_url.rstrip("/")
2880 + db = _load_trust_db()
2881 + if repo_url not in db:
2882 + print(_(' ℹ {arg1} has no pinned fingerprint.', arg1=(repo_url)))
2883 + return 0
2884 + del db[repo_url]
2885 + _save_trust_db(db)
2886 + print(_(' ✅ Removed pin for {arg1}.', arg1=(repo_url)))
2887 + return 0
2888 +
2889 +
2890 +def cmd_key_trusted():
2891 + """Listuje przypięte fingerprinty repozytoriów."""
2892 + db = _load_trust_db()
2893 + if not db:
2894 + print(_("no_keys"))
2895 + return
2896 + for url, fp in sorted(db.items()):
2897 + print(f" {url}\n {fp}")
2898 +
2899 +# =============================================================================
2900 +# ATOMOWA INSTALACJA (STAGING)
2901 +# =============================================================================
2902 +
2903 +def _safe_rename(src: str, dst: str) -> bool:
2904 + """
2905 + Atomowe przeniesienie pliku. Jeśli src i dst są na różnych
2906 + systemach plików (EXDEV), kopiuje + usuwa źródło.
2907 + """
2908 + try:
2909 + os.rename(src, dst)
2910 + return True
2911 + except OSError as e:
2912 + if e.errno == 18: # EXDEV – cross-device link
2913 + shutil.copy2(src, dst)
2914 + os.remove(src)
2915 + return True
2916 + raise
2917 +
2918 +
2919 +def _install_file(src: str, rel: str, data_staging: str, sums: dict,
2920 + staging: str, journal: list, installed_files: list,
2921 + deploy_dir: str = "", backup_dir: str = "",
2922 + backup_journal: Optional[list] = None,
2923 + old_checksums: Optional[dict] = None,
2924 + privileged=frozenset()) -> bool:
2925 + """
2926 + Instaluje pojedynczy plik (zwykły lub symlink).
2927 + Obsługuje: cross-device rename, symlinki, weryfikację SHA256.
2928 +
2929 + Jeśli deploy_dir jest podany (tryb immutable), pliki systemowe trafiają
2930 + do deploymentu, a współdzielone (/var, /etc, ...) bezpośrednio do /.
2931 +
2932 + Jeśli backup_dir jest podany, a pod dst istnieje już plik (upgrade/reinstall),
2933 + stara wersja jest przenoszona do backup_dir, by rollback mógł ją przywrócić.
2934 +
2935 + old_checksums: {ścieżka: sha256 z chwili instalacji}. Gdy podane i plik /etc
2936 + został zmodyfikowany przez użytkownika, nowa wersja ląduje jako .pacnew
2937 + (stary plik NIE jest ruszany) – wzorzec jak w pacmanie.
2938 + """
2939 + # W trybie immutable: pliki współdzielone idą do /, reszta do deploymentu
2940 + if deploy_dir and _is_shared_path("/" + rel):
2941 + dst_root = PAG_ROOT
2942 + elif deploy_dir:
2943 + dst_root = deploy_dir
2944 + else:
2945 + dst_root = PAG_ROOT
2946 +
2947 + dst = os.path.join(dst_root, rel)
2948 +
2949 + # --- SYMLINK ---
2950 + if os.path.islink(src):
2951 + link_target = os.readlink(src)
2952 + # Weryfikuj sums.json dla symlinka (hash ścieżki docelowej)
2953 + expected = sums.get("/" + rel, "")
2954 + if expected:
2955 + link_hash = hashlib.sha256(link_target.encode()).hexdigest()
2956 + if expected and link_hash != expected:
2957 + return False
2958 +
2959 + os.makedirs(os.path.dirname(dst), exist_ok=True)
2960 + # Backup istniejącego symlinka (upgrade) – dla poprawnego rollbacku
2961 + if backup_dir and backup_journal is not None and os.path.lexists(dst):
2962 + try:
2963 + backup_path = os.path.join(backup_dir, rel)
2964 + os.makedirs(os.path.dirname(backup_path), exist_ok=True)
2965 + os.replace(dst, backup_path)
2966 + backup_journal.append((backup_path, "/" + rel))
2967 + journal.append(("backup", backup_path, dst))
2968 + except OSError:
2969 + pass
2970 + # Jeśli docelowy symlink już istnieje, usuń go
2971 + if os.path.islink(dst) or os.path.exists(dst):
2972 + os.remove(dst)
2973 + os.symlink(link_target, dst)
2974 + journal.append(("symlink", "", dst))
2975 + installed_files.append({
2976 + "path": "/" + rel,
2977 + "sha256": hashlib.sha256(link_target.encode()).hexdigest(),
2978 + "size": len(link_target),
2979 + "is_symlink": True,
2980 + "symlink_target": link_target,
2981 + })
2982 + return True
2983 +
2984 + # --- ZWYKŁY PLIK ---
2985 + # Oblicz SHA256
2986 + try:
2987 + file_sha = _sha256_file(src)
2988 + except Exception:
2989 + file_sha = ""
2990 +
2991 + # Weryfikuj sums.json
2992 + expected = sums.get("/" + rel, "")
2993 + if expected and file_sha and file_sha != expected:
2994 + return False
2995 +
2996 + # --- .pacnew: NIE nadpisuj pliku konfiguracyjnego, którego nie wolno zgubić ---
2997 + # Robimy `<plik>.pacnew`, gdy:
2998 + # a) plik jest śledzony i użytkownik go zmodyfikował (hash != zapisanej sumy),
2999 + # b) to wrażliwa konfiguracja (/etc/pam.d, /etc/security, sudoers, shadow…),
3000 + # a treść na dysku różni się od tej z pakietu – chroni auth przed
3001 + # cichym nadpisaniem przez `install`/`upgrade` (np. przez shadow).
3002 + # NIE robimy .pacnew, jeśli plik na dysku jest identyczny z nowym albo był
3003 + # niezmieniony od instalacji (wtedy nadpisanie jest bezpieczne).
3004 + old_sha = (old_checksums or {}).get("/" + rel, "")
3005 + if file_sha and _is_config_path(rel) and os.path.isfile(dst) and not os.path.islink(dst):
3006 + tracked_modified = bool(old_sha) and file_sha != old_sha
3007 + if tracked_modified or _is_sensitive_config(rel):
3008 + try:
3009 + cur_sha = _sha256_file(dst)
3010 + except OSError:
3011 + cur_sha = ""
3012 + if cur_sha and cur_sha != file_sha and not (old_sha and cur_sha == old_sha):
3013 + pacnew = dst + ".pacnew"
3014 + try:
3015 + _safe_rename(src, pacnew)
3016 + try:
3017 + os.chown(pacnew, 0, 0)
3018 + except (OSError, PermissionError):
3019 + pass
3020 + # Journal (do cofnięcia przy nieudanej transakcji) – ale NIE
3021 + # zapisujemy .pacnew w bazie plików: to artefakt użytkownika.
3022 + journal.append(("file", src, pacnew))
3023 + print(f" ⚠ {_('conf_pacnew', path=pacnew)}")
3024 + return True
3025 + except OSError:
3026 + pass # nie udało się – kontynuuj normalną instalację
3027 +
3028 + # Utwórz katalog docelowy
3029 + os.makedirs(os.path.dirname(dst), exist_ok=True)
3030 +
3031 + # Backup istniejącego pliku (upgrade) – dla poprawnego rollbacku
3032 + if backup_dir and backup_journal is not None and os.path.lexists(dst):
3033 + try:
3034 + backup_path = os.path.join(backup_dir, rel)
3035 + os.makedirs(os.path.dirname(backup_path), exist_ok=True)
3036 + os.replace(dst, backup_path)
3037 + backup_journal.append((backup_path, "/" + rel))
3038 + journal.append(("backup", backup_path, dst))
3039 + except OSError:
3040 + pass
3041 +
3042 + # Atomowe przeniesienie (z fallbackiem dla cross-device).
3043 + # Zachowuje bity uprawnień (SUID/SGID/sticky) – NIE używamy filter='data'.
3044 + _safe_rename(src, dst)
3045 +
3046 + if "/" + rel in privileged:
3047 + # Plik uprzywilejowany: zostaw właściciela, grupę i bity z pakietu
3048 + # (np. sudo 4755 root:root, qemu-bridge-helper 4750 root:kvm).
3049 + try:
3050 + st = os.stat(dst)
3051 + if st.st_mode & 0o6000:
3052 + _audit(f"privileged {dst} mode={oct(st.st_mode & 0o7777)} "
3053 + f"uid={st.st_uid} gid={st.st_gid}")
3054 + except OSError:
3055 + pass
3056 + else:
3057 + # Wymuś właściciela root:root. UWAGA: os.chown() NIE czyści bitów SUID/SGID.
3058 + try:
3059 + os.chown(dst, 0, 0)
3060 + except (OSError, PermissionError):
3061 + # Na niektórych systemach plików (tmpfs, fat) chown może się nie powieść
3062 + pass
3063 +
3064 + journal.append(("file", src, dst))
3065 + installed_files.append({
3066 + "path": "/" + rel,
3067 + "sha256": file_sha,
3068 + "size": os.path.getsize(dst),
3069 + "is_symlink": False,
3070 + })
3071 + return True
3072 +
3073 +
3074 +
3075 +def _stage_package(pkg_path: str, pkg: PackageInfo) -> Optional[dict]:
3076 + """Rozpakowuje pakiet do stagingu, NIE dotykając systemu.
3077 +
3078 + Zwraca dict: staging, data, sums, hooks. None przy błędzie.
3079 +
3080 + To pierwsza faza transakcji grupowej: najpierw przygotowujemy WSZYSTKIE
3081 + pakiety (np. całe GNOME – 50 paczek). Dopiero gdy każda się rozpakuje i
3082 + przejdzie weryfikację SHA256, przechodzimy do fazy commit. Błąd jednej
3083 + paczki nie zostawia więc systemu w połowie instalacji.
3084 + """
3085 + staging = tempfile.mkdtemp(dir=STAGING_DIR, prefix=f".stage-{pkg.name}-")
3086 + try:
3087 + with tarfile.open(pkg_path, "r:xz") as tf:
3088 + _safe_extractall(tf, staging)
3089 +
3090 + data_tar = os.path.join(staging, "data.tar.xz")
3091 + if not os.path.exists(data_tar):
3092 + raise RuntimeError(_("pkg_missing_data_tar"))
3093 +
3094 + data_staging = os.path.join(staging, "data")
3095 + os.makedirs(data_staging, exist_ok=True)
3096 + priv = PRIVILEGED_PATHS | frozenset(pkg.privileged or ())
3097 + with tarfile.open(data_tar, "r:xz") as tf:
3098 + _safe_extractall(tf, data_staging, privileged=priv)
3099 +
3100 + sums_path = os.path.join(data_staging, "sums.json")
3101 + sums = json.load(open(sums_path)) if os.path.exists(sums_path) else {}
3102 +
3103 + # Weryfikacja SHA256 JUŻ w stagingu – uszkodzona paczka nie dojdzie
3104 + # do fazy commit, więc nie zdąży nadpisać żadnego pliku w systemie.
3105 + _bad: List[str] = []
3106 + for _root, _dirs, _files in os.walk(data_staging):
3107 + for _name in list(_dirs) + _files:
3108 + if _name == "sums.json":
3109 + continue
3110 + _fp = os.path.join(_root, _name)
3111 + _rel = "/" + os.path.relpath(_fp, data_staging)
3112 + _expected = sums.get(_rel, "")
3113 + if not _expected:
3114 + continue
3115 + try:
3116 + if os.path.islink(_fp):
3117 + _actual = hashlib.sha256(
3118 + os.readlink(_fp).encode()).hexdigest()
3119 + elif os.path.isfile(_fp):
3120 + _actual = _sha256_file(_fp)
3121 + else:
3122 + continue
3123 + except OSError:
3124 + _actual = ""
3125 + if _actual != _expected:
3126 + _bad.append(_rel)
3127 + if len(_bad) >= 5:
3128 + break
3129 + if len(_bad) >= 5:
3130 + break
3131 + if _bad:
3132 + raise RuntimeError(_("pkg_sha_mismatch", ", ".join(_bad[:5])))
3133 +
3134 + return {
3135 + "staging": staging,
3136 + "data": data_staging,
3137 + "sums": sums,
3138 + "hooks": os.path.join(staging, "hooks"),
3139 + }
3140 + except Exception as e:
3141 + shutil.rmtree(staging, ignore_errors=True)
3142 + print(_(' ❌ {arg1}: preparation stage failed ({arg2})', arg1=(pkg.name), arg2=(e)))
3143 + return None
3144 +
3145 +
3146 +def _discard_staged(staged: Optional[dict]):
3147 + """Usuwa katalog stagingu przygotowanego pakietu (bez zmian w systemie)."""
3148 + if staged and staged.get("staging"):
3149 + shutil.rmtree(staged["staging"], ignore_errors=True)
3150 +
3151 +
3152 +def _apply_staged_package(staged: dict, pkg: PackageInfo, deploy_dir: str = "",
3153 + backup_dir: str = "",
3154 + old_checksums: Optional[dict] = None
3155 + ) -> Tuple[bool, List[dict], List[Tuple[str, str]]]:
3156 + """Faza commit: przenosi przygotowany pakiet do systemu.
3157 +
3158 + Hooki pre/post-install uruchamiane są tutaj – dopiero po tym, jak cała
3159 + grupa pakietów została poprawnie rozpakowana w stagingu.
3160 + """
3161 + staging = staged["staging"]
3162 + data_staging = staged["data"]
3163 + sums = staged["sums"]
3164 + hooks_dir = staged["hooks"]
3165 + priv = PRIVILEGED_PATHS | frozenset(pkg.privileged or ())
3166 + journal: List[tuple] = []
3167 + installed_files: List[dict] = []
3168 + backup_journal: List[Tuple[str, str]] = []
3169 +
3170 + try:
3171 + # Hook pre-install (przed przeniesieniem plików do systemu)
3172 + _run_hook(hooks_dir, "pre-install", pkg)
3173 +
3174 + # Przenieś pliki: staging/data/* → /
3175 + for root, dirs, files in os.walk(data_staging):
3176 + # Symlink do katalogu (np. /lib → usr/lib) os.walk zwraca w `dirs`.
3177 + # Nie wolno tworzyć z niego prawdziwego katalogu – przekieruj do
3178 + # pętli plików, gdzie _install_file odtworzy symlink.
3179 + for _d in list(dirs):
3180 + if os.path.islink(os.path.join(root, _d)):
3181 + dirs.remove(_d)
3182 + files.append(_d)
3183 +
3184 + # Odtwórz katalogi z pakietu – w tym PUSTE (np. /etc/pulse/default.pa.d).
3185 + for d in dirs:
3186 + src_dir = os.path.join(root, d)
3187 + rel_dir = os.path.relpath(src_dir, data_staging)
3188 + if deploy_dir and _is_shared_path("/" + rel_dir):
3189 + dst_root = PAG_ROOT
3190 + elif deploy_dir:
3191 + dst_root = deploy_dir
3192 + else:
3193 + dst_root = PAG_ROOT
3194 + dst_dir = os.path.join(dst_root, rel_dir)
3195 + if not os.path.isdir(dst_dir):
3196 + try:
3197 + os.makedirs(dst_dir, exist_ok=True)
3198 + except OSError:
3199 + pass
3200 + for fname in files:
3201 + if fname == "sums.json":
3202 + continue
3203 + src = os.path.join(root, fname)
3204 + rel = os.path.relpath(src, data_staging)
3205 +
3206 + ok = _install_file(src, rel, data_staging, sums,
3207 + staging, journal, installed_files, deploy_dir,
3208 + backup_dir, backup_journal,
3209 + old_checksums=old_checksums,
3210 + privileged=priv)
3211 + if not ok:
3212 + # Cofnij wszystkie operacje
3213 + _rollback_journal(journal, staging)
3214 + return False, [], backup_journal
3215 +
3216 + # Odbuduj cache ikon GTK dla motywów dotkniętych instalacją.
3217 + _icon_dirs = set()
3218 + for f in installed_files:
3219 + fp = f.get("path", "") or ""
3220 + if fp.startswith("/usr/share/icons/"):
3221 + _rest = fp[len("/usr/share/icons/"):]
3222 + _theme = _rest.split("/", 1)[0]
3223 + if _theme:
3224 + _icon_dirs.add(os.path.join(PAG_ROOT, "usr/share/icons", _theme))
3225 + if _icon_dirs:
3226 + try:
3227 + subprocess.run(["gtk-update-icon-cache", "--version"],
3228 + capture_output=True, timeout=10)
3229 + for _d in sorted(_icon_dirs):
3230 + if os.path.isdir(_d):
3231 + subprocess.run(["gtk-update-icon-cache", "-f", "-q", _d],
3232 + capture_output=True, timeout=300)
3233 + except Exception:
3234 + pass
3235 +
3236 + # Uruchom hooki post-install
3237 + _run_hook(hooks_dir, "post-install", pkg)
3238 +
3239 + # Zachowaj hooki na wypadek usunięcia pakietu (pre/post-remove)
3240 + try:
3241 + if os.path.isdir(hooks_dir):
3242 + persisted = os.path.join(PAG_DB, "hooks", pkg.name)
3243 + shutil.rmtree(persisted, ignore_errors=True)
3244 + shutil.copytree(hooks_dir, persisted)
3245 + except Exception:
3246 + pass
3247 +
3248 + # Zapisz do SQLite
3249 + _db_record_files(pkg.name, installed_files)
3250 +
3251 + shutil.rmtree(staging, ignore_errors=True)
3252 + return True, installed_files, backup_journal
3253 +
3254 + except Exception as e:
3255 + _rollback_journal(journal, staging)
3256 + print(_(' ❌ {arg1}: commit error – {arg2}', arg1=(pkg.name), arg2=(e)))
3257 + return False, [], backup_journal
3258 +
3259 +
3260 +def _atomic_install(pkg_path: str, pkg: PackageInfo, deploy_dir: str = "",
3261 + backup_dir: str = "",
3262 + old_checksums: Optional[dict] = None
3263 + ) -> Tuple[bool, List[dict], List[Tuple[str, str]]]:
3264 + """Instaluje pojedynczy pakiet dwufazowo: staging → commit.
3265 +
3266 + Zachowane jako publiczny wrapper dla instalacji pojedynczych plików
3267 + lokalnych; transakcja grupowa w cmd_install przygotowuje staging dla
3268 + całej grupy i wywołuje _apply_staged_package bezpośrednio.
3269 + """
3270 + staged = _stage_package(pkg_path, pkg)
3271 + if not staged:
3272 + return False, [], []
3273 + return _apply_staged_package(staged, pkg, deploy_dir, backup_dir, old_checksums)
3274 +
3275 +def _refresh_dynamic_linker_cache(deploy_dir: str = "") -> bool:
3276 + """Odświeża cache ld.so po udanej instalacji pakietów."""
3277 + ldconfig = shutil.which("ldconfig")
3278 + if not ldconfig:
3279 + print(_(' ⚠ ldconfig not found — linker cache was not refreshed.'),
3280 + file=sys.stderr)
3281 + return False
3282 +
3283 + target_root = deploy_dir or PAG_ROOT
3284 + command = [ldconfig]
3285 + if target_root != "/":
3286 + command.extend(["-r", target_root])
3287 +
3288 + try:
3289 + subprocess.run(command, check=True, timeout=60,
3290 + stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
3291 + text=True)
3292 + return True
3293 + except (OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc:
3294 + detail = getattr(exc, "stderr", None) or str(exc)
3295 + print(_(' ⚠ Failed to refresh ld.so cache: {arg1}', arg1=(detail.strip())),
3296 + file=sys.stderr)
3297 + return False
3298 +
3299 +
3300 +def _rollback_journal(journal: list, staging_path: str):
3301 + """Cofa wszystkie operacje z journala (odwrotna kolejność)."""
3302 + for entry in reversed(journal):
3303 + op = entry[0]
3304 + if op == "file":
3305 + _, src, dst = entry
3306 + try:
3307 + if os.path.exists(dst) or os.path.islink(dst):
3308 + _safe_rename(dst, src)
3309 + except Exception:
3310 + pass
3311 + elif op == "symlink":
3312 + _, _, dst = entry
3313 + try:
3314 + if os.path.islink(dst) or os.path.exists(dst):
3315 + os.remove(dst)
3316 + except Exception:
3317 + pass
3318 + elif op == "backup":
3319 + # Przywróć starą wersję pliku z backupu (upgrade)
3320 + _, bpath, dst = entry
3321 + try:
3322 + if os.path.lexists(bpath):
3323 + os.replace(bpath, dst)
3324 + except Exception:
3325 + pass
3326 + shutil.rmtree(staging_path, ignore_errors=True)
3327 +
3328 +# =============================================================================
3329 +# BEZPIECZNE USUWANIE
3330 +# =============================================================================
3331 +
3332 +def _safe_remove_files(pkg_name: str, installed_db: dict) -> Tuple[int, List[str]]:
3333 + """
3334 + Usuwa pliki pakietu, ale tylko jeśli NIE są współdzielone z innym pakietem.
3335 + Zwraca (liczba usuniętych, [lista usuniętych ścieżek]).
3336 + """
3337 + pkg_files = _db_get_package_files(pkg_name)
3338 + recorded = _db_get_package_checksums(pkg_name)
3339 + removed = []
3340 + skipped_shared = []
3341 + skipped_sensitive = []
3342 +
3343 + for fpath in pkg_files:
3344 + owners = _db_get_file_owners(fpath)
3345 + # Sprawdź czy inny ZAINSTALOWANY pakiet też jest właścicielem
3346 + other_owners = [o for o in owners if o != pkg_name and o in installed_db]
3347 +
3348 + if other_owners:
3349 + # Plik współdzielony – tylko usuń wpis w DB, nie kasuj pliku
3350 + skipped_shared.append(fpath)
3351 + continue
3352 +
3353 + full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
3354 + if os.path.isfile(full) or os.path.islink(full):
3355 + # Wrażliwej konfiguracji systemowej (/etc/pam.d, sudoers, shadow…)
3356 + # NIE kasujemy przy `remove` – jej brak potrafi zablokować logowanie
3357 + # i sudo (np. usunięcie system-auth/system-account). Zostaje wpis w bazie.
3358 + if _is_sensitive_config(fpath):
3359 + skipped_sensitive.append(fpath)
3360 + continue
3361 + # .pacsave: zachowaj ZMIENIONY plik konfiguracyjny zamiast kasować
3362 + # (porównanie z sumą z chwili instalacji), wzorzec jak w pacmanie.
3363 + if not os.path.islink(full) and _is_config_path(fpath):
3364 + old_sha = recorded.get(fpath, "")
3365 + if old_sha:
3366 + try:
3367 + cur_sha = _sha256_file(full)
3368 + except OSError:
3369 + cur_sha = ""
3370 + if cur_sha and cur_sha != old_sha:
3371 + pacsave = full + ".pacsave"
3372 + try:
3373 + os.replace(full, pacsave)
3374 + print(f" ⚠ {_('conf_pacsave', path=pacsave)}")
3375 + removed.append(fpath)
3376 + continue
3377 + except OSError:
3378 + pass
3379 + os.remove(full)
3380 + removed.append(fpath)
3381 +
3382 + # Usuń puste katalogi (od najgłębszych)
3383 + dirs = set()
3384 + for fpath in removed + skipped_shared:
3385 + parent = os.path.dirname(fpath)
3386 + while parent and parent != "/":
3387 + dirs.add(parent)
3388 + parent = os.path.dirname(parent)
3389 +
3390 + for d in sorted(dirs, key=len, reverse=True):
3391 + full_d = os.path.join(PAG_ROOT, d.lstrip("/"))
3392 + if os.path.isdir(full_d):
3393 + try:
3394 + os.rmdir(full_d)
3395 + except OSError:
3396 + pass # nie jest pusty – OK
3397 +
3398 + # Usuń z SQLite
3399 + _db_remove_package_files(pkg_name)
3400 +
3401 + if skipped_shared:
3402 + print(_(' ⚠ {arg1} shared files preserved', arg1=(len(skipped_shared))))
3403 + if skipped_sensitive:
3404 + print(_(' ⚠ {arg1} sensitive system files preserved', arg1=(len(skipped_sensitive))))
3405 +
3406 + return len(removed) + len(skipped_shared) + len(skipped_sensitive), removed
3407 +
3408 +
3409 +def _remove_stale_files(pkg_name: str, old_files: List[str], new_paths: List[str],
3410 + installed_db: dict, deploy_dir: str = "",
3411 + backup_dir: str = "", backup_journal: Optional[list] = None) -> Tuple[int, List[str]]:
3412 + """
3413 + Po upgrade usuwa pliki starej wersji, których nie ma w nowej.
3414 +
3415 + - Pliki współdzielone z innym zainstalowanym pakietem są ZACHOWYWANE
3416 + (usuwany jest tylko wpis z bazy `files` dla tego pakietu).
3417 + - Sprząta puste katalogi i wpisy SQLite starej wersji.
3418 + Zwraca (liczba usuniętych, [usunięte ścieżki]).
3419 + """
3420 + new_set = set(new_paths)
3421 + # Warianty /usr/lib <-> /usr/lib64: plik obecny w nowej wersji pod równoważną
3422 + # ścieżką NIE jest przestarzały. Bez tego upgrade kasował właśnie
3423 + # zainstalowany plik, gdy stara i nowa wersja używały różnych libdir
3424 + # (kolizja lib/lib64).
3425 + new_effective = set()
3426 + for _p in new_set:
3427 + new_effective.add(_p)
3428 + if _p.startswith("/usr/lib64/"):
3429 + new_effective.add("/usr/lib/" + _p[len("/usr/lib64/"):])
3430 + elif _p.startswith("/usr/lib/"):
3431 + new_effective.add("/usr/lib64/" + _p[len("/usr/lib/"):])
3432 + stale = [f for f in old_files if f not in new_effective]
3433 + if not stale:
3434 + return 0, []
3435 +
3436 + root = deploy_dir or PAG_ROOT
3437 + removed = []
3438 + skipped = 0
3439 + for fpath in stale:
3440 + owners = _db_get_file_owners(fpath)
3441 + other_owners = [o for o in owners if o != pkg_name and o in installed_db]
3442 + if other_owners:
3443 + # Współdzielony z innym pakietem – tylko usuń wpis z DB dla tego pakietu
3444 + skipped += 1
3445 + else:
3446 + # Wrażliwych plików systemowych NIE kasujemy, gdy nowy pakiet ich już
3447 + # nie dostarcza (np. shadow przestaje pakować system-*). Ich brak
3448 + # blokuje login/sudo; usuwamy więc tylko wpis w bazie.
3449 + if _is_sensitive_config(fpath):
3450 + skipped += 1
3451 + else:
3452 + # Gdy nowa wersja pliku /etc trafiła do .pacnew, plik użytkownika
3453 + # MUSI zostać – nie jest „przestarzały”. Zachowujemy też wpis w bazie
3454 + # (stara suma), by kolejny upgrade dalej wykrywał zmiany użytkownika.
3455 + if _is_config_path(fpath):
3456 + _cfg_full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
3457 + if os.path.lexists(_cfg_full + ".pacnew"):
3458 + skipped += 1
3459 + continue
3460 + full = os.path.join(root, fpath.lstrip("/"))
3461 + if os.path.isfile(full) or os.path.islink(full):
3462 + try:
3463 + if backup_dir and backup_journal is not None:
3464 + backup_path = os.path.join(backup_dir, fpath.lstrip("/"))
3465 + os.makedirs(os.path.dirname(backup_path), exist_ok=True)
3466 + os.replace(full, backup_path) # przenieś do backupu (rollback)
3467 + backup_journal.append((backup_path, fpath))
3468 + else:
3469 + os.remove(full)
3470 + removed.append(fpath)
3471 + except OSError:
3472 + pass
3473 + # Usuń wpis `files` dla tego pakietu (stara wersja już go nie zawiera)
3474 + with _db_session() as db:
3475 + db.execute("DELETE FROM files WHERE package=? AND path=?", (pkg_name, fpath))
3476 +
3477 + # Usuń puste katalogi (od najgłębszych)
3478 + dirs = set()
3479 + for fpath in removed:
3480 + parent = os.path.dirname(fpath)
3481 + while parent and parent != "/":
3482 + dirs.add(parent)
3483 + parent = os.path.dirname(parent)
3484 + for d in sorted(dirs, key=len, reverse=True):
3485 + full_d = os.path.join(root, d.lstrip("/"))
3486 + if os.path.isdir(full_d):
3487 + try:
3488 + os.rmdir(full_d)
3489 + except OSError:
3490 + pass # nie jest pusty – OK
3491 +
3492 + if removed:
3493 + print(_(' 🧹 Removed {arg1} obsolete files ({arg2})', arg1=(len(removed)), arg2=(pkg_name)))
3494 + if skipped:
3495 + print(_(' ⚠ {arg1} shared files preserved', arg1=(skipped)))
3496 +
3497 + return len(removed), removed
3498 +
3499 +
3500 +def _new_transaction_backup_root() -> str:
3501 + """Katalog na backupy NADPISYWANYCH plików dla bieżącej transakcji.
3502 +
3503 + Tworzony dla KAŻDEJ transakcji, nie tylko upgrade: „świeża” instalacja
3504 + pakietu też potrafi nadpisać pliki spoza bazy pag (baza rootfs/ISO).
3505 + Gdy transakcja padnie, rollback MUSI mieć co przywrócić – inaczej kasuje
3506 + te pliki (tak zniknął m.in. libpam.so.0 i przestał działać sudo)."""
3507 + txn = datetime.now().strftime("%Y%m%dT%H%M%S") + "-" + str(os.getpid())
3508 + root = os.path.join(STAGING_DIR, "backups", txn)
3509 + os.makedirs(root, exist_ok=True)
3510 + return root
3511 +
3512 +
3513 +def _purge_old_backups(keep_root: str = ""):
3514 + """Usuwa backupy starszych transakcji (zostawia bieżący – dla `pag rollback`)."""
3515 + base = os.path.join(STAGING_DIR, "backups")
3516 + if not os.path.isdir(base):
3517 + return
3518 + for entry in os.listdir(base):
3519 + p = os.path.join(base, entry)
3520 + if p != keep_root and os.path.isdir(p):
3521 + shutil.rmtree(p, ignore_errors=True)
3522 +
3523 +
3524 +def _recover_interrupted_transactions(verbose=True) -> int:
3525 + """Przywraca pliki po transakcji PRZERWANEJ w polowie (crash / kill -9).
3526 +
3527 + Backup transakcji (/.pag_staging/backups/<txn>) powstaje, ZANIM pliki zostana
3528 + podmienione. Jesli pag zginie w trakcie, czesc plikow jest juz przeniesiona do
3529 + backupu, a nowych jeszcze nie ma -> system zostaje bez pliku.
3530 +
3531 + Dla kazdego katalogu backupu, ktory NIE jest zapisany w historii jako UDANA
3532 + transakcja (`upgrade_backup_root` przy `success=true`; takie zostawiamy dla
3533 + `pag rollback`), przywracamy pliki nieobecne w systemie. Potem odswiezamy
3534 + cache linkera.
3535 + """
3536 + base = os.path.join(STAGING_DIR, "backups")
3537 + if not os.path.isdir(base):
3538 + return 0
3539 + try:
3540 + history = load_json(HISTORY_FILE) or []
3541 + except Exception:
3542 + history = []
3543 + done_roots = {
3544 + e.get("upgrade_backup_root") for e in history
3545 + if isinstance(e, dict) and e.get("success") and e.get("upgrade_backup_root")
3546 + }
3547 + restored = 0
3548 + for txn in sorted(os.listdir(base)):
3549 + root = os.path.join(base, txn)
3550 + if not os.path.isdir(root) or root in done_roots:
3551 + continue
3552 + for dirpath, _dirs, files in os.walk(root):
3553 + for fn in files:
3554 + src = os.path.join(dirpath, fn)
3555 + rel = os.path.relpath(src, root)
3556 + dst = os.path.join(PAG_ROOT, rel)
3557 + if os.path.lexists(dst):
3558 + continue
3559 + try:
3560 + os.makedirs(os.path.dirname(dst), exist_ok=True)
3561 + if os.path.islink(src):
3562 + os.symlink(os.readlink(src), dst)
3563 + else:
3564 + shutil.copy2(src, dst)
3565 + restored += 1
3566 + except OSError:
3567 + pass
3568 + if restored:
3569 + try:
3570 + subprocess.run(["ldconfig"], capture_output=True, timeout=120)
3571 + except Exception:
3572 + pass
3573 + if verbose:
3574 + print(_(' 🛠 Interrupted transaction detected – restored {arg1} missing files.', arg1=(restored)))
3575 + return restored
3576 +
3577 +
3578 +# =============================================================================
3579 +# HOOKI
3580 +# =============================================================================
3581 +# Hooki uruchamiają dowolny plik z pakietu jako root — to naturalna cecha
3582 +# menedżera pakietów (apt/pacman też tak mają), dlatego MUSISZ ufać repozytorium.
3583 +# Aby ograniczyć ryzyko:
3584 +# - hook dostaje minimalne, "czyste" środowisko (bez LD_PRELOAD, BASH_ENV itp.)
3585 +# - hooki można wyłączyć (PAG_NO_HOOKS=1) i ustawić timeout (PAG_HOOK_TIMEOUT)
3586 +# - każde uruchomienie jest logowane do /var/log/pag/audit.log
3587 +# - hook ma wersjonowane API (PKG_HOOK_API)
3588 +# =============================================================================
3589 +
3590 +# Lista wykonanych hooków — trafia do wpisu transakcji (informacja w rejestrze).
3591 +_HOOKS_RUN: List[str] = []
3592 +
3593 +
3594 +def _hook_env(pkg: PackageInfo, hook_name: str) -> dict:
3595 + """Buduje minimalne środowisko dla hooka (bez niebezpiecznych zmiennych)."""
3596 + return {
3597 + "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
3598 + "HOME": "/root",
3599 + "LANG": "C.UTF-8",
3600 + "LC_ALL": "C.UTF-8",
3601 + "PKG_NAME": pkg.name,
3602 + "PKG_VERSION": pkg.version,
3603 + "PKG_ACTION": hook_name,
3604 + "PKG_HOOK_API": HOOK_API_VERSION,
3605 + }
3606 +
3607 +
3608 +def _hook_timeout() -> int:
3609 + try:
3610 + return max(1, int(os.environ.get("PAG_HOOK_TIMEOUT", "60")))
3611 + except Exception:
3612 + return 60
3613 +
3614 +
3615 +def _run_hook(hooks_dir: str, hook_name: str, pkg: PackageInfo) -> bool:
3616 + """Uruchamia skrypt hooka jeśli istnieje.
3617 +
3618 + Zwraca True jeśli hook został WYKONANY (istniał i uruchomiono go), False w
3619 + pozostałych przypadkach (brak pliku, wyłączone hooki, błąd). Obsługuje
3620 + ograniczone środowisko, timeout, logowanie do audytu i rejestr w transakcji.
3621 + """
3622 + hook_path = os.path.join(hooks_dir, hook_name)
3623 + if not os.path.exists(hook_path):
3624 + return False
3625 +
3626 + if os.environ.get("PAG_NO_HOOKS", "") == "1":
3627 + print(_(' ⚠ Hook skipped (PAG_NO_HOOKS=1): {arg1} for {arg2}', arg1=(hook_name), arg2=(pkg.name)))
3628 + _audit(f"hook SKIP {hook_name} {pkg.name}-{pkg.version} (PAG_NO_HOOKS=1)")
3629 + return False
3630 +
3631 + os.chmod(hook_path, 0o755)
3632 + env = _hook_env(pkg, hook_name)
3633 + tag = f"{hook_name} {pkg.name}-{pkg.version}"
3634 + try:
3635 + result = subprocess.run([hook_path], env=env, timeout=_hook_timeout(),
3636 + check=False, capture_output=True, text=True,
3637 + cwd="/")
3638 + _HOOKS_RUN.append(tag)
3639 + if result.returncode != 0:
3640 + print(_(' ⚠ Hook {arg1} for {arg2} exited with code {arg3}', arg1=(hook_name), arg2=(pkg.name), arg3=(result.returncode)))
3641 + if result.stderr:
3642 + print(f" {result.stderr.strip()[-200:]}")
3643 + _audit(f"hook FAIL {tag} rc={result.returncode}")
3644 + else:
3645 + _audit(f"hook OK {tag}")
3646 + return True
3647 + except subprocess.TimeoutExpired:
3648 + print(_(' ⚠ Hook {arg1} for {arg2} timed out ({arg3}s)', arg1=(hook_name), arg2=(pkg.name), arg3=(_hook_timeout())))
3649 + _audit(f"hook TIMEOUT {tag}")
3650 + return False
3651 + except Exception as e:
3652 + print(_(' ⚠ Hook {arg1} for {arg2}: {arg3}', arg1=(hook_name), arg2=(pkg.name), arg3=(e)))
3653 + _audit(f"hook ERROR {tag}: {e}")
3654 + return False
3655 +
3656 +# =============================================================================
3657 +# TRANSAKCJE I ROLLBACK
3658 +# =============================================================================
3659 +
3660 +def _record_transaction(action, packages, success, snapshot, file_journal=None, hooks=None,
3661 + upgrade_backups=None, upgrade_backup_root="", snapshot_id=""):
3662 + history = load_json(HISTORY_FILE) if os.path.exists(HISTORY_FILE) else []
3663 + # Rejestr wykonanych hooków – informacja o tym, że uruchomiono kod pakietu
3664 + # jako root. Trafia do historii, by dało się później sprawdzić, co się działo.
3665 + executed_hooks = list(_HOOKS_RUN) if hooks is None else hooks
3666 + _HOOKS_RUN.clear()
3667 + entry = {
3668 + "action": action, "packages": packages, "success": success,
3669 + "timestamp": datetime.now().isoformat(),
3670 + "snapshot": snapshot,
3671 + "file_journal": file_journal, # lista plików do wycofania
3672 + "hooks": executed_hooks, # wykonane hooki (pre/post-install/remove)
3673 + }
3674 + if snapshot_id:
3675 + # Snapshot systemu (btrfs) z chwili PRZED transakcją – można z niego
3676 + # uruchomić system z menu GRUB albo podejrzeć `pag snapshot-list`.
3677 + entry["snapshot_id"] = snapshot_id
3678 + if upgrade_backups:
3679 + entry["upgrade_backups"] = upgrade_backups # {dst: backup_path}
3680 + entry["upgrade_backup_root"] = upgrade_backup_root
3681 + history.append(entry)
3682 + if len(history) > 50:
3683 + history = history[-50:]
3684 + save_json(HISTORY_FILE, history)
3685 +
3686 +def _action_label(action):
3687 + key = "action_" + str(action)
3688 + return _(key) if key in T.get("en", {}) else str(action)
3689 +
3690 +def cmd_history():
3691 + if not os.path.exists(HISTORY_FILE):
3692 + print(_("no_history")); return
3693 + history = load_json(HISTORY_FILE)
3694 + if not history:
3695 + print(_("no_history")); return
3696 + print(_('Recent transactions ({arg1}):', arg1=(len(history))))
3697 + for i, e in enumerate(reversed(history), 1):
3698 + icon = "✅" if e["success"] else "❌"
3699 + pkgs = ", ".join(e["packages"][:5])
3700 + if len(e["packages"]) > 5: pkgs += f" (+{len(e['packages'])-5})"
3701 + print(f" {i}. {icon} {_action_label(e['action'])}: {pkgs}")
3702 + print(f" {e['timestamp']}")
3703 +
3704 +def cmd_rollback():
3705 + if not os.path.exists(HISTORY_FILE):
3706 + print(_("no_history")); return 1
3707 + history = load_json(HISTORY_FILE)
3708 + if not history:
3709 + print(_("no_history")); return 1
3710 +
3711 + last = None
3712 + for e in reversed(history):
3713 + if e["success"] and e.get("snapshot"):
3714 + last = e; break
3715 +
3716 + if not last:
3717 + print(_('❌ No snapshot to restore.')); return 1
3718 +
3719 + print(_('⏪ Rolling back: {arg1} ({arg2})', arg1=(_action_label(last['action'])), arg2=(last['timestamp'])))
3720 + print(_(' Packages: {arg1}', arg1=(', '.join(last['packages'][:10]))))
3721 +
3722 + if not _ask_confirm():
3723 + return 0
3724 +
3725 + # Przywróć installed.json
3726 + save_json(INSTALLED_DB, last["snapshot"])
3727 +
3728 + # Wycofaj fizyczne pliki (jeśli zapisano journal)
3729 + # Deduplikacja: pakiet może zgłosić ten sam plik więcej niż raz (np. przez
3730 + # `provides` lub wspólną ścieżkę), a journal z historii mógł zostać zapisany
3731 + # przed dodaniem deduplikacji.
3732 + file_journal = list(dict.fromkeys(last.get("file_journal", [])))
3733 + upgrade_backups = last.get("upgrade_backups", {}) or {}
3734 + backup_root = last.get("upgrade_backup_root", "")
3735 +
3736 + # Przywróć stare wersje z backupów (upgrade) – nadpisane i usunięte stale pliki
3737 + for dst, bpath in upgrade_backups.items():
3738 + full = os.path.join(PAG_ROOT, dst.lstrip("/"))
3739 + if bpath and os.path.lexists(bpath):
3740 + try:
3741 + os.makedirs(os.path.dirname(full), exist_ok=True)
3742 + os.replace(bpath, full)
3743 + except OSError:
3744 + pass
3745 +
3746 + # Usuń nowe pliki (które nie miały poprzedniej wersji)
3747 + backed = set(upgrade_backups)
3748 + if file_journal:
3749 + for fpath in reversed(file_journal):
3750 + if fpath in backed:
3751 + continue
3752 + full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
3753 + if os.path.exists(full) or os.path.islink(full):
3754 + os.remove(full)
3755 + print(f" {_('rollback_files', len(file_journal))}")
3756 +
3757 + # Sprzątanie pustych katalogów + katalogu backupów
3758 + dirs = set()
3759 + for fpath in file_journal:
3760 + parent = os.path.dirname(fpath)
3761 + while parent and parent != "/":
3762 + dirs.add(parent)
3763 + parent = os.path.dirname(parent)
3764 + for d in sorted(dirs, key=len, reverse=True):
3765 + full_d = os.path.join(PAG_ROOT, d.lstrip("/"))
3766 + if os.path.isdir(full_d):
3767 + try:
3768 + os.rmdir(full_d)
3769 + except OSError:
3770 + pass
3771 + if backup_root:
3772 + shutil.rmtree(backup_root, ignore_errors=True)
3773 +
3774 + print(f"✅ {_('rollback_restored')}")
3775 + _record_transaction("rollback", last["packages"], True, None)
3776 + return 0
3777 +
3778 +# =============================================================================
3779 +# INSTALACJA
3780 +# =============================================================================
3781 +
3782 +def _install_local_pkg_files(paths, install_succeeded):
3783 + """Instaluje lokalne pliki .pag (bez repozytorium).
3784 +
3785 + Najpierw przygotowuje WSZYSTKIE paczki w stagingu, potem je nakłada.
3786 + Dzięki temu uszkodzony plik w środku grupy nie zostawia systemu
3787 + w połowie instalacji. Zwraca (failed_count, installed_files).
3788 + """
3789 + failed = 0
3790 + prepared = []
3791 + for p in paths:
3792 + p = os.path.abspath(p)
3793 + if not os.path.isfile(p):
3794 + print(_(' ❌ Package not found: {arg1}', arg1=(p)))
3795 + failed += 1
3796 + break
3797 + if not _verify_local_pkg_signature(p):
3798 + failed += 1
3799 + break
3800 + try:
3801 + with tarfile.open(p, "r:xz") as tf:
3802 + meta = tf.extractfile("metadata.json")
3803 + if meta is None:
3804 + print(_(' ❌ {arg1}: missing metadata.json', arg1=(p)))
3805 + failed += 1
3806 + break
3807 + data = json.loads(meta.read())
3808 + except Exception as e:
3809 + print(_(' ❌ {arg1}: failed to read package ({arg2})', arg1=(p), arg2=(e)))
3810 + failed += 1
3811 + break
3812 + pkg = PackageInfo(data, repo="local")
3813 + staged = _stage_package(p, pkg)
3814 + if not staged:
3815 + failed += 1
3816 + break
3817 + prepared.append((pkg, staged))
3818 +
3819 + if failed:
3820 + for _pkg, _st in prepared:
3821 + _discard_staged(_st)
3822 + print(_(' ↩ Preparation stage failed – the system was NOT changed.'))
3823 + return failed, []
3824 +
3825 + all_files = []
3826 + for pkg, staged in prepared:
3827 + print(_(' ↓ {arg1}-{arg2} (local) ... ', arg1=(pkg.name), arg2=(pkg.version)), end="", flush=True)
3828 + ok, files, _ = _apply_staged_package(staged, pkg)
3829 + if ok:
3830 + install_succeeded(pkg, files)
3831 + all_files.extend(f["path"] for f in files)
3832 + print("✅")
3833 + else:
3834 + print("❌")
3835 + failed += 1
3836 + return failed, all_files
3837 +
3838 +
3839 +def _preflight_disk(total_bytes: int) -> bool:
3840 + """Pre-flight przed transakcją: wolne miejsce + mount read-only.
3841 +
3842 + Zwraca False (przerywa instalację) gdy na partycji docelowej brakuje
3843 + miejsca na pakiety albo katalog stagingu jest zamontowany read-only
3844 + (inaczej instalacja rwałaby się w połowie, zostawiając uszkodzony system).
3845 + """
3846 + target = PAG_ROOT or "/"
3847 + try:
3848 + st = os.statvfs(target)
3849 + free = st.f_bavail * st.f_frsize
3850 + except OSError:
3851 + return True # nie da się sprawdzić – nie blokuj
3852 + need_mb = total_bytes // 1048576
3853 + free_mb = free // 1048576
3854 + if free < total_bytes:
3855 + print(_(' ❌ Not enough disk space: need ~{arg1} MB, free {arg2} MB ({arg3})', arg1=(need_mb), arg2=(free_mb), arg3=(target)))
3856 + return False
3857 + if free < total_bytes * 3:
3858 + print(_(' ⚠ Low disk space: {arg1} MB free, packages ~{arg2} MB (extracted will take more)', arg1=(free_mb), arg2=(need_mb)))
3859 + # Wykryj mount read-only (test zapisu w stagingu)
3860 + try:
3861 + probe = os.path.join(STAGING_DIR, ".pag-probe")
3862 + with open(probe, "w") as f:
3863 + f.write("x")
3864 + os.remove(probe)
3865 + except OSError:
3866 + print(_(' ❌ {arg1} is mounted read-only – cannot install.', arg1=(target)))
3867 + return False
3868 + return True
3869 +
3870 +
3871 +def cmd_install(package_names, as_dep=False, upgrade=False):
3872 + ensure_dirs()
3873 + installed_db = load_json(INSTALLED_DB)
3874 + world = load_world()
3875 + pinned = load_json(PINNED_FILE)
3876 +
3877 + # Obsługa lokalnych plików .pkg.tar.xz (zbudowanych przez pagbuild) –
3878 + # nie wymaga repozytorium ani GPG.
3879 + local_files = [p for p in package_names if p.endswith(PKG_EXT) or
3880 + (os.sep in p and os.path.isfile(os.path.abspath(p)))]
3881 + if local_files:
3882 + _local_need = sum(
3883 + os.path.getsize(os.path.abspath(p))
3884 + for p in local_files if os.path.isfile(os.path.abspath(p))
3885 + )
3886 + if not _preflight_disk(_local_need):
3887 + return 1
3888 +
3889 + def _ok(pkg, files):
3890 + installed_db[pkg.name] = {
3891 + "version": pkg.version, "release": pkg.release, "description": pkg.description,
3892 + "dependencies": pkg.dependencies, "size_bytes": pkg.size_bytes,
3893 + "sha256": pkg.sha256, "installed_at": datetime.now().isoformat(),
3894 + "repo": "local",
3895 + "provides": getattr(pkg, "provides", None) or [],
3896 + "provides_so": getattr(pkg, "provides_so", None) or [],
3897 + "requires_so": getattr(pkg, "requires_so", None) or [],
3898 + }
3899 + world.add(pkg.name)
3900 + failed_local, _fl = _install_local_pkg_files(local_files, _ok)
3901 + save_json(INSTALLED_DB, installed_db)
3902 + save_world(world)
3903 + if failed_local:
3904 + return 1
3905 + _refresh_dynamic_linker_cache()
3906 + package_names = [n for n in package_names if n not in
3907 + [os.path.abspath(x) for x in local_files] and
3908 + n not in local_files]
3909 + to_install = []
3910 + if not package_names:
3911 + return 0
3912 + # pozostałe argumenty to nazwy pakietów z repo – kontynuuj
3913 +
3914 + repo_pkgs = fetch_all_packages()
3915 +
3916 + if not repo_pkgs:
3917 + print(f"❌ {_('no_index')}"); return 1
3918 +
3919 + for name in list(package_names):
3920 + if name in pinned:
3921 + print(f"⚠ {name} {_('pinned_to')} {pinned[name]} – skipping")
3922 + package_names.remove(name)
3923 +
3924 + to_install, missing_deps = _resolve_deps(package_names, repo_pkgs, installed_db)
3925 +
3926 + # ── Pakiety, których NIE MA w repo ani nie są zainstalowane ──
3927 + # Zgłoś od razu zamiast mylącego „Do zainstalowania: N (0.00 MB)”
3928 + # i prośby o potwierdzenie (np. `pag install steam` gdy steam nie istnieje).
3929 + not_found = []
3930 + for n in package_names:
3931 + real = _resolve_provides(n, repo_pkgs, installed_db)
3932 + if real not in repo_pkgs and real not in installed_db \
3933 + and not os.path.exists(os.path.abspath(n)):
3934 + not_found.append(n)
3935 + if not_found:
3936 + print(f"\n ❌ {_('pkg_not_found', ', '.join(not_found))}")
3937 + print(f" {_('not_found_hint')}")
3938 + return 1
3939 +
3940 + # --- Tryb upgrade: pakiety już zainstalowane MUSZĄ zostać ponownie
3941 + # zainstalowane z nowszej wersji (zastąpienie w tej samej transakcji).
3942 + if upgrade:
3943 + # `pag update` przekazuje tu tylko pakiety z NOWSZĄ wersją (już
3944 + # przefiltrowane w _pending_updates), a `pag install -f` wymusza
3945 + # reinstalację nawet tej SAMEJ wersji – dlatego nie filtrujemy po
3946 + # _version_newer.
3947 + upgrade_targets = [
3948 + name for name in package_names
3949 + if name in repo_pkgs
3950 + and name in installed_db
3951 + and name not in pinned
3952 + ]
3953 + for name in upgrade_targets:
3954 + if name not in to_install:
3955 + to_install.append(name)
3956 +
3957 + if not to_install and not missing_deps:
3958 + print(f"✅ {_('all_installed')}"); return 0
3959 +
3960 + # ── WERYFIKACJA ZALEŻNOŚCI ──────────────────────────────────────────
3961 + fatal_missing = _verify_dependencies(to_install, repo_pkgs, installed_db)
3962 +
3963 + if fatal_missing > 0:
3964 + print(_('❌ Cannot continue – {arg1} missing dependencies.', arg1=(fatal_missing)))
3965 + print(_(' Install the missing packages or add repositories.'))
3966 + return 1
3967 +
3968 + so_missing = _verify_so_deps(to_install, repo_pkgs, installed_db)
3969 + if so_missing > 0:
3970 + print(_(' Install the library provider or update the repository.'))
3971 + return 1
3972 +
3973 + if not to_install:
3974 + print(f"✅ {_('all_installed')}"); return 0
3975 +
3976 + MAX_MB = MAX_PKG_SIZE // 1048576
3977 + for n in to_install:
3978 + if not _validate_pkg_name(n):
3979 + print(f" {_("sec_badname", name=n)}")
3980 + return 1
3981 + sz = repo_pkgs[n].size_bytes if n in repo_pkgs else 0
3982 + if sz > MAX_PKG_SIZE:
3983 + mb = sz // 1048576
3984 + print(f" {_("sec_toobig", size_mb=mb, max_mb=MAX_MB)}")
3985 + return 1
3986 + total_size = sum(repo_pkgs[n].size_bytes for n in to_install if n in repo_pkgs)
3987 + if not _preflight_disk(total_size):
3988 + return 1
3989 + print(f"\n📦 {_('to_install', len(to_install), total_size/1048576)}")
3990 + for name in to_install:
3991 + p = repo_pkgs.get(name)
3992 + if p:
3993 + if name in installed_db:
3994 + marker = f" {_('upgrade_marker')}" if upgrade else ""
3995 + else:
3996 + marker = f" [{_('new')}]"
3997 + print(f" {name}-{p.version}{marker}")
3998 +
3999 + # Pakiet z bazy obrazu ISO (nie w installed.json) → ostrzeż, że pliki z ISO
4000 + # zostaną zastąpione pakietem z repo (kopia do `pag rollback`).
4001 + _base_warn_overwrite(to_install)
4002 +
4003 + if not as_dep and not upgrade:
4004 + if not _ask_confirm():
4005 + print(_("cancelled")); return 0
4006 +
4007 + # `--dry-run`: pokaż plan i wyjdź. Nic nie jest pobierane, rozpakowywane
4008 + # ani zmieniane – bezpieczne sprawdzenie, co zrobiłaby transakcja.
4009 + if os.environ.get("PAG_DRY_RUN", "") == "1":
4010 + print(f"\n 🧪 {_('dry_run_plan')}")
4011 + for _n in to_install:
4012 + _p = repo_pkgs.get(_n)
4013 + if _p:
4014 + _mark = f" {_('upgrade_marker')}" if _n in installed_db else f" [{_('new')}]"
4015 + print(f" {_n}-{_p.version}{_mark}")
4016 + print(f" {_('dry_run_done')}")
4017 + return 0
4018 +
4019 + snapshot = copy.deepcopy(installed_db)
4020 + all_installed_files = []
4021 + failed = []
4022 + # Pary (pkg, stare_pliki, nowe_pliki) do usunięcia martwych plików po upgrade
4023 + stale_candidates = []
4024 + # Katalog backupów nadpisywanych plików – dla poprawnego rollbacku.
4025 + # Dla KAŻDEJ transakcji: instalacja „nowego” pakietu także nadpisuje pliki
4026 + # spoza bazy pag (baza rootfs/ISO), a rollback bez backupu by je skasował.
4027 + backup_root = ""
4028 + all_backups: List[Tuple[str, str]] = [] # (backup_path, dst)
4029 + if to_install:
4030 + backup_root = _new_transaction_backup_root()
4031 +
4032 + # --- Dziennik transakcji (dla pełnej atomowości) ---
4033 + # Jeśli którykolwiek pakiet zawiedzie, cofamy WSZYSTKIE zainstalowane
4034 + # w tej transakcji przez _rollback_transaction().
4035 + transaction_journal: List[Tuple[str, str, str]] = [] # (op, src, dst)
4036 +
4037 + # --- Tryb immutable: utwórz nowy deployment ---
4038 + immutable = os.environ.get("PAG_IMMUTABLE", "") == "1"
4039 + deploy_dir = ""
4040 + deploy_id = ""
4041 + if immutable:
4042 + print(_('\n 🏗️ Creating a new deployment...'))
4043 + deploy_dir, deploy_id = _create_deployment(to_install, "upgrade" if upgrade else "install")
4044 + target_root = deploy_dir
4045 + else:
4046 + target_root = ""
4047 +
4048 + # --- Faza 1: Równoległe pobieranie wszystkich pakietów ---
4049 + to_download = [repo_pkgs[name] for name in to_install if name in repo_pkgs]
4050 + if len(to_download) > 1:
4051 + print(_('\n ⏬ Downloading {arg1} packages in parallel...', arg1=(len(to_download))))
4052 + downloaded = _download_packages_parallel(to_download)
4053 + else:
4054 + downloaded = {}
4055 +
4056 + # --- Faza 1b: WERYFIKACJA WSZYSTKICH paczek PRZED instalacją ---
4057 + # KLUCZOWE: GPG i SHA256 sprawdzamy dla WSZYSTKICH paczek, ZANIM
4058 + # zainstalujemy choćby jedną. Inaczej instalowany pakiet może podmienić
4059 + # bibliotekę używaną przez sam gpg (np. libassuan 3.0.1 zmienił namespace
4060 + # symboli LIBASSUAN_1.0 -> LIBASSUAN_2.0) i wtedy weryfikacja kolejnych
4061 + # paczek w tej samej transakcji pada, dając fałszywe
4062 + # „NIEPRAWIDŁOWY PODPIS GPG".
4063 + verified = {}
4064 + _vfail = []
4065 + for _name in to_install:
4066 + _pkg = repo_pkgs.get(_name)
4067 + if not _pkg:
4068 + _vfail.append((_name, _('not_found')))
4069 + continue
4070 + _pp = downloaded.get(_name)
4071 + if not _pp:
4072 + _pp = _download_pkg(_pkg)
4073 + if not _pp:
4074 + _vfail.append((_name, _('download_fail')))
4075 + continue
4076 + _gok, _gmsg = _verify_pkg_gpg(_pp, repo_url=_pkg.repo_url)
4077 + if not _gok:
4078 + _vfail.append((_name, f"{_('gpg_fail')}: {_gmsg[:60]}"))
4079 + continue
4080 + if _pkg.sha256 and _sha256_file(_pp) != _pkg.sha256:
4081 + _vfail.append((_name, _('sha256_mismatch')))
4082 + continue
4083 + verified[_name] = _pp
4084 + if _vfail:
4085 + for _n, _m in _vfail:
4086 + print(f" ❌ {_n}: {_m}")
4087 + print(_(' ↩ Aborted BEFORE installation – no package was changed.'))
4088 + return 1
4089 +
4090 + # --- Snapshot systemu PRZED transakcją (btrfs CoW) ---
4091 + # Tworzymy go PO pobraniu i weryfikacji paczek, ale PRZED rozpakowaniem
4092 + # czegokolwiek do systemu. Domyślnie `auto`: tylko na btrfs. `--snapshot`
4093 + # wymusza migawkę (i przerywa, gdy się nie uda), `--no-snapshot` wyłącza.
4094 + snapshot_mode = (os.environ.get("PAG_SNAPSHOT") or "auto").strip().lower()
4095 + sys_snap: Optional[dict] = None
4096 + if to_install and snapshot_mode not in ("never", "no", "0", "off"):
4097 + _snap_ok, _snap_why = _snapshot_support()
4098 + if _snap_ok:
4099 + sys_snap = _create_system_snapshot(
4100 + to_install, "upgrade" if upgrade else "install")
4101 + if sys_snap:
4102 + _refresh_bootloader()
4103 + elif snapshot_mode in ("always", "require", "1", "yes"):
4104 + print(_(' ❌ Failed to create snapshot (--snapshot mode) – aborting.'))
4105 + return 1
4106 + elif snapshot_mode in ("always", "require", "1", "yes"):
4107 + print(f" ❌ {_('snapshot_unsupported', _snap_why)}")
4108 + return 1
4109 + else:
4110 + print(f" ℹ {_('snapshot_unsupported', _snap_why)}")
4111 +
4112 + # --- Faza 1c: PRZYGOTOWANIE CAŁEJ GRUPY W STAGINGU ---
4113 + # Rozpakowujemy WSZYSTKIE pakiety do `/.pag_staging/.stage-*`, zanim
4114 + # dotkniemy systemu. Jeśli jedna z 50 paczek (np. GNOME) jest uszkodzona,
4115 + # transakcja kończy się tutaj – na dysku nie ma żadnych zmian.
4116 + atomic = os.environ.get("PAG_ATOMIC", "1") != "0"
4117 + staged_pkgs: List[Tuple[str, PackageInfo, Optional[dict]]] = []
4118 + if atomic and to_install:
4119 + print(f"\n 🧰 {_('staging_prepare', len(to_install))}")
4120 + _sbar = _StepBar(len(to_install), icon="🧰 ", width=25)
4121 + _stage_failed: List[str] = []
4122 + for _si, _name in enumerate(to_install, 1):
4123 + _pkg = repo_pkgs.get(_name)
4124 + _pp = verified.get(_name)
4125 + if not _pkg or not _pp:
4126 + _stage_failed.append(_name)
4127 + break
4128 + _sbar.step(_si, f"{_name}-{_pkg.version}")
4129 + _st = _stage_package(_pp, _pkg)
4130 + if not _st:
4131 + _stage_failed.append(_name)
4132 + break
4133 + staged_pkgs.append((_name, _pkg, _st))
4134 + _sbar.end()
4135 + if _stage_failed:
4136 + for _n, _p, _st in staged_pkgs:
4137 + _discard_staged(_st)
4138 + print(f" ↩ {_('staging_failed')}")
4139 + if backup_root:
4140 + shutil.rmtree(backup_root, ignore_errors=True)
4141 + _record_transaction("upgrade" if upgrade else "install", to_install, False,
4142 + snapshot,
4143 + snapshot_id=sys_snap["id"] if sys_snap else "")
4144 + return 1
4145 + print(f" ✅ {_('staging_commit')}")
4146 + elif to_install:
4147 + staged_pkgs = [(n, repo_pkgs[n], None) for n in to_install]
4148 +
4149 + # --- Faza 2: Instalacja – JEDNA nadpisywana linia postępu (jak przy
4150 + # pobieraniu), bez ściany tekstu na każdy pakiet. W trybie
4151 + # nieinteraktywnym (logi, netinstall instalatora) wypisujemy linię na
4152 + # pakiet – tam to pożądane do logu.
4153 + t0 = time.time()
4154 + stdout_tty = sys.stdout.isatty()
4155 +
4156 + # Animowany pasek postępu („drakkar”) – jedna nadpisywana linia; morze
4157 + # faluje nawet wtedy, gdy pojedynczy pakiet instaluje się długo.
4158 + _pbar = _StepBar(len(to_install), icon="📦 ", width=25)
4159 +
4160 + def _bar_draw(idx: int, name: str) -> None:
4161 + _pbar.step(idx, name)
4162 +
4163 + def _bar_end() -> None:
4164 + _pbar.end()
4165 +
4166 + for _pkg_i, (name, pkg, _staged) in enumerate(staged_pkgs, 1):
4167 + if not pkg:
4168 + _bar_end()
4169 + print(f" ❌ {name}: {_('not_found')}")
4170 + failed.append(name)
4171 + break
4172 +
4173 + _bar_draw(_pkg_i, f"{name}-{pkg.version}")
4174 +
4175 + # Przed instalacją zapamiętaj pliki starej wersji (potrzebne w upgrade)
4176 + old_files = _db_get_package_files(name) if name in installed_db else []
4177 + # Stare sumy SHA256 – do wykrycia zmian użytkownika w plikach /etc (.pacnew)
4178 + old_checksums = _db_get_package_checksums(name) if name in installed_db else None
4179 +
4180 + # Commit przygotowanego pakietu (w upgrade backupuje nadpisywane pliki).
4181 + # Tryb `PAG_ATOMIC=0` zachowuje starą ścieżkę pojedynczą (staging per pakiet).
4182 + if _staged is not None:
4183 + ok, files, backup_j = _apply_staged_package(
4184 + _staged, pkg, deploy_dir,
4185 + backup_dir=backup_root,
4186 + old_checksums=old_checksums)
4187 + else:
4188 + # Ścieżka pobrana i ZWERYFIKOWANA w fazie 1b.
4189 + pkg_path = verified.get(name)
4190 + if not pkg_path:
4191 + _bar_end()
4192 + print(f" ❌ {name}: {_('download_fail')}")
4193 + failed.append(name)
4194 + break # przerwij transakcję
4195 + ok, files, backup_j = _atomic_install(
4196 + pkg_path, pkg, deploy_dir,
4197 + backup_dir=backup_root,
4198 + old_checksums=old_checksums)
4199 + if ok:
4200 + installed_db[name] = {
4201 + "version": pkg.version, "release": pkg.release, "description": pkg.description,
4202 + "dependencies": pkg.dependencies, "size_bytes": pkg.size_bytes,
4203 + "sha256": pkg.sha256, "installed_at": datetime.now().isoformat(),
4204 + "repo": pkg.repo_url,
4205 + "provides": getattr(pkg, "provides", None) or [],
4206 + "provides_so": getattr(pkg, "provides_so", None) or [],
4207 + "requires_so": getattr(pkg, "requires_so", None) or [],
4208 + }
4209 + if not as_dep and name in package_names:
4210 + world.add(name)
4211 + if not stdout_tty:
4212 + print(f" ✓ {name}-{pkg.version}", flush=True)
4213 + all_installed_files.extend(f["path"] for f in files)
4214 + all_backups.extend(backup_j)
4215 +
4216 + # Upgrade: zapamiętaj stare pliki, by po sukcesie usunąć te,
4217 + # których nie ma już w nowej wersji.
4218 + if upgrade and old_files:
4219 + stale_candidates.append((name, old_files, [f["path"] for f in files]))
4220 +
4221 + # Po instalacji kernela – przebuduj initramfs
4222 + if _is_kernel_package(name):
4223 + _rebuild_initramfs(deploy_dir)
4224 + else:
4225 + _bar_end()
4226 + print(f" ❌ {name}: {_('install_failed')}")
4227 + failed.append(name)
4228 + break # PRZERWIJ – błąd instalacji
4229 +
4230 + # Deduplikacja journalu – ten sam plik może trafić tu dwukrotnie (np. przez
4231 + # `provides`); rollback i historia nie potrzebują duplikatów.
4232 + all_installed_files = list(dict.fromkeys(all_installed_files))
4233 +
4234 + # --- Rollback całej transakcji jeśli cokolwiek zawiodło ---
4235 + if failed:
4236 + _bar_end()
4237 + print(_('\n ↩ Rolling back transaction ({arg1} errors)...', arg1=(len(failed))))
4238 + for _n, _p, _st in staged_pkgs:
4239 + _discard_staged(_st)
4240 + _rollback_transaction(installed_db, snapshot, all_installed_files,
4241 + deploy_dir, immutable, backups=all_backups)
4242 + if backup_root:
4243 + shutil.rmtree(backup_root, ignore_errors=True)
4244 + _record_transaction("upgrade" if upgrade else "install", to_install, False,
4245 + snapshot,
4246 + snapshot_id=sys_snap["id"] if sys_snap else "")
4247 + return 1
4248 +
4249 + save_json(INSTALLED_DB, installed_db)
4250 + save_world(world)
4251 +
4252 + # --- Po ZAPISANIU bazy: usuń nieaktualne pliki starych wersji (upgrade).
4253 + # Kolejność ma znaczenie: najpierw utrwalamy stan nowej wersji w bazie, a
4254 + # dopiero potem kasujemy pliki, których nowa wersja nie zawiera. Odwrotna
4255 + # kolejność (kasowanie przed zapisem) przy przerwaniu zostawiała system bez
4256 + # plików. Usunięte pliki trafiają do backupu, aby `pag rollback` mógł je
4257 + # przywrócić.
4258 + for pkg_name, old_files, new_paths in stale_candidates:
4259 + _remove_stale_files(pkg_name, old_files, new_paths, installed_db, deploy_dir,
4260 + backup_root, all_backups)
4261 + _record_transaction("upgrade" if upgrade else "install", to_install, True, snapshot,
4262 + file_journal=all_installed_files,
4263 + upgrade_backups={dst: bp for bp, dst in all_backups} if all_backups else None,
4264 + upgrade_backup_root=backup_root,
4265 + snapshot_id=sys_snap["id"] if sys_snap else "")
4266 +
4267 + # Zachowaj backupy bieżącej transakcji (dla `pag rollback`), usuń starsze.
4268 + if backup_root:
4269 + _purge_old_backups(keep_root=backup_root)
4270 +
4271 + _bar_end()
4272 +
4273 + # --- Tryb immutable: przełącz na nowy deployment ---
4274 + if immutable and not failed:
4275 + _refresh_dynamic_linker_cache(deploy_dir)
4276 + print(_('\n 🔄 Switching to deployment {arg1}...', arg1=(deploy_id)))
4277 + _switch_deployment(deploy_dir)
4278 + print(_(' ✅ Active deployment: {arg1}', arg1=(deploy_id)))
4279 + _update_grub_config()
4280 + cmd_deploy_cleanup(keep=5) # Zostawia 5 najnowszych deploymentów
4281 + print(_(' 💡 Restart required to reload the system.'))
4282 + else:
4283 + _refresh_dynamic_linker_cache()
4284 + # Hooki zbiorcze – raz na transakcję (fc-cache itp.), tylko gdy pliki
4285 + # trafiły do realnego systemu (nie do deploymentu).
4286 + _process_triggers(all_installed_files)
4287 + # Jądro zmienione na ZWYKŁEJ instalacji → odśwież GRUB (hook pakietu
4288 + # nie może: trzymany lock PAG-a). Bez tego menu zostaje przy starym jądrze.
4289 + if any(_is_kernel_package(_n) for _n in to_install):
4290 + _post_kernel_hooks()
4291 + elif sys_snap:
4292 + # Snapshot istnieje, ale nie było zmiany jądra – odśwież menu GRUB,
4293 + # żeby wpis migawki był widoczny przy najbliższym starcie.
4294 + _ensure_snapshot_grub_script()
4295 + _refresh_bootloader()
4296 +
4297 + print(f"\n✅ {_('installed', len(to_install))} ({(time.time()-t0):.0f}s)")
4298 + return 0
4299 +
4300 +
4301 +def _rollback_transaction(installed_db: dict, snapshot: dict,
4302 + installed_files: List[str],
4303 + deploy_dir: str, is_immutable: bool,
4304 + backups: Optional[List[Tuple[str, str]]] = None):
4305 + """
4306 + Cofa WSZYSTKIE pakiety zainstalowane w bieżącej transakcji.
4307 + Przywraca installed_db do stanu sprzed transakcji.
4308 + Usuwa fizyczne pliki z systemu (lub deploymentu w trybie immutable).
4309 + Jeśli podano `backups` (upgrade) – przywraca stare wersje nadpisanych plików.
4310 + """
4311 + # Przywróć installed_db
4312 + installed_db.clear()
4313 + installed_db.update(snapshot)
4314 +
4315 + root = deploy_dir if is_immutable else PAG_ROOT
4316 + backup_map = {dst: src for src, dst in (backups or [])}
4317 +
4318 + # Przywróć stare wersje z backupów (upgrade)
4319 + for dst, bpath in backup_map.items():
4320 + full = os.path.join(root, dst.lstrip("/"))
4321 + if os.path.lexists(bpath):
4322 + try:
4323 + os.makedirs(os.path.dirname(full), exist_ok=True)
4324 + os.replace(bpath, full)
4325 + except OSError:
4326 + pass
4327 +
4328 + # Usuń nowe pliki (które nie miały poprzedniej wersji)
4329 + for fpath in reversed(installed_files):
4330 + if fpath in backup_map:
4331 + continue
4332 + full = os.path.join(root, fpath.lstrip("/"))
4333 + if os.path.isfile(full) or os.path.islink(full):
4334 + try:
4335 + os.remove(full)
4336 + except OSError:
4337 + pass
4338 +
4339 + # Wyczyść puste katalogi
4340 + dirs_to_check = set()
4341 + for fpath in installed_files:
4342 + parent = os.path.dirname(fpath)
4343 + while parent and parent != "/":
4344 + dirs_to_check.add(parent)
4345 + parent = os.path.dirname(parent)
4346 + for d in sorted(dirs_to_check, key=len, reverse=True):
4347 + full_d = os.path.join(root, d.lstrip("/"))
4348 + if os.path.isdir(full_d):
4349 + try:
4350 + os.rmdir(full_d)
4351 + except OSError:
4352 + pass
4353 +
4354 + # W trybie immutable: usuń nieudany deployment
4355 + if is_immutable and deploy_dir:
4356 + shutil.rmtree(deploy_dir, ignore_errors=True)
4357 +
4358 + save_json(INSTALLED_DB, snapshot)
4359 +
4360 +
4361 +# =============================================================================
4362 +# USUWANIE
4363 +# =============================================================================
4364 +
4365 +def cmd_remove(package_names):
4366 + installed_db = load_json(INSTALLED_DB)
4367 + world = load_world()
4368 + snapshot = copy.deepcopy(installed_db)
4369 + removed = []
4370 + removed_files = []
4371 +
4372 + total = len(package_names)
4373 + for i, name in enumerate(package_names, 1):
4374 + if name not in installed_db:
4375 + print(_(' ⚠ {arg1}: not installed', arg1=(name))); continue
4376 +
4377 + # Pasek postępu (animowany „drakkar” na TTY)
4378 + pct = (i - 1) / total * 100
4379 + bar = _pagan_bar(pct, 25, time.time(), animated=sys.stderr.isatty())
4380 + print(f" 🗑 [{bar}] {i}/{total} ({pct:.0f}%) ", end="\r", file=sys.stderr, flush=True)
4381 +
4382 + print(f"🗑 {name}-{installed_db[name]['version']} ...", end=" ", flush=True)
4383 +
4384 + # Pre-remove hook (jeśli dostępny w staging)
4385 + _run_hook_for_installed(name, "pre-remove")
4386 +
4387 + count, rm_files = _safe_remove_files(name, installed_db)
4388 + del installed_db[name]
4389 + world.discard(name)
4390 + removed.append(name)
4391 + removed_files.extend(rm_files)
4392 + print(_('✅ ({arg1} files)', arg1=(count)))
4393 +
4394 + # Post-remove hook + sprzątanie zapisanych hooków
4395 + _run_hook_for_installed(name, "post-remove")
4396 + shutil.rmtree(os.path.join(PAG_DB, "hooks", name), ignore_errors=True)
4397 +
4398 + save_json(INSTALLED_DB, installed_db)
4399 + save_world(world)
4400 + _record_transaction("remove", removed, True, snapshot)
4401 +
4402 + print(file=sys.stderr) # wyczyść linię paska postępu
4403 +
4404 + if not removed: return 0
4405 + print(_('\n✅ Removed {arg1}.', arg1=(len(removed))))
4406 + _process_triggers(removed_files)
4407 +
4408 + orphans = _find_orphans(installed_db, world)
4409 + if orphans:
4410 + print(f"\n💡 {_('orphans_found', len(orphans), ', '.join(sorted(orphans)[:10]))}")
4411 + print(_(" 'pag remove-orphans' to clean up."))
4412 + return 0
4413 +
4414 +def _run_hook_for_installed(pkg_name, hook_name):
4415 + """Próbuje uruchomić hook z katalogu pakietu (jeśli został zapisany)."""
4416 + hook_dir = os.path.join(PAG_DB, "hooks", pkg_name)
4417 + if os.path.isdir(hook_dir):
4418 + ver = load_json(INSTALLED_DB).get(pkg_name, {}).get("version", "")
4419 + _run_hook(hook_dir, hook_name, PackageInfo({"name": pkg_name, "version": ver}))
4420 +
4421 +
4422 +# =============================================================================
4423 +# TRIGGERS – hooki zbiorcze (raz na transakcję, nie per pakiet)
4424 +# =============================================================================
4425 +# Wzorem pacman/dpkg: pakiet/administrator deklaruje zainteresowanie ścieżkami,
4426 +# a pasujący trigger uruchamia się DOKŁADNIE RAZ na końcu transakcji
4427 +# (np. fc-cache, glib-compile-schemas, update-desktop-database) zamiast po
4428 +# każdym pakiecie z osobna.
4429 +
4430 +TRIGGERS_DIR = PAG_CONF + "/triggers"
4431 +
4432 +DEFAULT_TRIGGERS = [
4433 + {"name": "font-cache", "paths": ["/usr/share/fonts/", "/usr/local/share/fonts/"],
4434 + "run": "fc-cache -fs"},
4435 + {"name": "glib-schemas", "paths": ["/usr/share/glib-2.0/schemas/"],
4436 + "run": "glib-compile-schemas /usr/share/glib-2.0/schemas"},
4437 + {"name": "desktop-database", "paths": ["/usr/share/applications/"],
4438 + "run": "update-desktop-database -q /usr/share/applications"},
4439 + {"name": "mime-database", "paths": ["/usr/share/mime/"],
4440 + "run": "update-mime-database /usr/share/mime"},
4441 + {"name": "systemd-daemon-reload", "paths": ["/usr/lib/systemd/system/"],
4442 + "run": "systemctl daemon-reload"},
4443 + {"name": "systemd-user-daemon-reload", "paths": ["/usr/lib/systemd/user/"],
4444 + "run": "systemctl --global daemon-reload"},
4445 + {"name": "udev-reload", "paths": ["/usr/lib/udev/rules.d/"],
4446 + "run": "udevadm control --reload-rules"},
4447 +]
4448 +
4449 +def _load_triggers() -> List[dict]:
4450 + """Ładuje triggery: domyślne (tylko gdy binarka istnieje) + /etc/pag/triggers/*.json."""
4451 + out = []
4452 + for t in DEFAULT_TRIGGERS:
4453 + bin_name = t["run"].split()[0]
4454 + if shutil.which(bin_name):
4455 + out.append(dict(t))
4456 + if os.path.isdir(TRIGGERS_DIR):
4457 + for fn in sorted(os.listdir(TRIGGERS_DIR)):
4458 + if not fn.endswith(".json"):
4459 + continue
4460 + try:
4461 + with open(os.path.join(TRIGGERS_DIR, fn)) as f:
4462 + data = json.load(f)
4463 + except (OSError, json.JSONDecodeError):
4464 + continue
4465 + if isinstance(data, dict):
4466 + data = [data]
4467 + for t in data:
4468 + if isinstance(t, dict) and t.get("name") and t.get("paths") and t.get("run"):
4469 + out.append(t)
4470 + return out
4471 +
4472 +def _reload_user_media_services(touched_paths: List[str]) -> None:
4473 + """Po aktualizacji multimediow przeladuj uslugi UZYTKOWNIKA (pipewire/wireplumber).
4474 +
4475 + Nowe binarki/moduly sa juz na dysku, ale dzialajace sesje maja stare w
4476 + pamieci i probuja ladowac nieistniejace wersje modulow. Best-effort:
4477 + `systemctl --global daemon-reload` + try-restart w kazdej aktywnej sesji.
4478 + """
4479 + if os.environ.get("PAG_NO_HOOKS", "") == "1":
4480 + return
4481 + _pfx = ("/usr/lib/systemd/user/pipewire", "/usr/lib/systemd/user/wireplumber",
4482 + "/usr/bin/pipewire", "/usr/bin/wireplumber",
4483 + "/usr/lib/pipewire-0.3/", "/usr/lib64/pipewire-0.3/",
4484 + "/usr/lib/wireplumber-0.5/", "/usr/lib64/wireplumber-0.5/")
4485 + if not any(_p.startswith(_x) for _x in _pfx for _p in touched_paths):
4486 + return
4487 + try:
4488 + subprocess.run(["systemctl", "--global", "daemon-reload"],
4489 + capture_output=True, timeout=60)
4490 + except Exception:
4491 + pass
4492 + try:
4493 + _r = subprocess.run(["loginctl", "list-users", "--no-legend"],
4494 + capture_output=True, text=True, timeout=30)
4495 + _users = [ln.split()[1] for ln in (_r.stdout or "").splitlines()
4496 + if len(ln.split()) >= 2]
4497 + except Exception:
4498 + _users = []
4499 + _done = []
4500 + for _u in _users:
4501 + try:
4502 + _rr = subprocess.run(
4503 + ["su", "-", _u, "-c",
4504 + "systemctl --user try-restart pipewire.socket pipewire.service "
4505 + "wireplumber.service"],
4506 + capture_output=True, timeout=60)
4507 + if _rr.returncode == 0:
4508 + _done.append(_u)
4509 + except Exception:
4510 + pass
4511 + if _done:
4512 + print(_("audio_services_reloaded", ", ".join(sorted(set(_done)))))
4513 +
4514 +def _process_triggers(touched_paths: List[str]):
4515 + """Uruchamia pasujące triggery RAZ na końcu transakcji (best-effort)."""
4516 + if not touched_paths:
4517 + return
4518 + if os.environ.get("PAG_NO_HOOKS", "") == "1":
4519 + return
4520 + import shlex as _shlex
4521 + matched = []
4522 + for trig in _load_triggers():
4523 + if any(path.startswith(p) for p in trig["paths"] for path in touched_paths):
4524 + matched.append(trig)
4525 + for trig in matched:
4526 + run = trig["run"]
4527 + print(_(' ⚡ Trigger: {arg1} ({arg2})', arg1=(trig['name']), arg2=(run)))
4528 + try:
4529 + r = subprocess.run(_shlex.split(run), capture_output=True, text=True, timeout=120)
4530 + _audit(f"TRIGGER {trig['name']}: {run} rc={r.returncode}")
4531 + if r.returncode != 0:
4532 + print(f" ⚠ rc={r.returncode}: {(r.stderr or r.stdout or '').strip()[:160]}")
4533 + except subprocess.TimeoutExpired:
4534 + print(_(' ⚠ trigger {arg1} timed out (120 s)', arg1=(trig['name'])))
4535 + _audit(f"TRIGGER {trig['name']} TIMEOUT")
4536 + except Exception as e:
4537 + print(_(' ⚠ trigger {arg1}: {arg2}', arg1=(trig['name']), arg2=(e)))
4538 + _reload_user_media_services(touched_paths)
4539 +
4540 +
4541 +# =============================================================================
4542 +# UPDATE / UPGRADE / LIST / SEARCH / INFO / VERIFY
4543 +# =============================================================================
4544 +
4545 +def _cleanup_tmp_files(*paths):
4546 + """Usuwa tymczasowe pliki (np. .pag.new) po nieudanej operacji."""
4547 + for p in paths:
4548 + try:
4549 + if os.path.isfile(p):
4550 + os.remove(p)
4551 + except OSError:
4552 + pass
4553 +
4554 +
4555 +def cmd_self_update():
4556 + """Aktualizuje samego klienta pag z repo (podpisany /stable/pag).
4557 +
4558 + Kolejność: pobierz → weryfikacja GPG (+ fingerprint repo) → SHA256 →
4559 + kontrola składni (compile) → backup → atomowe os.replace.
4560 +
4561 + Podmieniamy plik, z którego pag ZOSTAŁ URUCHOMIONY (a nie hardkodowane
4562 + /usr/local/bin/pag): gdy pakiet instaluje /usr/bin/pag, a self-update
4563 + pisał do /usr/local/bin/pag, powstawały DWIE kopie o różnych wersjach
4564 + i zależnie od PATH `pag --version` pokazywał raz jedną, raz drugą."""
4565 + # Dedykowana blokada – patrz SelfUpdateLock. Chroni zapis dst.new oraz
4566 + # os.replace przed równoległą aktualizacją (np. cron + ręcznie).
4567 + with SelfUpdateLock():
4568 + return _self_update_impl()
4569 +
4570 +
4571 +def _self_update_impl():
4572 + repos = get_repos()
4573 + if not repos:
4574 + print(_('❌ No repositories configured.'))
4575 + return 1
4576 + # Aktualizuj bieżący plik (Python ≥3.9 ustawia __file__ jako ścieżkę
4577 + # bezwzględną). Poza /usr|/usr/local (np. uruchomienie z checkoutu)
4578 + # nie nadpisujemy niczego – wracamy do domyślnej lokalizacji instalacji.
4579 + dst = "/usr/local/bin/pag"
4580 + try:
4581 + cand = os.path.realpath(__file__)
4582 + if cand.startswith(("/usr/", "/usr/local/")):
4583 + dst = cand
4584 + except Exception:
4585 + pass
4586 + base = repos[0]
4587 + dst_new = dst + ".new"
4588 + dst_bak = dst + ".bak"
4589 + print(_('🔄 Checking for pag update from {arg1}...', arg1=(base)))
4590 + try:
4591 + with urlopen(Request(f"{base}/pag", headers={"User-Agent": "pag/3.0"}), timeout=20) as r:
4592 + data = r.read()
4593 + with urlopen(Request(f"{base}/pag.asc", headers={"User-Agent": "pag/3.0"}), timeout=20) as r:
4594 + sig = r.read()
4595 + except Exception as e:
4596 + print(_(' ❌ Cannot download pag: {arg1}', arg1=(e)))
4597 + return 1
4598 +
4599 + # Zapisz nową wersję w katalogu docelowym (ta sama partycja → atomowy rename)
4600 + with open(dst_new, "wb") as f:
4601 + f.write(data)
4602 + with open(dst_new + ".asc", "wb") as f:
4603 + f.write(sig)
4604 +
4605 + # --- 1. Weryfikacja podpisu GPG – bez tego nie instalujemy ---
4606 + insecure = os.environ.get("PAG_INSECURE", "") == "1"
4607 + ok, fp = _gpg_verify_fp(dst_new + ".asc", dst_new)
4608 + if not ok:
4609 + # Automatyczny import klucza (TOFU) – jak w _verify_repo_sig
4610 + res = _gpg_run("--verify", dst_new + ".asc", dst_new,
4611 + capture_output=True, text=True)
4612 + _stderr = res.stderr.decode(errors="replace") if isinstance(res.stderr, bytes) else (res.stderr or "")
4613 + if "public key" in _stderr.lower() and "no public key" in _stderr.lower():
4614 + try:
4615 + with urlopen(Request(f"{base}/paganos.asc", headers={"User-Agent": "pag/3.0"}), timeout=20) as r:
4616 + keydata = r.read()
4617 + with tempfile.NamedTemporaryFile(delete=False, suffix=".asc") as tmp:
4618 + tmp.write(keydata); tmp.flush()
4619 + _gpg_run("--import", tmp.name, capture_output=True, timeout=30)
4620 + os.unlink(tmp.name)
4621 + print(_(' 🔑 Imported repo key from {arg1}/paganos.asc', arg1=(base)))
4622 + ok, fp = _gpg_verify_fp(dst_new + ".asc", dst_new)
4623 + except Exception:
4624 + pass
4625 + if not ok:
4626 + if insecure:
4627 + print(_(' ⚠ Invalid update signature (PAG_INSECURE – ignoring)'))
4628 + else:
4629 + print(_(' ❌ Invalid update signature – not updating.'))
4630 + _cleanup_tmp_files(dst_new, dst_new + ".asc")
4631 + return 1
4632 + # Sprawdź fingerprint względem przypiętego klucza repo
4633 + pinned = _repo_pinned_fp(base)
4634 + if pinned:
4635 + if not fp:
4636 + print(_(' ❌ Cannot confirm the update signature fingerprint.'))
4637 + _cleanup_tmp_files(dst_new, dst_new + ".asc")
4638 + return 1
4639 + if fp != pinned.upper():
4640 + if insecure:
4641 + print(_(' ⚠ Update signed with a different key (PAG_INSECURE – ignoring)'))
4642 + else:
4643 + print(_(' ❌ [SECURITY ERROR] Update signed with a different key than the repo!'))
4644 + print(_(' Expected: {arg1}, received: {arg2}', arg1=(pinned), arg2=(fp)))
4645 + _cleanup_tmp_files(dst_new, dst_new + ".asc")
4646 + return 1
4647 +
4648 + # --- 2. Weryfikacja SHA256 (jeśli repo publikuje pag.sha256) ---
4649 + try:
4650 + with urlopen(Request(f"{base}/pag.sha256", headers={"User-Agent": "pag/3.0"}), timeout=15) as r:
4651 + sha = r.read().decode().strip().split()[0]
4652 + if sha:
4653 + actual = hashlib.sha256(data).hexdigest()
4654 + if actual.lower() != sha.lower():
4655 + print(_(' ❌ SHA256 mismatch! Expected {arg1}, got {arg2}', arg1=(sha), arg2=(actual)))
4656 + _cleanup_tmp_files(dst_new, dst_new + ".asc")
4657 + return 1
4658 + print(_(' ✅ SHA256 matches'))
4659 + except Exception:
4660 + # Brak pag.sha256 w repo – opcjonalne; nie blokuj aktualizacji.
4661 + pass
4662 +
4663 + # --- 3. Kontrola składni (nie uruchamiaj uszkodzonego/poddanego edycji pliku) ---
4664 + try:
4665 + compile(data, "pag", "exec")
4666 + except SyntaxError as e:
4667 + print(_(' ❌ Syntax error in new pag: {arg1}', arg1=(e)))
4668 + _cleanup_tmp_files(dst_new, dst_new + ".asc")
4669 + return 1
4670 +
4671 + m = (re.search(rb'PAG_VERSION\s*=\s*"(\d+\.\d+\.\d+[a-z]?)"', data[:3000])
4672 + or re.search(rb"v(\d+\.\d+\.\d+[a-z]?)", data[:3000]))
4673 + new_ver = m.group(1).decode() if m else "?"
4674 + print(_(' ✅ Downloaded pag {arg1} (current {arg2}), signature verified', arg1=(new_ver), arg2=(PAG_VERSION)))
4675 +
4676 + # --- 4. Backup + atomowa podmiana ---
4677 + if os.path.exists(dst):
4678 + shutil.copy2(dst, dst_bak)
4679 + os.chmod(dst_new, 0o755)
4680 + os.replace(dst_new, dst) # atomowe na tym samym FS
4681 + try:
4682 + if os.path.exists(dst_new + ".asc"):
4683 + os.remove(dst_new + ".asc")
4684 + except OSError:
4685 + pass
4686 + print(_(' ✅ Installed new pag. Old version kept as {arg1}', arg1=(dst_bak)))
4687 + # Ostrzeż, gdy w PATH pierwsza jest INNA kopia `pag` – inaczej
4688 + # `pag --version` dalej pokaże starą wersję i wygląda to jak brak update.
4689 + other = shutil.which("pag")
4690 + if other and os.path.realpath(other) != os.path.realpath(dst):
4691 + print(_(' ⚠ A different pag is first in PATH: {arg1} (updated {arg2})', arg1=(other), arg2=(dst)))
4692 + print(_(' Remove the old copy: sudo rm {arg1}', arg1=(other)))
4693 + print(_(' Restart pag to use the new version.'))
4694 + return 0
4695 +
4696 +
4697 +def _candidate_newer(rp, inst):
4698 + """Czy pakiet z repo jest nowszy od zainstalowanego.
4699 + Porównuje (version, release): sam bump pkgrel (np. auto-rebuild modułów
4700 + po aktualizacji jądra: nvidia-kernel-618 610.57.04-1 -> -2) też musi być
4701 + widziany przez `pag update`. Stare rekordy instalacji (bez pola release)
4702 + traktujemy jak release=1 – nie generują churnu, dopóki nie wrócą do
4703 + reinstalacji/zmiany wersji."""
4704 + rv = getattr(rp, "version", "0")
4705 + iv = inst.get("version", "0")
4706 + if _version_newer(rv, iv):
4707 + return True
4708 + if rv != iv:
4709 + return False
4710 + rr = int(getattr(rp, "release", 1) or 1)
4711 + ir = int(inst.get("release", 1) or 1)
4712 + return rr > ir
4713 +
4714 +
4715 +def _pending_updates() -> List[str]:
4716 + """Zainstalowane pakiety z nowszą wersją/release w repo (bez przypiętych)."""
4717 + installed = load_json(INSTALLED_DB)
4718 + pinned = load_json(PINNED_FILE)
4719 + repo = fetch_all_packages()
4720 + if not repo:
4721 + return []
4722 + return [n for n, i in installed.items()
4723 + if n not in pinned and (rp := repo.get(n)) and _candidate_newer(rp, i)]
4724 +
4725 +# =============================================================================
4726 +# BAZA Z OBRAZU ISO → REPO (`pag base`) – pełny rolling
4727 +# =============================================================================
4728 +# ISO jest zbudowane ZE ŹRÓDEŁ (glibc, gcc, gtk, XFCE, …) – pag tych pakietów
4729 +# nie instalował, więc nie ma ich w installed.json/files.db. Skutki:
4730 +# • `pag upgrade` ich NIE dotyka (nie ma o nich pojęcia),
4731 +# • mimo to `pag install <nazwa>` je NADPISZE – pag robi kopię plików spoza
4732 +# swojej bazy (patrz _new_transaction_backup_root), więc nie są nietykalne.
4733 +#
4734 +# /usr/share/pag/base.json (wypalany przez build-pagan.sh) mówi, co jest w bazie
4735 +# obrazu i w jakiej wersji. `pag base` pokazuje stan, a `pag base adopt` dogrywa
4736 +# te pakiety z repo – po tym zabiegu pag zarządza nimi normalnie, więc
4737 +# `pag upgrade` aktualizuje CAŁY system (rolling), a nie tylko to, co sam
4738 +# wcześniej zainstalował.
4739 +#
4740 +# Nazwy z buildera różnią się od nazw pakietów w repo (builder buduje „libX11”,
4741 +# repo ma pakiet „xorg-libx11”), stąd aliasy poniżej. Nazwy bez odpowiednika
4742 +# w repo zostają w wersji z obrazu – raport mówi o tym wprost, zamiast udawać,
4743 +# że są aktualne.
4744 +BASE_NAME_ALIASES = {
4745 + "atk": "at-spi2-core",
4746 + "dejavu-fonts": "dejavu-ttf",
4747 + "fontconfig": "xorg-fontconfig",
4748 + "gtk": "gtk3",
4749 + "iceauth": "xorg-iceauth",
4750 + "libX11": "xorg-libx11",
4751 + "libXau": "xorg-libxau",
4752 + "libXdmcp": "xorg-libxdmcp",
4753 + "libXext": "xorg-libxext",
4754 + "libXft": "xorg-libxft",
4755 + "libdrm": "xorg-libdrm",
4756 + "libnspr": "nspr",
4757 + "libxkbfile": "xorg-libxkbfile",
4758 + "libxklavier": "xorg-libxklavier",
4759 + "linux-pam": "pam",
4760 + "pixman": "xorg-pixman",
4761 + "sdl2": "sdl",
4762 + "setxkbmap": "xorg-setxkbmap",
4763 + "xauth": "xorg-xauth",
4764 + "xf86-input-libinput": "xorg-xf86-input-libinput",
4765 + "xf86-video-fbdev": "xorg-xf86-video-fbdev",
4766 + "xinit": "xorg-xinit",
4767 + "xkbcomp": "xorg-xkbcomp",
4768 + "xkeyboard-config": "xorg-xkeyboard-config",
4769 + # Builder buduje wpa_supplicant (z podkreślnikiem), a repo ma wpa-supplicant
4770 + # (z myślnikiem) – bez tego aliasu pakiet nie dostawał aktualizacji z repo,
4771 + # mimo że repo.json zna DOKŁADNIE tę samą wersję.
4772 + "wpa_supplicant": "wpa-supplicant",
4773 +}
4774 +
4775 +
4776 +def _base_manifest() -> dict:
4777 + """Manifest bazy z obrazu ({} gdy obraz go nie dostarcza)."""
4778 + _d = load_json(os.path.join(PAG_ROOT, BASE_MANIFEST.lstrip("/")))
4779 + return _d if isinstance(_d, dict) else {}
4780 +
4781 +
4782 +def _base_entries() -> list:
4783 + """[(nazwa_z_buildera, wersja_z_obrazu), ...] z manifestu."""
4784 + _out = []
4785 + for _e in (_base_manifest().get("packages") or []):
4786 + if isinstance(_e, str):
4787 + if _e:
4788 + _out.append((_e, "?"))
4789 + elif isinstance(_e, dict) and _e.get("name"):
4790 + _out.append((str(_e["name"]), str(_e.get("version") or "?")))
4791 + return _out
4792 +
4793 +
4794 +def _base_repo_name(name: str, repo: dict, installed: dict) -> str:
4795 + """Nazwa pakietu w repo dla nazwy z buildera (alias → provides → brak)."""
4796 + if name in repo:
4797 + return name
4798 + _alias = BASE_NAME_ALIASES.get(name)
4799 + if _alias and _alias in repo:
4800 + return _alias
4801 + _real = _resolve_provides(name, repo, installed)
4802 + return _real if _real in repo else ""
4803 +
4804 +
4805 +def _base_summary(repo: Optional[dict] = None) -> dict:
4806 + """Klasyfikacja pakietów bazy z obrazu wobec repo.
4807 +
4808 + repo=None → pobiera indeks repo (potrzebny do listy „do adoptowania”).
4809 + repo={} → bez sieci: rozpoznaje tylko to, czym pag już zarządza.
4810 + """
4811 + _entries = _base_entries()
4812 + if not _entries:
4813 + return {"total": 0, "tracked": 0, "adoptable": [], "unmatched": []}
4814 + if repo is None:
4815 + repo = fetch_all_packages()
4816 + installed = load_json(INSTALLED_DB)
4817 + tracked, adoptable, unmatched = 0, [], []
4818 + for _n, _v in _entries:
4819 + _real = _base_repo_name(_n, repo, installed)
4820 + if _n in installed or (_real and _real in installed):
4821 + tracked += 1
4822 + elif _real:
4823 + adoptable.append((_n, _real, _v))
4824 + else:
4825 + unmatched.append(_n)
4826 + return {"total": len(_entries), "tracked": tracked,
4827 + "adoptable": adoptable, "unmatched": unmatched}
4828 +
4829 +
4830 +def _base_hint_unmanaged() -> None:
4831 + """Jednozdaniowa informacja dla `pag sync/update/upgrade`."""
4832 + try:
4833 + _s = _base_summary()
4834 + except Exception:
4835 + return
4836 + if _s["adoptable"]:
4837 + print(f"\n ℹ {_('base_unmanaged_hint', len(_s['adoptable']))}")
4838 +
4839 +
4840 +def _base_warn_overwrite(names) -> None:
4841 + """Ostrzeżenie w `pag install`, gdy pakiet pochodzi z bazy obrazu ISO."""
4842 + _entries = _base_entries()
4843 + if not _entries:
4844 + return
4845 + _known = set()
4846 + for _n, _v in _entries:
4847 + _known.add(_n)
4848 + _al = BASE_NAME_ALIASES.get(_n)
4849 + if _al:
4850 + _known.add(_al)
4851 + _hit = [n for n in names if n in _known]
4852 + if _hit:
4853 + _listed = ", ".join(_hit[:5]) + (" …" if len(_hit) > 5 else "")
4854 + print(f" ℹ {_('base_overwrite', _listed)}")
4855 +
4856 +
4857 +def cmd_base_status():
4858 + """`pag base` / `pag base status` – co w systemie pochodzi z obrazu,
4859 + czym pag już zarządza i co da się zaadoptować z repo."""
4860 + _man = _base_manifest()
4861 + if not _man:
4862 + print(f" ℹ {_('base_no_manifest')}")
4863 + return 0
4864 + _s = _base_summary()
4865 + print(f"\n {_c('bold', _('base_title'))}")
4866 + print(f" {'─' * 46}")
4867 + _de = _man.get("de") or ""
4868 + print(f" {_('base_iso_version'):<34} {_man.get('iso_version', '?')}" + (f" ({_de})" if _de else ""))
4869 + print(f" {_('base_total'):<34} {_s['total']}")
4870 + print(f" {_('base_tracked'):<34} {_s['tracked']}")
4871 + print(f" {_('base_adoptable'):<34} {len(_s['adoptable'])}")
4872 + print(f" {_('base_unmatched'):<34} {len(_s['unmatched'])}")
4873 + if _s["adoptable"]:
4874 + print(f"\n {_('base_adopt_hint')}")
4875 + for _iso_n, _real, _v in _s["adoptable"][:10]:
4876 + _m = "" if _iso_n == _real else f" ({_iso_n})"
4877 + print(f" {_real}-{_v}{_m}")
4878 + if len(_s["adoptable"]) > 10:
4879 + print(f" … {len(_s['adoptable']) - 10} {_('base_more')}")
4880 + if _s["unmatched"]:
4881 + print(f"\n {_('base_unmatched_hint')}")
4882 + print(" " + ", ".join(_s["unmatched"][:12])
4883 + + (f" … +{len(_s['unmatched']) - 12}" if len(_s["unmatched"]) > 12 else ""))
4884 + return 0
4885 +
4886 +
4887 +def cmd_base_adopt(args):
4888 + """`pag base adopt [pkg...] [--dry-run]` – dograj bazę z obrazu z repo.
4889 +
4890 + Pakiety bazy nie ma w installed.json, więc pag traktuje je jak NOWĄ
4891 + instalację: pliki z obrazu trafiają do kopii transakcji (działa
4892 + `pag rollback`), a po sukcesie pag zarządza nimi jak każdym innym pakietem.
4893 + """
4894 + if not _base_manifest():
4895 + print(f" ℹ {_('base_no_manifest')}")
4896 + return 1
4897 + repo = fetch_all_packages()
4898 + if not repo:
4899 + print(f"❌ {_('no_index')}")
4900 + return 1
4901 + _want = [a for a in args if not a.startswith("-") and a != "adopt"]
4902 + _s = _base_summary(repo)
4903 + plan = _s["adoptable"]
4904 + if _want:
4905 + _sel = set(_want)
4906 + plan = [p for p in plan if p[0] in _sel or p[1] in _sel]
4907 + if not plan:
4908 + print(f" ℹ {_('base_nothing_selected')}")
4909 + return 0
4910 + if not plan:
4911 + print(f"✅ {_('base_all_managed')}")
4912 + return 0
4913 + _size = sum(repo[r].size_bytes for _i, r, _v in plan if r in repo)
4914 + print(f"\n {_('base_adopt_plan', len(plan), _size / 1048576)}")
4915 + for _iso_n, _real, _v in plan[:20]:
4916 + _p = repo.get(_real)
4917 + _rv = _p.version if _p else "?"
4918 + _rr = (getattr(_p, "release", "") or "") if _p else ""
4919 + _rvr = f"{_rv}-{_rr}" if _rr else _rv
4920 + _m = "" if _iso_n == _real else f" ({_iso_n} → {_real})"
4921 + print(f" {_real}: {_v} → {_rvr}{_m}")
4922 + if len(plan) > 20:
4923 + print(f" … {len(plan) - 20} {_('base_more')}")
4924 + if "-n" in args or "--dry-run" in args:
4925 + print(f" {_('base_dry_run')}")
4926 + return 0
4927 + _rc = cmd_install([r for _i, r, _v in plan])
4928 + if _rc == 0:
4929 + # Wymienione biblioteki/narzędzia (glibc, gcc, GTK…) są już nowe na dysku,
4930 + # ale działające procesy wciąż mają stare w pamięci – restart domyka.
4931 + print(f"\n ℹ {_('base_reboot_hint')}")
4932 + return _rc
4933 +
4934 +
4935 +def _base_cached_index() -> dict:
4936 + """Indeks repo TYLKO z lokalnego cache (zero sieci) – do mapowania nazw.
4937 +
4938 + Potrzebne dla `pag base register`: rejestracja bazy obrazu nie może zależeć
4939 + od sieci (odpala się w buildzie, w chroocie, bez DNS). Cache indeksu powstaje
4940 + przy okazji `pag sync`/`pag install` i po nim wystarcza.
4941 + """
4942 + _out = {}
4943 + try:
4944 + for _r in get_repos():
4945 + _cp = _repo_cache_path(_r)
4946 + if not os.path.exists(_cp):
4947 + continue
4948 + for _pdata in (_load_repo_cache(_cp) or []):
4949 + _n = _pdata.get("name") or _pdata.get("filename", "?").split("-")[0]
4950 + _pkg = PackageInfo(_pdata, _r)
4951 + if _n not in _out or _version_newer(_pkg.version, _out[_n].version):
4952 + _out[_n] = _pkg
4953 + except Exception:
4954 + return _out
4955 + return _out
4956 +
4957 +
4958 +def cmd_base_register(args):
4959 + """`pag base register [--force] [--dry-run]` – wpisz bazę obrazu do installed.json.
4960 +
4961 + PO CO: pakietów zbudowanych przez builder (glibc, gcc, GTK, XFCE…) nie ma
4962 + w installed.json, więc `pag upgrade` ich NIE widzi i system nie da się
4963 + prowadzić w trybie rolling – trzeba by najpierw `pag base adopt`, czyli
4964 + ponownie ŚCIĄGNĄĆ całą bazę z repo. Rejestracja zamiast tego zapisuje je
4965 + jako zainstalowane **z wersją z obrazu** (to ona leży na dysku), więc
4966 + `pag upgrade` porówna ją z repo i podniesie tylko to, co nowsze.
4967 +
4968 + Offline: nic nie pobiera. Cache indeksu repo (jeśli jest) służy WYŁĄCZNIE do
4969 + mapowania nazw builder → repo (BASE_NAME_ALIASES/provides) i metadanych
4970 + (release/opis/zależności). Nazwy bez odpowiednika w repo zostają jak są.
4971 +
4972 + OGRANICZENIE: rejestracja nie zna listy plików pakietu (files.db), więc
4973 + dopóki pakiet nie zostanie zaktualizowany z repo, `pag verify`/`pag remove`
4974 + go nie obejmą (`pag base adopt` nadal jest drogą do pełnego przejęcia).
4975 + """
4976 + _force = "-f" in args or "--force" in args
4977 + _dry = "-n" in args or "--dry-run" in args
4978 +
4979 + _entries = _base_entries()
4980 + if not _entries:
4981 + print(f" ℹ {_('base_no_manifest')}")
4982 + return 1
4983 +
4984 + _repo = _base_cached_index()
4985 + installed = load_json(INSTALLED_DB)
4986 + world = load_world()
4987 + _now = datetime.now().isoformat()
4988 +
4989 + added, skipped, renamed = [], 0, 0
4990 + for _n, _v in _entries:
4991 + _real = _base_repo_name(_n, _repo, installed) if _repo else ""
4992 + _key = _real or _n
4993 + if _real and _real != _n:
4994 + renamed += 1
4995 + if _key in installed and not _force:
4996 + skipped += 1
4997 + continue
4998 + _pkg = _repo.get(_key)
4999 + installed[_key] = {
5000 + "version": _v or (getattr(_pkg, "version", "") or "?"),
5001 + "release": getattr(_pkg, "release", "") or "1",
5002 + "description": (getattr(_pkg, "description", "") or "")
5003 + or "Pagan Linux – pakiet bazy obrazu",
5004 + "dependencies": list(getattr(_pkg, "dependencies", []) or []),
5005 + "size_bytes": getattr(_pkg, "size_bytes", 0) or 0,
5006 + "sha256": "",
5007 + "installed_at": _now,
5008 + "repo": "base",
5009 + "provides": list(getattr(_pkg, "provides", []) or []),
5010 + "provides_so": list(getattr(_pkg, "provides_so", []) or []),
5011 + "requires_so": list(getattr(_pkg, "requires_so", []) or []),
5012 + }
5013 + world.add(_key)
5014 + added.append(_key)
5015 +
5016 + if _dry:
5017 + print(f" ℹ {_('base_register_plan', len(added))}")
5018 + return 0
5019 + if added:
5020 + save_json(INSTALLED_DB, installed)
5021 + save_world(world)
5022 + print(f" ✅ {_('base_register_ok', len(added), skipped)}")
5023 + if renamed:
5024 + print(f" ℹ {_('base_register_renamed', renamed)}")
5025 + if not _repo:
5026 + print(f" ℹ {_('base_register_nocache')}")
5027 + return 0
5028 +
5029 +
5030 +def cmd_update(do_upgrade: bool = False):
5031 + """`pag sync` / `pag update` – odświeżenie indeksów + raport aktualizacji.
5032 +
5033 + sync → tylko odświeżenie indeksów + info: „jest X pakietów do
5034 + zaktualizowania – wpisz: pag update".
5035 + update → odświeżenie indeksów + AKTUALIZACJA PAKIETÓW (pakiety, nie system).
5036 + Pomijamy cache TTL (inaczej nowe pakiety/aktualizacje są niewidoczne nawet
5037 + przez godzinę). Pełne pobranie + weryfikacja GPG przy każdym odświeżeniu.
5038 + """
5039 + force = True
5040 + print(_('🔄 Refreshing indexes...'))
5041 + for repo_url in get_repos():
5042 + pkgs = fetch_repo_index(repo_url, force=force)
5043 + cp = _repo_cache_path(repo_url)
5044 + has_sig = os.path.exists(cp + ".sig")
5045 + print(_(' {arg1} {arg2}: {arg3} packages {arg4}', arg1=('✅' if pkgs is not None else '❌'), arg2=(repo_url), arg3=(len(pkgs or [])), arg4=('🔐' if has_sig else '⚠')))
5046 + print(f"✅ {_('indexes_refreshed')}")
5047 +
5048 + # Powiadomienie o nowszej wersji pag (repo.json["pag_version"])
5049 + try:
5050 + for r in get_repos():
5051 + cp = _repo_cache_path(r)
5052 + if os.path.exists(cp):
5053 + d = json.load(open(cp))
5054 + rv = d.get("pag_version", "")
5055 + if rv and rv != PAG_VERSION:
5056 + print(_(' ⚠ New pag version {arg1} available – run: pag self-update', arg1=(rv)))
5057 + except Exception:
5058 + pass
5059 +
5060 + # Raport: pakiety do aktualizacji
5061 + pending = _kernel_group_updates(_pending_updates())
5062 + if not pending:
5063 + print(f"✅ {_('all_up_to_date')}")
5064 + _base_hint_unmanaged()
5065 + return 0
5066 + print(f"{_('updates_available', len(pending))}")
5067 + installed = load_json(INSTALLED_DB)
5068 + repo = fetch_all_packages()
5069 + for n in pending:
5070 + _i = installed.get(n, {})
5071 + _ir = _i.get("release")
5072 + _nr = getattr(repo[n], "release", "") or ""
5073 + _old = f"{_i.get('version', '?')}-{_ir}" if _ir else _i.get("version", "?")
5074 + _new = f"{repo[n].version}-{_nr}" if _nr else repo[n].version
5075 + print(f" {n}: {_old} → {_new}")
5076 + if not do_upgrade:
5077 + _base_hint_unmanaged()
5078 + return 0 # sync: tylko informacja
5079 + if not _ask_confirm():
5080 + return 0
5081 + _rc = cmd_install(pending, upgrade=True)
5082 + _base_hint_unmanaged()
5083 + return _rc
5084 +
5085 +def _initramfs_stale() -> bool:
5086 + """Czy initramfs jest starszy niż najnowsze jądro (wymaga przebudowy)."""
5087 + try:
5088 + kernels = [k for k in os.listdir("/boot") if k.startswith("vmlinuz-")] if os.path.isdir("/boot") else []
5089 + if not kernels:
5090 + return False
5091 + newest = max(os.path.getmtime(os.path.join("/boot", k)) for k in kernels)
5092 + initrd = "/boot/initramfs.img"
5093 + return (not os.path.exists(initrd)) or os.path.getmtime(initrd) < newest
5094 + except Exception:
5095 + return False
5096 +
5097 +def cmd_upgrade():
5098 + """`pag upgrade` – aktualizacja SYSTEMU: pakiety + kernel/initramfs/GRUB."""
5099 + rc = cmd_update(do_upgrade=True)
5100 + if rc != 0:
5101 + return rc
5102 + # System: dopilnuj initramfs (gdyby kernel był nowszy) + GRUB.
5103 + if _initramfs_stale():
5104 + print(_(' 🐧 Rebuilding initramfs (newer kernel)...'))
5105 + _rebuild_initramfs()
5106 + _refresh_bootloader()
5107 + return 0
5108 +
5109 +def cmd_list(installed_only=False):
5110 + if installed_only:
5111 + db = load_json(INSTALLED_DB)
5112 + pinned = load_json(PINNED_FILE)
5113 + if not db: print(_('No packages installed.')); return
5114 + print(_('Installed ({arg1}):', arg1=(len(db))))
5115 + for n, i in sorted(db.items()):
5116 + pin = " 📌" if n in pinned else ""
5117 + print(f" {n}-{i['version']}{pin} – {i.get('description','')}")
5118 + else:
5119 + pkgs = fetch_all_packages()
5120 + installed = load_json(INSTALLED_DB)
5121 + pinned = load_json(PINNED_FILE)
5122 + print(_('Available ({arg1}):', arg1=(len(pkgs))))
5123 + for n, p in sorted(pkgs.items()):
5124 + m = "✓" if n in installed else " "
5125 + extra = f" [{_('installed_marker')}: {installed[n]['version']}]" if n in installed else ""
5126 + if n in pinned: extra += " 📌"
5127 + print(f" [{m}] {n}-{p.version} – {p.description}{extra}")
5128 +
5129 +def cmd_search(query):
5130 + pkgs = fetch_all_packages()
5131 + results = [(n,p) for n,p in pkgs.items() if query.lower() in n.lower() or query.lower() in p.description.lower()]
5132 + if not results: print(_('❌ No results for: {arg1}', arg1=(query))); return
5133 + installed = load_json(INSTALLED_DB)
5134 + print(_("Results for '{arg1}' ({arg2}):", arg1=(query), arg2=(len(results))))
5135 + for n,p in sorted(results):
5136 + print(f" [{'✓' if n in installed else ' '}] {n}-{p.version}")
5137 + print(f" {p.description}")
5138 +
5139 +
5140 +def _smart_search(query: str) -> int:
5141 + """
5142 + Inteligentne wyszukiwanie: repo PaganOS + Flathub.
5143 + Uruchamiane gdy użytkownik wpisze `pag <nazwa>` zamiast `pag install <nazwa>`.
5144 + Pokazuje dostępne źródła i sugeruje komendy instalacji.
5145 + """
5146 + # 1. Repo PaganOS
5147 + try:
5148 + pkgs = fetch_all_packages()
5149 + except Exception:
5150 + pkgs = {}
5151 + repo_lower = [(n, p) for n, p in pkgs.items()
5152 + if query.lower() in n.lower() or query.lower() in p.description.lower()]
5153 +
5154 + # 2. Flathub (jeśli dostępny)
5155 + flat = _flatpak_search_raw(query) if _check_flatpak(quiet=True) else []
5156 +
5157 + if not repo_lower and not flat:
5158 + print(_("\n ❌ '{arg1}' — not found.", arg1=(query)))
5159 + print(_(' PaganOS repo: pag search {arg1}', arg1=(query)))
5160 + if _check_flatpak(quiet=True):
5161 + print(_(' Flathub: pag flatpak search {arg1}', arg1=(query)))
5162 + print(_(' Add repo: pag repo-add <url>'))
5163 + return 1
5164 +
5165 + installed = load_json(INSTALLED_DB)
5166 +
5167 + # ── Repo PaganOS ──
5168 + if repo_lower:
5169 + exact = [(n, p) for n, p in repo_lower if n.lower() == query.lower()]
5170 + show = (exact or repo_lower)[:6]
5171 + print(f"\n 📦 PaganOS — '{query}':")
5172 + for n, p in sorted(show):
5173 + mark = "✓" if n in installed else " "
5174 + desc = p.description[:70] if len(p.description) > 75 else p.description
5175 + print(f" [{mark}] {n}-{p.version}")
5176 + if desc:
5177 + print(f" {desc}")
5178 + if len(repo_lower) > 6:
5179 + print(_(' ... and {arg1} more (pag search {arg2})', arg1=(len(repo_lower) - 6), arg2=(query)))
5180 +
5181 + # ── Flathub ──
5182 + if flat:
5183 + print(f"\n 📦 Flathub — '{query}':")
5184 + for r in flat[:5]:
5185 + mark = "✓" if r.get("installed") else " "
5186 + name = r.get("name") or r.get("application", "?")
5187 + desc = (r.get("description") or "")[:65]
5188 + print(f" [{mark}] {name}")
5189 + if desc:
5190 + print(f" {desc}")
5191 + if len(flat) > 5:
5192 + print(_(' ... and {arg1} more (pag flatpak search {arg2})', arg1=(len(flat) - 5), arg2=(query)))
5193 +
5194 + # ── Sugestie instalacji ──
5195 + print()
5196 + if repo_lower:
5197 + 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]
5198 + if best in installed:
5199 + print(_(' ✓ {arg1} is already installed ({arg2})', arg1=(best), arg2=(installed[best]['version'])))
5200 + else:
5201 + print(f" 💡 sudo pag install {best}")
5202 + if flat:
5203 + best_fp = flat[0].get("application") or flat[0].get("name", query)
5204 + print(f" 💡 pag flatpak install {best_fp}")
5205 +
5206 + return 0
5207 +
5208 +def cmd_info(name):
5209 + pkgs = fetch_all_packages()
5210 + p = pkgs.get(name)
5211 + info = load_json(INSTALLED_DB).get(name)
5212 + if not p and not info: print(_("❌ '{arg1}' not found.", arg1=(name))); return 1
5213 + print(f"📦 {name}")
5214 + if p:
5215 + print(_(' Version (repo): {arg1}', arg1=(p.version)))
5216 + print(_(' Description: {arg1}', arg1=(p.description)))
5217 + print(_(' Size: {arg1:.1f} MB', arg1=(p.size_bytes/1048576)))
5218 + print(_(' SHA256: {arg1}...', arg1=(p.sha256[:32])))
5219 + print(_(' GPG: {arg1}', arg1=(p.gpg_fp or _('none_value'))))
5220 + print(_(' Dependencies: {arg1}', arg1=((', '.join(p.dependencies)) if p.dependencies else _('none_parenthesized'))))
5221 + if p.optdepends:
5222 + print(f" {_('optional_deps')}")
5223 + for _od in p.optdepends:
5224 + print(f" - {_od}")
5225 + if info:
5226 + print(_(' Installed: {arg1} ({arg2})', arg1=(info['version']), arg2=(info.get('installed_at','?'))))
5227 +
5228 +def cmd_files(name):
5229 + if name not in load_json(INSTALLED_DB):
5230 + print(_("❌ '{arg1}' not installed.", arg1=(name))); return 1
5231 + files = _db_get_package_files(name)
5232 + print(_('Files in {arg1} ({arg2}):', arg1=(name), arg2=(len(files))))
5233 + for f in sorted(files): print(f" {f}")
5234 +
5235 +def cmd_repair(dry_run=False):
5236 + """Naprawia system: reinstaluje pakiety, ktorych pliki zginely.
5237 +
5238 + Przechodzi po bazie plikow (jak `verify`), zbiera pakiety z brakujacymi
5239 + plikami i dla kazdego robi REINSTALACJE z repozytorium (staging + GPG).
5240 + Reinstalacja nie rusza konfiguracji uzytkownika (.pacnew), a przywraca
5241 + brakujace pliki pakietu (np. qt6-declarative, accountsservice).
5242 + """
5243 + installed = load_json(INSTALLED_DB)
5244 + if not installed:
5245 + print(_('Nothing to repair (no packages installed).'))
5246 + return 0
5247 + missing = {}
5248 + for name in installed:
5249 + cnt = 0
5250 + for fpath in _db_get_package_files(name):
5251 + full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
5252 + if not (os.path.exists(full) or os.path.islink(full)):
5253 + cnt += 1
5254 + if cnt:
5255 + missing[name] = cnt
5256 + if not missing:
5257 + print(_('✅ All files are in place – nothing to repair.'))
5258 + return 0
5259 + total = sum(missing.values())
5260 + print(_('🔧 Packages with missing files: {arg1} (total {arg2} files)', arg1=(len(missing)), arg2=(total)))
5261 + for n, c in sorted(missing.items(), key=lambda kv: (-kv[1], kv[0])):
5262 + print(f" {n}: {c}")
5263 + if dry_run:
5264 + print(_('\n(--dry-run: nothing is changed)'))
5265 + return 0
5266 + if not _ask_confirm():
5267 + print(_("cancelled")); return 0
5268 + # Jedna migawka na całą naprawę – nie tworzymy snapshotu per pakiet.
5269 + _snap_ok, _ = _snapshot_support()
5270 + if _snap_ok:
5271 + _create_system_snapshot(list(missing), "repair")
5272 + _refresh_bootloader()
5273 + _prev_snap = os.environ.get("PAG_SNAPSHOT")
5274 + os.environ["PAG_SNAPSHOT"] = "never"
5275 + failed = []
5276 + try:
5277 + for n in sorted(missing, key=lambda x: (-missing[x], x)):
5278 + print(_('\n🔧 repair: {arg1}', arg1=(n)))
5279 + try:
5280 + rc = cmd_install([n], upgrade=True)
5281 + except SystemExit as e:
5282 + rc = e.code
5283 + except Exception as e:
5284 + print(f" ❌ {n}: {e}")
5285 + rc = 1
5286 + if rc:
5287 + failed.append(n)
5288 + finally:
5289 + if _prev_snap is None:
5290 + os.environ.pop("PAG_SNAPSHOT", None)
5291 + else:
5292 + os.environ["PAG_SNAPSHOT"] = _prev_snap
5293 + print()
5294 + ok = len(missing) - len(failed)
5295 + if failed:
5296 + print(_('⚠ Repaired {arg1}/{arg2}. Failed: {arg3}', arg1=(ok), arg2=(len(missing)), arg3=(', '.join(failed))))
5297 + return 1
5298 + print(_('✅ Repaired {arg1} packages.', arg1=(ok)))
5299 + return 0
5300 +
5301 +
5302 +def cmd_verify(deep=False):
5303 + installed = load_json(INSTALLED_DB)
5304 + if not installed: print(_('Nothing to verify.')); return
5305 + errors = []
5306 +
5307 + # Wczytaj WSZYSTKIE sumy RAZ (nie w pętli!) – przy 50k plików wywołanie
5308 + # _db_get_all_file_checksums() per-plik dawało O(n²) i godziny zamiast sekund.
5309 + all_checksums = _db_get_all_file_checksums() if deep else {}
5310 + for name in installed:
5311 + for fpath in _db_get_package_files(name):
5312 + full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
5313 + if not (os.path.exists(full) or os.path.islink(full)):
5314 + errors.append(_("verify_missing_file", name, fpath))
5315 + elif deep:
5316 + expected = all_checksums.get(fpath, "")
5317 + if expected:
5318 + actual = _sha256_file(full)
5319 + if actual != expected:
5320 + errors.append(_("verify_sha_mismatch", name, fpath))
5321 +
5322 + if errors:
5323 + print(f"❌ {_('verify_errors', len(errors))}")
5324 + for e in errors: print(e)
5325 + return 1
5326 + total = _db_count_files()
5327 + print(f"✅ {_('verify_ok', total)}")
5328 +
5329 +# =============================================================================
5330 +# PINNING / CLEAN / ORPHANS / REPO / FLATPAK
5331 +# =============================================================================
5332 +
5333 +def cmd_pin(name, version=""):
5334 + pinned = load_json(PINNED_FILE)
5335 + if version:
5336 + pinned[name] = version
5337 + else:
5338 + info = load_json(INSTALLED_DB).get(name, {})
5339 + pinned[name] = info.get("version", "?")
5340 + save_json(PINNED_FILE, pinned)
5341 + print(f"📌 {name} {_('pinned_to')} {pinned[name]}")
5342 +
5343 +def cmd_unpin(name):
5344 + pinned = load_json(PINNED_FILE)
5345 + if name in pinned:
5346 + del pinned[name]; save_json(PINNED_FILE, pinned)
5347 + print(f"🔓 {name} {_('unpinned')}")
5348 + else:
5349 + print(f"⚠ {name} {_('not_pinned')}")
5350 +
5351 +def cmd_pinned():
5352 + pinned = load_json(PINNED_FILE)
5353 + if not pinned: print(_("no_pinned")); return
5354 + print(_("pinned_list", len(pinned)))
5355 + for n,v in sorted(pinned.items()): print(f" 📌 {n} = {v}")
5356 +
5357 +def cmd_clean():
5358 + if os.path.isdir(PAG_CACHE):
5359 + count = size = 0
5360 + for f in os.listdir(PAG_CACHE):
5361 + fp = os.path.join(PAG_CACHE, f)
5362 + if os.path.isfile(fp):
5363 + size += os.path.getsize(fp); os.remove(fp); count += 1
5364 + print(f"✅ {_('cache_cleared', count, size/1048576)}")
5365 +
5366 +def cmd_remove_orphans():
5367 + installed = load_json(INSTALLED_DB)
5368 + world = load_world()
5369 + orphans = _find_orphans(installed, world)
5370 + if not orphans: print(_('✅ No orphans.')); return
5371 + print(_('Orphans ({arg1}):', arg1=(len(orphans))))
5372 + for n in sorted(orphans): print(f" {n}-{installed[n]['version']}")
5373 + if not _ask_confirm():
5374 + return
5375 + cmd_remove(list(orphans))
5376 +
5377 +
5378 +# =============================================================================
5379 +# PROVIDES – PAKIETY WIRTUALNE
5380 +# =============================================================================
5381 +
5382 +PROVIDES_MAP = {
5383 + "pkgconfig(glib-2.0)": "glib",
5384 + "pkgconfig(gobject-introspection-1.0)": "gobject-introspection",
5385 + "pkgconfig(gtk+-3.0)": "gtk",
5386 + "pkgconfig(gtk4)": "gtk",
5387 + "pkgconfig(zlib)": "zlib",
5388 + "pkgconfig(libffi)": "libffi",
5389 + "pkgconfig(expat)": "expat",
5390 + "pkgconfig(libsystemd)": "systemd",
5391 + "pkgconfig(dbus-1)": "dbus",
5392 + "pkgconfig(mount)": "util-linux",
5393 + "pkgconfig(blkid)": "util-linux",
5394 + "pkgconfig(libcap)": "libcap",
5395 + "pkgconfig(liblzma)": "xz",
5396 + "pkgconfig(libzstd)": "zstd",
5397 + "pkgconfig(bzip2)": "bzip2",
5398 + "pkgconfig(libcurl)": "curl",
5399 + "pkgconfig(openssl)": "openssl",
5400 + "pkgconfig(libpcre2-8)": "pcre2",
5401 + "pkgconfig(libxml-2.0)": "libxml2",
5402 + "pkgconfig(libxslt)": "libxslt",
5403 + "pkgconfig(freetype2)": "freetype",
5404 + "pkgconfig(fontconfig)": "fontconfig",
5405 + "pkgconfig(harfbuzz)": "harfbuzz",
5406 + "pkgconfig(cairo)": "cairo",
5407 + "pkgconfig(pango)": "pango",
5408 + "pkgconfig(xt)": "xorg-libxt",
5409 + "pkgconfig(xmu)": "xorg-libxmu",
5410 + "pkgconfig(ice)": "xorg-libice",
5411 + "pkgconfig(sm)": "xorg-libsm",
5412 + "pkgconfig(x11)": "xorg-libx11",
5413 + "pkgconfig(xext)": "xorg-libxext",
5414 + "pkgconfig(xrandr)": "xorg-libxrandr",
5415 + "pkgconfig(xfixes)": "xorg-libxfixes",
5416 + "pkgconfig(xcursor)": "xorg-libxcursor",
5417 + "pkgconfig(xinerama)": "xorg-libxinerama",
5418 + "pkgconfig(xrender)": "xorg-libxrender",
5419 + "pkgconfig(xau)": "xorg-libxau",
5420 + "pkgconfig(xcb)": "xorg-libxcb",
5421 + "pkgconfig(xdamage)": "xorg-libxdamage",
5422 + "pkgconfig(xcomposite)": "xorg-libxcomposite",
5423 + "pkgconfig(xft)": "xorg-libxft",
5424 + "pkgconfig(xss)": "xorg-libxss",
5425 + "pkgconfig(libsoup-3.0)": "libsoup3",
5426 + "pkgconfig(libsoup-2.4)": "libsoup2",
5427 + "pkgconfig(gdk-pixbuf-2.0)": "gdk-pixbuf2",
5428 + "pkgconfig(libpng)": "libpng",
5429 + "pkgconfig(libjpeg)": "libjpeg-turbo",
5430 + "pkgconfig(libtiff-4)": "libtiff",
5431 + "pkgconfig(ffi)": "libffi",
5432 + # ── system / baza ──
5433 + "pkgconfig(libcrypto)": "openssl",
5434 + "pkgconfig(libssl)": "openssl",
5435 + "pkgconfig(libudev)": "systemd",
5436 + "pkgconfig(libmount)": "util-linux",
5437 + "pkgconfig(libblkid)": "util-linux",
5438 + "pkgconfig(uuid)": "util-linux",
5439 + "pkgconfig(libexpat)": "expat",
5440 + "pkgconfig(libpcre)": "pcre",
5441 + "pkgconfig(ncursesw)": "ncurses",
5442 + "pkgconfig(tinfo)": "ncurses",
5443 + "pkgconfig(panel)": "ncurses",
5444 + "pkgconfig(readline)": "readline",
5445 + "pkgconfig(libseccomp)": "libseccomp",
5446 + "pkgconfig(pam)": "linux-pam",
5447 + "pkgconfig(libxcrypt)": "libxcrypt",
5448 + "pkgconfig(libcrypt)": "libxcrypt",
5449 + "pkgconfig(libnsl)": "libnsl",
5450 + "pkgconfig(liblz4)": "lz4",
5451 + "pkgconfig(libevent)": "libevent",
5452 + "pkgconfig(libarchive)": "libarchive",
5453 + "pkgconfig(sqlite3)": "sqlite",
5454 + "pkgconfig(libpq)": "postgresql",
5455 + "pkgconfig(mysqlclient)": "mariadb",
5456 + "pkgconfig(json-c)": "json-c",
5457 + "pkgconfig(json-glib-1.0)": "json-glib",
5458 + "pkgconfig(libunistring)": "libunistring",
5459 + "pkgconfig(libidn2)": "libidn2",
5460 + "pkgconfig(libpsl)": "libpsl",
5461 + "pkgconfig(icu-uc)": "icu",
5462 + "pkgconfig(icu-i18n)": "icu",
5463 + "pkgconfig(icu-io)": "icu",
5464 + "pkgconfig(gnutls)": "gnutls",
5465 + "pkgconfig(nettle)": "nettle",
5466 + "pkgconfig(hogweed)": "nettle",
5467 + "pkgconfig(libgcrypt)": "libgcrypt",
5468 + "pkgconfig(libgpg-error)": "libgpg-error",
5469 + "pkgconfig(libassuan)": "libassuan",
5470 + "pkgconfig(libusb-1.0)": "libusb",
5471 + "pkgconfig(libusb)": "libusb",
5472 + "pkgconfig(libgudev-1.0)": "libgudev",
5473 + "pkgconfig(gudev-1.0)": "libgudev",
5474 + "pkgconfig(polkit-gobject-1)": "polkit",
5475 + "pkgconfig(polkit-agent-1)": "polkit",
5476 + "pkgconfig(libpciaccess)": "libpciaccess",
5477 + "pkgconfig(pixman-1)": "pixman",
5478 + "pkgconfig(libdrm)": "libdrm",
5479 + "pkgconfig(libva)": "libva",
5480 + "pkgconfig(libva-drm)": "libva",
5481 + "pkgconfig(libva-x11)": "libva",
5482 + "pkgconfig(libva-wayland)": "libva",
5483 + "pkgconfig(vdpau)": "libvdpau",
5484 + "pkgconfig(libvdpau)": "libvdpau",
5485 + "pkgconfig(libinput)": "libinput",
5486 + "pkgconfig(libevdev)": "libevdev",
5487 + "pkgconfig(mtdev)": "mtdev",
5488 + # ── grafika / GL / multimedia ──
5489 + "pkgconfig(gbm)": "mesa",
5490 + "pkgconfig(gl)": "libglvnd",
5491 + "pkgconfig(egl)": "libglvnd",
5492 + "pkgconfig(glesv2)": "libglvnd",
5493 + "pkgconfig(glx)": "libglvnd",
5494 + "pkgconfig(vulkan)": "vulkan-loader",
5495 + "pkgconfig(libxkbcommon)": "libxkbcommon",
5496 + "pkgconfig(xkbcommon)": "libxkbcommon",
5497 + "pkgconfig(xkbcommon-x11)": "libxkbcommon",
5498 + "pkgconfig(xcb)": "xorg-libxcb",
5499 + "pkgconfig(xcb-util)": "xcb-util",
5500 + "pkgconfig(xcb-keysyms)": "xcb-util-keysyms",
5501 + "pkgconfig(xcb-icccm)": "xcb-util-wm",
5502 + "pkgconfig(xcb-cursor)": "xcb-util-cursor",
5503 + "pkgconfig(xcb-renderutil)": "xcb-util-renderutil",
5504 + "pkgconfig(xcb-image)": "xcb-util-image",
5505 + "pkgconfig(xcb-errors)": "xcb-util-errors",
5506 + "pkgconfig(wayland-client)": "wayland",
5507 + "pkgconfig(wayland-server)": "wayland",
5508 + "pkgconfig(wayland-cursor)": "wayland",
5509 + "pkgconfig(wayland-egl)": "wayland",
5510 + "pkgconfig(wayland-protocols)": "wayland-protocols",
5511 + "pkgconfig(gstreamer-1.0)": "gstreamer",
5512 + "pkgconfig(gstreamer-base-1.0)": "gstreamer",
5513 + "pkgconfig(gstreamer-check-1.0)": "gstreamer",
5514 + "pkgconfig(gstreamer-controller-1.0)": "gstreamer",
5515 + "pkgconfig(gstreamer-app-1.0)": "gst-plugins-base",
5516 + "pkgconfig(gstreamer-video-1.0)": "gst-plugins-base",
5517 + "pkgconfig(gstreamer-audio-1.0)": "gst-plugins-base",
5518 + "pkgconfig(gstreamer-pbutils-1.0)": "gst-plugins-base",
5519 + "pkgconfig(gstreamer-fft-1.0)": "gst-plugins-base",
5520 + "pkgconfig(gstreamer-riff-1.0)": "gst-plugins-base",
5521 + "pkgconfig(gstreamer-rtp-1.0)": "gst-plugins-base",
5522 + "pkgconfig(gstreamer-rtsp-1.0)": "gst-plugins-base",
5523 + "pkgconfig(gstreamer-sdp-1.0)": "gst-plugins-base",
5524 + "pkgconfig(gstreamer-net-1.0)": "gst-plugins-base",
5525 + "pkgconfig(gstreamer-gl-1.0)": "gst-plugins-base",
5526 + "pkgconfig(libpulse)": "libpulse",
5527 + "pkgconfig(libpulse-simple)": "libpulse",
5528 + "pkgconfig(libpulse-mainloop-glib)": "libpulse",
5529 + "pkgconfig(alsa)": "alsa-lib",
5530 + "pkgconfig(jack)": "jack2",
5531 + "pkgconfig(libsamplerate)": "libsamplerate",
5532 + "pkgconfig(sndfile)": "libsndfile",
5533 + "pkgconfig(libavcodec)": "ffmpeg",
5534 + "pkgconfig(libavformat)": "ffmpeg",
5535 + "pkgconfig(libavutil)": "ffmpeg",
5536 + "pkgconfig(libavfilter)": "ffmpeg",
5537 + "pkgconfig(libswscale)": "ffmpeg",
5538 + "pkgconfig(libswresample)": "ffmpeg",
5539 + "pkgconfig(libpostproc)": "ffmpeg",
5540 + "pkgconfig(SDL2)": "sdl2",
5541 + "pkgconfig(SDL)": "sdl",
5542 + "pkgconfig(SDL2_image)": "sdl2-image",
5543 + "pkgconfig(SDL2_ttf)": "sdl2-ttf",
5544 + "pkgconfig(SDL2_mixer)": "sdl2-mixer",
5545 + "pkgconfig(SDL2_net)": "sdl2-net",
5546 + "pkgconfig(libpng16)": "libpng",
5547 + "pkgconfig(libwebp)": "libwebp",
5548 + "pkgconfig(libwebpmux)": "libwebp",
5549 + "pkgconfig(libwebpdemux)": "libwebp",
5550 + "pkgconfig(libopenjp2)": "openjpeg2",
5551 + "pkgconfig(lcms2)": "lcms2",
5552 + "pkgconfig(libheif)": "libheif",
5553 + "pkgconfig(libde265)": "libde265",
5554 + "pkgconfig(x264)": "x264",
5555 + "pkgconfig(x265)": "x265",
5556 + # ── glib / gio ──
5557 + "pkgconfig(gio-unix-2.0)": "glib",
5558 + "pkgconfig(gmodule-2.0)": "glib",
5559 + "pkgconfig(gthread-2.0)": "glib",
5560 + "pkgconfig(girepository-2.0)": "gobject-introspection",
5561 + "pkgconfig(girepository-1.0)": "gobject-introspection",
5562 + "pkgconfig(libglib-2.0)": "glib",
5563 + "pkgconfig(libgobject-2.0)": "glib",
5564 +}
5565 +
5566 +# Ostrzeżenia o wielu dostawcach tej samej wirtualnej nazwy – raz na proces.
5567 +_PROVIDES_WARNED = set()
5568 +# Cache indeksu provides dla danego obiektu repo: (repo_obj, {virtual: [pkg,...]}).
5569 +# Trzymamy referencję do repo, by uniknąć pomyłki przy ponownym użyciu id().
5570 +_provides_cache = (None, {})
5571 +
5572 +def _provides_index(repo: dict) -> dict:
5573 + """Buduje (i cache’uje) mapę wirtualna nazwa → lista dostawców w repo.
5574 +
5575 + Pozwala wybrać dostawcę DETERMINISTYCZNIE (posortowanego) zamiast zależeć
5576 + od kolejności wstawiania w repo.json, oraz ostrzec o konflikcie provides."""
5577 + global _provides_cache
5578 + cached_repo, idx = _provides_cache
5579 + if cached_repo is repo:
5580 + return idx
5581 + idx = {}
5582 + for _pn, _p in repo.items():
5583 + for _prov in (getattr(_p, "provides", None) or []):
5584 + idx.setdefault(_prov, []).append(_pn)
5585 + for _prov, _pns in idx.items():
5586 + if len(_pns) > 1 and _prov not in _PROVIDES_WARNED:
5587 + _PROVIDES_WARNED.add(_prov)
5588 + _sorted = sorted(_pns)
5589 + print(f" ⚠ {_('provides_conflict', name=_prov, providers=', '.join(_sorted), chosen=_sorted[0])}",
5590 + file=sys.stderr)
5591 + _provides_cache = (repo, idx)
5592 + return idx
5593 +
5594 +
5595 +def _resolve_provides(name: str, repo: dict, installed: Optional[dict] = None) -> str:
5596 + """Rozwija wirtualną nazwę pakietu do rzeczywistej nazwy.
5597 +
5598 + Kolejność: repo → PROVIDES_MAP → wzorce → provides z repo.json →
5599 + provides ZAINSTALOWANYCH pakietów (lokalnie zbudowane poza repo też
5600 + dostarczają wirtualne zależności) → fallback pkgconfig (czyszczenie nazwy).
5601 + """
5602 + if name in repo:
5603 + return name
5604 + if name in PROVIDES_MAP:
5605 + real = PROVIDES_MAP[name]
5606 + if real in repo:
5607 + return real
5608 + # Wzorce: moduły Qt (Qt5Core/Qt6Widgets) i GStreamer (gstreamer-video-1.0)
5609 + if name.startswith("pkgconfig(Qt5"):
5610 + real = "qt5"
5611 + if real in repo:
5612 + return real
5613 + if name.startswith("pkgconfig(Qt6"):
5614 + real = "qt6"
5615 + if real in repo:
5616 + return real
5617 + if name.startswith("pkgconfig(gstreamer-") and name.endswith("-1.0)"):
5618 + real = "gstreamer"
5619 + if real in repo:
5620 + return real
5621 + if name.startswith("pkgconfig(gst-"):
5622 + real = "gst-plugins-base"
5623 + if real in repo:
5624 + return real
5625 + # Dynamiczne provides z repo.json (sekcja provides: w PAGBUILD.yaml)
5626 + # Determinizm: przy wielu dostawcach wybieramy posortowanego pierwszego
5627 + # (i ostrzegamy raz), zamiast zależeć od kolejności w repo.json.
5628 + _idx = _provides_index(repo)
5629 + if name in _idx:
5630 + return min(_idx[name])
5631 + # provides ZAINSTALOWANYCH pakietów – lokalnie zbudowane (pagbuild, poza
5632 + # repo) też dostarczają wirtualne zależności i muszą być rozpoznawane.
5633 + if installed:
5634 + _inst_cands = [pn for pn, meta in installed.items()
5635 + if isinstance(meta, dict) and name in (meta.get("provides") or [])]
5636 + if _inst_cands:
5637 + return min(_inst_cands)
5638 + clean = name
5639 + if name.startswith("pkgconfig(") and ")" in name:
5640 + clean = name.split("(", 1)[1].rstrip(")")
5641 + elif name.startswith("pkgconfig32(") and ")" in name:
5642 + clean = name.split("(", 1)[1].rstrip(")")
5643 + if clean != name and clean in repo:
5644 + return clean
5645 + return name
5646 +
5647 +
5648 +def cmd_why(pkg_name: str):
5649 + """Pokazuje dlaczego pakiet jest zainstalowany."""
5650 + installed = load_json(INSTALLED_DB)
5651 + world = load_world()
5652 + if pkg_name not in installed:
5653 + print(f" {pkg_name}: {_('why_not_installed')}"); return 1
5654 + if pkg_name in world:
5655 + print(f" {pkg_name}-{installed[pkg_name]['version']}: {_('why_explicit')}")
5656 + return 0
5657 + parents = set()
5658 + for w in world:
5659 + _find_dep_path(w, pkg_name, installed, set(), [], parents)
5660 + if parents:
5661 + for pp in sorted(parents):
5662 + print(f" {pkg_name}: {_('why_dependency')} {' → '.join(pp)}")
5663 + else:
5664 + print(f" {pkg_name}: {_('why_dependency')} (unknown/orphan)")
5665 + return 0
5666 +
5667 +
5668 +def _find_dep_path(cur, target, installed, visited, path, results):
5669 + if cur in visited: return
5670 + visited.add(cur); path.append(cur)
5671 + if cur == target:
5672 + results.add(tuple(path))
5673 + else:
5674 + for dep in installed.get(cur, {}).get("dependencies", []):
5675 + _find_dep_path(dep, target, installed, visited, path, results)
5676 + path.pop(); visited.discard(cur)
5677 +
5678 +
5679 +def cmd_rdepends(pkg_name: str):
5680 + """Pokazuje które pakiety zależą od danego pakietu (reverse dependencies).
5681 +
5682 + Odwrotność `pag why`: dla każdego zainstalowanego pakietu sprawdza, czy
5683 + któraś z jego zależności (także wirtualna, przez provides) wskazuje na
5684 + pkg_name. Przydatne przed `pag remove` – pokazuje, co przestanie działać.
5685 + """
5686 + installed = load_json(INSTALLED_DB)
5687 + if pkg_name not in installed:
5688 + print(f" {pkg_name}: {_('why_not_installed')}"); return 1
5689 + world = load_world()
5690 + # Nazwy, które zależą od pkg_name – sama nazwa plus jej wirtualne provides.
5691 + provided = {pkg_name} | set(installed[pkg_name].get("provides") or [])
5692 + rev = []
5693 + for name, meta in installed.items():
5694 + if name == pkg_name:
5695 + continue
5696 + for dep in (meta.get("dependencies") or []):
5697 + if dep in provided or _resolve_provides(dep, {}, installed) == pkg_name:
5698 + rev.append(name); break
5699 + if not rev:
5700 + print(f" {pkg_name}: {_('rdepends_none')}")
5701 + return 0
5702 + print(f"🔗 {_('rdepends_title', pkg_name, len(rev))}")
5703 + for n in sorted(rev):
5704 + kind = _("why_explicit") if n in world else _("why_dependency")
5705 + print(f" {n}-{installed[n].get('version', '?')} ({kind})")
5706 + return 0
5707 +
5708 +
5709 +def cmd_autoremove():
5710 + """Automatycznie usuwa osierocone zależności bez pytania."""
5711 + installed = load_json(INSTALLED_DB)
5712 + world = load_world()
5713 + orphans = _find_orphans(installed, world)
5714 + if not orphans: print(f"✅ {_('autoremove_none')}"); return 0
5715 + print(f"🗑 {_('orphans_found', len(orphans), ', '.join(sorted(orphans)[:10]))}")
5716 + return cmd_remove(list(orphans))
5717 +
5718 +
5719 +def cmd_download(package_names):
5720 + """Pobiera pakiety do cache bez instalowania."""
5721 + ensure_dirs()
5722 + repo = fetch_all_packages()
5723 + if not repo: print(f"❌ {_('no_index')}"); return 1
5724 + total_size = 0; downloaded = []
5725 + for name in package_names:
5726 + pkg = repo.get(name)
5727 + if not pkg:
5728 + print(f" ❌ {name}: {_('not_found')}"); continue
5729 + print(f" ↓ {name}-{pkg.version} ...", end=" ", flush=True)
5730 + path = _download_pkg(pkg)
5731 + if path:
5732 + total_size += os.path.getsize(path)
5733 + downloaded.append(name)
5734 + print(_c("green", "✓"))
5735 + else:
5736 + print(_c("red", "✗"))
5737 + if downloaded:
5738 + print(f"\n✅ {_('downloaded', len(downloaded), total_size/1048576)}")
5739 + return 0 if len(downloaded) == len(package_names) else 1
5740 +
5741 +
5742 +def cmd_stats():
5743 + """Wyświetla statystyki PAG."""
5744 + installed = load_json(INSTALLED_DB)
5745 + history = load_json(HISTORY_FILE) if os.path.exists(HISTORY_FILE) else []
5746 + total_size = sum(i.get("size_bytes", 0) for i in installed.values())
5747 + total_files = _db_count_files()
5748 + cache_size = sum(
5749 + os.path.getsize(os.path.join(PAG_CACHE, f))
5750 + for f in os.listdir(PAG_CACHE)
5751 + if os.path.isfile(os.path.join(PAG_CACHE, f))
5752 + ) if os.path.isdir(PAG_CACHE) else 0
5753 + last_update = _("never")
5754 + for e in reversed(history):
5755 + if e.get("action") in ("install", "upgrade") and e.get("success"):
5756 + last_update = e.get("timestamp", "?")[:19]; break
5757 + print(f"\n {_c('bold', _('stats_title'))}")
5758 + print(f" {'─' * 40}")
5759 + print(f" {_('stats_packages'):<30} {len(installed)}")
5760 + print(f" {_('stats_files'):<30} {total_files}")
5761 + print(f" {_('stats_size'):<30} {total_size/1048576:.1f} MB")
5762 + print(f" {_('stats_cache'):<30} {cache_size/1048576:.1f} MB")
5763 + print(f" {_('stats_history'):<30} {len(history)}")
5764 + print(f" {_('stats_last_update'):<30} {last_update}")
5765 + _bs = _base_summary(repo={}) # bez sieci – tylko stan zarządzania bazą
5766 + if _bs["total"]:
5767 + _bt = f"{_bs['tracked']}/{_bs['total']}"
5768 + if _bs["tracked"] < _bs["total"]:
5769 + _bt += " (sudo pag base adopt)"
5770 + print(f" {_('stats_base'):<30} {_bt}")
5771 + by_size = sorted(installed.items(), key=lambda x: x[1].get("size_bytes", 0), reverse=True)[:5]
5772 + if by_size:
5773 + print(f"\n {_c('dim', _('stats_top'))}")
5774 + for n, i in by_size:
5775 + print(f" {n}-{i['version']} {i.get('size_bytes',0)/1048576:.1f} MB")
5776 + return 0
5777 +
5778 +
5779 +def cmd_repo_add(url, name=None):
5780 + if not url.startswith("https://") and not os.environ.get("PAG_INSECURE"):
5781 + print(f" {_('sec_https')}"); return 1
5782 + ensure_dirs()
5783 + url = url.rstrip("/")
5784 + repos = get_repos()
5785 + if url in repos: print(f"⚠ {_('repo_exists', url)}"); return
5786 + if name:
5787 + # Drop-in: /etc/pag/repos/<nazwa>.conf (jak `echo url > .../stable.conf`)
5788 + os.makedirs(REPOS_DIR, exist_ok=True)
5789 + target = os.path.join(REPOS_DIR, name.rstrip("/").replace("/", "_") + ".conf")
5790 + with open(target, "w") as f: f.write(f"{url}\n")
5791 + print(f"✅ {_('repo_added', url)} → {target}")
5792 + return
5793 + with open(REPOS_CONF, "a") as f: f.write(f"{url}\n")
5794 + print(f"✅ {_('repo_added', url)}")
5795 +
5796 +def cmd_repo_list():
5797 + for i, url in enumerate(get_repos(), 1): print(f" {i}. {url}")
5798 +
5799 +FLATPAK_REMOTE_URL = "https://flathub.org/repo/flathub.flatpakrepo"
5800 +
5801 +def _check_flatpak(quiet: bool = False):
5802 + if not shutil.which("flatpak"):
5803 + if not quiet:
5804 + print(f"❌ {_('flatpak_missing')}")
5805 + return False
5806 + r = subprocess.run(["flatpak", "remotes"], capture_output=True, text=True)
5807 + if "flathub" not in r.stdout:
5808 + print(f"⚠ {_('flatpak_adding')}")
5809 + # Jako root dodajemy remote systemowy; bez roota – w instalacji użytkownika,
5810 + # żeby remote i miejsce instalacji były spójne (patrz _flatpak_do_install).
5811 + add = ["flatpak", "remote-add", "--if-not-exists"]
5812 + if os.geteuid() != 0:
5813 + add.append("--user")
5814 + subprocess.run(add + ["flathub", FLATPAK_REMOTE_URL], check=False)
5815 + return True
5816 +
5817 +def _spinner(msg: str):
5818 + """Prosty spinner „myślenia” w osobnym wątku. Zwraca funkcję stop()."""
5819 + stop = threading.Event()
5820 + def _spin():
5821 + for c in itertools.cycle("|/-\\"):
5822 + if stop.is_set():
5823 + break
5824 + sys.stdout.write(f"\r {msg} {c}")
5825 + sys.stdout.flush()
5826 + time.sleep(0.1)
5827 + t = threading.Thread(target=_spin, daemon=True)
5828 + t.start()
5829 + def _stop():
5830 + stop.set()
5831 + t.join(timeout=0.3)
5832 + sys.stdout.write("\r" + " " * (len(msg) + 4) + "\r")
5833 + sys.stdout.flush()
5834 + return _stop
5835 +
5836 +
5837 +def _flatpak_search_raw(query: str) -> List[dict]:
5838 + """Szuka we Flathub i zwraca listę wyników jako słowniki."""
5839 + if not _check_flatpak():
5840 + return []
5841 + stop = _spinner(_("flatpak_searching_any"))
5842 + try:
5843 + try:
5844 + r = subprocess.run(
5845 + ["flatpak", "search", "--columns=name,description,application,version,branch,remotes", query],
5846 + capture_output=True, text=True, timeout=120
5847 + )
5848 + finally:
5849 + stop()
5850 + if r.returncode != 0 and "No matches found" not in r.stdout and not r.stdout.strip():
5851 + print(f" ⚠ flatpak search: {r.stderr.strip()[:150]}")
5852 + results = []
5853 + for line in r.stdout.strip().split("\n"):
5854 + parts = line.split("\t")
5855 + if len(parts) >= 3:
5856 + results.append({
5857 + "name": parts[0].strip(),
5858 + "description": parts[1].strip() if len(parts) > 1 else "",
5859 + "app_id": parts[2].strip() if len(parts) > 2 else "",
5860 + "version": parts[3].strip() if len(parts) > 3 else "",
5861 + "branch": parts[4].strip() if len(parts) > 4 else "stable",
5862 + "origin": parts[5].strip() if len(parts) > 5 else "flathub",
5863 + })
5864 + return results
5865 + except Exception as e:
5866 + print(_(' ⚠ Search error: {arg1}', arg1=(e)), file=sys.stderr)
5867 + return []
5868 +
5869 +def _flatpak_find_best(query: str) -> Optional[dict]:
5870 + """
5871 + Szuka we Flathub i próbuje znaleźć najlepsze dopasowanie.
5872 + - Jeśli query dokładnie pasuje do app_id → zwraca od razu
5873 + - Jeśli query pasuje do nazwy → zwraca pierwsze
5874 + - Jeśli wiele wyników → wyświetla listę i pyta użytkownika
5875 + - Jeśli brak → zwraca None
5876 + """
5877 + results = _flatpak_search_raw(query)
5878 + if not results:
5879 + return None
5880 +
5881 + # Dokładne dopasowanie app_id
5882 + exact = [r for r in results if r["app_id"].lower() == query.lower()]
5883 + if exact:
5884 + return exact[0]
5885 +
5886 + # Dokładne dopasowanie nazwy
5887 + exact_name = [r for r in results if r["name"].lower() == query.lower()]
5888 + if exact_name:
5889 + return exact_name[0]
5890 +
5891 + # Jednoznaczne dopasowanie (tylko 1 wynik)
5892 + if len(results) == 1:
5893 + return results[0]
5894 +
5895 + # Wiele wyników – pokaż użytkownikowi
5896 + print(f"\n {_('flatpak_found', len(results))}")
5897 + for i, r in enumerate(results):
5898 + print(f" {i+1}. {_c('bold', r['name'])} ({r['app_id']})")
5899 + if r["version"]:
5900 + print(f" {_('flatpak_info_version')}: {r['version']}")
5901 + if r["description"]:
5902 + desc = r["description"][:80] + ("..." if len(r["description"]) > 80 else "")
5903 + print(f" {desc}")
5904 +
5905 + try:
5906 + choice = input(_('\n Choose a number (1-{arg1}) or press Enter to cancel:', arg1=(len(results)))).strip()
5907 + if not choice:
5908 + return None
5909 + idx = int(choice) - 1
5910 + if 0 <= idx < len(results):
5911 + return results[idx]
5912 + except (EOFError, ValueError, IndexError):
5913 + pass
5914 + return None
5915 +
5916 +def _flatpak_get_installed_info(app_id: str) -> Optional[dict]:
5917 + """Zwraca info o zainstalowanym flatpaku lub None."""
5918 + try:
5919 + r = subprocess.run(
5920 + ["flatpak", "info", "--columns=name,version,branch,origin,installed-size,description", app_id],
5921 + capture_output=True, text=True, timeout=10
5922 + )
5923 + if r.returncode != 0:
5924 + return None
5925 + parts = r.stdout.strip().split("\t")
5926 + if len(parts) < 3:
5927 + return None
5928 + return {
5929 + "name": parts[0].strip(),
5930 + "version": parts[1].strip() if len(parts) > 1 else "",
5931 + "branch": parts[2].strip() if len(parts) > 2 else "",
5932 + "origin": parts[3].strip() if len(parts) > 3 else "",
5933 + "size": parts[4].strip() if len(parts) > 4 else "",
5934 + "description": parts[5].strip() if len(parts) > 5 else "",
5935 + }
5936 + except Exception:
5937 + return None
5938 +
5939 +def _flatpak_is_installed(app_id: str) -> bool:
5940 + """Sprawdza czy flatpak o danym ID jest zainstalowany."""
5941 + try:
5942 + r = subprocess.run(
5943 + ["flatpak", "info", app_id],
5944 + capture_output=True, text=True, timeout=10
5945 + )
5946 + return r.returncode == 0
5947 + except Exception:
5948 + return False
5949 +
5950 +# =============================================================================
5951 +# FLATPAK – KOMENDY GŁÓWNE (zunifikowany interfejs)
5952 +# =============================================================================
5953 +# pag flatpak <query> → szuka i proponuje instalację (jeśli nie zainstalowany)
5954 +# pag flatpak search <query> → tylko szuka
5955 +# pag flatpak install <query> → instaluje
5956 +# pag flatpak remove <id> → usuwa
5957 +# pag flatpak list → lista zainstalowanych
5958 +# pag flatpak update → aktualizuje wszystkie
5959 +# pag flatpak info <id> → szczegóły flatpaka
5960 +
5961 +def cmd_flatpak(args: list):
5962 + """
5963 + Główna komenda flatpak – inteligentnie rozpoznaje intencję:
5964 + pag flatpak firefox → szuka i instaluje (jeśli nieznaleziony → szuka)
5965 + pag flatpak search firefox → tylko wyszukiwanie
5966 + pag flatpak install ... → bezpośrednia instalacja
5967 + pag flatpak remove ... → odinstalowanie
5968 + pag flatpak list → lista
5969 + pag flatpak update → aktualizacja
5970 + pag flatpak info ... → szczegóły
5971 + """
5972 + if not _check_flatpak():
5973 + return 1
5974 +
5975 + if not args:
5976 + # Bez argumentów – domyślnie lista
5977 + return cmd_flatpak_list()
5978 +
5979 + subcmd = args[0].lower()
5980 + rest = args[1:]
5981 +
5982 + # ── Podkomendy jawne ────────────────────────────────────────────────
5983 + if subcmd == "search":
5984 + if not rest:
5985 + print(_("flatpak_usage")); return 1
5986 + return cmd_flatpak_search(" ".join(rest))
5987 +
5988 + elif subcmd == "install":
5989 + if not rest:
5990 + print(_("flatpak_usage")); return 1
5991 + return _flatpak_smart_install(rest)
5992 +
5993 + elif subcmd == "remove" or subcmd == "uninstall":
5994 + if not rest:
5995 + print(_("flatpak_usage")); return 1
5996 + return _flatpak_smart_remove(rest)
5997 +
5998 + elif subcmd == "list":
5999 + return cmd_flatpak_list()
6000 +
6001 + elif subcmd == "update":
6002 + return cmd_flatpak_update()
6003 +
6004 + elif subcmd == "info":
6005 + if not rest:
6006 + print(_("flatpak_usage")); return 1
6007 + return cmd_flatpak_info(rest[0])
6008 +
6009 + else:
6010 + # ── Inteligentne wykrywanie: pag flatpak <nazwa> ────────────────
6011 + # Sprawdź czy to zainstalowany flatpak → pokaż info
6012 + # Jeśli nie → szukaj i zaproponuj instalację
6013 + query = " ".join(args)
6014 +
6015 + # Najpierw sprawdź czy już zainstalowany
6016 + if _flatpak_is_installed(query):
6017 + print(_(" 📦 {arg1} – already installed (use 'pag flatpak info {arg2}' for details)", arg1=(_c('green', query)), arg2=(query)))
6018 + return cmd_flatpak_info(query)
6019 +
6020 + # Szukaj we Flathub
6021 + print(f" {_('flatpak_searching', query)}")
6022 + best = _flatpak_find_best(query)
6023 + if not best:
6024 + print(f" ❌ '{query}' – {_('flatpak_not_found')}")
6025 + return 1
6026 +
6027 + print(f"\n {_c('cyan', best['name'])} ({best['app_id']})")
6028 + if best["version"]:
6029 + print(f" {_('flatpak_info_version')}: {best['version']}")
6030 + if best["description"]:
6031 + print(f" {best['description']}")
6032 +
6033 + try:
6034 + ans = input(f"\n {_('flatpak_install_prompt', best['name'])}").strip().lower()
6035 + except (EOFError, KeyboardInterrupt):
6036 + print(f"\n ⚠ {_('no_tty')}")
6037 + return 0
6038 + if ans and ans not in ("t", "y"):
6039 + print(_("cancelled"))
6040 + return 0
6041 +
6042 + return _flatpak_do_install(best["app_id"])
6043 +
6044 +def _flatpak_smart_install(names: list) -> int:
6045 + """Instaluje flatpaki – obsługuje nazwy częściowe (wyszukuje przed instalacją)."""
6046 + failed = 0
6047 + for name in names:
6048 + if "." in name and "/" not in name:
6049 + # Wygląda na pełne app_id (np. org.mozilla.firefox)
6050 + app_id = name
6051 + else:
6052 + # Szukaj najlepszego dopasowania
6053 + best = _flatpak_find_best(name)
6054 + if not best:
6055 + print(f" ❌ '{name}' – {_('flatpak_not_found')}")
6056 + failed += 1
6057 + continue
6058 + app_id = best["app_id"]
6059 + print(f" → {best['name']} ({app_id})")
6060 +
6061 + if _flatpak_do_install(app_id) != 0:
6062 + failed += 1
6063 + return 1 if failed else 0
6064 +
6065 +def _flatpak_export_dirs() -> List[str]:
6066 + """Katalogi eksportów Flatpaka (system + użytkownika) obecne na dysku.
6067 +
6068 + Instalacja użytkownika roota (/root/.local/share/flatpak) jest świadomie
6069 + POMIJANA – to wewnętrzny artefakt roota, którego sesja użytkownika nigdy
6070 + nie zobaczy (patrz _flatpak_do_install)."""
6071 + dirs = ["/var/lib/flatpak/exports"]
6072 + home = os.path.expanduser("~")
6073 + if home and home not in ("/root", "/"):
6074 + dirs.append(os.path.join(home, ".local", "share", "flatpak", "exports"))
6075 + return [d for d in dirs if os.path.isdir(d)]
6076 +
6077 +
6078 +def _flatpak_refresh_caches() -> None:
6079 + """Odświeża cache pulpitu i ikon po zmianie w Flatpaku (best-effort).
6080 +
6081 + Flatpak robi to sam, ale tylko gdy `update-desktop-database` jest w PATH.
6082 + Bez tego nowo zainstalowana aplikacja bywa nieobecna w menu."""
6083 + for exports in _flatpak_export_dirs():
6084 + apps = os.path.join(exports, "share", "applications")
6085 + if os.path.isdir(apps) and shutil.which("update-desktop-database"):
6086 + subprocess.run(["update-desktop-database", apps],
6087 + capture_output=True, check=False, timeout=60)
6088 + icons = os.path.join(exports, "share", "icons", "hicolor")
6089 + if os.path.isdir(icons) and shutil.which("gtk-update-icon-cache"):
6090 + subprocess.run(["gtk-update-icon-cache", "-q", "-t", "-f", icons],
6091 + capture_output=True, check=False, timeout=120)
6092 +
6093 +
6094 +def _flatpak_session_sees_exports() -> bool:
6095 + """Czy bieżąca sesja ma eksporty Flatpaka w XDG_DATA_DIRS."""
6096 + raw = os.environ.get("XDG_DATA_DIRS", "")
6097 + dirs = {d for d in raw.split(":") if d} or {"/usr/local/share", "/usr/share"}
6098 + return any(os.path.join(e, "share") in dirs for e in _flatpak_export_dirs())
6099 +
6100 +
6101 +def _flatpak_warn_if_invisible() -> None:
6102 + """Ostrzega, gdy sesja nie widzi eksportów – inaczej wygląda to jak
6103 + „zainstalowało się, ale nie ma go w menu / na PC”."""
6104 + if not _flatpak_session_sees_exports():
6105 + print(f" ⚠ {_('flatpak_menu_hint')}")
6106 + print(f" {_('flatpak_menu_fix')}")
6107 +
6108 +
6109 +def _flatpak_do_install(app_id: str) -> int:
6110 + """Wykonuje właściwą instalację flatpaka.
6111 +
6112 + Jako root wymuszamy instalację SYSTEMOWĄ (--system). Bez tego `flatpak`
6113 + uruchomiony jako root potrafi zainstalować aplikację w instalacji
6114 + użytkownika roota (/root/.local/share/flatpak) – widocznej dla roota, ale
6115 + nie dla zalogowanego użytkownika. To dokładnie efekt „instaluje, ale nie
6116 + mam tego na PC”. Bez roota próbujemy instalacji systemowej (polkit),
6117 + a w razie niepowodzenia cofamy się do instalacji użytkownika (--user).
6118 +
6119 + Zakres (scope) ma znaczenie: instalacja SYSTEMOWA (--system) jest widoczna
6120 + dla wszystkich użytkowników, a --user tylko dla bieżącego (dla roota:
6121 + /root/.local/... → niewidoczna dla sesji). `flatpak list` bez flag pokazuje
6122 + oba zakresy, więc systemowa instalacja roota jest widoczna też dla
6123 + zwykłego użytkownika."""
6124 + print(f" {_('flatpak_installing', app_id)}")
6125 + if os.geteuid() == 0:
6126 + result = subprocess.run(
6127 + ["flatpak", "install", "-y", "--system", "flathub", app_id],
6128 + check=False, timeout=600)
6129 + else:
6130 + result = subprocess.run(
6131 + ["flatpak", "install", "-y", "flathub", app_id],
6132 + check=False, timeout=600)
6133 + if result.returncode != 0:
6134 + # Flathub tylko dla użytkownika / brak agenta polkit – instalacja
6135 + # lokalna użytkownika jest lepsza niż twardy błąd.
6136 + subprocess.run(
6137 + ["flatpak", "remote-add", "--if-not-exists", "--user",
6138 + "flathub", FLATPAK_REMOTE_URL], check=False, timeout=60)
6139 + result = subprocess.run(
6140 + ["flatpak", "install", "-y", "--user", "flathub", app_id],
6141 + check=False, timeout=600)
6142 + if result.returncode != 0:
6143 + print(f" ❌ {_('download_fail')}: {app_id}")
6144 + return 1
6145 + _flatpak_refresh_caches()
6146 + print(f" ✅ {_('flatpak_installed', app_id)}")
6147 + _flatpak_warn_if_invisible()
6148 + return 0
6149 +
6150 +def _flatpak_smart_remove(names: list) -> int:
6151 + """Usuwa flatpaki – obsługuje nazwy częściowe."""
6152 + # Pobierz listę zainstalowanych
6153 + try:
6154 + r = subprocess.run(
6155 + ["flatpak", "list", "--columns=application,name"],
6156 + capture_output=True, text=True, timeout=10
6157 + )
6158 + installed = {}
6159 + for line in r.stdout.strip().split("\n"):
6160 + parts = line.split("\t")
6161 + if len(parts) >= 2:
6162 + installed[parts[0].strip()] = parts[1].strip()
6163 + except Exception:
6164 + installed = {}
6165 +
6166 + failed = 0
6167 + for name in names:
6168 + app_id = name
6169 +
6170 + # Jeśli nie podano pełnego ID – spróbuj dopasować
6171 + if name not in installed:
6172 + matches = {aid: aname for aid, aname in installed.items()
6173 + if name.lower() in aid.lower() or name.lower() in aname.lower()}
6174 + if len(matches) == 0:
6175 + print(f" ❌ '{name}' – {_('flatpak_not_installed', name)}")
6176 + failed += 1
6177 + continue
6178 + elif len(matches) == 1:
6179 + app_id = list(matches.keys())[0]
6180 + print(f" → {matches[app_id]} ({app_id})")
6181 + else:
6182 + print(_("\n Multiple matches for '{arg1}':", arg1=(name)))
6183 + for i, (aid, aname) in enumerate(sorted(matches.items()), 1):
6184 + print(f" {i}. {aname} ({aid})")
6185 + try:
6186 + choice = input(_('\n Choose a number (1-{arg1}) or press Enter:', arg1=(len(matches)))).strip()
6187 + if not choice:
6188 + failed += 1
6189 + continue
6190 + aid_list = sorted(matches.keys())
6191 + app_id = aid_list[int(choice) - 1]
6192 + except (EOFError, ValueError, IndexError):
6193 + failed += 1
6194 + continue
6195 +
6196 + print(f" 🗑 {app_id} ...", end=" ", flush=True)
6197 + result = subprocess.run(
6198 + ["flatpak", "uninstall", "-y", app_id],
6199 + capture_output=True, text=True, timeout=120
6200 + )
6201 + if result.returncode == 0:
6202 + print("✅")
6203 + print(f" {_('flatpak_removed', app_id)}")
6204 + else:
6205 + print("❌")
6206 + failed += 1
6207 + if not failed:
6208 + _flatpak_refresh_caches()
6209 + return 1 if failed else 0
6210 +
6211 +def cmd_flatpak_search(q: str):
6212 + """Wyszukuje we Flathub i wyświetla wyniki (z możliwością wyboru do instalacji)."""
6213 + if not _check_flatpak():
6214 + return 1
6215 + results = _flatpak_search_raw(q)
6216 + if not results:
6217 + print(f" ❌ '{q}' – {_('flatpak_not_found')}")
6218 + return 1
6219 + print(f"\n {_('flatpak_found', len(results))}")
6220 + shown = results[:30] # max 30 wyników
6221 + for i, r in enumerate(shown, 1):
6222 + installed = "📦 " if _flatpak_is_installed(r["app_id"]) else " "
6223 + print(f" {i:>2}. {installed}{_c('bold', r['name'])} ({r['app_id']})")
6224 + if r["version"]:
6225 + print(f" {_('flatpak_info_version')}: {r['version']} | {_('flatpak_info_branch')}: {r['branch']}")
6226 + if r["description"]:
6227 + desc = r["description"][:100] + ("..." if len(r["description"]) > 100 else "")
6228 + print(f" {_c('dim', desc)}")
6229 + if len(results) > 30:
6230 + print(_(' ... and {arg1} more. Refine your query.', arg1=(len(results) - 30)))
6231 +
6232 + # Interaktywny wybór – wpisz numer, aby zainstalować (Enter = anuluj)
6233 + try:
6234 + ans = input(_('\n Choose a number to install (1-{arg1}) or press Enter to cancel:', arg1=(len(shown)))).strip()
6235 + except (EOFError, KeyboardInterrupt):
6236 + return 0
6237 + if ans:
6238 + try:
6239 + idx = int(ans) - 1
6240 + if 0 <= idx < len(shown):
6241 + return _flatpak_do_install(shown[idx]["app_id"])
6242 + print(_("cancelled"))
6243 + except (ValueError, IndexError):
6244 + print(_("cancelled"))
6245 + return 0
6246 +
6247 +def cmd_flatpak_list():
6248 + """Wyświetla zainstalowane flatpaki."""
6249 + if not _check_flatpak():
6250 + return 1
6251 + r = subprocess.run(
6252 + ["flatpak", "list", "--columns=application,name,version,origin,installation,installed-size"],
6253 + capture_output=True, text=True, timeout=10
6254 + )
6255 + lines = [l for l in r.stdout.strip().split("\n") if l.strip()]
6256 + if not lines:
6257 + print(_(' (no installed flatpaks)'))
6258 + return 0
6259 + print(_('Installed flatpaks ({arg1}):', arg1=(len(lines))))
6260 + for line in lines:
6261 + parts = line.split("\t")
6262 + if len(parts) >= 3:
6263 + app_id, name, version = parts[0], parts[1], parts[2]
6264 + scope = parts[4] if len(parts) > 4 else ""
6265 + size = parts[5] if len(parts) > 5 else ""
6266 + size_str = f" ({size})" if size else ""
6267 + scope_str = f" [{scope}]" if scope else ""
6268 + print(f" 📦 {_c('bold', name)} {version}{scope_str}{size_str}")
6269 + print(f" {_c('dim', app_id)}")
6270 + return 0
6271 +
6272 +def cmd_flatpak_update():
6273 + """Aktualizuje wszystkie flatpaki."""
6274 + if not _check_flatpak():
6275 + return 1
6276 + print(_(' 🔄 Updating flatpaks...'))
6277 + result = subprocess.run(["flatpak", "update", "-y"], check=False, timeout=600)
6278 + if result.returncode == 0:
6279 + _flatpak_refresh_caches()
6280 + print(f" ✅ {_('flatpak_updated')}")
6281 + return result.returncode
6282 +
6283 +def cmd_flatpak_info(app_id: str):
6284 + """Wyświetla szczegóły flatpaka (zainstalowanego lub z Flathub)."""
6285 + if not _check_flatpak():
6286 + return 1
6287 +
6288 + # Najpierw sprawdź zainstalowany
6289 + info = _flatpak_get_installed_info(app_id)
6290 + if info:
6291 + print(f"\n 📦 {_c('bold', info['name'])} {_c('green', '[zainstalowany]')}")
6292 + print(f" {'─' * 45}")
6293 + print(f" {_('flatpak_info_id'):<16} {app_id}")
6294 + print(f" {_('flatpak_info_version'):<16} {info['version']}")
6295 + print(f" {_('flatpak_info_branch'):<16} {info['branch']}")
6296 + print(f" {_('flatpak_info_origin'):<16} {info['origin']}")
6297 + if info["size"]:
6298 + print(f" {_('flatpak_info_size'):<16} {info['size']}")
6299 + if info["description"]:
6300 + print(f" {_('flatpak_info_desc'):<16} {info['description']}")
6301 + return 0
6302 +
6303 + # Szukaj we Flathub
6304 + results = _flatpak_search_raw(app_id)
6305 + exact = [r for r in results if r["app_id"].lower() == app_id.lower()]
6306 + if not exact:
6307 + # Spróbuj częściowego dopasowania
6308 + if results:
6309 + exact = [results[0]]
6310 + else:
6311 + print(f" ❌ '{app_id}' – {_('flatpak_not_found')}")
6312 + return 1
6313 +
6314 + r = exact[0]
6315 + print(f"\n 📦 {_c('bold', r['name'])} (Flathub)")
6316 + print(f" {'─' * 45}")
6317 + print(f" {_('flatpak_info_id'):<16} {r['app_id']}")
6318 + print(f" {_('flatpak_info_version'):<16} {r['version']}")
6319 + if r["description"]:
6320 + print(f" {_('flatpak_info_desc'):<16} {r['description']}")
6321 + print(_('\n 💡 To install: pag flatpak install {arg1}', arg1=(r['app_id'])))
6322 + return 0
6323 +
6324 +# =============================================================================
6325 +# IMMUTABLE OS – KOMENDY DEPLOYMENTOWE
6326 +# =============================================================================
6327 +
6328 +# Pakiety jądra – po ich instalacji trzeba przebudować initramfs
6329 +KERNEL_PACKAGE_PATTERNS = ["linux", "kernel", "linux-kernel", "linux-lts"]
6330 +
6331 +def _is_kernel_package(name: str) -> bool:
6332 + """Sprawdza czy pakiet to jądro (wymaga przebudowy initramfs)."""
6333 + name_lower = name.lower()
6334 + return any(pattern in name_lower for pattern in KERNEL_PACKAGE_PATTERNS)
6335 +
6336 +# Towarzysze jądra – aktualizowani RAZEM z jądrem, jeśli są zainstalowani,
6337 +# żeby userspace i moduły jądra nie rozjechały się wersjami.
6338 +KERNEL_SIBLINGS = ("linux-headers", "nvidia-dkms", "nvidia-kernel", "dkms",
6339 + "virtualbox-host-modules", "virtualbox-guest-modules")
6340 +
6341 +
6342 +def _kernel_group_updates(pending):
6343 + """Gdy w transakcji jest jądro, dołóż jego towarzyszy (jeśli zainstalowani)."""
6344 + if not any(_is_kernel_package(n) for n in pending):
6345 + return pending
6346 + try:
6347 + installed = load_json(INSTALLED_DB)
6348 + repo = fetch_all_packages()
6349 + except Exception:
6350 + return pending
6351 + out = list(pending)
6352 + for sib in KERNEL_SIBLINGS:
6353 + if sib in installed and sib in repo and sib not in out:
6354 + out.append(sib)
6355 + return out
6356 +
6357 +
6358 +def _post_kernel_hooks():
6359 + """Po zmianie jądra na ZWYKŁEJ instalacji: initramfs + DKMS + GRUB.
6360 +
6361 + Kolejność ma znaczenie: najpierw initramfs dla nowego jądra, potem moduły
6362 + out-of-tree (DKMS) pod to samo jądro, na końcu wpisy GRUB. Bez tego
6363 + aktualizacja jądra zostawia system z „nowymi modułami na starym jądrze”.
6364 + """
6365 + try:
6366 + _rebuild_initramfs()
6367 + except Exception:
6368 + pass
6369 + if shutil.which("dkms"):
6370 + try:
6371 + print(_(' 🔧 DKMS: rebuilding out-of-tree modules (nvidia/vbox)...'))
6372 + subprocess.run(["dkms", "autoinstall"],
6373 + capture_output=True, text=True, timeout=1800)
6374 + except Exception:
6375 + pass
6376 + _refresh_bootloader()
6377 +
6378 +def _rebuild_initramfs(deploy_dir: str = "") -> bool:
6379 + """
6380 + Przebudowuje initramfs dla aktywnego (lub podanego) deploymentu.
6381 + Używa skryptu pag-initramfs lub ręcznego cpio.
6382 + """
6383 + if deploy_dir:
6384 + root = deploy_dir
6385 + else:
6386 + root = _get_deployment_root()
6387 +
6388 + if root == PAG_ROOT:
6389 + # Zwykły system – NAJPIERW natywne narzędzie PaganOS (per-wersja +
6390 + # root=UUID/PARTUUID/LABEL), potem dracut/mkinitcpio.
6391 + if shutil.which("pagan-initramfs"):
6392 + print(_(' 🔧 Rebuilding initramfs (pagan-initramfs)...'))
6393 + try:
6394 + r = subprocess.run(["pagan-initramfs"], capture_output=True,
6395 + text=True, timeout=600)
6396 + if r.returncode == 0:
6397 + return True
6398 + except Exception:
6399 + pass
6400 + # Zwykły system – użyj dracut jeśli dostępny
6401 + if shutil.which("dracut"):
6402 + print(_(' 🔧 Rebuilding initramfs (dracut)...'))
6403 + result = subprocess.run(
6404 + ["dracut", "--force", "/boot/initramfs.img"],
6405 + capture_output=True, text=True, timeout=120
6406 + )
6407 + return result.returncode == 0
6408 + elif shutil.which("mkinitcpio"):
6409 + print(_(' 🔧 Rebuilding initramfs (mkinitcpio)...'))
6410 + result = subprocess.run(
6411 + ["mkinitcpio", "-g", "/boot/initramfs.img"],
6412 + capture_output=True, text=True, timeout=120
6413 + )
6414 + return result.returncode == 0
6415 + else:
6416 + print(_(' ⚠ No dracut/mkinitcpio – initramfs was not rebuilt'))
6417 + return False
6418 +
6419 + # Tryb immutable – budujemy initramfs dla deploymentu
6420 + print(_(' 🔧 Building initramfs for the deployment...'))
6421 +
6422 + # Sprawdź czy mamy nasz skrypt init
6423 + pag_init_script = "/usr/share/pag/initramfs-init"
6424 + if not os.path.exists(pag_init_script):
6425 + # Szukaj w źródłach (developerski fallback)
6426 + alt_paths = [
6427 + os.path.join(os.path.dirname(os.path.abspath(__file__)), "scripts", "initramfs-init"),
6428 + "/usr/share/pag/init",
6429 + ]
6430 + for p in alt_paths:
6431 + if os.path.exists(p):
6432 + pag_init_script = p
6433 + break
6434 +
6435 + if not os.path.exists(pag_init_script):
6436 + print(_(' ⚠ pag-initramfs-init not found – skipping initramfs build'))
6437 + return False
6438 +
6439 + boot_dir = os.path.join(root, "boot")
6440 + os.makedirs(boot_dir, exist_ok=True)
6441 +
6442 + # Znajdź jądro (vmlinuz-*)
6443 + kernels = sorted(
6444 + [f for f in os.listdir(boot_dir) if f.startswith("vmlinuz-")],
6445 + reverse=True
6446 + ) if os.path.exists(boot_dir) else []
6447 + if not kernels:
6448 + print(_(" ⚠ No vmlinuz-* found in the deployment's /boot"))
6449 + return False
6450 +
6451 + kernel_ver = kernels[0].replace("vmlinuz-", "")
6452 + print(_(' 🐧 Kernel: {arg1}', arg1=(kernel_ver)))
6453 +
6454 + # Buduj initramfs ręcznie (cpio)
6455 + tmpdir = tempfile.mkdtemp(prefix="pag-initramfs-")
6456 + try:
6457 + # Podstawowa struktura
6458 + for d in ["bin", "sbin", "dev", "proc", "sys", "run", "new_root",
6459 + "usr/bin", "usr/sbin", "lib", "lib64", "etc"]:
6460 + os.makedirs(os.path.join(tmpdir, d), exist_ok=True)
6461 +
6462 + # Skopiuj init
6463 + shutil.copy2(pag_init_script, os.path.join(tmpdir, "init"))
6464 + os.chmod(os.path.join(tmpdir, "init"), 0o755)
6465 +
6466 + # Skopiuj niezbędne binaria (busybox lub podstawowe narzędzia)
6467 + busybox_paths = [
6468 + os.path.join(root, "usr/bin/busybox"),
6469 + os.path.join(root, "bin/busybox"),
6470 + "/usr/bin/busybox",
6471 + "/bin/busybox",
6472 + ]
6473 + busybox = None
6474 + for bp in busybox_paths:
6475 + if os.path.exists(bp):
6476 + busybox = bp
6477 + break
6478 +
6479 + if busybox:
6480 + shutil.copy2(busybox, os.path.join(tmpdir, "bin/busybox"))
6481 + # Utwórz symlinki dla podstawowych komend
6482 + for cmd in ["sh", "mount", "umount", "ls", "cat", "echo", "sleep",
6483 + "readlink", "mkdir", "switch_root", "cp", "rm"]:
6484 + link = os.path.join(tmpdir, "bin", cmd)
6485 + if not os.path.exists(link):
6486 + os.symlink("busybox", link)
6487 + # /bin/sh → busybox
6488 + if not os.path.exists(os.path.join(tmpdir, "bin/sh")):
6489 + os.symlink("busybox", os.path.join(tmpdir, "bin/sh"))
6490 + else:
6491 + # Bez busybox – kopiuj podstawowe narzędzia z deploymentu
6492 + for tool in ["bash", "mount", "umount", "readlink", "mkdir", "cat", "sleep", "cp", "rm"]:
6493 + src = os.path.join(root, "usr/bin", tool)
6494 + if not os.path.exists(src):
6495 + src = os.path.join(root, "bin", tool)
6496 + if os.path.exists(src):
6497 + dest = os.path.join(tmpdir, "bin", os.path.basename(tool))
6498 + shutil.copy2(src, dest)
6499 + # Kopiuj zależności .so
6500 + _copy_libs_for_binary(src, tmpdir, root)
6501 +
6502 + # Dodaj moduły jądra (opcjonalnie – dla sterowników dyskowych)
6503 + modules_src = os.path.join(root, "lib/modules", kernel_ver)
6504 + if os.path.isdir(modules_src):
6505 + modules_dst = os.path.join(tmpdir, "lib/modules", kernel_ver)
6506 + # Kopiuj tylko niezbędne (fs, block, drivers/ata, drivers/nvme)
6507 + for sub in ["kernel/fs", "kernel/drivers/ata", "kernel/drivers/nvme",
6508 + "kernel/drivers/scsi", "kernel/drivers/virtio",
6509 + "modules.order", "modules.builtin"]:
6510 + src_sub = os.path.join(modules_src, sub)
6511 + if os.path.exists(src_sub):
6512 + dst_sub = os.path.join(modules_dst, sub)
6513 + os.makedirs(os.path.dirname(dst_sub), exist_ok=True)
6514 + if os.path.isdir(src_sub):
6515 + try:
6516 + shutil.copytree(src_sub, dst_sub, dirs_exist_ok=True, symlinks=True,
6517 + ignore_dangling_symlinks=True)
6518 + except (FileNotFoundError, PermissionError):
6519 + print(_(' ⚠ Skipping unavailable files: {arg1}', arg1=(sub)))
6520 + else:
6521 + try:
6522 + shutil.copy2(src_sub, dst_sub)
6523 + except (FileNotFoundError, PermissionError):
6524 + print(_(' ⚠ Skipping unavailable file: {arg1}', arg1=(sub)))
6525 +
6526 + # Pakuj do initramfs.img
6527 + initramfs_path = os.path.join(boot_dir, "initramfs.img")
6528 + old_cwd = os.getcwd()
6529 + os.chdir(tmpdir)
6530 + try:
6531 + with open(initramfs_path + ".tmp", "wb") as out:
6532 + _run_cpio_pipeline(tmpdir, out)
6533 + os.rename(initramfs_path + ".tmp", initramfs_path)
6534 + finally:
6535 + os.chdir(old_cwd)
6536 +
6537 + size_mb = os.path.getsize(initramfs_path) / 1048576
6538 + print(_(' ✅ initramfs.img ({arg1:.1f} MB) → {arg2}', arg1=(size_mb), arg2=(initramfs_path)))
6539 + return True
6540 +
6541 + except Exception as e:
6542 + print(_(' ❌ initramfs build error: {arg1}', arg1=(e)))
6543 + return False
6544 + finally:
6545 + shutil.rmtree(tmpdir, ignore_errors=True)
6546 +
6547 +
6548 +def _run_cpio_pipeline(tmpdir: str, out):
6549 + """find . -print0 | cpio --null -oH newc | gzip — bez shell=True.
6550 +
6551 + Buduje pipeline przez subprocess.Popen, unikając pośrednika powłoki
6552 + (brak ryzyka injection i niepotrzebnego procesu sh). Wykonuje się w cwd=tmpdir.
6553 + Separatory NUL (\0): plik/katalog ze znakiem nowej linii w nazwie nie
6554 + rozjeżdża cpio (inaczej uszkodzone archiwum → kernel panic przy rozruchu).
6555 + """
6556 + find = subprocess.Popen(["find", ".", "-print0"], cwd=tmpdir, stdout=subprocess.PIPE)
6557 + cpio = subprocess.Popen(["cpio", "--null", "-oH", "newc"], cwd=tmpdir,
6558 + stdin=find.stdout, stdout=subprocess.PIPE)
6559 + find.stdout.close() # zwolnij uchwyt – cpio dostanie SIGPIPE po zakończeniu find
6560 + gzip = subprocess.Popen(["gzip"], stdin=cpio.stdout, stdout=out)
6561 + cpio.stdout.close()
6562 + try:
6563 + gzip.wait(timeout=120)
6564 + if gzip.returncode != 0:
6565 + raise subprocess.CalledProcessError(gzip.returncode, ["gzip"])
6566 + cpio.wait(timeout=30)
6567 + find.wait(timeout=30)
6568 + except subprocess.TimeoutExpired:
6569 + for p in (gzip, cpio, find):
6570 + p.kill()
6571 + raise
6572 + finally:
6573 + for p in (find, cpio, gzip):
6574 + if p.poll() is None:
6575 + p.kill()
6576 + # Skontroluj też kody procesów pośrednich (cpio/find mogą zawieść, a gzip zwrócić 0)
6577 + if cpio.returncode != 0:
6578 + raise subprocess.CalledProcessError(cpio.returncode, ["cpio"])
6579 + if find.returncode != 0:
6580 + raise subprocess.CalledProcessError(find.returncode, ["find"])
6581 +
6582 +
6583 +def _copy_libs_for_binary(binary: str, dest_dir: str, root: str):
6584 + """Kopiuje zależności .so dla binarki do initramfs (uproszczone ldd)."""
6585 + try:
6586 + result = subprocess.run(
6587 + ["ldd", binary], capture_output=True, text=True, timeout=10
6588 + )
6589 + for line in result.stdout.split("\n"):
6590 + m = re.search(r'=>\s+(/\S+)', line)
6591 + if m:
6592 + lib_path = m.group(1)
6593 + lib_rel = lib_path.lstrip("/")
6594 + lib_dest = os.path.join(dest_dir, lib_rel)
6595 + if not os.path.exists(lib_dest):
6596 + os.makedirs(os.path.dirname(lib_dest), exist_ok=True)
6597 + # Szukaj w deployment root lub systemie
6598 + if os.path.exists(lib_path):
6599 + shutil.copy2(lib_path, lib_dest)
6600 + else:
6601 + alt = os.path.join(root, lib_rel)
6602 + if os.path.exists(alt):
6603 + shutil.copy2(alt, lib_dest)
6604 + except Exception:
6605 + pass
6606 +
6607 +
6608 +def cmd_initramfs_update():
6609 + """Ręcznie przebudowuje initramfs dla bieżącego deploymentu."""
6610 + ensure_dirs()
6611 + deploy_dir = _get_deployment_root()
6612 + if deploy_dir != PAG_ROOT:
6613 + print(_('🏗️ Deployment: {arg1}', arg1=(os.path.basename(deploy_dir))))
6614 + ok = _rebuild_initramfs(deploy_dir)
6615 + if ok:
6616 + print(_('✅ Initramfs updated.'))
6617 + # Po initramfs – zaktualizuj też GRUB
6618 + _update_grub_config()
6619 + else:
6620 + print(_('❌ Initramfs update failed.'))
6621 + return 0 if ok else 1
6622 +
6623 +
6624 +def _boot_prefix() -> str:
6625 + """Prefiks ścieżek jądra/initrd w grub.cfg.
6626 +
6627 + Gdy /boot jest OSOBNYM punktem montowania, GRUB ma w `root` partycję
6628 + /boot (tam leży grub.cfg i jądra), więc ścieżki podajemy względem niej:
6629 + "/vmlinuz-…", "/initramfs.img" – BEZ przedrostka /boot. Gdy /boot leży
6630 + na roocie, wymagane jest "/boot/…". Zły przedrostek = "file not found".
6631 + """
6632 + try:
6633 + if os.path.isdir("/boot") and os.path.ismount("/boot"):
6634 + return ""
6635 + except OSError:
6636 + pass
6637 + return "/boot"
6638 +
6639 +
6640 +def _refresh_bootloader():
6641 + """Odświeża wpisy bootloadera po zmianie jądra.
6642 +
6643 + Deploymenty (immutable OS): własny generator _update_grub_config().
6644 + Zwykła instalacja: standardowy `grub-mkconfig` – /etc/grub.d/10_linux
6645 + sam wygeneruje wpisy dla KAŻDEGO /boot/vmlinuz-* wraz z jego własnym
6646 + initrd. Bez tego `pag upgrade kernel` zostawiał w menu STARY wpis:
6647 + system startował ze starym jądrem, a nowe moduły leżały bezużyteczne
6648 + ("moduły 7.2.8 na jądrze 7.2.5" → zawieszenie na starcie).
6649 + """
6650 + try:
6651 + if _load_deployments():
6652 + _update_grub_config()
6653 + return
6654 + except Exception:
6655 + pass
6656 + grub_cfg = "/boot/grub/grub.cfg"
6657 + if not os.path.isdir("/boot/grub"):
6658 + return
6659 + for tool, cmd in ((
6660 + "grub-mkconfig", ["grub-mkconfig", "-o", grub_cfg]), (
6661 + "grub2-mkconfig", ["grub2-mkconfig", "-o", grub_cfg])):
6662 + if shutil.which(tool):
6663 + try:
6664 + print(_(' 📋 Regenerating GRUB (grub-mkconfig)...'))
6665 + subprocess.run(cmd, capture_output=True, text=True,
6666 + errors="replace", timeout=180)
6667 + except Exception:
6668 + pass
6669 + return
6670 +
6671 +
6672 +def _update_grub_config():
6673 + """
6674 + Generuje wpisy GRUB dla wszystkich deploymentów.
6675 + Każdy deployment dostaje własny wpis – rollback możliwy z bootloadera.
6676 + """
6677 + grub_cfg = "/boot/grub/grub.cfg"
6678 + if not os.path.exists(os.path.dirname(grub_cfg)):
6679 + return # brak GRUB
6680 +
6681 + deployments = _load_deployments()
6682 + root_dev = _detect_root_device()
6683 + if not root_dev:
6684 + print(_(' ⚠ Could not detect the root partition – GRUB entries will have no root=.'),
6685 + file=sys.stderr)
6686 + print(_(' Set PAG_ROOT_DEVICE=/dev/... (or PAG_GRUB_ROOT) and retry.'),
6687 + file=sys.stderr)
6688 + root_arg = f" root={root_dev}" if root_dev else ""
6689 +
6690 + lines = [
6691 + "# =====================================================================",
6692 + "# Pagan Linux – GRUB config (wygenerowane przez pag grub-update)",
6693 + f"# Data: {datetime.now().isoformat()}",
6694 + "# =====================================================================",
6695 + "",
6696 + ]
6697 +
6698 + # Domyślny – ostatni (najnowszy) deployment
6699 + if deployments:
6700 + latest = deployments[-1]["id"]
6701 + lines.append(f"set default=0")
6702 + lines.append(f"set timeout=5")
6703 + else:
6704 + lines.append("set default=0")
6705 + lines.append("set timeout=5")
6706 + lines.append("")
6707 +
6708 + # Wpisy dla każdego deploymentu (od najnowszego)
6709 + entry_num = 0
6710 + for d in reversed(deployments):
6711 + deploy_dir = os.path.join(DEPLOYMENTS_DIR, d["id"])
6712 + boot_dir = os.path.join(deploy_dir, "boot")
6713 + kernels = sorted(
6714 + [f for f in os.listdir(boot_dir) if f.startswith("vmlinuz-")],
6715 + reverse=True
6716 + ) if os.path.isdir(boot_dir) else []
6717 +
6718 + kernel_path = f"/.deployments/{d['id']}/boot/{kernels[0]}" if kernels else ""
6719 + initrd_path = f"/.deployments/{d['id']}/boot/initramfs.img"
6720 + initrd_line = f"initrd {initrd_path}" if os.path.exists(os.path.join(boot_dir, "initramfs.img")) else ""
6721 +
6722 + active_mark = f" [{_('active_deployment')}]" if d.get("active") else ""
6723 + pkg_list = ", ".join(d.get("packages", [])[:3])
6724 + label = f"Pagan Linux – {d['id']}{active_mark}"
6725 +
6726 + lines.append(f"menuentry '{label}' {{")
6727 + if kernel_path:
6728 + lines.append(f" linux {kernel_path}{root_arg} rw quiet")
6729 + else:
6730 + lines.append(f" # Brak jądra w tym deploymencie")
6731 + if initrd_line:
6732 + lines.append(f" {initrd_line}")
6733 + lines.append("}")
6734 + lines.append("")
6735 + entry_num += 1
6736 +
6737 + # Snapshoty systemu (btrfs) – każdy jako osobny wpis do uruchomienia.
6738 + _snap_lines = _grub_snapshot_entries()
6739 + if _snap_lines:
6740 + lines.append("# --- Snapshoty systemu (CoW) ---")
6741 + lines.extend(_snap_lines)
6742 +
6743 + # Wpis fallback: zwykły root (gdyby wszystko padło).
6744 + # Uwaga: GRUB NIE rozwija globów – trzeba podać KONKRETNY plik jądra
6745 + # (wcześniejsze `linux /boot/vmlinuz-*` było niepoprawne).
6746 + fallback_kernels = sorted(
6747 + [f for f in os.listdir("/boot") if f.startswith("vmlinuz-")],
6748 + reverse=True
6749 + ) if os.path.isdir("/boot") else []
6750 + # Osobna partycja /boot => GRUB ma ją w `root`, ścieżki BEZ /boot.
6751 + _bp = _boot_prefix()
6752 + lines.append(f"menuentry '{_('grub_fallback_label')}' {{")
6753 + if fallback_kernels:
6754 + lines.append(f" linux {_bp}/{fallback_kernels[0]}{root_arg} rw quiet")
6755 + _fi = _initrd_for_kernel("/boot", fallback_kernels[0])
6756 + if _fi:
6757 + lines.append(f" initrd {_bp}/{_fi}")
6758 + else:
6759 + lines.append(" # Brak jądra w /boot")
6760 + lines.append("}")
6761 + lines.append("")
6762 +
6763 + # Zapisz
6764 + os.makedirs(os.path.dirname(grub_cfg), exist_ok=True)
6765 + with open(grub_cfg, "w") as f:
6766 + f.write("\n".join(lines))
6767 +
6768 + print(_(' 📋 GRUB config updated – entries for each deployment'))
6769 +
6770 +
6771 +def _root_device_from_fstab(path: str = "/etc/fstab") -> str:
6772 + """Zwraca DEVICE z wpisu dla '/' w fstab (pomija komentarze)."""
6773 + try:
6774 + with open(path, "r", encoding="utf-8", errors="replace") as fh:
6775 + for line in fh:
6776 + line = line.split("#", 1)[0].strip()
6777 + if not line:
6778 + continue
6779 + parts = line.split()
6780 + if len(parts) >= 2 and parts[1] == "/":
6781 + return parts[0]
6782 + except OSError:
6783 + pass
6784 + return ""
6785 +
6786 +
6787 +def _in_chroot() -> bool:
6788 + """Heurystyka: czy działamy w chrocie (build ISO/IMG)?
6789 +
6790 + W chrocie /proc/1/root to root HOSTA – inny system plików niż nasz '/'.
6791 + Na zwykłym systemie PID 1 ma root równy '/'. PAGAN_ROOT ustawiają skrypty
6792 + budujące i jest dziedziczony przez chroot (dodatkowa wskazówka).
6793 + """
6794 + if os.environ.get("PAG_IN_CHROOT") == "1":
6795 + return True
6796 + if os.environ.get("PAGAN_ROOT"):
6797 + return True
6798 + try:
6799 + return os.stat("/").st_dev != os.stat("/proc/1/root").st_dev
6800 + except OSError:
6801 + return False
6802 +
6803 +
6804 +def _detect_root_device() -> str:
6805 + """Wykrywa urządzenie/identyfikator partycji root dla GRUB (root=...).
6806 +
6807 + Kolejność (od najbardziej wiarygodnego w danym kontekście):
6808 + 1) PAG_ROOT_DEVICE / PAG_GRUB_ROOT – jawny override (build ISO/IMG,
6809 + instalator); najpewniejszy, bo nie zgadujemy.
6810 + 2) /etc/fstab TARGETU – w chrocie findmnt '/' zwraca partycję HOSTA,
6811 + a fstab opisuje target (np. root=/dev/sda2 dla obrazu IMG).
6812 + 3) findmnt '/' – na żywym systemie (obsługuje UUID/LUKS/subvol).
6813 + Zwraca "" gdy nie da się ustalić – wtedy GRUB nie dostaje błędnego root=.
6814 + """
6815 + explicit = (os.environ.get("PAG_ROOT_DEVICE")
6816 + or os.environ.get("PAG_GRUB_ROOT") or "").strip()
6817 + if explicit:
6818 + return explicit
6819 +
6820 + fstab_dev = _root_device_from_fstab()
6821 + if _in_chroot() and fstab_dev:
6822 + return fstab_dev
6823 +
6824 + try:
6825 + result = subprocess.run(
6826 + ["findmnt", "-n", "-o", "SOURCE", "/"],
6827 + capture_output=True, text=True, timeout=5
6828 + )
6829 + if result.returncode == 0 and result.stdout.strip():
6830 + return result.stdout.strip()
6831 + except Exception:
6832 + pass
6833 +
6834 + # Ostatnia deska: fstab targetu (lepsze niż hardkodowane /dev/sda1,
6835 + # które na sprzęcie z NVMe dawało niebootowalny system).
6836 + return fstab_dev
6837 +
6838 +
6839 +def cmd_grub_update():
6840 + """Ręcznie regeneruje konfigurację GRUB (deploymenty + snapshoty)."""
6841 + ensure_dirs()
6842 + print(_('📋 Updating GRUB configuration...'))
6843 + _ensure_snapshot_grub_script()
6844 + # Deploymenty mają własny generator; zwykły system – grub-mkconfig,
6845 + # który uruchomi /etc/grub.d/40_pagan_snapshots i zachowa pozostałe wpisy.
6846 + _refresh_bootloader()
6847 + print(_('✅ GRUB updated.'))
6848 + return 0
6849 +
6850 +def cmd_deploy_list():
6851 + """Wyświetla listę wszystkich deploymentów."""
6852 + deployments = _load_deployments()
6853 + if not deployments:
6854 + print(_("no_deployments")); return
6855 +
6856 + print(_("deployments_list", len(deployments)))
6857 + active = os.readlink(ACTIVE_LINK) if os.path.islink(ACTIVE_LINK) else ""
6858 +
6859 + for d in reversed(deployments):
6860 + marker = f" ◀ {_('active_deployment')}" if d.get("active") or d["id"] == os.path.basename(active) else ""
6861 + print(f" {d['id']}{marker}")
6862 + print(f" {_action_label(d['action'])}: {', '.join(d['packages'][:5])}")
6863 + if len(d.get('packages', [])) > 5:
6864 + print(_(' +{arg1} more...', arg1=(len(d['packages']) - 5)))
6865 + print(f" {d['timestamp']}")
6866 +
6867 +
6868 +def cmd_deploy_rollback():
6869 + """Przełącza na poprzedni deployment."""
6870 + deployments = _load_deployments()
6871 + active_indices = [i for i, d in enumerate(deployments) if d.get("active")]
6872 +
6873 + if len(deployments) < 2:
6874 + print(f"❌ {_('deploy_rollback_fail')}"); return 1
6875 +
6876 + current_idx = active_indices[0] if active_indices else len(deployments) - 1
6877 + prev_idx = current_idx - 1 if current_idx > 0 else -1
6878 +
6879 + if prev_idx < 0:
6880 + print(f"❌ {_('deploy_rollback_fail')}"); return 1
6881 +
6882 + prev = deployments[prev_idx]
6883 + prev_dir = os.path.join(DEPLOYMENTS_DIR, prev["id"])
6884 +
6885 + if not os.path.isdir(prev_dir):
6886 + print(_('❌ Deployment {arg1} does not exist on disk', arg1=(prev['id']))); return 1
6887 +
6888 + print(_('⏪ Restoring deployment: {arg1}', arg1=(prev['id'])))
6889 + print(f" {prev['action']}: {', '.join(prev['packages'][:5])}")
6890 +
6891 + if not _ask_confirm():
6892 + return 0
6893 +
6894 + _switch_deployment(prev_dir)
6895 +
6896 + for d in deployments:
6897 + d["active"] = (d["id"] == prev["id"])
6898 + _save_deployments(deployments)
6899 +
6900 + _update_grub_config()
6901 + print(f"✅ {_('deploy_rollback_ok', prev['id'])}")
6902 + print(_(' 💡 Restart required to reload the system.'))
6903 + return 0
6904 +
6905 +
6906 +def cmd_deploy_cleanup(keep: int = 3):
6907 + """Usuwa stare deploymenty, zachowując ostatnie `keep`."""
6908 + deployments = _load_deployments()
6909 +
6910 + if len(deployments) <= keep:
6911 + print(f"✅ {_('deploy_cleanup_none', keep)}"); return 0
6912 +
6913 + to_remove = deployments[:-keep]
6914 + removed = 0
6915 +
6916 + for d in to_remove:
6917 + deploy_dir = os.path.join(DEPLOYMENTS_DIR, d["id"])
6918 + if os.path.isdir(deploy_dir):
6919 + shutil.rmtree(deploy_dir, ignore_errors=True)
6920 + removed += 1
6921 +
6922 + remaining = deployments[-keep:]
6923 + _save_deployments(remaining)
6924 +
6925 + print(f"✅ {_('deploy_cleanup_ok', removed)}")
6926 + return 0
6927 +
6928 +
6929 +# =============================================================================
6930 +# POMOCNICZE
6931 +# =============================================================================
6932 +
6933 +# Pakiety dostarczane przez bazowy system (zawsze "zainstalowane"). Wchodzą do
6934 +# rootfs z ISO przez data.tar.xz, więc NIE ma ich w repo.json ani w bazie pag –
6935 +# każda zależność od nich (glibc, bash, python3…) wyglądałaby na "brakującą".
6936 +# Współdzielone przez rozwijanie i weryfikację zależności.
6937 +SYSTEM_BASE = {
6938 + "glibc", "libc", "gcc", "g++", "make", "binutils", "coreutils", "bash",
6939 + "linux-api-headers", "kernel-headers", "zlib", "pkg-config", "pkgconf",
6940 + "tar", "gzip", "xz", "bzip2", "findutils", "grep", "sed", "gawk", "awk",
6941 + "diffutils", "patch", "file", "m4", "perl", "python3", "sh",
6942 +}
6943 +
6944 +
6945 +def _resolve_deps(names, repo, installed):
6946 + resolved, visited = [], set()
6947 + missing = [] # zależności których nie ma ani w repo ani zainstalowane
6948 +
6949 + def _is_base(dep):
6950 + """True, gdy zależność dostarcza bazowy system (także przez provides)."""
6951 + return dep in SYSTEM_BASE \
6952 + or _resolve_provides(dep, repo, installed) in SYSTEM_BASE
6953 +
6954 + def visit(name, explicit=False):
6955 + if name in visited: return
6956 +
6957 + # Rozwijanie wirtualnych zależności przez provides
6958 + target = _resolve_provides(name, repo, installed)
6959 +
6960 + # Zależność dostarczana przez bazowy system – nie ma jej w repo ani w
6961 + # bazie pag, więc nie "brakuje" jej i nie próbujemy jej instalować.
6962 + # Wyjątek: nazwa podana wprost przez użytkownika (explicit=True).
6963 + if not explicit and target in SYSTEM_BASE:
6964 + return
6965 +
6966 + if target in visited: return
6967 + visited.add(target)
6968 + if target in repo:
6969 + for dep in repo[target].dependencies:
6970 + real_dep = _resolve_provides(dep, repo, installed)
6971 + real_target = real_dep if real_dep in repo else dep
6972 +
6973 + if _is_base(dep):
6974 + continue
6975 +
6976 + # Sprawdź czy zależność jest dostępna
6977 + if real_target not in installed and real_target not in repo:
6978 + if dep not in missing:
6979 + missing.append(dep)
6980 +
6981 + if dep not in installed:
6982 + visit(real_target)
6983 + elif target not in installed:
6984 + # Pakiet nie istnieje ani w repo ani zainstalowany
6985 + if target not in missing:
6986 + missing.append(target)
6987 +
6988 + if target not in installed and target not in resolved:
6989 + resolved.append(target)
6990 +
6991 + for name in names:
6992 + visit(name, explicit=True)
6993 +
6994 + # Zwróć brakujące (do sprawdzenia przez wywołującego)
6995 + return resolved, missing
6996 +
6997 +def _verify_dependencies(to_install: list, repo: dict, installed: dict) -> int:
6998 + """
6999 + Sprawdza czy wszystkie zależności pakietów do instalacji są spełnione.
7000 + Zwraca liczbę brakujących zależności.
7001 + """
7002 + all_missing = []
7003 + all_warnings = []
7004 +
7005 + for pkg_name in to_install:
7006 + pkg = repo.get(pkg_name)
7007 + if not pkg:
7008 + continue
7009 +
7010 + for dep in pkg.dependencies:
7011 + if dep in SYSTEM_BASE:
7012 + continue # bazowy system dostarcza tę zależność
7013 + real_dep = _resolve_provides(dep, repo, installed)
7014 + # Sprawdź czy zależność jest dostępna (w repo lub już zainstalowana)
7015 + in_repo = real_dep in repo
7016 + in_installed = real_dep in installed
7017 + will_be_installed = real_dep in to_install
7018 +
7019 + if not in_repo and not in_installed and not will_be_installed:
7020 + if dep not in all_missing:
7021 + all_missing.append((pkg_name, dep))
7022 + elif in_repo and not in_installed and not will_be_installed:
7023 + if dep not in [w[1] for w in all_warnings]:
7024 + all_warnings.append((pkg_name, dep, real_dep))
7025 +
7026 + if all_missing:
7027 + print(_('\n❌ {arg1} – cannot install:', arg1=(_c('red', 'BRAKUJĄCE ZALEŻNOŚCI'))))
7028 + for pkg, dep in all_missing:
7029 + print(_(' {arg1} → needs {arg2} (missing from repositories)', arg1=(pkg), arg2=(_c('red', dep))))
7030 + print()
7031 +
7032 + if all_warnings:
7033 + print(_('\n⚠ {arg1} – will be installed as dependencies:', arg1=(_c('yellow', 'NIESPEŁNIONE ZALEŻNOŚCI'))))
7034 + for pkg, dep, real in all_warnings:
7035 + print(_(' {arg1} → {arg2} ({arg3} – will be downloaded)', arg1=(pkg), arg2=(dep), arg3=(_c('green', real))))
7036 + print()
7037 +
7038 + return len(all_missing)
7039 +
7040 +# Biblioteki bazowe (glibc/gcc runtime) – zawsze dostępne, nie wymagają pakietu
7041 +BASE_SO = {
7042 + "libc.so.6", "libm.so.6", "libpthread.so.0", "libdl.so.2", "librt.so.1",
7043 + "libutil.so.1", "libresolv.so.2", "libnsl.so.1", "libcrypt.so.1",
7044 + "ld-linux.so.2", "ld-linux-x86-64.so.2", "ld-linux-aarch64.so.1",
7045 + "libgcc_s.so.1", "linux-vdso.so.1",
7046 +}
7047 +
7048 +def _verify_so_deps(to_install: list, repo: dict, installed: dict) -> int:
7049 + """Sprawdza wymagania ABI (provides_so / requires_so z metadata.json).
7050 +
7051 + Fail-closed TYLKO gdy metadata jawnie deklaruje requires_so, a żaden pakiet
7052 + (bazowy, zainstalowany lub instalowany w tej transakcji) nie dostarcza
7053 + wymaganej wersji biblioteki. Stare pakiety bez tych pól są pomijane.
7054 + """
7055 + provided = set(BASE_SO)
7056 + for n in to_install:
7057 + p = repo.get(n)
7058 + if p:
7059 + provided.update(p.provides_so or [])
7060 + for n, info in installed.items():
7061 + provided.update(info.get("provides_so", []) or [])
7062 +
7063 + # NAPRAWA: soname faktycznie obecne w systemie (ldconfig -p). Metadane
7064 + # starych paczek (zbudowanych przed polem provides_so) ich nie deklaruja,
7065 + # a biblioteki sa na dysku - bez tego fail-closed check blokuje legalne
7066 + # aktualizacje (np. mesa -> libLLVM.so.22.1).
7067 + try:
7068 + import shutil as _sh, subprocess as _sp
7069 + _ld = _sh.which("ldconfig")
7070 + if _ld:
7071 + _o = _sp.run([_ld, "-p"], capture_output=True, text=True).stdout
7072 + for _ln in _o.splitlines():
7073 + _ln = _ln.strip()
7074 + if "=>" in _ln:
7075 + provided.add(_ln.split("=>")[0].strip().split()[0])
7076 + except Exception:
7077 + pass
7078 +
7079 + missing = []
7080 + for n in sorted(to_install):
7081 + p = repo.get(n)
7082 + if not p:
7083 + continue
7084 + for so in (p.requires_so or []):
7085 + if so not in provided:
7086 + missing.append((n, so))
7087 +
7088 + if missing:
7089 + print(f"\n❌ {_c('red', 'BRAK WYMAGANYCH BIBLIOTEK (ABI so-name)')}:")
7090 + for n, so in missing:
7091 + print(_(' {arg1} → requires {arg2} – no package provides this version', arg1=(n), arg2=(_c('red', so))))
7092 + print()
7093 + return len(missing)
7094 +
7095 +def _download_pkg(pkg, attempts: int = 3, progress: bool = True):
7096 + """Pobiera pakiet do cache. `progress=False` wycisza pasek (np. gdy
7097 + równoległy pobierający pokazuje własny pasek zbiorczy)."""
7098 + url = f"{pkg.repo_url}/{pkg.filename}"
7099 + dest = os.path.join(PAG_CACHE, pkg.filename)
7100 + if os.path.exists(dest) and (not pkg.sha256 or _sha256_file(dest) == pkg.sha256):
7101 + _download_pkg_sig(pkg, dest) # upewnij się, że sygnatura jest w cache
7102 + return dest
7103 + last_err = None
7104 + for attempt in range(1, attempts + 1):
7105 + try:
7106 + req = Request(url, headers={"User-Agent":"pag/3.0"})
7107 + with urlopen(req, timeout=600) as resp:
7108 + total = int(resp.headers.get("Content-Length", 0))
7109 + bar = DownloadBar(pkg.filename, total) if progress else None
7110 + with open(dest, "wb") as f:
7111 + while True:
7112 + chunk = resp.read(65536)
7113 + if not chunk:
7114 + break
7115 + f.write(chunk)
7116 + if bar is not None:
7117 + bar.update(len(chunk))
7118 + if bar is not None:
7119 + bar.close()
7120 + if pkg.sha256 and _sha256_file(dest) != pkg.sha256:
7121 + last_err = _("sha256_mismatch")
7122 + try:
7123 + os.remove(dest)
7124 + except OSError:
7125 + pass
7126 + if attempt < attempts:
7127 + print(_(' ↻ Retrying download of {arg1} ({arg2}/{arg3})...', arg1=(pkg.filename), arg2=(attempt), arg3=(attempts - 1)), file=sys.stderr)
7128 + time.sleep(attempt)
7129 + continue
7130 + return None
7131 + _download_pkg_sig(pkg, dest)
7132 + return dest
7133 + except Exception as e:
7134 + last_err = e
7135 + # Usuń częściowy plik – bez tego mógłby zostać użyty jako „cache”
7136 + # (gdy pakiet nie ma sha256) albo mylić kolejną próbę.
7137 + try:
7138 + if os.path.exists(dest):
7139 + os.remove(dest)
7140 + except OSError:
7141 + pass
7142 + if attempt < attempts:
7143 + print(_(' ↻ Retrying download of {arg1} ({arg2}/{arg3})...', arg1=(pkg.filename), arg2=(attempt), arg3=(attempts - 1)), file=sys.stderr)
7144 + time.sleep(attempt)
7145 + continue
7146 + print(_(' ⚠ Download error {arg1}: {arg2}', arg1=(pkg.filename), arg2=(last_err)), file=sys.stderr)
7147 + return None
7148 +
7149 +def _download_pkg_sig(pkg, dest):
7150 + """Zapewnia AKTUALNY podpis pakietu (.asc, fallback .sig) w cache.
7151 +
7152 + Istniejący podpis jest używany tylko wtedy, gdy faktycznie weryfikuje TĘ
7153 + paczkę. Inaczej po przebudowie tej samej wersji (ten sam plik, nowy sha256)
7154 + stary podpis zostawał obok nowej paczki i weryfikacja dawała fałszywe
7155 + „NIEPRAWIDŁOWY PODPIS GPG”.
7156 + """
7157 + for ext in (".asc", ".sig"):
7158 + sig_dest = dest + ext
7159 + if os.path.exists(sig_dest):
7160 + ok, _fp = _gpg_verify_fp(sig_dest, dest)
7161 + if ok:
7162 + return
7163 + for ext in (".asc", ".sig"):
7164 + sig_dest = dest + ext
7165 + try:
7166 + req = Request(f"{pkg.repo_url}/{pkg.filename}{ext}", headers={"User-Agent":"pag/3.0"})
7167 + with urlopen(req, timeout=30) as resp:
7168 + data = resp.read()
7169 + except Exception:
7170 + continue
7171 + # nie mieszaj rozszerzeń – zostaje tylko ten wariant podpisu
7172 + for other in (".asc", ".sig"):
7173 + if other != ext:
7174 + try:
7175 + os.remove(dest + other)
7176 + except OSError:
7177 + pass
7178 + with open(sig_dest, "wb") as f:
7179 + f.write(data)
7180 + return
7181 + # Nie udało się pobrać podpisu – usuń nieaktualny z cache, żeby weryfikacja
7182 + # nie porównywała paczki z podpisem od innej wersji (czytelny „BRAK PODPISU”).
7183 + for other in (".asc", ".sig"):
7184 + try:
7185 + os.remove(dest + other)
7186 + except OSError:
7187 + pass
7188 +
7189 +def _download_packages_parallel(pkgs: List[PackageInfo], max_workers: int = 4) -> Dict[str, Optional[str]]:
7190 + """
7191 + Równoległe pobieranie wielu pakietów przez ThreadPoolExecutor.
7192 + Znacząco przyspiesza przy dużych aktualizacjach (50+ pakietów).
7193 + Zwraca słownik {nazwa_pakietu: ścieżka_lub_None}.
7194 + """
7195 + results = {}
7196 + total = len(pkgs)
7197 + completed = 0
7198 + with ThreadPoolExecutor(max_workers=max_workers) as executor:
7199 + future_to_pkg = {executor.submit(_download_pkg, pkg, progress=False): pkg for pkg in pkgs}
7200 + for future in as_completed(future_to_pkg):
7201 + pkg = future_to_pkg[future]
7202 + try:
7203 + results[pkg.name] = future.result()
7204 + except Exception:
7205 + results[pkg.name] = None
7206 + completed += 1
7207 + # Pasek postępu (animowany „drakkar” na TTY)
7208 + pct = completed / total * 100
7209 + bar = _pagan_bar(pct, 20, time.time(), animated=sys.stderr.isatty())
7210 + print(f"\r ⏬ [{bar}] {completed}/{total} ({pct:.0f}%)", end="", file=sys.stderr, flush=True)
7211 + print(file=sys.stderr) # nowa linia po zakończeniu
7212 + return results
7213 +
7214 +def load_world():
7215 + if not os.path.exists(WORLD_FILE): return set()
7216 + return {l.strip() for l in open(WORLD_FILE) if l.strip()}
7217 +
7218 +def save_world(w):
7219 + with open(WORLD_FILE,"w") as f:
7220 + for n in sorted(w): f.write(f"{n}\n")
7221 +
7222 +def _find_orphans(installed, world):
7223 + needed = set(world)
7224 + changed = True
7225 + while changed:
7226 + changed = False
7227 + for n in list(needed):
7228 + for dep in installed.get(n,{}).get("dependencies",[]):
7229 + if dep not in needed and dep in installed:
7230 + needed.add(dep); changed = True
7231 + return {n for n in installed if n not in needed}
7232 +
7233 +# =============================================================================
7234 +# MAIN
7235 +# =============================================================================
7236 +
7237 +def cmd_sbom(argv):
7238 + """pag sbom export [spdx|cyclonedx] – manifest SBOM zainstalowanych pakietów.
7239 +
7240 + Wypisuje na stdout JSON (SPDX 2.3 lub CycloneDX 1.5) z listą
7241 + zainstalowanych pakietów, wersji, licencji i sum SHA256.
7242 + """
7243 + fmt = (argv[0] if argv else "spdx").lower()
7244 + if fmt not in ("spdx", "cyclonedx"):
7245 + print(_('❌ Format: spdx | cyclonedx'))
7246 + return 1
7247 + installed = load_json(INSTALLED_DB)
7248 + if not installed:
7249 + print("{}") if fmt == "cyclonedx" else print("{\"packages\": []}")
7250 + return 0
7251 + # metadata repo (licencje) – best-effort
7252 + try:
7253 + repo = fetch_all_packages()
7254 + except Exception:
7255 + repo = {}
7256 + names = sorted(installed)
7257 + created = datetime.now().astimezone().isoformat(timespec="seconds")
7258 +
7259 + def _license_of(name):
7260 + p = repo.get(name)
7261 + lic = getattr(p, "license", None) or []
7262 + if isinstance(lic, list):
7263 + lic = ", ".join(x for x in lic if x)
7264 + return lic or "NOASSERTION"
7265 +
7266 + if fmt == "spdx":
7267 + doc = {
7268 + "spdxVersion": "SPDX-2.3",
7269 + "dataLicense": "CC0-1.0",
7270 + "SPDXID": "SPDXRef-DOCUMENT",
7271 + "name": "PaganOS-installed",
7272 + "documentNamespace": f"https://repo.paganlinux.eu/sbom/installed-{int(time.time())}",
7273 + "creationInfo": {
7274 + "created": created,
7275 + "creators": [f"Tool: pag-{PAG_VERSION}"],
7276 + },
7277 + "packages": [],
7278 + }
7279 + for i, n in enumerate(names):
7280 + info = installed[n]
7281 + doc["packages"].append({
7282 + "SPDXID": f"SPDXRef-Package-{i+1}",
7283 + "name": n,
7284 + "versionInfo": info.get("version", ""),
7285 + "downloadLocation": info.get("repo", "NOASSERTION"),
7286 + "filesAnalyzed": False,
7287 + "licenseConcluded": _license_of(n),
7288 + "checksums": [{"algorithm": "SHA256", "checksumValue": info.get("sha256", "")}],
7289 + })
7290 + else: # cyclonedx
7291 + doc = {
7292 + "bomFormat": "CycloneDX",
7293 + "specVersion": "1.5",
7294 + "serialNumber": f"urn:uuid:{str(uuid.uuid4())}",
7295 + "version": 1,
7296 + "metadata": {
7297 + "timestamp": created,
7298 + "tools": [{"vendor": "PaganOS", "name": "pag", "version": PAG_VERSION}],
7299 + },
7300 + "components": [],
7301 + }
7302 + for n in names:
7303 + info = installed[n]
7304 + lic = _license_of(n)
7305 + comp = {
7306 + "type": "library",
7307 + "name": n,
7308 + "version": info.get("version", ""),
7309 + "hashes": [{"alg": "SHA-256", "content": info.get("sha256", "")}],
7310 + }
7311 + if lic != "NOASSERTION":
7312 + comp["licenses"] = [{"license": {"id": lic}}]
7313 + doc["components"].append(comp)
7314 + print(json.dumps(doc, indent=2, ensure_ascii=False))
7315 + return 0
7316 +
7317 +
7318 +USAGE_EN = """pag v3 – Pagan Linux Package Manager
7319 +
7320 +BASIC:
7321 + pag install <pkg>... Install packages
7322 + pag remove <pkg>... Remove packages
7323 + pag update Update PACKAGES (refreshes indexes first)
7324 + pag sync Refresh indexes + show pending package updates
7325 + pag upgrade Update SYSTEM (packages + kernel/initramfs/GRUB)
7326 + pag list [--installed] List available / installed
7327 + pag search <query> Search packages
7328 + pag info <pkg> Package details
7329 + pag files <pkg> List package files
7330 + pag verify [--deep] Verify integrity (--deep = SHA256 per file)
7331 + pag clean Clear download cache
7332 + pag stats System statistics
7333 + pag download <pkg>... Download packages to cache (offline prep)
7334 +
7335 +ROLLING (base baked into the image):
7336 + pag base [status] Image packages vs. repo (what pag manages)
7337 + pag base adopt [pkg...] Adopt base packages from the repo (--dry-run = preview)
7338 +
7339 +SECURITY:
7340 + pag key-add <url|file> Import GPG key
7341 + pag key-list List trusted keys
7342 + pag key-remove <id> Remove key
7343 + pag key-trust <repo> Pin repo signing key fingerprint (no TOFU)
7344 + pag key-untrust <repo> Forget repo fingerprint (back to TOFU)
7345 + pag key-trusted List pinned repo fingerprints
7346 +
7347 +ADVANCED:
7348 + pag why <pkg> Show why a package is installed
7349 + pag rdepends <pkg> Show which packages depend on a package
7350 + pag autoremove Auto-remove orphaned dependencies
7351 + pag pin <pkg> [ver] Pin package version
7352 + pag unpin <pkg> Unpin
7353 + pag pinned List pinned
7354 + pag history Transaction history
7355 + pag rollback Rollback last transaction
7356 + pag repair [--dry-run] Reinstall packages with missing files
7357 + pag remove-orphans Remove orphaned deps
7358 + pag repo-add <url> [name] Add repository (drop-in /etc/pag/repos/)
7359 + pag repo-list List repositories
7360 + pag sbom export [fmt] SBOM manifest (spdx|cyclonedx)
7361 +
7362 +FLATPAK:
7363 + pag flatpak [<query>] Search & install (smart)
7364 + pag flatpak search <q> Search Flathub
7365 + pag flatpak install <id> Install flatpak
7366 + pag flatpak remove <id> Remove flatpak
7367 + pag flatpak list List installed flatpaks
7368 + pag flatpak update Update all flatpaks
7369 + pag flatpak info <id> Show flatpak details
7370 +
7371 +SNAPSHOTS (btrfs CoW):
7372 + pag snapshot-list List system snapshots
7373 + pag snapshot-create [label] Create a snapshot now
7374 + pag snapshot-rollback [id] Start from snapshot at next boot (GRUB)
7375 + pag snapshot-delete <id> Delete a snapshot
7376 +
7377 +IMMUTABLE OS (PAG_IMMUTABLE=1):
7378 + pag deploy-list List all deployments
7379 + pag deploy-rollback Switch to previous deployment
7380 + pag deploy-cleanup [N] Remove old deployments (keep last N, default 3)
7381 + pag initramfs-update Rebuild initramfs for current kernel/deployment
7382 + pag grub-update Regenerate GRUB entries for all deployments
7383 +"""
7384 +
7385 +USAGE_PL = """pag v3 – Pagan Linux Package Manager
7386 +
7387 +PODSTAWOWE:
7388 + pag install <pkg>... Instalacja pakietów
7389 + pag remove <pkg>... Usuwanie pakietów
7390 + pag update Aktualizacja PAKIETÓW (odświeża indeksy)
7391 + pag sync Odśwież indeksy + info o aktualizacjach
7392 + pag upgrade Aktualizacja SYSTEMU (pakiety + kernel/initramfs/GRUB)
7393 + pag list [--installed] Lista dostępnych / zainstalowanych
7394 + pag search <query> Szukaj pakietów
7395 + pag info <pkg> Szczegóły pakietu
7396 + pag files <pkg> Lista plików pakietu
7397 + pag verify [--deep] Weryfikacja integralności
7398 + pag clean Wyczyść cache pobierania
7399 + pag stats Statystyki systemu
7400 + pag download <pkg>... Pobierz do cache (offline)
7401 +
7402 +ROLLING (baza wypalona w obrazie):
7403 + pag base [status] Pakiety z obrazu vs repo (czym pag zarządza)
7404 + pag base adopt [pkg...] Adoptuj pakiety bazy z repo (--dry-run = podgląd)
7405 +
7406 +BEZPIECZEŃSTWO:
7407 + pag key-add <url|file> Importuj klucz GPG
7408 + pag key-list Lista zaufanych kluczy
7409 + pag key-remove <id> Usuń klucz
7410 + pag key-trust <repo> Przypnij fingerprint klucza repo (bez TOFU)
7411 + pag key-untrust <repo> Zapomnij fingerprint repo (powrót do TOFU)
7412 + pag key-trusted Lista przypiętych fingerprintów repo
7413 +
7414 +ZAAWANSOWANE:
7415 + pag why <pkg> Dlaczego pakiet jest zainstalowany
7416 + pag rdepends <pkg> Które pakiety zależą od pakietu
7417 + pag autoremove Usuń osierocone zależności
7418 + pag pin <pkg> [ver] Przypnij wersję pakietu
7419 + pag unpin <pkg> Odepnij
7420 + pag pinned Lista przypiętych
7421 + pag history Historia transakcji
7422 + pag rollback Cofnij ostatnią transakcję
7423 + pag repair [--dry-run] Napraw brakujące pliki pakietów (reinstalacja)
7424 + pag remove-orphans Usuń osierocone zależności
7425 + pag repo-add <url> [nazwa] Dodaj repozytorium (drop-in w /etc/pag/repos/)
7426 + pag repo-list Lista repozytoriów
7427 + pag sbom export [fmt] Manifest SBOM (spdx|cyclonedx)
7428 +
7429 +FLATPAK:
7430 + pag flatpak [<query>] Szukaj i instaluj
7431 + pag flatpak search <q> Szukaj na Flathub
7432 + pag flatpak install <id> Zainstaluj flatpak
7433 + pag flatpak remove <id> Usuń flatpak
7434 + pag flatpak list Lista zainstalowanych
7435 + pag flatpak update Aktualizuj wszystkie
7436 + pag flatpak info <id> Szczegóły flatpaka
7437 +
7438 +SNAPSHOTY (btrfs CoW):
7439 + pag snapshot-list Lista snapshotów systemu
7440 + pag snapshot-create [opis] Utwórz snapshot teraz
7441 + pag snapshot-rollback [id] Uruchom snapshot przy następnym starcie (GRUB)
7442 + pag snapshot-delete <id> Usuń snapshot
7443 +
7444 +IMMUTABLE OS (PAG_IMMUTABLE=1):
7445 + pag deploy-list Lista wdrożeń
7446 + pag deploy-rollback Przełącz na poprzednie wdrożenie
7447 + pag deploy-cleanup [N] Usuń stare wdrożenia (zachowaj N, domyślnie 3)
7448 + pag initramfs-update Przebuduj initramfs
7449 + pag grub-update Regeneruj wpisy GRUB"""
7450 +
7451 +def _get_usage():
7452 + # Plik językowy może dostarczyć klucz "usage" – wtedy wygrywa z wbudowanym.
7453 + _u = T.get(LANG, {}).get("usage")
7454 + if _u:
7455 + return _u
7456 + if LANG == "pl":
7457 + return USAGE_PL
7458 + return USAGE_EN
7459 +
7460 +
7461 +def _extract_lang(outdir: str) -> int:
7462 + """Eksport wbudowanych tłumaczeń do outdir/{pl,en}.json (+ klucz "usage").
7463 +
7464 + Używane przez recepturę pakietu (pag.pag), żeby tłumaczenia jechały RAZEM
7465 + z wersją paga – po `pag install/upgrade pag` i self-update są zawsze zgodne.
7466 + """
7467 + os.makedirs(outdir, exist_ok=True)
7468 + for _code in ("pl", "en"):
7469 + _d = dict(T.get(_code, {}))
7470 + _u = globals().get(f"USAGE_{_code.upper()}", "")
7471 + if _u:
7472 + _d["usage"] = _u
7473 + _p = os.path.join(outdir, f"{_code}.json")
7474 + with open(_p, "w", encoding="utf-8") as _fh:
7475 + json.dump(_d, _fh, ensure_ascii=False, indent=2, sort_keys=True)
7476 + print(_(' ✓ {arg1} ({arg2} keys)', arg1=(_p), arg2=(len(_d))))
7477 + return 0
7478 +
7479 +
7480 +def main():
7481 + # Ukryte (używane przy budowie pakietu): eksport tłumaczeń do plików
7482 + if len(sys.argv) >= 3 and sys.argv[1] == "--lang-extract":
7483 + sys.exit(_extract_lang(sys.argv[2]))
7484 + if len(sys.argv) >= 2 and sys.argv[1] in ("--version", "-V", "version"):
7485 + print(f"pag {PAG_VERSION}")
7486 + sys.exit(0)
7487 + if len(sys.argv) == 2 and sys.argv[1] in ("--help", "-h", "help"):
7488 + print(_get_usage()); sys.exit(0)
7489 + if len(sys.argv) < 2:
7490 + print(_get_usage()); sys.exit(0)
7491 +
7492 + cmd = sys.argv[1]
7493 + args = sys.argv[2:]
7494 +
7495 + # Python bez modułu ssl = brak HTTPS w urllib. Powiedz to wprost, zamiast
7496 + # pokazywać mylące „unknown url type: https” przy każdej operacji sieciowej.
7497 + if not _ssl_ok():
7498 + print(f" ⚠ {_('ssl_broken')}", file=sys.stderr)
7499 +
7500 + # `pag repair --dry-run`: diagnostyka bez roota (nic nie zmienia).
7501 + if cmd == "repair" and "--dry-run" in args and os.geteuid() != 0:
7502 + sys.exit(cmd_repair(dry_run=True) or 0)
7503 +
7504 + # --- Komendy TYLKO DO ODCZYTU (nie wymagają roota) ---
7505 + READ_ONLY = {
7506 + "list": lambda: cmd_list("--installed" in args),
7507 + "search": lambda: cmd_search(args[0]) if args else print(_('Usage: pag search <query>')),
7508 + "info": lambda: cmd_info(args[0]) if args else print(_('Usage: pag info <pkg>')),
7509 + "files": lambda: cmd_files(args[0]) if args else print(_('Usage: pag files <pkg>')),
7510 + "verify": lambda: cmd_verify("--deep" in args),
7511 + "why": lambda: cmd_why(args[0]) if args else print(_('Usage: pag why <pkg>')),
7512 + "rdepends": lambda: cmd_rdepends(args[0]) if args else print(_('Usage: pag rdepends <pkg>')),
7513 + "stats": cmd_stats,
7514 + "pinned": cmd_pinned,
7515 + "history": cmd_history,
7516 + "repo-list": cmd_repo_list,
7517 + "key-list": cmd_key_list,
7518 + "key-trusted": cmd_key_trusted,
7519 + "flatpak": lambda: cmd_flatpak(args),
7520 + "flatpak-search": lambda: cmd_flatpak_search(args[0]) if args else print(_('Usage: pag flatpak-search <query>')),
7521 + "flatpak-list": cmd_flatpak_list,
7522 + "flatpak-info": lambda: cmd_flatpak_info(args[0]) if args else print(_('Usage: pag flatpak-info <id>')),
7523 + "deploy-list": cmd_deploy_list,
7524 + "deploy": cmd_deploy_list,
7525 + "snapshot-list": cmd_snapshot_list,
7526 + "snapshots": cmd_snapshot_list,
7527 + "snapshot-grub": cmd_snapshot_grub,
7528 + "sbom": lambda: cmd_sbom(args),
7529 + }
7530 +
7531 + if cmd in READ_ONLY:
7532 + sys.exit(READ_ONLY[cmd]() or 0)
7533 +
7534 + # --- `pag base` / `pag base status`: tylko odczyt (bez roota i bez locka) ---
7535 + # `pag base adopt` NIE wpada tutaj – idzie ścieżką komend zapisu (roota + lock
7536 + # pilnuje wspólna obsługa niżej), żeby transakcja była bezpieczna.
7537 + if cmd in ("base", "base-status") and not (args and args[0] in ("adopt", "register")):
7538 + sys.exit(cmd_base_status() or 0)
7539 +
7540 + # --- Smart search: `pag <nazwa-pakietu>` → repo + Flathub + sugestie ---
7541 + WRITE_CMDS = {
7542 + "install", "remove", "update", "sync", "upgrade", "clean", "download",
7543 + "autoremove", "remove-orphans", "pin", "unpin", "rollback",
7544 + "repo-add", "key-add", "key-remove", "key-trust", "key-untrust",
7545 + "self-update",
7546 + "flatpak", "flatpak-install", "flatpak-remove", "flatpak-update",
7547 + "deploy-rollback", "deploy-cleanup", "initramfs-update", "grub-update",
7548 + "snapshot-create", "snapshot-delete", "snapshot-rollback",
7549 + "base", "base-adopt", "base-register",
7550 + "repair",
7551 + }
7552 + if cmd not in WRITE_CMDS:
7553 + # Literówka komendy? (np. `pag instal steam` zamiast `pag install`) –
7554 + # zasugeruj poprawną komendę ZAMIAST wpadać w smart search (który
7555 + # potrafi wisieć na `flatpak search` aż do Ctrl-C).
7556 + _known = set(READ_ONLY) | set(WRITE_CMDS)
7557 + _close = difflib.get_close_matches(cmd, _known, n=1, cutoff=0.75)
7558 + if _close:
7559 + print(_("❌ Unknown command: '{arg1}'. Did you mean '{arg2}'?", arg1=(cmd), arg2=(_close[0])))
7560 + print(_(" Run 'pag' without arguments to see the command list."))
7561 + sys.exit(1)
7562 + sys.exit(_smart_search(" ".join([cmd] + args)) or 0)
7563 +
7564 + # Obsługa flag globalnych (-y/--yes oraz transakcji/snapshotów)
7565 + global_args = []
7566 + for a in args:
7567 + if a in ("-y", "--yes"):
7568 + os.environ["PAG_YES"] = "1"
7569 + elif a == "--dry-run":
7570 + os.environ["PAG_DRY_RUN"] = "1"
7571 + global_args.append(a) # `repair`/`base adopt` czytają flagę
7572 + elif a == "--snapshot":
7573 + os.environ["PAG_SNAPSHOT"] = "always"
7574 + elif a == "--no-snapshot":
7575 + os.environ["PAG_SNAPSHOT"] = "never"
7576 + elif a == "--atomic":
7577 + os.environ["PAG_ATOMIC"] = "1"
7578 + elif a == "--no-atomic":
7579 + os.environ["PAG_ATOMIC"] = "0"
7580 + else:
7581 + global_args.append(a)
7582 + args = global_args
7583 +
7584 + # --- Komendy ZAPISU (wymagają roota) ---
7585 + if os.geteuid() != 0:
7586 + print(f"❌ {_('root_required')}", file=sys.stderr); sys.exit(1)
7587 +
7588 + ensure_dirs()
7589 +
7590 + with DatabaseLock():
7591 + # Auto-naprawa: backup z przerwanej transakcji (bez wpisu „success")
7592 + # -> przywróć brakujące pliki, zanim cokolwiek innego zrobimy.
7593 + _recover_interrupted_transactions()
7594 + WRITE_COMMANDS = {
7595 + "install": lambda: cmd_install(
7596 + [a for a in args if a not in (
7597 + "-f", "--force", "--dry-run", "--snapshot", "--no-snapshot",
7598 + "--atomic", "--no-atomic", "--")],
7599 + upgrade=("-f" in args or "--force" in args)),
7600 + "remove": lambda: cmd_remove(args),
7601 + "update": lambda: cmd_update(do_upgrade=True),
7602 + "sync": lambda: cmd_update(do_upgrade=False),
7603 + "upgrade": cmd_upgrade,
7604 + "clean": cmd_clean,
7605 + "download": lambda: cmd_download(args),
7606 + "autoremove": cmd_autoremove,
7607 + "remove-orphans": cmd_remove_orphans,
7608 + "pin": lambda: cmd_pin(args[0], args[1] if len(args)>1 else ""),
7609 + "unpin": lambda: cmd_unpin(args[0]) if args else print(_('Usage: pag unpin <pkg>')),
7610 + "rollback": cmd_rollback,
7611 + "repair": lambda: cmd_repair(dry_run="--dry-run" in args),
7612 + "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]')),
7613 + "key-add": lambda: cmd_key_add(args[0]) if args else print(_('Usage: pag key-add <url|file>')),
7614 + "key-remove": lambda: cmd_key_remove(args[0]) if args else print(_('Usage: pag key-remove <id>')),
7615 + "key-trust": lambda: cmd_key_trust(args[0]) if args else print(_('Usage: pag key-trust <repo_url>')),
7616 + "key-untrust": lambda: cmd_key_untrust(args[0]) if args else print(_('Usage: pag key-untrust <repo_url>')),
7617 + "self-update": cmd_self_update,
7618 + "flatpak": lambda: cmd_flatpak(args),
7619 + "flatpak-install": lambda: _flatpak_smart_install(args) if args else print(_('Usage: pag flatpak-install <app>')),
7620 + "flatpak-remove": lambda: _flatpak_smart_remove(args) if args else print(_('Usage: pag flatpak-remove <app>')),
7621 + "flatpak-update": cmd_flatpak_update,
7622 + "deploy-rollback": cmd_deploy_rollback,
7623 + "deploy-cleanup": lambda: cmd_deploy_cleanup(int(args[0]) if args else 3),
7624 + "snapshot-create": lambda: cmd_snapshot_create(" ".join(
7625 + a for a in args if not a.startswith("-"))),
7626 + "snapshot-delete": lambda: cmd_snapshot_delete(args[0]) if args else print(
7627 + _('Usage: pag snapshot-delete <id>')),
7628 + "snapshot-rollback": lambda: cmd_snapshot_rollback(
7629 + args[0] if args else ""),
7630 + "initramfs-update": cmd_initramfs_update,
7631 + "grub-update": cmd_grub_update,
7632 + "base": lambda: cmd_base_register(args) if (args and args[0] == "register") else cmd_base_adopt(args),
7633 + "base-adopt": lambda: cmd_base_adopt(args),
7634 + "base-register": lambda: cmd_base_register(args),
7635 + }
7636 +
7637 + fn = WRITE_COMMANDS.get(cmd)
7638 + if fn:
7639 + sys.exit(fn() or 0)
7640 + # Should never reach here – _smart_search handles unknowns
7641 + sys.exit(_smart_search(" ".join([cmd] + args)) or 0)
7642 +
7643 +if __name__ == "__main__":
7644 + try:
7645 + main()
7646 + except KeyboardInterrupt:
7647 + # Ctrl-C (np. podczas flatpak search / pobierania) – bez tracebacka
7648 + print(_('\n ⚠ Interrupted (Ctrl-C).'))
7384 7649 sys.exit(130)
@@ -1,7 +1,199 @@
1 1 {
2 + "\n Choose a number (1-{arg1}) or press Enter to cancel:": "\n Choose a number (1-{arg1}) or press Enter to cancel:",
3 + "\n Choose a number (1-{arg1}) or press Enter:": "\n Choose a number (1-{arg1}) or press Enter:",
4 + "\n Choose a number to install (1-{arg1}) or press Enter to cancel:": "\n Choose a number to install (1-{arg1}) or press Enter to cancel:",
5 + "\n Multiple matches for '{arg1}':": "\n Multiple matches for '{arg1}':",
6 + "\n ↩ Rolling back transaction ({arg1} errors)...": "\n ↩ Rolling back transaction ({arg1} errors)...",
7 + "\n ⏬ Downloading {arg1} packages in parallel...": "\n ⏬ Downloading {arg1} packages in parallel...",
8 + "\n ⚠ Interrupted (Ctrl-C).": "\n ⚠ Interrupted (Ctrl-C).",
9 + "\n ❌ '{arg1}' — not found.": "\n ❌ '{arg1}' — not found.",
10 + "\n 🏗️ Creating a new deployment...": "\n 🏗️ Creating a new deployment...",
11 + "\n 💡 To install: pag flatpak install {arg1}": "\n 💡 To install: pag flatpak install {arg1}",
12 + "\n 🔄 Switching to deployment {arg1}...": "\n 🔄 Switching to deployment {arg1}...",
13 + "\n(--dry-run: nothing is changed)": "\n(--dry-run: nothing is changed)",
14 + "\n⚠ {arg1} – will be installed as dependencies:": "\n⚠ {arg1} – will be installed as dependencies:",
15 + "\n✅ Removed {arg1}.": "\n✅ Removed {arg1}.",
16 + "\n❌ {arg1} – cannot install:": "\n❌ {arg1} – cannot install:",
17 + "\n🔧 repair: {arg1}": "\n🔧 repair: {arg1}",
18 + " ... and {arg1} more (pag flatpak search {arg2})": " ... and {arg1} more (pag flatpak search {arg2})",
19 + " ... and {arg1} more (pag search {arg2})": " ... and {arg1} more (pag search {arg2})",
20 + " ⚠ {arg1} sensitive system files preserved": " ⚠ {arg1} sensitive system files preserved",
21 + " ⚠ {arg1} shared files preserved": " ⚠ {arg1} shared files preserved",
22 + " (TOFU – first trust. If the key changes, pag will refuse updates.)": " (TOFU – first trust. If the key changes, pag will refuse updates.)",
23 + " +{arg1} more...": " +{arg1} more...",
24 + " A .pag.asc/.pag.sig file from the same source is required.": " A .pag.asc/.pag.sig file from the same source is required.",
25 + " Add repo: pag repo-add <url>": " Add repo: pag repo-add <url>",
26 + " Expected: {arg1}": " Expected: {arg1}",
27 + " Expected: {arg1}, received: {arg2}": " Expected: {arg1}, received: {arg2}",
28 + " Flathub: pag flatpak search {arg1}": " Flathub: pag flatpak search {arg1}",
29 + " From now on, a key change will be reported as SECURITY ERROR.": " From now on, a key change will be reported as SECURITY ERROR.",
30 + " If this is an intentional key rotation: pag key-trust {arg1}": " If this is an intentional key rotation: pag key-trust {arg1}",
31 + " Install gnupg or set PAG_INSECURE=1 (not recommended)": " Install gnupg or set PAG_INSECURE=1 (not recommended)",
32 + " Make sure the repo key is in the keyring (pag key-add <url|file>).": " Make sure the repo key is in the keyring (pag key-add <url|file>).",
33 + " PaganOS repo: pag search {arg1}": " PaganOS repo: pag search {arg1}",
34 + " Pinned key: {arg1} – rejecting the index.": " Pinned key: {arg1} – rejecting the index.",
35 + " Received: {arg1}": " Received: {arg1}",
36 + " Remove the old copy: sudo rm {arg1}": " Remove the old copy: sudo rm {arg1}",
37 + " Run first: sudo pag sync": " Run first: sudo pag sync",
38 + " Set PAG_INSECURE=1 to skip (not recommended)": " Set PAG_INSECURE=1 to skip (not recommended)",
39 + " Set PAG_ROOT_DEVICE=/dev/... (or PAG_GRUB_ROOT) and retry.": " Set PAG_ROOT_DEVICE=/dev/... (or PAG_GRUB_ROOT) and retry.",
40 + " To avoid TOFU, add the fingerprint to /etc/pag/repos.conf.": " To avoid TOFU, add the fingerprint to /etc/pag/repos.conf.",
41 + " ⚠ trigger {arg1} timed out (120 s)": " ⚠ trigger {arg1} timed out (120 s)",
42 + " ⚠ trigger {arg1}: {arg2}": " ⚠ trigger {arg1}: {arg2}",
43 + " 'pag remove-orphans' to clean up.": " 'pag remove-orphans' to clean up.",
44 + " Dependencies: {arg1}": " Dependencies: {arg1}",
45 + " Description: {arg1}": " Description: {arg1}",
46 + " GPG: {arg1}": " GPG: {arg1}",
47 + " Install the library provider or update the repository.": " Install the library provider or update the repository.",
48 + " Install the missing packages or add repositories.": " Install the missing packages or add repositories.",
49 + " Installed: {arg1} ({arg2})": " Installed: {arg1} ({arg2})",
50 + " Packages: {arg1}": " Packages: {arg1}",
51 + " Restart pag to use the new version.": " Restart pag to use the new version.",
52 + " Run 'pag' without arguments to see the command list.": " Run 'pag' without arguments to see the command list.",
53 + " SHA256: {arg1}...": " SHA256: {arg1}...",
54 + " Size: {arg1:.1f} MB": " Size: {arg1:.1f} MB",
55 + " Version (repo): {arg1}": " Version (repo): {arg1}",
56 + " {arg1} → needs {arg2} (missing from repositories)": " {arg1} → needs {arg2} (missing from repositories)",
57 + " {arg1} → requires {arg2} – no package provides this version": " {arg1} → requires {arg2} – no package provides this version",
58 + " {arg1} → {arg2} ({arg3} – will be downloaded)": " {arg1} → {arg2} ({arg3} – will be downloaded)",
59 + " (no installed flatpaks)": " (no installed flatpaks)",
60 + " ... and {arg1} more. Refine your query.": " ... and {arg1} more. Refine your query.",
61 + " {arg1} {arg2}: {arg3} packages {arg4}": " {arg1} {arg2}: {arg3} packages {arg4}",
62 + " ℹ {arg1} has no pinned fingerprint.": " ℹ {arg1} has no pinned fingerprint.",
63 + " ↓ {arg1}-{arg2} (local) ... ": " ↓ {arg1}-{arg2} (local) ... ",
64 + " ↩ Aborted BEFORE installation – no package was changed.": " ↩ Aborted BEFORE installation – no package was changed.",
65 + " ↩ Preparation stage failed – the system was NOT changed.": " ↩ Preparation stage failed – the system was NOT changed.",
66 + " ↻ Retrying download of {arg1} ({arg2}/{arg3})...": " ↻ Retrying download of {arg1} ({arg2}/{arg3})...",
67 + " ⏪ Snapshot: {arg1}": " ⏪ Snapshot: {arg1}",
68 + " ⚠ A different pag is first in PATH: {arg1} (updated {arg2})": " ⚠ A different pag is first in PATH: {arg1} (updated {arg2})",
69 + " ⚠ Cannot create {arg1}: {arg2}": " ⚠ Cannot create {arg1}: {arg2}",
70 + " ⚠ Corrupted index cache {arg1}: {arg2}": " ⚠ Corrupted index cache {arg1}: {arg2}",
71 + " ⚠ Could not detect the root partition – GRUB entries will have no root=.": " ⚠ Could not detect the root partition – GRUB entries will have no root=.",
72 + " ⚠ Download error {arg1}: {arg2}": " ⚠ Download error {arg1}: {arg2}",
73 + " ⚠ Failed to create snapshot: {arg1}": " ⚠ Failed to create snapshot: {arg1}",
74 + " ⚠ Failed to download index {arg1}: {arg2}": " ⚠ Failed to download index {arg1}: {arg2}",
75 + " ⚠ Failed to extract {arg1}: {arg2}": " ⚠ Failed to extract {arg1}: {arg2}",
76 + " ⚠ Failed to refresh ld.so cache: {arg1}": " ⚠ Failed to refresh ld.so cache: {arg1}",
77 + " ⚠ HTTP {arg1} for {arg2}": " ⚠ HTTP {arg1} for {arg2}",
78 + " ⚠ Hook skipped (PAG_NO_HOOKS=1): {arg1} for {arg2}": " ⚠ Hook skipped (PAG_NO_HOOKS=1): {arg1} for {arg2}",
79 + " ⚠ Hook {arg1} for {arg2} exited with code {arg3}": " ⚠ Hook {arg1} for {arg2} exited with code {arg3}",
80 + " ⚠ Hook {arg1} for {arg2} timed out ({arg3}s)": " ⚠ Hook {arg1} for {arg2} timed out ({arg3}s)",
81 + " ⚠ Hook {arg1} for {arg2}: {arg3}": " ⚠ Hook {arg1} for {arg2}: {arg3}",
82 + " ⚠ Index downloaded, but failed to save cache ({arg1}): {arg2}": " ⚠ Index downloaded, but failed to save cache ({arg1}): {arg2}",
83 + " ⚠ Invalid update signature (PAG_INSECURE – ignoring)": " ⚠ Invalid update signature (PAG_INSECURE – ignoring)",
84 + " ⚠ Low disk space: {arg1} MB free, packages ~{arg2} MB (extracted will take more)": " ⚠ Low disk space: {arg1} MB free, packages ~{arg2} MB (extracted will take more)",
85 + " ⚠ New pag version {arg1} available – run: pag self-update": " ⚠ New pag version {arg1} available – run: pag self-update",
86 + " ⚠ No dracut/mkinitcpio – initramfs was not rebuilt": " ⚠ No dracut/mkinitcpio – initramfs was not rebuilt",
87 + " ⚠ No vmlinuz-* found in the deployment's /boot": " ⚠ No vmlinuz-* found in the deployment's /boot",
88 + " ⚠ PAG_INSECURE=1 – skipping local package signature verification": " ⚠ PAG_INSECURE=1 – skipping local package signature verification",
89 + " ⚠ Search error: {arg1}": " ⚠ Search error: {arg1}",
90 + " ⚠ Skipping unavailable file: {arg1}": " ⚠ Skipping unavailable file: {arg1}",
91 + " ⚠ Skipping unavailable files: {arg1}": " ⚠ Skipping unavailable files: {arg1}",
92 + " ⚠ Update signed with a different key (PAG_INSECURE – ignoring)": " ⚠ Update signed with a different key (PAG_INSECURE – ignoring)",
93 + " ⚠ btrfs snapshot failed: {arg1}": " ⚠ btrfs snapshot failed: {arg1}",
94 + " ⚠ ldconfig not found — linker cache was not refreshed.": " ⚠ ldconfig not found — linker cache was not refreshed.",
95 + " ⚠ pag-initramfs-init not found – skipping initramfs build": " ⚠ pag-initramfs-init not found – skipping initramfs build",
96 + " ⚠ {arg1}: SIGNING KEY CHANGED (PAG_INSECURE – ignoring)": " ⚠ {arg1}: SIGNING KEY CHANGED (PAG_INSECURE – ignoring)",
97 + " ⚠ {arg1}: cannot read signature fingerprint (PAG_INSECURE – ignoring)": " ⚠ {arg1}: cannot read signature fingerprint (PAG_INSECURE – ignoring)",
98 + " ⚠ {arg1}: invalid GPG signature (PAG_INSECURE – ignoring)": " ⚠ {arg1}: invalid GPG signature (PAG_INSECURE – ignoring)",
99 + " ⚠ {arg1}: not installed": " ⚠ {arg1}: not installed",
100 + " ⚡ Copying the active deployment...": " ⚡ Copying the active deployment...",
101 + " ⚡ Trigger: {arg1} ({arg2})": " ⚡ Trigger: {arg1} ({arg2})",
102 + " ✅ Active deployment: {arg1}": " ✅ Active deployment: {arg1}",
103 + " ✅ Deployment: {arg1} ({arg2})": " ✅ Deployment: {arg1} ({arg2})",
104 + " ✅ Downloaded pag {arg1} (current {arg2}), signature verified": " ✅ Downloaded pag {arg1} (current {arg2}), signature verified",
105 + " ✅ First deployment: {arg1}": " ✅ First deployment: {arg1}",
106 + " ✅ Installed new pag. Old version kept as {arg1}": " ✅ Installed new pag. Old version kept as {arg1}",
107 + " ✅ Pinned {arg1} for {arg2}": " ✅ Pinned {arg1} for {arg2}",
108 + " ✅ Removed pin for {arg1}.": " ✅ Removed pin for {arg1}.",
109 + " ✅ SHA256 matches": " ✅ SHA256 matches",
110 + " ✅ initramfs.img ({arg1:.1f} MB) → {arg2}": " ✅ initramfs.img ({arg1:.1f} MB) → {arg2}",
111 + " ✓ {arg1} ({arg2} keys)": " ✓ {arg1} ({arg2} keys)",
112 + " ✓ {arg1} is already installed ({arg2})": " ✓ {arg1} is already installed ({arg2})",
113 + " ❌ Cannot confirm the update signature fingerprint.": " ❌ Cannot confirm the update signature fingerprint.",
114 + " ❌ Cannot download pag: {arg1}": " ❌ Cannot download pag: {arg1}",
115 + " ❌ Cannot read signature fingerprint (missing/failed).": " ❌ Cannot read signature fingerprint (missing/failed).",
116 + " ❌ Failed to create snapshot (--snapshot mode) – aborting.": " ❌ Failed to create snapshot (--snapshot mode) – aborting.",
117 + " ❌ Invalid package signature: {arg1}": " ❌ Invalid package signature: {arg1}",
118 + " ❌ Invalid snapshot path – refusing to delete.": " ❌ Invalid snapshot path – refusing to delete.",
119 + " ❌ Invalid update signature – not updating.": " ❌ Invalid update signature – not updating.",
120 + " ❌ No pinned repo key for the local package.": " ❌ No pinned repo key for the local package.",
121 + " ❌ No signature for package: {arg1}": " ❌ No signature for package: {arg1}",
122 + " ❌ Not enough disk space: need ~{arg1} MB, free {arg2} MB ({arg3})": " ❌ Not enough disk space: need ~{arg1} MB, free {arg2} MB ({arg3})",
123 + " ❌ Package not found: {arg1}": " ❌ Package not found: {arg1}",
124 + " ❌ SHA256 mismatch! Expected {arg1}, got {arg2}": " ❌ SHA256 mismatch! Expected {arg1}, got {arg2}",
125 + " ❌ Syntax error in new pag: {arg1}": " ❌ Syntax error in new pag: {arg1}",
126 + " ❌ [SECURITY ERROR] Package was signed with a different repo key.": " ❌ [SECURITY ERROR] Package was signed with a different repo key.",
127 + " ❌ [SECURITY ERROR] Update signed with a different key than the repo!": " ❌ [SECURITY ERROR] Update signed with a different key than the repo!",
128 + " ❌ [SECURITY ERROR] {arg1}: Repository signing key has changed!": " ❌ [SECURITY ERROR] {arg1}: Repository signing key has changed!",
129 + " ❌ [SECURITY ERROR] {arg1}: cannot read signature fingerprint!": " ❌ [SECURITY ERROR] {arg1}: cannot read signature fingerprint!",
130 + " ❌ initramfs build error: {arg1}": " ❌ initramfs build error: {arg1}",
131 + " ❌ {arg1} is mounted read-only – cannot install.": " ❌ {arg1} is mounted read-only – cannot install.",
132 + " ❌ {arg1}: CANNOT DOWNLOAD SIGNATURE repo.json.asc/.sig!": " ❌ {arg1}: CANNOT DOWNLOAD SIGNATURE repo.json.asc/.sig!",
133 + " ❌ {arg1}: GPG is not installed – cannot verify the signature!": " ❌ {arg1}: GPG is not installed – cannot verify the signature!",
134 + " ❌ {arg1}: INVALID GPG SIGNATURE of the repository index!": " ❌ {arg1}: INVALID GPG SIGNATURE of the repository index!",
135 + " ❌ {arg1}: cannot refresh index – {arg2} is read-only": " ❌ {arg1}: cannot refresh index – {arg2} is read-only",
136 + " ❌ {arg1}: commit error – {arg2}": " ❌ {arg1}: commit error – {arg2}",
137 + " ❌ {arg1}: failed to read package ({arg2})": " ❌ {arg1}: failed to read package ({arg2})",
138 + " ❌ {arg1}: missing metadata.json": " ❌ {arg1}: missing metadata.json",
139 + " ❌ {arg1}: no GPG keys – verification impossible!": " ❌ {arg1}: no GPG keys – verification impossible!",
140 + " ❌ {arg1}: preparation stage failed ({arg2})": " ❌ {arg1}: preparation stage failed ({arg2})",
141 + " 🐧 Kernel: {arg1}": " 🐧 Kernel: {arg1}",
142 + " 🐧 Rebuilding initramfs (newer kernel)...": " 🐧 Rebuilding initramfs (newer kernel)...",
143 + " 💡 At boot, choose an entry in the GRUB menu (snapshots section).": " 💡 At boot, choose an entry in the GRUB menu (snapshots section).",
144 + " 💡 Reboot the system – GRUB will boot the selected snapshot.": " 💡 Reboot the system – GRUB will boot the selected snapshot.",
145 + " 💡 Restart required to reload the system.": " 💡 Restart required to reload the system.",
146 + " 📋 GRUB config updated – entries for each deployment": " 📋 GRUB config updated – entries for each deployment",
147 + " 📋 Regenerating GRUB (grub-mkconfig)...": " 📋 Regenerating GRUB (grub-mkconfig)...",
148 + " 📦 {arg1} – already installed (use 'pag flatpak info {arg2}' for details)": " 📦 {arg1} – already installed (use 'pag flatpak info {arg2}' for details)",
149 + " 📸 System snapshot: {arg1} (subvol={arg2})": " 📸 System snapshot: {arg1} (subvol={arg2})",
150 + " 🔄 Updating flatpaks...": " 🔄 Updating flatpaks...",
151 + " 🔐 Package signature OK ({arg1})": " 🔐 Package signature OK ({arg1})",
152 + " 🔐 Pinned repo fingerprint {arg1}: {arg2}": " 🔐 Pinned repo fingerprint {arg1}: {arg2}",
153 + " 🔑 Imported repo key from {arg1}/paganos.asc": " 🔑 Imported repo key from {arg1}/paganos.asc",
154 + " 🔧 Building initramfs for the deployment...": " 🔧 Building initramfs for the deployment...",
155 + " 🔧 DKMS: rebuilding out-of-tree modules (nvidia/vbox)...": " 🔧 DKMS: rebuilding out-of-tree modules (nvidia/vbox)...",
156 + " 🔧 Rebuilding initramfs (dracut)...": " 🔧 Rebuilding initramfs (dracut)...",
157 + " 🔧 Rebuilding initramfs (mkinitcpio)...": " 🔧 Rebuilding initramfs (mkinitcpio)...",
158 + " 🔧 Rebuilding initramfs (pagan-initramfs)...": " 🔧 Rebuilding initramfs (pagan-initramfs)...",
159 + " 🛠 Interrupted transaction detected – restored {arg1} missing files.": " 🛠 Interrupted transaction detected – restored {arg1} missing files.",
160 + " 🧹 Removed {arg1} obsolete files ({arg2})": " 🧹 Removed {arg1} obsolete files ({arg2})",
161 + "Available ({arg1}):": "Available ({arg1}):",
162 + "Files in {arg1} ({arg2}):": "Files in {arg1} ({arg2}):",
163 + "Installed ({arg1}):": "Installed ({arg1}):",
164 + "Installed flatpaks ({arg1}):": "Installed flatpaks ({arg1}):",
165 + "No packages installed.": "No packages installed.",
166 + "Nothing to repair (no packages installed).": "Nothing to repair (no packages installed).",
167 + "Nothing to verify.": "Nothing to verify.",
168 + "Orphans ({arg1}):": "Orphans ({arg1}):",
169 + "Recent transactions ({arg1}):": "Recent transactions ({arg1}):",
170 + "Results for '{arg1}' ({arg2}):": "Results for '{arg1}' ({arg2}):",
171 + "Usage: pag files <pkg>": "Usage: pag files <pkg>",
172 + "Usage: pag flatpak-info <id>": "Usage: pag flatpak-info <id>",
173 + "Usage: pag flatpak-install <app>": "Usage: pag flatpak-install <app>",
174 + "Usage: pag flatpak-remove <app>": "Usage: pag flatpak-remove <app>",
175 + "Usage: pag flatpak-search <query>": "Usage: pag flatpak-search <query>",
176 + "Usage: pag info <pkg>": "Usage: pag info <pkg>",
177 + "Usage: pag key-add <url|file>": "Usage: pag key-add <url|file>",
178 + "Usage: pag key-remove <id>": "Usage: pag key-remove <id>",
179 + "Usage: pag key-trust <repo_url>": "Usage: pag key-trust <repo_url>",
180 + "Usage: pag key-untrust <repo_url>": "Usage: pag key-untrust <repo_url>",
181 + "Usage: pag rdepends <pkg>": "Usage: pag rdepends <pkg>",
182 + "Usage: pag repo-add <url> [name]": "Usage: pag repo-add <url> [name]",
183 + "Usage: pag search <query>": "Usage: pag search <query>",
184 + "Usage: pag snapshot-delete <id>": "Usage: pag snapshot-delete <id>",
185 + "Usage: pag unpin <pkg>": "Usage: pag unpin <pkg>",
186 + "Usage: pag why <pkg>": "Usage: pag why <pkg>",
187 + "action_install": "install",
188 + "action_manual": "manual",
189 + "action_remove": "remove",
190 + "action_repair": "repair",
191 + "action_rollback": "rollback",
192 + "action_upgrade": "upgrade",
2 193 "active_deployment": "ACTIVE",
3 194 "all_installed": "All packages are already installed.",
4 195 "all_up_to_date": "All packages are up to date.",
196 + "audio_services_reloaded": " ⚡ audio services reloaded for sessions: {}",
5 197 "autoremove_none": "No orphaned packages.",
6 198 "autoremove_ok": "Removed {} orphaned packages.",
7 199 "base_adopt_hint": "Adopt them (image files get replaced by repo packages): sudo pag base adopt",
@@ -31,13 +223,16 @@
31 223 "conf_pacnew": "Modified config kept; new version saved as {path}",
32 224 "conf_pacsave": "Modified config kept as {path}",
33 225 "continue_q": "Continue? [Y/n] ",
226 + "copy_method": "full copy",
34 227 "db_lock_hint": "If no other pag process is running, wait a moment and retry.",
35 228 "db_locked": "Another pag instance is running.",
36 229 "deploy_cleanup_none": "No deployments to clean (minimum {}).",
37 230 "deploy_cleanup_ok": "Removed {} old deployments.",
231 + "deploy_copy_failed": "Failed to copy the deployment by any method",
38 232 "deploy_rollback_fail": "No previous deployment.",
39 233 "deploy_rollback_ok": "Switched to deployment: {}",
40 234 "deployments_list": "Deployments ({}):",
235 + "done": "done",
41 236 "download_fail": "download failed",
42 237 "downloaded": "Downloaded {} to cache ({:.2f} MB).",
43 238 "downloading": "Downloading",
@@ -62,16 +257,23 @@
62 257 "flatpak_removed": "Flatpak {} removed.",
63 258 "flatpak_scope": "Installation",
64 259 "flatpak_searching": "Searching Flathub for '{}'...",
260 + "flatpak_searching_any": "Searching Flathub...",
65 261 "flatpak_updated": "Flatpaks updated.",
66 262 "flatpak_usage": "Usage: pag flatpak <search|install|remove|list|update|info> [args]",
263 + "gpg_binary_not_found": "GPG binary not found ({})",
67 264 "gpg_fail": "GPG verification failed",
68 265 "gpg_missing": "GNUPG MISSING – install gnupg and retry",
266 + "gpg_timeout": "GPG operation timed out",
267 + "grub_fallback_label": "Pagan Linux – fallback (plain root)",
268 + "hardlink_method": "hardlinks",
69 269 "indexes_refreshed": "Indexes refreshed.",
70 270 "install_failed": "installation failed",
71 271 "installed": "Installed {} packages.",
272 + "installed_marker": "installed",
72 273 "key_add_failed": "Key import failed (gpg error) – key was NOT added.",
73 274 "key_imported": "Key imported successfully.",
74 275 "key_removed": "Key removed: {}",
276 + "never": "never",
75 277 "new": "NEW",
76 278 "no_deployments": "No deployments.",
77 279 "no_history": "No transaction history.",
@@ -79,6 +281,8 @@
79 281 "no_keys": "No trusted GPG keys.",
80 282 "no_pinned": "No pinned packages.",
81 283 "no_tty": "No TTY / stdin closed (EOF) – cancelling.",
284 + "none_parenthesized": "(none)",
285 + "none_value": "none",
82 286 "not_found": "not found in repos",
83 287 "not_found_hint": "Check the spelling or run 'pag search <query>'.",
84 288 "not_pinned": "was not pinned.",
@@ -86,14 +290,18 @@
86 290 "orphans_found": "Orphaned dependencies ({}): {}",
87 291 "pinned_list": "Pinned packages ({}):",
88 292 "pinned_to": "pinned to",
293 + "pkg_missing_data_tar": "missing data.tar.xz in package",
89 294 "pkg_not_found": "Package not found: {} (not in any repo)",
295 + "pkg_sha_mismatch": "SHA256 mismatch: {}",
90 296 "provides_conflict": "Multiple providers for '{name}' ({providers}) – using '{chosen}'",
91 297 "provides_mapped": "{} → {} (provides)",
92 298 "rdepends_none": "nothing depends on it.",
93 299 "rdepends_title": "Reverse dependencies of {} ({}):",
300 + "reflink_method": "CoW (reflink)",
94 301 "removing": "Removing",
95 302 "repo_added": "Added repository: {}",
96 303 "repo_exists": "Repository already exists: {}",
304 + "repo_index_invalid": "missing 'packages' list",
97 305 "rollback_files": "Rolled back {} files.",
98 306 "rollback_restored": "Restored previous state from snapshot.",
99 307 "root_required": "pag requires root privileges (sudo).",
@@ -126,15 +334,46 @@
126 334 "stats_packages": "Installed packages",
127 335 "stats_size": "Total size",
128 336 "stats_title": "PAG Statistics",
337 + "stats_top": "Top 5:",
129 338 "to_install": "To install: {} packages ({:.2f} MB)",
130 339 "unpinned": "unpinned.",
131 340 "updated_done": "Index refresh complete. {} packages cached.",
132 341 "updates_available": "⚠ {} packages have updates – run: pag update",
342 + "upgrade_marker": "[upgrade]",
133 343 "upgrading": "Upgrading: {} packages",
134 - "usage": "pag v4 – Pagan Linux Package Manager\n\nBASIC:\n pag install <pkg>... Install packages\n pag remove <pkg>... Remove packages\n pag update Update PACKAGES (refreshes indexes first)\n pag sync Refresh indexes + show pending package updates\n pag upgrade Update SYSTEM (packages + kernel/initramfs/GRUB)\n pag list [--installed] List available / installed\n pag search <query> Search packages\n pag info <pkg> Package details\n pag files <pkg> List package files\n pag verify [--deep] Verify integrity (--deep = SHA256 per file)\n pag clean Clear download cache\n pag stats System statistics\n pag download <pkg>... Download packages to cache (offline prep)\n\nROLLING (base baked into the image):\n pag base [status] Image packages vs. repo (what pag manages)\n pag base adopt [pkg...] Adopt base packages from the repo (--dry-run = preview)\n\nSECURITY:\n pag key-add <url|file> Import GPG key\n pag key-list List trusted keys\n pag key-remove <id> Remove key\n pag key-trust <repo> Pin repo signing key fingerprint (no TOFU)\n pag key-untrust <repo> Forget repo fingerprint (back to TOFU)\n pag key-trusted List pinned repo fingerprints\n\nADVANCED:\n pag why <pkg> Show why a package is installed\n pag autoremove Auto-remove orphaned dependencies\n pag pin <pkg> [ver] Pin package version\n pag unpin <pkg> Unpin\n pag pinned List pinned\n pag history Transaction history\n pag rollback Rollback last transaction\n pag remove-orphans Remove orphaned deps\n pag repo-add <url> [name] Add repository (drop-in /etc/pag/repos/)\n pag repo-list List repositories\n pag sbom export [fmt] SBOM manifest (spdx|cyclonedx)\n\nFLATPAK:\n pag flatpak [<query>] Search & install (smart)\n pag flatpak search <q> Search Flathub\n pag flatpak install <id> Install flatpak\n pag flatpak remove <id> Remove flatpak\n pag flatpak list List installed flatpaks\n pag flatpak update Update all flatpaks\n pag flatpak info <id> Show flatpak details\n\nSNAPSHOTS (btrfs CoW):\n pag snapshot-list List system snapshots\n pag snapshot-create [label] Create a snapshot now\n pag snapshot-rollback [id] Start from snapshot at next boot (GRUB)\n pag snapshot-delete <id> Delete a snapshot\n\nIMMUTABLE OS (PAG_IMMUTABLE=1):\n pag deploy-list List all deployments\n pag deploy-rollback Switch to previous deployment\n pag deploy-cleanup [N] Remove old deployments (keep last N, default 3)\n pag initramfs-update Rebuild initramfs for current kernel/deployment\n pag grub-update Regenerate GRUB entries for all deployments\n",
344 + "usage": "pag v3 – Pagan Linux Package Manager\n\nBASIC:\n pag install <pkg>... Install packages\n pag remove <pkg>... Remove packages\n pag update Update PACKAGES (refreshes indexes first)\n pag sync Refresh indexes + show pending package updates\n pag upgrade Update SYSTEM (packages + kernel/initramfs/GRUB)\n pag list [--installed] List available / installed\n pag search <query> Search packages\n pag info <pkg> Package details\n pag files <pkg> List package files\n pag verify [--deep] Verify integrity (--deep = SHA256 per file)\n pag clean Clear download cache\n pag stats System statistics\n pag download <pkg>... Download packages to cache (offline prep)\n\nROLLING (base baked into the image):\n pag base [status] Image packages vs. repo (what pag manages)\n pag base adopt [pkg...] Adopt base packages from the repo (--dry-run = preview)\n\nSECURITY:\n pag key-add <url|file> Import GPG key\n pag key-list List trusted keys\n pag key-remove <id> Remove key\n pag key-trust <repo> Pin repo signing key fingerprint (no TOFU)\n pag key-untrust <repo> Forget repo fingerprint (back to TOFU)\n pag key-trusted List pinned repo fingerprints\n\nADVANCED:\n pag why <pkg> Show why a package is installed\n pag rdepends <pkg> Show which packages depend on a package\n pag autoremove Auto-remove orphaned dependencies\n pag pin <pkg> [ver] Pin package version\n pag unpin <pkg> Unpin\n pag pinned List pinned\n pag history Transaction history\n pag rollback Rollback last transaction\n pag repair [--dry-run] Reinstall packages with missing files\n pag remove-orphans Remove orphaned deps\n pag repo-add <url> [name] Add repository (drop-in /etc/pag/repos/)\n pag repo-list List repositories\n pag sbom export [fmt] SBOM manifest (spdx|cyclonedx)\n\nFLATPAK:\n pag flatpak [<query>] Search & install (smart)\n pag flatpak search <q> Search Flathub\n pag flatpak install <id> Install flatpak\n pag flatpak remove <id> Remove flatpak\n pag flatpak list List installed flatpaks\n pag flatpak update Update all flatpaks\n pag flatpak info <id> Show flatpak details\n\nSNAPSHOTS (btrfs CoW):\n pag snapshot-list List system snapshots\n pag snapshot-create [label] Create a snapshot now\n pag snapshot-rollback [id] Start from snapshot at next boot (GRUB)\n pag snapshot-delete <id> Delete a snapshot\n\nIMMUTABLE OS (PAG_IMMUTABLE=1):\n pag deploy-list List all deployments\n pag deploy-rollback Switch to previous deployment\n pag deploy-cleanup [N] Remove old deployments (keep last N, default 3)\n pag initramfs-update Rebuild initramfs for current kernel/deployment\n pag grub-update Regenerate GRUB entries for all deployments\n",
135 345 "verify_errors": "{} problems found:",
346 + "verify_missing_file": " ❌ {}: missing {}",
136 347 "verify_ok": "All {} files intact.",
348 + "verify_sha_mismatch": " ❌ {}: SHA256 mismatch {}",
137 349 "why_dependency": "dependency of",
138 350 "why_explicit": "explicitly installed",
139 - "why_not_installed": "not installed"
140 -}
351 + "why_not_installed": "not installed",
352 + "⏪ Restoring deployment: {arg1}": "⏪ Restoring deployment: {arg1}",
353 + "⏪ Rolling back: {arg1} ({arg2})": "⏪ Rolling back: {arg1} ({arg2})",
354 + "⚠ Repaired {arg1}/{arg2}. Failed: {arg3}": "⚠ Repaired {arg1}/{arg2}. Failed: {arg3}",
355 + "✅ ({arg1} files)": "✅ ({arg1} files)",
356 + "✅ All files are in place – nothing to repair.": "✅ All files are in place – nothing to repair.",
357 + "✅ GRUB updated.": "✅ GRUB updated.",
358 + "✅ Initramfs updated.": "✅ Initramfs updated.",
359 + "✅ No orphans.": "✅ No orphans.",
360 + "✅ Repaired {arg1} packages.": "✅ Repaired {arg1} packages.",
361 + "❌ '{arg1}' not found.": "❌ '{arg1}' not found.",
362 + "❌ '{arg1}' not installed.": "❌ '{arg1}' not installed.",
363 + "❌ Another pag update is in progress – try again later.": "❌ Another pag update is in progress – try again later.",
364 + "❌ Cannot continue – {arg1} missing dependencies.": "❌ Cannot continue – {arg1} missing dependencies.",
365 + "❌ Deployment {arg1} does not exist on disk": "❌ Deployment {arg1} does not exist on disk",
366 + "❌ Download error: {arg1}": "❌ Download error: {arg1}",
367 + "❌ Format: spdx | cyclonedx": "❌ Format: spdx | cyclonedx",
368 + "❌ Initramfs update failed.": "❌ Initramfs update failed.",
369 + "❌ No repositories configured.": "❌ No repositories configured.",
370 + "❌ No results for: {arg1}": "❌ No results for: {arg1}",
371 + "❌ No snapshot to restore.": "❌ No snapshot to restore.",
372 + "❌ Unknown command: '{arg1}'. Did you mean '{arg2}'?": "❌ Unknown command: '{arg1}'. Did you mean '{arg2}'?",
373 + "🏗️ Deployment: {arg1}": "🏗️ Deployment: {arg1}",
374 + "📋 Updating GRUB configuration...": "📋 Updating GRUB configuration...",
375 + "🔄 Checking for pag update from {arg1}...": "🔄 Checking for pag update from {arg1}...",
376 + "🔄 Refreshing indexes...": "🔄 Refreshing indexes...",
377 + "🔐 Pinning repo key {arg1}...": "🔐 Pinning repo key {arg1}...",
378 + "🔧 Packages with missing files: {arg1} (total {arg2} files)": "🔧 Packages with missing files: {arg1} (total {arg2} files)"
379 +}
@@ -1,7 +1,199 @@
1 1 {
2 + "\n Choose a number (1-{arg1}) or press Enter to cancel:": "\n Wybierz numer (1-{arg1}) lub Enter aby anulować: ",
3 + "\n Choose a number (1-{arg1}) or press Enter:": "\n Wybierz numer (1-{arg1}) lub Enter: ",
4 + "\n Choose a number to install (1-{arg1}) or press Enter to cancel:": "\n Wybierz numer do zainstalowania (1-{arg1}) lub Enter aby anulować: ",
5 + "\n Multiple matches for '{arg1}':": "\n Wiele dopasowań dla '{arg1}':",
6 + "\n ↩ Rolling back transaction ({arg1} errors)...": "\n ↩ Cofanie transakcji ({arg1} błędów)...",
7 + "\n ⏬ Downloading {arg1} packages in parallel...": "\n ⏬ Pobieranie {arg1} pakietów równolegle...",
8 + "\n ⚠ Interrupted (Ctrl-C).": "\n ⚠ Przerwano (Ctrl-C).",
9 + "\n ❌ '{arg1}' — not found.": "\n ❌ '{arg1}' — nie znaleziono.",
10 + "\n 🏗️ Creating a new deployment...": "\n 🏗️ Tworzenie nowego deploymentu...",
11 + "\n 💡 To install: pag flatpak install {arg1}": "\n 💡 Aby zainstalować: pag flatpak install {arg1}",
12 + "\n 🔄 Switching to deployment {arg1}...": "\n 🔄 Przełączanie na deployment {arg1}...",
13 + "\n(--dry-run: nothing is changed)": "\n(--dry-run: nic nie zmieniam)",
14 + "\n⚠ {arg1} – will be installed as dependencies:": "\n⚠ {arg1} – zostaną doinstalowane:",
15 + "\n✅ Removed {arg1}.": "\n✅ Usunięto {arg1}.",
16 + "\n❌ {arg1} – cannot install:": "\n❌ {arg1} – nie można zainstalować:",
17 + "\n🔧 repair: {arg1}": "\n🔧 naprawa: {arg1}",
18 + " ... and {arg1} more (pag flatpak search {arg2})": " ... i {arg1} więcej (pag flatpak search {arg2})",
19 + " ... and {arg1} more (pag search {arg2})": " ... i {arg1} więcej (pag search {arg2})",
20 + " ⚠ {arg1} sensitive system files preserved": " ⚠ {arg1} wrażliwych plików systemowych zachowanych",
21 + " ⚠ {arg1} shared files preserved": " ⚠ {arg1} plików współdzielonych zachowanych",
22 + " (TOFU – first trust. If the key changes, pag will refuse updates.)": " (TOFU – pierwsze zaufanie. Gdy klucz się zmieni, pag odmówi aktualizacji.)",
23 + " +{arg1} more...": " +{arg1} więcej...",
24 + " A .pag.asc/.pag.sig file from the same source is required.": " Wymagany jest plik .pag.asc/.pag.sig z tego samego źródła.",
25 + " Add repo: pag repo-add <url>": " Dodaj repo: pag repo-add <url>",
26 + " Expected: {arg1}": " Oczekiwany: {arg1}",
27 + " Expected: {arg1}, received: {arg2}": " Oczekiwany: {arg1}, Otrzymany: {arg2}",
28 + " Flathub: pag flatpak search {arg1}": " Flathub: pag flatpak search {arg1}",
29 + " From now on, a key change will be reported as SECURITY ERROR.": " Od teraz zmiana klucza zostanie zgłoszona jako SECURITY ERROR.",
30 + " If this is an intentional key rotation: pag key-trust {arg1}": " Jeśli to celowa rotacja klucza: pag key-trust {arg1}",
31 + " Install gnupg or set PAG_INSECURE=1 (not recommended)": " Zainstaluj gnupg lub ustaw PAG_INSECURE=1 (niezalecane)",
32 + " Make sure the repo key is in the keyring (pag key-add <url|file>).": " Upewnij się, że klucz repo jest w keyringu (pag key-add <url|file>).",
33 + " PaganOS repo: pag search {arg1}": " Repo PaganOS: pag search {arg1}",
34 + " Pinned key: {arg1} – rejecting the index.": " Przypięty klucz: {arg1} – odrzucam indeks.",
35 + " Received: {arg1}": " Otrzymany: {arg1}",
36 + " Remove the old copy: sudo rm {arg1}": " Usuń starą kopię: sudo rm {arg1}",
37 + " Run first: sudo pag sync": " Uruchom najpierw: sudo pag sync",
38 + " Set PAG_INSECURE=1 to skip (not recommended)": " Ustaw PAG_INSECURE=1 aby pominąć (niezalecane)",
39 + " Set PAG_ROOT_DEVICE=/dev/... (or PAG_GRUB_ROOT) and retry.": " Ustaw PAG_ROOT_DEVICE=/dev/... (lub PAG_GRUB_ROOT) i powtórz.",
40 + " To avoid TOFU, add the fingerprint to /etc/pag/repos.conf.": " Aby uniknąć TOFU, dopisz fingerprint w /etc/pag/repos.conf.",
41 + " ⚠ trigger {arg1} timed out (120 s)": " ⚠ trigger {arg1} przekroczył limit czasu (120 s)",
42 + " ⚠ trigger {arg1}: {arg2}": " ⚠ wyzwalacz {arg1}: {arg2}",
43 + " 'pag remove-orphans' to clean up.": " Uruchom 'pag remove-orphans', aby posprzątać.",
44 + " Dependencies: {arg1}": " Zależności: {arg1}",
45 + " Description: {arg1}": " Opis: {arg1}",
46 + " GPG: {arg1}": " GPG: {arg1}",
47 + " Install the library provider or update the repository.": " Zainstaluj dostawcę biblioteki lub zaktualizuj repozytorium.",
48 + " Install the missing packages or add repositories.": " Zainstaluj brakujące pakiety lub dodaj repozytoria.",
49 + " Installed: {arg1} ({arg2})": " Zainstalowany: {arg1} ({arg2})",
50 + " Packages: {arg1}": " Pakiety: {arg1}",
51 + " Restart pag to use the new version.": " Uruchom ponownie pag, aby użyć nowej wersji.",
52 + " Run 'pag' without arguments to see the command list.": " Uruchom 'pag' bez argumentów, aby zobaczyć listę komend.",
53 + " SHA256: {arg1}...": " SHA256: {arg1}...",
54 + " Size: {arg1:.1f} MB": " Rozmiar: {arg1:.1f} MB",
55 + " Version (repo): {arg1}": " Wersja (repo): {arg1}",
56 + " {arg1} → needs {arg2} (missing from repositories)": " {arg1} → potrzebuje {arg2} (brak w repozytoriach)",
57 + " {arg1} → requires {arg2} – no package provides this version": " {arg1} → wymaga {arg2} – żaden pakiet nie dostarcza tej wersji",
58 + " {arg1} → {arg2} ({arg3} – will be downloaded)": " {arg1} → {arg2} ({arg3} – będzie pobrane)",
59 + " (no installed flatpaks)": " (brak zainstalowanych flatpaków)",
60 + " ... and {arg1} more. Refine your query.": " ... i {arg1} więcej. Doprecyzuj zapytanie.",
61 + " {arg1} {arg2}: {arg3} packages {arg4}": " {arg1} {arg2}: {arg3} pakietów {arg4}",
62 + " ℹ {arg1} has no pinned fingerprint.": " ℹ {arg1} nie ma przypiętego fingerprintu.",
63 + " ↓ {arg1}-{arg2} (local) ... ": " ↓ {arg1}-{arg2} (lokalny) ... ",
64 + " ↩ Aborted BEFORE installation – no package was changed.": " ↩ Przerwano PRZED instalacją – żadna paczka nie została zmieniona.",
65 + " ↩ Preparation stage failed – the system was NOT changed.": " ↩ Etap przygotowania nieudany – system NIE został zmieniony.",
66 + " ↻ Retrying download of {arg1} ({arg2}/{arg3})...": " ↻ Ponawiam pobieranie {arg1} ({arg2}/{arg3})...",
67 + " ⏪ Snapshot: {arg1}": " ⏪ Snapshot: {arg1}",
68 + " ⚠ A different pag is first in PATH: {arg1} (updated {arg2})": " ⚠ W PATH pierwszy jest inny pag: {arg1} (zaktualizowano {arg2})",
69 + " ⚠ Cannot create {arg1}: {arg2}": " ⚠ Nie mogę utworzyć {arg1}: {arg2}",
70 + " ⚠ Corrupted index cache {arg1}: {arg2}": " ⚠ Uszkodzony cache indeksu {arg1}: {arg2}",
71 + " ⚠ Could not detect the root partition – GRUB entries will have no root=.": " ⚠ Nie udało się wykryć partycji root – wpisy GRUB nie dostaną root=.",
72 + " ⚠ Download error {arg1}: {arg2}": " ⚠ Błąd pobierania {arg1}: {arg2}",
73 + " ⚠ Failed to create snapshot: {arg1}": " ⚠ Nie udało się utworzyć snapshotu: {arg1}",
74 + " ⚠ Failed to download index {arg1}: {arg2}": " ⚠ Błąd pobierania indeksu {arg1}: {arg2}",
75 + " ⚠ Failed to extract {arg1}: {arg2}": " ⚠ Nie rozpakowano {arg1}: {arg2}",
76 + " ⚠ Failed to refresh ld.so cache: {arg1}": " ⚠ Nie udało się odświeżyć cache'a ld.so: {arg1}",
77 + " ⚠ HTTP {arg1} for {arg2}": " ⚠ HTTP {arg1} dla {arg2}",
78 + " ⚠ Hook skipped (PAG_NO_HOOKS=1): {arg1} for {arg2}": " ⚠ Hook pominięty (PAG_NO_HOOKS=1): {arg1} dla {arg2}",
79 + " ⚠ Hook {arg1} for {arg2} exited with code {arg3}": " ⚠ Hook {arg1} dla {arg2} zakończony z kodem {arg3}",
80 + " ⚠ Hook {arg1} for {arg2} timed out ({arg3}s)": " ⚠ Hook {arg1} dla {arg2} przekroczył timeout ({arg3}s)",
81 + " ⚠ Hook {arg1} for {arg2}: {arg3}": " ⚠ Hook {arg1} dla {arg2}: {arg3}",
82 + " ⚠ Index downloaded, but failed to save cache ({arg1}): {arg2}": " ⚠ Indeks pobrany, ale nie udało się zapisać cache ({arg1}): {arg2}",
83 + " ⚠ Invalid update signature (PAG_INSECURE – ignoring)": " ⚠ Nieprawidłowy podpis aktualizacji (PAG_INSECURE – ignoruję)",
84 + " ⚠ Low disk space: {arg1} MB free, packages ~{arg2} MB (extracted will take more)": " ⚠ Mało miejsca na dysku: wolne {arg1} MB, pakiety ~{arg2} MB (rozpakowane zajmą więcej)",
85 + " ⚠ New pag version {arg1} available – run: pag self-update": " ⚠ Nowa wersja pag {arg1} dostępna – uruchom: pag self-update",
86 + " ⚠ No dracut/mkinitcpio – initramfs was not rebuilt": " ⚠ Brak dracut/mkinitcpio – initramfs nie został przebudowany",
87 + " ⚠ No vmlinuz-* found in the deployment's /boot": " ⚠ Nie znaleziono vmlinuz-* w /boot deploymentu",
88 + " ⚠ PAG_INSECURE=1 – skipping local package signature verification": " ⚠ PAG_INSECURE=1 – pomijam weryfikację podpisu pakietu lokalnego",
89 + " ⚠ Search error: {arg1}": " ⚠ Błąd wyszukiwania: {arg1}",
90 + " ⚠ Skipping unavailable file: {arg1}": " ⚠ Pomijam niedostępny plik: {arg1}",
91 + " ⚠ Skipping unavailable files: {arg1}": " ⚠ Pomijam niedostępne pliki: {arg1}",
92 + " ⚠ Update signed with a different key (PAG_INSECURE – ignoring)": " ⚠ Podpis aktualizacji innym kluczem (PAG_INSECURE – ignoruję)",
93 + " ⚠ btrfs snapshot failed: {arg1}": " ⚠ btrfs snapshot nie udał się: {arg1}",
94 + " ⚠ ldconfig not found — linker cache was not refreshed.": " ⚠ Nie znaleziono ldconfig — cache linkera nie został odświeżony.",
95 + " ⚠ pag-initramfs-init not found – skipping initramfs build": " ⚠ Nie znaleziono pag-initramfs-init – pomijam budowę initramfs",
96 + " ⚠ {arg1}: SIGNING KEY CHANGED (PAG_INSECURE – ignoring)": " ⚠ {arg1}: ZMIENIONY KLUCZ PODPISU (PAG_INSECURE – ignoruję)",
97 + " ⚠ {arg1}: cannot read signature fingerprint (PAG_INSECURE – ignoring)": " ⚠ {arg1}: nie można odczytać fingerprintu (PAG_INSECURE – ignoruję)",
98 + " ⚠ {arg1}: invalid GPG signature (PAG_INSECURE – ignoring)": " ⚠ {arg1}: nieprawidłowy podpis GPG (PAG_INSECURE – ignoruję)",
99 + " ⚠ {arg1}: not installed": " ⚠ {arg1}: nie zainstalowano",
100 + " ⚡ Copying the active deployment...": " ⚡ Kopiowanie aktywnego deploymentu...",
101 + " ⚡ Trigger: {arg1} ({arg2})": " ⚡ Wyzwalacz: {arg1} ({arg2})",
102 + " ✅ Active deployment: {arg1}": " ✅ Aktywny deployment: {arg1}",
103 + " ✅ Deployment: {arg1} ({arg2})": " ✅ Deployment: {arg1} ({arg2})",
104 + " ✅ Downloaded pag {arg1} (current {arg2}), signature verified": " ✅ Pobrano pag {arg1} (obecny {arg2}), podpis zweryfikowany",
105 + " ✅ First deployment: {arg1}": " ✅ Pierwszy deployment: {arg1}",
106 + " ✅ Installed new pag. Old version kept as {arg1}": " ✅ Zainstalowano nowy pag. Stary zachowany jako {arg1}",
107 + " ✅ Pinned {arg1} for {arg2}": " ✅ Przypięto {arg1} dla {arg2}",
108 + " ✅ Removed pin for {arg1}.": " ✅ Usunięto przypięcie dla {arg1}.",
109 + " ✅ SHA256 matches": " ✅ SHA256 zgodny",
110 + " ✅ initramfs.img ({arg1:.1f} MB) → {arg2}": " ✅ initramfs.img ({arg1:.1f} MB) → {arg2}",
111 + " ✓ {arg1} ({arg2} keys)": " ✓ {arg1} ({arg2} kluczy)",
112 + " ✓ {arg1} is already installed ({arg2})": " ✓ {arg1} jest już zainstalowany ({arg2})",
113 + " ❌ Cannot confirm the update signature fingerprint.": " ❌ Nie można potwierdzić fingerprintu podpisu aktualizacji.",
114 + " ❌ Cannot download pag: {arg1}": " ❌ Nie można pobrać pag: {arg1}",
115 + " ❌ Cannot read signature fingerprint (missing/failed).": " ❌ Nie można odczytać fingerprintu podpisu (brak/nieudany).",
116 + " ❌ Failed to create snapshot (--snapshot mode) – aborting.": " ❌ Nie udało się utworzyć snapshotu (tryb --snapshot) – przerywam.",
117 + " ❌ Invalid package signature: {arg1}": " ❌ Nieprawidłowy podpis pakietu: {arg1}",
118 + " ❌ Invalid snapshot path – refusing to delete.": " ❌ Nieprawidłowa ścieżka snapshotu – odmawiam usunięcia.",
119 + " ❌ Invalid update signature – not updating.": " ❌ Nieprawidłowy podpis aktualizacji – nie aktualizuję.",
120 + " ❌ No pinned repo key for the local package.": " ❌ Brak przypiętego klucza repo dla lokalnego pakietu.",
121 + " ❌ No signature for package: {arg1}": " ❌ Brak podpisu dla pakietu: {arg1}",
122 + " ❌ Not enough disk space: need ~{arg1} MB, free {arg2} MB ({arg3})": " ❌ Za mało miejsca na dysku: potrzeba ~{arg1} MB, wolne {arg2} MB ({arg3})",
123 + " ❌ Package not found: {arg1}": " ❌ Nie znaleziono pakietu: {arg1}",
124 + " ❌ SHA256 mismatch! Expected {arg1}, got {arg2}": " ❌ SHA256 niezgodny! Oczekiwano {arg1}, jest {arg2}",
125 + " ❌ Syntax error in new pag: {arg1}": " ❌ Błąd składni w nowym pag: {arg1}",
126 + " ❌ [SECURITY ERROR] Package was signed with a different repo key.": " ❌ [SECURITY ERROR] Pakiet podpisano innym kluczem repo.",
127 + " ❌ [SECURITY ERROR] Update signed with a different key than the repo!": " ❌ [SECURITY ERROR] Podpis aktualizacji innym kluczem niż repo!",
128 + " ❌ [SECURITY ERROR] {arg1}: Repository signing key has changed!": " ❌ [SECURITY ERROR] {arg1}: Klucz podpisujący repo uległ zmianie!",
129 + " ❌ [SECURITY ERROR] {arg1}: cannot read signature fingerprint!": " ❌ [SECURITY ERROR] {arg1}: nie można odczytać fingerprintu podpisu!",
130 + " ❌ initramfs build error: {arg1}": " ❌ Błąd budowy initramfs: {arg1}",
131 + " ❌ {arg1} is mounted read-only – cannot install.": " ❌ {arg1} jest zamontowane tylko-do-odczytu – nie można instalować.",
132 + " ❌ {arg1}: CANNOT DOWNLOAD SIGNATURE repo.json.asc/.sig!": " ❌ {arg1}: NIE MOŻNA POBRAĆ PODPISU repo.json.asc/.sig!",
133 + " ❌ {arg1}: GPG is not installed – cannot verify the signature!": " ❌ {arg1}: GPG nie jest zainstalowane – nie można zweryfikować podpisu!",
134 + " ❌ {arg1}: INVALID GPG SIGNATURE of the repository index!": " ❌ {arg1}: NIEPRAWIDŁOWY PODPIS GPG indeksu repozytorium!",
135 + " ❌ {arg1}: cannot refresh index – {arg2} is read-only": " ❌ {arg1}: nie można odświeżyć indeksu – {arg2} jest tylko-do-odczytu",
136 + " ❌ {arg1}: commit error – {arg2}": " ❌ {arg1}: błąd commit – {arg2}",
137 + " ❌ {arg1}: failed to read package ({arg2})": " ❌ {arg1}: nie udało się odczytać pakietu ({arg2})",
138 + " ❌ {arg1}: missing metadata.json": " ❌ {arg1}: brak metadata.json",
139 + " ❌ {arg1}: no GPG keys – verification impossible!": " ❌ {arg1}: brak kluczy GPG – weryfikacja niemożliwa!",
140 + " ❌ {arg1}: preparation stage failed ({arg2})": " ❌ {arg1}: etap przygotowania nieudany ({arg2})",
141 + " 🐧 Kernel: {arg1}": " 🐧 Jądro: {arg1}",
142 + " 🐧 Rebuilding initramfs (newer kernel)...": " 🐧 Przebudowa initramfs (nowsze jądro)...",
143 + " 💡 At boot, choose an entry in the GRUB menu (snapshots section).": " 💡 Przy starcie wybierz wpis w menu GRUB (sekcja snapshotów).",
144 + " 💡 Reboot the system – GRUB will boot the selected snapshot.": " 💡 Zrestartuj system – GRUB uruchomi wybrany snapshot.",
145 + " 💡 Restart required to reload the system.": " 💡 Restart wymagany do przeładowania systemu.",
146 + " 📋 GRUB config updated – entries for each deployment": " 📋 GRUB config zaktualizowany – wpisy dla każdego deploymentu",
147 + " 📋 Regenerating GRUB (grub-mkconfig)...": " 📋 Regeneracja GRUB (grub-mkconfig)...",
148 + " 📦 {arg1} – already installed (use 'pag flatpak info {arg2}' for details)": " 📦 {arg1} – już zainstalowany (szczegóły: 'pag flatpak info {arg2}')",
149 + " 📸 System snapshot: {arg1} (subvol={arg2})": " 📸 Snapshot systemu: {arg1} (subvol={arg2})",
150 + " 🔄 Updating flatpaks...": " 🔄 Aktualizacja flatpaków...",
151 + " 🔐 Package signature OK ({arg1})": " 🔐 Podpis pakietu OK ({arg1})",
152 + " 🔐 Pinned repo fingerprint {arg1}: {arg2}": " 🔐 Przypięto fingerprint repo {arg1}: {arg2}",
153 + " 🔑 Imported repo key from {arg1}/paganos.asc": " 🔑 Importowano klucz repo z {arg1}/paganos.asc",
154 + " 🔧 Building initramfs for the deployment...": " 🔧 Budowanie initramfs dla deploymentu...",
155 + " 🔧 DKMS: rebuilding out-of-tree modules (nvidia/vbox)...": " 🔧 DKMS: przebudowa modułów out-of-tree (nvidia/vbox)...",
156 + " 🔧 Rebuilding initramfs (dracut)...": " 🔧 Przebudowa initramfs (dracut)...",
157 + " 🔧 Rebuilding initramfs (mkinitcpio)...": " 🔧 Przebudowa initramfs (mkinitcpio)...",
158 + " 🔧 Rebuilding initramfs (pagan-initramfs)...": " 🔧 Przebudowa initramfs (pagan-initramfs)...",
159 + " 🛠 Interrupted transaction detected – restored {arg1} missing files.": " 🛠 Wykryto przerwana transakcje – przywrocono {arg1} brakujacych plikow.",
160 + " 🧹 Removed {arg1} obsolete files ({arg2})": " 🧹 Usunięto {arg1} nieaktualnych plików ({arg2})",
161 + "Available ({arg1}):": "Dostępne ({arg1}):",
162 + "Files in {arg1} ({arg2}):": "Pliki w {arg1} ({arg2}):",
163 + "Installed ({arg1}):": "Zainstalowane ({arg1}):",
164 + "Installed flatpaks ({arg1}):": " Zainstalowane flatpaki ({arg1}):",
165 + "No packages installed.": "Brak zainstalowanych pakietów.",
166 + "Nothing to repair (no packages installed).": "Nic do naprawy (brak zainstalowanych pakietow).",
167 + "Nothing to verify.": "Nie ma czego weryfikować.",
168 + "Orphans ({arg1}):": "Osierocone ({arg1}):",
169 + "Recent transactions ({arg1}):": "Ostatnie transakcje ({arg1}):",
170 + "Results for '{arg1}' ({arg2}):": "Wyniki dla '{arg1}' ({arg2}):",
171 + "Usage: pag files <pkg>": "Użycie: pag files <pkg>",
172 + "Usage: pag flatpak-info <id>": "Użycie: pag flatpak-info <id>",
173 + "Usage: pag flatpak-install <app>": "Użycie: pag flatpak-install <app>",
174 + "Usage: pag flatpak-remove <app>": "Użycie: pag flatpak-remove <app>",
175 + "Usage: pag flatpak-search <query>": "Użycie: pag flatpak-search <query>",
176 + "Usage: pag info <pkg>": "Użycie: pag info <pkg>",
177 + "Usage: pag key-add <url|file>": "Użycie: pag key-add <url|file>",
178 + "Usage: pag key-remove <id>": "Użycie: pag key-remove <id>",
179 + "Usage: pag key-trust <repo_url>": "Użycie: pag key-trust <repo_url>",
180 + "Usage: pag key-untrust <repo_url>": "Użycie: pag key-untrust <repo_url>",
181 + "Usage: pag rdepends <pkg>": "Użycie: pag rdepends <pkg>",
182 + "Usage: pag repo-add <url> [name]": "Użycie: pag repo-add <url> [name]",
183 + "Usage: pag search <query>": "Użycie: pag search <query>",
184 + "Usage: pag snapshot-delete <id>": "Użycie: pag snapshot-delete <id>",
185 + "Usage: pag unpin <pkg>": "Użycie: pag unpin <pkg>",
186 + "Usage: pag why <pkg>": "Użycie: pag why <pkg>",
187 + "action_install": "instalacja",
188 + "action_manual": "ręczny",
189 + "action_remove": "usunięcie",
190 + "action_repair": "naprawa",
191 + "action_rollback": "wycofanie",
192 + "action_upgrade": "aktualizacja",
2 193 "active_deployment": "AKTYWNY",
3 194 "all_installed": "Wszystkie pakiety są już zainstalowane.",
4 195 "all_up_to_date": "Wszystkie pakiety są aktualne.",
196 + "audio_services_reloaded": " ⚡ przeładowano usługi audio dla sesji: {}",
5 197 "autoremove_none": "Brak osieroconych pakietów.",
6 198 "autoremove_ok": "Usunięto {} osieroconych pakietów.",
7 199 "base_adopt_hint": "Adoptuj (pliki z obrazu zostaną zastąpione pakietami z repo): sudo pag base adopt",
@@ -31,13 +223,16 @@
31 223 "conf_pacnew": "Zmieniony plik konfiguracyjny zachowany; nowa wersja: {path}",
32 224 "conf_pacsave": "Zmieniony plik konfiguracyjny zachowany jako {path}",
33 225 "continue_q": "Kontynuować? [T/n] ",
226 + "copy_method": "pełna kopia",
34 227 "db_lock_hint": "Jeśli żaden inny proces pag nie działa, poczekaj chwilę i spróbuj ponownie.",
35 228 "db_locked": "Inna instancja pag jest uruchomiona.",
36 229 "deploy_cleanup_none": "Nie ma deploymentów do wyczyszczenia (minimum {}).",
37 230 "deploy_cleanup_ok": "Usunięto {} starych deploymentów.",
231 + "deploy_copy_failed": "Nie udało się skopiować deploymentu żadną metodą",
38 232 "deploy_rollback_fail": "Brak poprzedniego deploymentu.",
39 233 "deploy_rollback_ok": "Przełączono na deployment: {}",
40 234 "deployments_list": "Deploymenty ({}):",
235 + "done": "gotowe",
41 236 "download_fail": "błąd pobierania",
42 237 "downloaded": "Pobrano {} do cache ({:.2f} MB).",
43 238 "downloading": "Pobieranie",
@@ -62,16 +257,23 @@
62 257 "flatpak_removed": "Flatpak {} usunięty.",
63 258 "flatpak_scope": "Instalacja",
64 259 "flatpak_searching": "Szukam '{}' we Flathub...",
260 + "flatpak_searching_any": "Szukam we Flathub...",
65 261 "flatpak_updated": "Flapaki zaktualizowane.",
66 262 "flatpak_usage": "Użycie: pag flatpak <search|install|remove|list|update|info> [args]",
263 + "gpg_binary_not_found": "Nie znaleziono binarki GPG ({})",
67 264 "gpg_fail": "błąd weryfikacji GPG",
68 265 "gpg_missing": "BRAK GNUPG – zainstaluj gnupg i spróbuj ponownie",
266 + "gpg_timeout": "Operacja GPG przekroczyła limit czasu",
267 + "grub_fallback_label": "Pagan Linux – fallback (zwykły root)",
268 + "hardlink_method": "hardlinki",
69 269 "indexes_refreshed": "Indeksy odświeżone.",
70 270 "install_failed": "błąd instalacji",
71 271 "installed": "Zainstalowano {} pakietów.",
272 + "installed_marker": "zainstalowany",
72 273 "key_add_failed": "Import klucza nie powiódł się (błąd gpg) – klucz NIE został dodany.",
73 274 "key_imported": "Klucz zaimportowany pomyślnie.",
74 275 "key_removed": "Klucz usunięty: {}",
276 + "never": "nigdy",
75 277 "new": "NOWY",
76 278 "no_deployments": "Brak deploymentów.",
77 279 "no_history": "Brak historii transakcji.",
@@ -79,6 +281,8 @@
79 281 "no_keys": "Brak zaufanych kluczy GPG.",
80 282 "no_pinned": "Brak przypiętych pakietów.",
81 283 "no_tty": "Brak terminala (EOF) – anuluję.",
284 + "none_parenthesized": "(brak)",
285 + "none_value": "brak",
82 286 "not_found": "brak w repozytoriach",
83 287 "not_found_hint": "Sprawdź pisownię lub uruchom 'pag search <fraza>'.",
84 288 "not_pinned": "nie był przypięty.",
@@ -86,14 +290,18 @@
86 290 "orphans_found": "Osierocone zależności ({}): {}",
87 291 "pinned_list": "Przypięte pakiety ({}):",
88 292 "pinned_to": "przypięty do",
293 + "pkg_missing_data_tar": "brak data.tar.xz w pakiecie",
89 294 "pkg_not_found": "Nie znaleziono pakietu: {} (brak w repozytoriach)",
295 + "pkg_sha_mismatch": "niezgodność SHA256: {}",
90 296 "provides_conflict": "Wielu dostawców dla '{name}' ({providers}) – używam '{chosen}'",
91 297 "provides_mapped": "{} → {} (provides)",
92 298 "rdepends_none": "nic od niego nie zależy.",
93 299 "rdepends_title": "Odwrotne zależności {} ({}):",
300 + "reflink_method": "CoW (reflink)",
94 301 "removing": "Usuwanie",
95 302 "repo_added": "Dodano repozytorium: {}",
96 303 "repo_exists": "Repozytorium już istnieje: {}",
304 + "repo_index_invalid": "brak listy 'packages'",
97 305 "rollback_files": "Wycofano {} plików.",
98 306 "rollback_restored": "Przywrócono poprzedni stan z migawki.",
99 307 "root_required": "pag wymaga uprawnień root (sudo).",
@@ -134,15 +342,46 @@
134 342 "stats_packages": "Zainstalowane pakiety",
135 343 "stats_size": "Całkowity rozmiar",
136 344 "stats_title": "Statystyki PAG",
345 + "stats_top": "Największe 5:",
137 346 "to_install": "Do zainstalowania: {} pakietów ({:.2f} MB)",
138 347 "unpinned": "odpięty.",
139 348 "updated_done": "Odświeżanie zakończone. {} pakietów w cache.",
140 349 "updates_available": "⚠ jest {} pakietów do zaktualizowania – wpisz: pag update",
350 + "upgrade_marker": "[aktualizacja]",
141 351 "upgrading": "Aktualizacje: {} pakietów",
142 - "usage": "pag v4 – Pagan Linux Package Manager\n\nPODSTAWOWE:\n pag install <pkg>... Instalacja pakietów\n pag remove <pkg>... Usuwanie pakietów\n pag update Aktualizacja PAKIETÓW (odświeża indeksy)\n pag sync Odśwież indeksy + info o aktualizacjach\n pag upgrade Aktualizacja SYSTEMU (pakiety + kernel/initramfs/GRUB)\n pag list [--installed] Lista dostępnych / zainstalowanych\n pag search <query> Szukaj pakietów\n pag info <pkg> Szczegóły pakietu\n pag files <pkg> Lista plików pakietu\n pag verify [--deep] Weryfikacja integralności\n pag clean Wyczyść cache pobierania\n pag stats Statystyki systemu\n pag download <pkg>... Pobierz do cache (offline)\n\nROLLING (baza wypalona w obrazie):\n pag base [status] Pakiety z obrazu vs repo (czym pag zarządza)\n pag base adopt [pkg...] Adoptuj pakiety bazy z repo (--dry-run = podgląd)\n\nBEZPIECZEŃSTWO:\n pag key-add <url|file> Importuj klucz GPG\n pag key-list Lista zaufanych kluczy\n pag key-remove <id> Usuń klucz\n pag key-trust <repo> Przypnij fingerprint klucza repo (bez TOFU)\n pag key-untrust <repo> Zapomnij fingerprint repo (powrót do TOFU)\n pag key-trusted Lista przypiętych fingerprintów repo\n\nZAAWANSOWANE:\n pag why <pkg> Dlaczego pakiet jest zainstalowany\n pag autoremove Usuń osierocone zależności\n pag pin <pkg> [ver] Przypnij wersję pakietu\n pag unpin <pkg> Odepnij\n pag pinned Lista przypiętych\n pag history Historia transakcji\n pag rollback Cofnij ostatnią transakcję\n pag remove-orphans Usuń osierocone zależności\n pag repo-add <url> [nazwa] Dodaj repozytorium (drop-in w /etc/pag/repos/)\n pag repo-list Lista repozytoriów\n pag sbom export [fmt] Manifest SBOM (spdx|cyclonedx)\n\nFLATPAK:\n pag flatpak [<query>] Szukaj i instaluj\n pag flatpak search <q> Szukaj na Flathub\n pag flatpak install <id> Zainstaluj flatpak\n pag flatpak remove <id> Usuń flatpak\n pag flatpak list Lista zainstalowanych\n pag flatpak update Aktualizuj wszystkie\n pag flatpak info <id> Szczegóły flatpaka\n\nSNAPSHOTY (btrfs CoW):\n pag snapshot-list Lista snapshotów systemu\n pag snapshot-create [opis] Utwórz snapshot teraz\n pag snapshot-rollback [id] Uruchom snapshot przy następnym starcie (GRUB)\n pag snapshot-delete <id> Usuń snapshot\n\nIMMUTABLE OS (PAG_IMMUTABLE=1):\n pag deploy-list Lista wdrożeń\n pag deploy-rollback Przełącz na poprzednie wdrożenie\n pag deploy-cleanup [N] Usuń stare wdrożenia (zachowaj N, domyślnie 3)\n pag initramfs-update Przebuduj initramfs\n pag grub-update Regeneruj wpisy GRUB",
352 + "usage": "pag v3 – Pagan Linux Package Manager\n\nPODSTAWOWE:\n pag install <pkg>... Instalacja pakietów\n pag remove <pkg>... Usuwanie pakietów\n pag update Aktualizacja PAKIETÓW (odświeża indeksy)\n pag sync Odśwież indeksy + info o aktualizacjach\n pag upgrade Aktualizacja SYSTEMU (pakiety + kernel/initramfs/GRUB)\n pag list [--installed] Lista dostępnych / zainstalowanych\n pag search <query> Szukaj pakietów\n pag info <pkg> Szczegóły pakietu\n pag files <pkg> Lista plików pakietu\n pag verify [--deep] Weryfikacja integralności\n pag clean Wyczyść cache pobierania\n pag stats Statystyki systemu\n pag download <pkg>... Pobierz do cache (offline)\n\nROLLING (baza wypalona w obrazie):\n pag base [status] Pakiety z obrazu vs repo (czym pag zarządza)\n pag base adopt [pkg...] Adoptuj pakiety bazy z repo (--dry-run = podgląd)\n\nBEZPIECZEŃSTWO:\n pag key-add <url|file> Importuj klucz GPG\n pag key-list Lista zaufanych kluczy\n pag key-remove <id> Usuń klucz\n pag key-trust <repo> Przypnij fingerprint klucza repo (bez TOFU)\n pag key-untrust <repo> Zapomnij fingerprint repo (powrót do TOFU)\n pag key-trusted Lista przypiętych fingerprintów repo\n\nZAAWANSOWANE:\n pag why <pkg> Dlaczego pakiet jest zainstalowany\n pag rdepends <pkg> Które pakiety zależą od pakietu\n pag autoremove Usuń osierocone zależności\n pag pin <pkg> [ver] Przypnij wersję pakietu\n pag unpin <pkg> Odepnij\n pag pinned Lista przypiętych\n pag history Historia transakcji\n pag rollback Cofnij ostatnią transakcję\n pag repair [--dry-run] Napraw brakujące pliki pakietów (reinstalacja)\n pag remove-orphans Usuń osierocone zależności\n pag repo-add <url> [nazwa] Dodaj repozytorium (drop-in w /etc/pag/repos/)\n pag repo-list Lista repozytoriów\n pag sbom export [fmt] Manifest SBOM (spdx|cyclonedx)\n\nFLATPAK:\n pag flatpak [<query>] Szukaj i instaluj\n pag flatpak search <q> Szukaj na Flathub\n pag flatpak install <id> Zainstaluj flatpak\n pag flatpak remove <id> Usuń flatpak\n pag flatpak list Lista zainstalowanych\n pag flatpak update Aktualizuj wszystkie\n pag flatpak info <id> Szczegóły flatpaka\n\nSNAPSHOTY (btrfs CoW):\n pag snapshot-list Lista snapshotów systemu\n pag snapshot-create [opis] Utwórz snapshot teraz\n pag snapshot-rollback [id] Uruchom snapshot przy następnym starcie (GRUB)\n pag snapshot-delete <id> Usuń snapshot\n\nIMMUTABLE OS (PAG_IMMUTABLE=1):\n pag deploy-list Lista wdrożeń\n pag deploy-rollback Przełącz na poprzednie wdrożenie\n pag deploy-cleanup [N] Usuń stare wdrożenia (zachowaj N, domyślnie 3)\n pag initramfs-update Przebuduj initramfs\n pag grub-update Regeneruj wpisy GRUB",
143 353 "verify_errors": "Znaleziono {} problemów:",
354 + "verify_missing_file": " ❌ {}: brakuje {}",
144 355 "verify_ok": "Wszystkie {} plików sprawne.",
356 + "verify_sha_mismatch": " ❌ {}: niezgodność SHA256 {}",
145 357 "why_dependency": "zależność od",
146 358 "why_explicit": "zainstalowany jawnie",
147 - "why_not_installed": "niezainstalowany"
148 -}
359 + "why_not_installed": "niezainstalowany",
360 + "⏪ Restoring deployment: {arg1}": "⏪ Przywracanie deploymentu: {arg1}",
361 + "⏪ Rolling back: {arg1} ({arg2})": "⏪ Wycofywanie: {arg1} ({arg2})",
362 + "⚠ Repaired {arg1}/{arg2}. Failed: {arg3}": "⚠ Naprawiono {arg1}/{arg2}. Nie udalo sie: {arg3}",
363 + "✅ ({arg1} files)": "✅ ({arg1} plików)",
364 + "✅ All files are in place – nothing to repair.": "✅ Wszystkie pliki na miejscu – nic do naprawy.",
365 + "✅ GRUB updated.": "✅ GRUB zaktualizowany.",
366 + "✅ Initramfs updated.": "✅ Initramfs zaktualizowany.",
367 + "✅ No orphans.": "Brak osieroconych pakietów.",
368 + "✅ Repaired {arg1} packages.": "✅ Naprawiono {arg1} pakietow.",
369 + "❌ '{arg1}' not found.": "❌ Nie znaleziono '{arg1}'.",
370 + "❌ '{arg1}' not installed.": "❌ '{arg1}' nie jest zainstalowany.",
371 + "❌ Another pag update is in progress – try again later.": "❌ Inna aktualizacja pag jest w toku – spróbuj ponownie później.",
372 + "❌ Cannot continue – {arg1} missing dependencies.": "❌ Nie można kontynuować – {arg1} brakujących zależności.",
373 + "❌ Deployment {arg1} does not exist on disk": "❌ Deployment {arg1} nie istnieje na dysku",
374 + "❌ Download error: {arg1}": "❌ Błąd pobierania: {arg1}",
375 + "❌ Format: spdx | cyclonedx": "❌ Format: spdx | cyclonedx",
376 + "❌ Initramfs update failed.": "❌ Błąd aktualizacji initramfs.",
377 + "❌ No repositories configured.": "❌ Brak repozytoriów w konfiguracji.",
378 + "❌ No results for: {arg1}": "❌ Brak wyników dla: {arg1}",
379 + "❌ No snapshot to restore.": "❌ Brak snapshotu do przywrócenia.",
380 + "❌ Unknown command: '{arg1}'. Did you mean '{arg2}'?": "❌ Nieznana komenda: '{arg1}'. Czy chodziło o '{arg2}'?",
381 + "🏗️ Deployment: {arg1}": "🏗️ Deployment: {arg1}",
382 + "📋 Updating GRUB configuration...": "📋 Aktualizacja konfiguracji GRUB...",
383 + "🔄 Checking for pag update from {arg1}...": "🔄 Sprawdzam aktualizację pag z {arg1}...",
384 + "🔄 Refreshing indexes...": "🔄 Odświeżanie indeksów...",
385 + "🔐 Pinning repo key {arg1}...": "🔐 Przypinam klucz repo {arg1}...",
386 + "🔧 Packages with missing files: {arg1} (total {arg2} files)": "🔧 Pakiety z brakujacymi plikami: {arg1} (lacznie {arg2} plikow)"
387 +}