Commit 6a3d745
0
plików
+0
dodanych
-0
usuniętych
@@ -1,8614 +1,8614 @@
1 -#!/usr/bin/env python3
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 _fmt_size(n: float) -> str:
148 - """Rozmiar w czytelnych jednostkach (1.2 MB, 345.6 KB)."""
149 - for unit in ("B", "KB", "MB", "GB"):
150 - if n < 1024:
151 - return f"{n:.1f} {unit}"
152 - n /= 1024
153 - return f"{n:.1f} TB"
154 -
155 -
156 -def _fmt_eta(seconds: float) -> str:
157 - """Czas pozostały w zwięzłej formie: 8s, 1.4m, 2.1h."""
158 - if seconds < 60:
159 - return f"{seconds:.0f}s"
160 - if seconds < 3600:
161 - return f"{seconds / 60:.1f}m"
162 - return f"{seconds / 3600:.1f}h"
163 -
164 -
165 -def _shrink_text(text: str, room: int) -> str:
166 - """Skróć `text` do `room` kolumn (wielokropek na końcu)."""
167 - if room <= 0:
168 - return ""
169 - if len(text) <= room:
170 - return text
171 - return "…" if room == 1 else text[:room - 1] + "…"
172 -
173 -
174 -def _fit_widget_line(line: str, stream) -> str:
175 - """Przytnij linię panelu do szerokości terminala (bez zawijania).
176 -
177 - Zawinięta linia rozjeżdża wielolinijkowy panel: kolejne odświeżenia
178 - trafiają do nowych wierszy zamiast nadpisywać poprzednie.
179 - """
180 - cap = _term_width(stream) - _BAR_MARGIN
181 - if cap <= 0 or len(line) <= cap:
182 - return line
183 - keep = cap - 1
184 - head = (keep + 1) // 2
185 - tail = keep - head
186 - return line[:head] + "…" + (line[-tail:] if tail > 0 else "")
187 -
188 -
189 -def _drakkar_bar(pct: float, width: int, t: float, filled: int) -> str:
190 - """Drakkar (łódź wikingów) płynący po falującym morzu.
191 -
192 - - przed łodzią: falujące morze (~ _ przesuwane w czasie),
193 - - dziób łodzi: » (kolumna = bieżący postęp),
194 - - za łodzią: smuga z wędrującym refleksem światła.
195 - """
196 - done = pct >= 100.0
197 - wave = _WAVE_PHASES[int(t * 6) % len(_WAVE_PHASES)]
198 - ship = min(filled, width - 1)
199 - glow = int(t * 10) % ship if ship > 0 else -1
200 - out = []
201 - for i in range(width):
202 - if done:
203 - out.append("»" if i == width - 1 else "█") # łódź zacumowana
204 - elif i < ship:
205 - out.append("█" if i == glow else "▓")
206 - elif i == ship:
207 - out.append("»")
208 - else:
209 - out.append(wave[i & 1])
210 - return "".join(out)
211 -
212 -
213 -def _snake_bar(pct: float, width: int, t: float, filled: int) -> str:
214 - """Jörmungandr – wąż sunący przez pasek (głowa @, łuski o/~, ogon ·)."""
215 - done = pct >= 100.0
216 - head = min(filled, width - 1)
217 - out = []
218 - for i in range(width):
219 - if done:
220 - out.append("@" if i == width - 1 else "o")
221 - elif i < head:
222 - out.append("o" if (i + int(t * 6)) & 1 else "~")
223 - elif i == head:
224 - out.append("@")
225 - else:
226 - out.append("·")
227 - return "".join(out)
228 -
229 -
230 -def _pagan_bar(pct: float, width: int = 30, t: float = 0.0,
231 - style: Optional[str] = None, animated: bool = True) -> str:
232 - """Zwraca jednoliniowy pasek postępu o STAŁEJ szerokości `width`.
233 -
234 - `pct` – postęp 0..100
235 - `t` – czas (s); różne `t` → inna klatka animacji
236 - `animated` – False wymusza klasyczny statyczny pasek (np. brak TTY)
237 - """
238 - width = max(6, int(width))
239 - pct = max(0.0, min(100.0, float(pct)))
240 - style = style or _PAGAN_STYLE
241 - if not animated or not _PAGAN_ANIM or style == "classic":
242 - return _classic_bar(pct, width)
243 - filled = int(round(width * pct / 100.0))
244 - if style == "snake":
245 - return _snake_bar(pct, width, t, filled)
246 - return _drakkar_bar(pct, width, t, filled)
247 -
248 -
249 -class _Bar:
250 - """Baza animowanych pasków: rysują JEDNĄ nadpisywaną linię na `stream`.
251 -
252 - Gdy mamy TTY, wątek w tle odświeża pasek ~10×/s, dzięki czemu morze faluje
253 - także wtedy, gdy postęp chwilowo się nie zmienia.
254 - """
255 - def __init__(self, width: int, stream=None):
256 - self.width = width
257 - self.stream = stream if stream is not None else sys.stderr
258 - self.tty = self.stream.isatty()
259 - self._lock = threading.RLock()
260 - self._last_len = 0
261 - self._stop = threading.Event()
262 - self._thread = None
263 -
264 - # -- wątek animacji -------------------------------------------------------
265 - def _start_anim(self):
266 - if _PAGAN_ANIM and self.tty and self._thread is None:
267 - self._thread = threading.Thread(target=self._anim_loop, daemon=True)
268 - self._thread.start()
269 -
270 - def _anim_loop(self):
271 - while not self._stop.wait(0.1):
272 - with self._lock:
273 - if self._stop.is_set():
274 - break
275 - self._write(self._line())
276 -
277 - def _stop_anim(self):
278 - self._stop.set()
279 - if self._thread is not None:
280 - self._thread.join(timeout=0.3)
281 - self._thread = None
282 -
283 - # -- rysowanie ------------------------------------------------------------
284 - def _cap(self) -> int:
285 - """Maksymalna liczba kolumn jednej linii paska (z zapasem na wrap)."""
286 - return _term_width(self.stream) - _BAR_MARGIN
287 -
288 - def _shrink(self, text: str, fixed: int) -> str:
289 - """Skróć `text` tak, by `text` + `fixed` kolumn zmieściło się w linii."""
290 - room = self._cap() - fixed
291 - if room >= 1 and len(text) > room:
292 - return "…" if room == 1 else text[:room - 1] + "…"
293 - return text
294 -
295 - def _fit(self, line: str) -> str:
296 - """Ostatnia linia obrony: przytnij linię do szerokości terminala.
297 -
298 - Wycinamy ŚRODEK (wielokropek), więc widoczne zostają początek (nazwa)
299 - i koniec (%, prędkość, ETA). Bez tego zawinięta linia = nowa linia przy
300 - każdym odświeżeniu zamiast nadpisywania poprzedniej.
301 - """
302 - cap = self._cap()
303 - if cap <= 0 or len(line) <= cap:
304 - return line
305 - keep = cap - 1 # miejsce na wielokropek „…”
306 - head = (keep + 1) // 2
307 - tail = keep - head
308 - return line[:head] + "…" + (line[-tail:] if tail > 0 else "")
309 -
310 - def _write(self, line: str):
311 - line = self._fit(line)
312 - clear = " " * max(0, self._last_len - len(line))
313 - with _DRAW_LOCK:
314 - self.stream.write(f"\r{line}{clear}")
315 - self.stream.flush()
316 - self._last_len = len(line)
317 -
318 - def _line(self) -> str:
319 - raise NotImplementedError
320 -
321 - def _clear_line(self):
322 - if self.tty and self._last_len:
323 - with _DRAW_LOCK:
324 - self.stream.write("\r" + " " * self._last_len + "\r")
325 - self.stream.flush()
326 - self._last_len = 0
327 -
328 - def _newline(self):
329 - if self.tty and self._last_len:
330 - self.stream.write("\n")
331 - self.stream.flush()
332 - self._last_len = 0
333 -
334 -
335 -class ProgressBar(_Bar):
336 - """Pasek postępu dla N elementów — animowany („drakkar”) na TTY."""
337 - def __init__(self, total: int, desc: str = "", unit: str = "", width: int = 30):
338 - super().__init__(width)
339 - self.total = max(total, 1)
340 - self.desc = desc
341 - self.unit = unit
342 - self.n = 0
343 - self.suffix = ""
344 - self.start = time.time()
345 - self._start_anim()
346 -
347 - def _line(self) -> str:
348 - pct = self.n / self.total * 100
349 - elapsed = time.time() - self.start
350 - speed = self.n / elapsed if elapsed > 0 else 0
351 - if self.n >= self.total:
352 - eta_str = _("done")
353 - elif speed > 0:
354 - eta_str = _fmt_eta((self.total - self.n) / speed)
355 - else:
356 - eta_str = "?..."
357 - bar = _pagan_bar(pct, self.width, time.time(), animated=self.tty)
358 - tail = f" [{bar}] {self.n}/{self.total} ({pct:.0f}%) ETA {eta_str}{self.suffix}"
359 - desc = self._shrink(self.desc, 2 + len(tail))
360 - return f" {desc}{tail}"
361 -
362 - def update(self, n: Optional[int] = None, suffix: str = ""):
363 - with self._lock:
364 - if n is not None:
365 - self.n = n
366 - else:
367 - self.n += 1
368 - self.suffix = suffix
369 - if self.tty:
370 - self._write(self._line())
371 - elif (self.n == 1 or self.n >= self.total
372 - or self.n % max(1, self.total // 10) == 0):
373 - # Bez TTY – tylko kamienie milowe (czysty log)
374 - print(self._line(), file=self.stream)
375 -
376 - def close(self):
377 - self._stop_anim()
378 - with self._lock:
379 - self._newline()
380 -
381 - def __enter__(self):
382 - return self
383 -
384 - def __exit__(self, *args):
385 - self.close()
386 -
387 -
388 -class DownloadBar(_Bar):
389 - """Animowany pasek pobierania (na podstawie Content-Length)."""
390 - def __init__(self, filename: str, total_bytes: int):
391 - super().__init__(25)
392 - self.filename = filename
393 - self.total = total_bytes
394 - self.downloaded = 0
395 - self.start = time.time()
396 - self._start_anim()
397 -
398 - def _line(self) -> str:
399 - pct = self.downloaded / self.total * 100 if self.total > 0 else 0.0
400 - elapsed = time.time() - self.start
401 - speed = self.downloaded / elapsed if elapsed > 0 else 0
402 - if self.total > 0 and speed > 0:
403 - eta_str = _fmt_eta((self.total - self.downloaded) / speed)
404 - else:
405 - eta_str = "?..."
406 - bar = _pagan_bar(pct, self.width, time.time(), animated=self.tty)
407 - sz = _fmt_size(self.total)
408 - spd = _fmt_size(int(speed))
409 - tail = f" [{bar}] {pct:.0f}% {sz} {spd}/s ETA {eta_str}"
410 - # Nazwa pliku bywa długa (np. linux-firmware-…-1.pag) i wtedy CAŁA linia
411 - # nie mieści się w terminalu (zawijanie → nowa linia przy każdym %).
412 - # Skracamy WYŁĄCZNIE nazwę – pełny pasek, prędkość i ETA zostają.
413 - name = self._shrink(self.filename, 4 + len(tail)) # prefiks „ ↓ ” = 4 kolumny
414 - return f" ↓ {name}{tail}"
415 -
416 - def update(self, chunk_size: int):
417 - with self._lock:
418 - self.downloaded += chunk_size
419 - if self.tty and self.total > 0:
420 - self._write(self._line())
421 -
422 - def close(self):
423 - self._stop_anim()
424 - with self._lock:
425 - if self.total > 0:
426 - self._newline()
427 -
428 -
429 -class _ParallelDownloadDisplay:
430 - """Panel pobierania równoległego: pasek zbiorczy + linia na każde pobranie.
431 -
432 - Linia pobrania pokazuje procent, a w nawiasie nazwę pakietu, liczbę
433 - pobranych bajtów i ETA – czyli dokładnie to, czego brakowało przy
434 - równoległym pobieraniu:
435 -
436 - ⏬ [████»~~~~] 4/12 (33%)
437 - ↓ [███»~~~~~~] 38% (mesa: 12.3/29.1 MB, ETA 8s)
438 - ↓ [█████»~~~~] 67% (glibc: 8.8/10.0 MB, ETA 3s)
439 -
440 - Na TTY panel jest rysowany „w miejscu” (ANSI): pasek zbiorczy i aktywne
441 - pobrania są nadpisywane, a ukończone pobrania zostają wypisane na stałe
442 - nad panelem. Poza TTY nie ruszamy kursora – log dostaje linię startu,
443 - kamienie milowe (25/50/75%) i wynik, więc pozostaje czytelny.
444 - """
445 - BAR_W = 20
446 - _POLL = 0.1
447 -
448 - def __init__(self, total: int, stream=None):
449 - self.stream = stream if stream is not None else sys.stderr
450 - self.tty = self.stream.isatty()
451 - self.total = max(1, int(total))
452 - self.completed = 0
453 - self._lock = threading.RLock()
454 - self._slots: Dict[int, dict] = {}
455 - self._next_id = 0
456 - self._drawn = 0
457 - self._stop = threading.Event()
458 - self._thread = None
459 - self._cursor_hidden = False
460 - if self.tty:
461 - self._emit("\x1b[?25l") # ukryj kursor na czas panelu
462 - self._cursor_hidden = True
463 - self._thread = threading.Thread(target=self._anim_loop, daemon=True)
464 - self._thread.start()
465 -
466 - # -- rysowanie -----------------------------------------------------------
467 - def _emit(self, text: str):
468 - with _DRAW_LOCK:
469 - self.stream.write(text)
470 - self.stream.flush()
471 -
472 - def _cap(self) -> int:
473 - return _term_width(self.stream) - _BAR_MARGIN
474 -
475 - def _clear_panel(self):
476 - """Wyczyść panel i ustaw kursor na początku jego pierwszej linii."""
477 - if not self.tty or self._drawn <= 0:
478 - return
479 - out = ["\r\x1b[2K"]
480 - out.extend("\x1b[1A\r\x1b[2K" for _ in range(self._drawn - 1))
481 - self._emit("".join(out))
482 - self._drawn = 0
483 -
484 - def _render_locked(self):
485 - if not self.tty:
486 - return
487 - self._clear_panel()
488 - lines = [self._overall_line()]
489 - lines.extend(self._slot_line(s) for s in self._slots.values())
490 - self._emit("\n".join(lines))
491 - self._drawn = len(lines)
492 -
493 - def _render(self):
494 - with self._lock:
495 - self._render_locked()
496 -
497 - def _anim_loop(self):
498 - while not self._stop.wait(self._POLL):
499 - self._render()
500 -
501 - def _overall_line(self) -> str:
502 - pct = self.completed / self.total * 100.0
503 - bar = _pagan_bar(pct, self.BAR_W, time.time(), animated=self.tty)
504 - line = f" ⏬ [{bar}] {self.completed}/{self.total} ({pct:.0f}%)"
505 - return _fit_widget_line(line, self.stream)
506 -
507 - def _slot_line(self, s: dict) -> str:
508 - total = int(s.get("total") or 0)
509 - done = int(s.get("downloaded") or 0)
510 - pct = (done / total * 100.0) if total > 0 else 0.0
511 - elapsed = time.time() - s["start"]
512 - speed = done / elapsed if elapsed > 0 else 0.0
513 - finished = total > 0 and done >= total
514 - if finished:
515 - eta = _("done")
516 - elif total > 0 and speed > 0:
517 - eta = _fmt_eta((total - done) / speed)
518 - else:
519 - eta = "?…"
520 - bar = _pagan_bar(pct, self.BAR_W, time.time(), animated=self.tty)
521 - prefix = f" ↓ [{bar}] {pct:3.0f}% "
522 - size = (f"{_fmt_size(done)}/{_fmt_size(total)}" if total > 0
523 - else _fmt_size(done))
524 - suffix = (f": {size}, {eta})" if finished
525 - else f": {size}, ETA {eta})")
526 - # Nazwa bywa długa – skracamy TYLKO ją, zostawiając %, rozmiar i ETA.
527 - room = self._cap() - len(prefix) - 1 - len(suffix)
528 - name = _shrink_text(s["name"], room)
529 - return _fit_widget_line(f"{prefix}({name}{suffix}", self.stream)
530 -
531 - # -- API wątków pobierających --------------------------------------------
532 - def start(self, name: str, expected_size: int = 0) -> int:
533 - with self._lock:
534 - sid = self._next_id
535 - self._next_id += 1
536 - self._slots[sid] = {
537 - "name": name,
538 - "downloaded": 0,
539 - "total": int(expected_size or 0),
540 - "start": time.time(),
541 - "milestone": -1,
542 - }
543 - if self.tty:
544 - self._render_locked()
545 - else:
546 - self._emit(f" ↓ {name}\n")
547 - return sid
548 -
549 - def progress(self, sid: int, downloaded: int, total: int = 0):
550 - with self._lock:
551 - s = self._slots.get(sid)
552 - if s is None:
553 - return
554 - s["downloaded"] = int(downloaded)
555 - if total and total > 0:
556 - s["total"] = int(total)
557 - if self.tty:
558 - return # odświeży wątek animacji
559 - total = s["total"]
560 - pct = downloaded / total * 100.0 if total > 0 else 0.0
561 - step = int(pct // 25) * 25
562 - if step > s["milestone"]:
563 - s["milestone"] = step
564 - if total > 0:
565 - detail = f"{_fmt_size(downloaded)}/{_fmt_size(total)}"
566 - else:
567 - detail = _fmt_size(downloaded)
568 - self._emit(f" ↓ {s['name']}: {pct:.0f}% ({detail})\n")
569 -
570 - def finish(self, sid: int, ok: bool = True):
571 - with self._lock:
572 - s = self._slots.pop(sid, None)
573 - if s is None:
574 - return
575 - self.completed += 1
576 - line = self._done_line(s, ok)
577 - if self.tty:
578 - self._clear_panel()
579 - self._emit(line + "\n")
580 - self._render_locked()
581 - else:
582 - self._emit(line + "\n")
583 -
584 - def log(self, text: str):
585 - """Wypisz komunikat (np. ponowienie pobierania) bez psucia panelu."""
586 - with self._lock:
587 - if self.tty:
588 - self._clear_panel()
589 - self._emit(text + "\n")
590 - self._render_locked()
591 - else:
592 - self._emit(text + "\n")
593 -
594 - def _done_line(self, s: dict, ok: bool) -> str:
595 - if not ok:
596 - return f" ❌ {s['name']}: {_('download_fail')}"
597 - total = int(s.get("total") or 0)
598 - size = _fmt_size(total if total > 0 else s.get("downloaded", 0))
599 - elapsed = _fmt_eta(time.time() - s["start"])
600 - return _fit_widget_line(f" ✅ {s['name']} ({size}, {elapsed})",
601 - self.stream)
602 -
603 - def close(self):
604 - self._stop.set()
605 - if self._thread is not None:
606 - self._thread.join(timeout=0.3)
607 - self._thread = None
608 - with self._lock:
609 - if self.tty:
610 - self._clear_panel()
611 - if self._cursor_hidden:
612 - self._emit("\x1b[?25h") # przywróć kursor
613 - self._cursor_hidden = False
614 -
615 -
616 -class _StepBar(_Bar):
617 - """Animowany pasek dla pętli „krok po kroku” (instalacja/aktualizacja).
618 -
619 - Pasek nie skacze skokowo co pakiet – między krokami łagodnie „dopełza”
620 - w stronę kolejnego progu (jak w instalatorach), więc rośnie w sposób
621 - ciągły. Wątek animacji odświeża go ~10×/s.
622 - """
623 - def __init__(self, total: int, icon: str = "", width: int = 25,
624 - creep_tau: float = 3.0):
625 - super().__init__(width)
626 - self.total = max(total, 1)
627 - self.icon = icon
628 - self.creep_tau = creep_tau # „stała czasu” dopełzania (s)
629 - self.idx = 0
630 - self.label = ""
631 - self.t0 = time.time()
632 - self._step_t = time.time() # start bieżącego pakietu
633 - self._start_anim()
634 -
635 - def _frac(self) -> float:
636 - """Ukończona część [0..1]: kroki + wygładzone dopełzanie w bieżącym."""
637 - done = max(0, self.idx - 1)
638 - if done >= self.total:
639 - return 1.0
640 - # 0.5 ** (dt/tau): 0 → ~1 asymptotycznie; cap 0.9, by krok był widoczny
641 - creep = 1.0 - 0.5 ** ((time.time() - self._step_t) / self.creep_tau)
642 - return (done + min(creep, 0.9)) / self.total
643 -
644 - def _line(self) -> str:
645 - pct = self._frac() * 100.0
646 - eta_s = ""
647 - if self.idx > 1:
648 - avg = (time.time() - self.t0) / (self.idx - 1)
649 - rem = avg * (self.total - self.idx + 1)
650 - eta_s = f" ~{rem:.0f}s" if rem < 60 else f" ~{rem/60:.1f}m"
651 - bar = _pagan_bar(pct, self.width, time.time(), animated=self.tty)
652 - tail = f"[{bar}] {self.idx}/{self.total} ({pct:.0f}%) "
653 - label = self._shrink(self.label, 2 + len(self.icon) + len(tail) + len(eta_s))
654 - return f" {self.icon}{tail}{label}{eta_s}"
655 -
656 - def step(self, idx: int, label: str):
657 - with self._lock:
658 - self.idx = idx
659 - self.label = label
660 - self._step_t = time.time()
661 - if self.tty:
662 - self._write(self._line())
663 - else:
664 - print(self._line(), file=self.stream)
665 -
666 - def end(self):
667 - self._stop_anim()
668 - with self._lock:
669 - self._clear_line()
670 -
671 -# =============================================================================
672 -# GPG – BEZPIECZNE WYWOŁYWANIE (odporne na brak binarki gpg)
673 -# =============================================================================
674 -
675 -GPG_BINARY = shutil.which("gpg2") or shutil.which("gpg") or "gpg"
676 -GPG_HOME = "/etc/pag/gpg" # izolowany keyring (działa z keyboxd GPG 2.4+)
677 -
678 -def _ssl_ok() -> bool:
679 - """Czy Python ma działający moduł ssl (HTTPS w urllib).
680 -
681 - Bez niego urllib nie zna schematu https i każda operacja sieciowa kończy
682 - się „unknown url type: https” – myląco, bo wygląda jak błąd adresu.
683 - """
684 - try:
685 - import ssl # noqa: F401
686 - return True
687 - except Exception:
688 - return False
689 -
690 -
691 -def _gpg_run(*args, timeout: int = 30, **kwargs) -> subprocess.CompletedProcess:
692 - """
693 - Bezpieczne wywołanie GPG – przechwytuje FileNotFoundError,
694 - gdyby gpg/gpg2 nie było zainstalowane w minimalnym środowisku.
695 - Wymusza LC_ALL=C aby komunikaty GPG były zawsze po angielsku
696 - (niezależnie od locale systemu) – kluczowe dla parsowania stderr.
697 - """
698 - env = kwargs.pop("env", None) or os.environ.copy()
699 - env["LC_ALL"] = "C"
700 - env["GNUPGHOME"] = GPG_HOME
701 - _text = bool(kwargs.get("text") or kwargs.get("universal_newlines"))
702 - try:
703 - return subprocess.run([GPG_BINARY, *args], timeout=timeout, env=env, **kwargs)
704 - except FileNotFoundError:
705 - # GPG nie jest dostępne – zwróć błąd z komunikatem
706 - # (szanuj text=True – inaczej caller dostaje bytes i może wybuchnąć TypeError)
707 - _text = bool(kwargs.get("text") or kwargs.get("universal_newlines"))
708 - _msg = _("gpg_binary_not_found", GPG_BINARY)
709 - return subprocess.CompletedProcess(
710 - [GPG_BINARY, *args], 127,
711 - stdout=("" if _text else b""),
712 - stderr=(_msg if _text else _msg.encode()),
713 - )
714 - except subprocess.TimeoutExpired:
715 - _msg = _("gpg_timeout")
716 - return subprocess.CompletedProcess(
717 - [GPG_BINARY, *args], 124,
718 - stdout=("" if _text else b""),
719 - stderr=(_msg if _text else _msg.encode())
720 - )
721 -
722 -def _load_trust_db() -> dict:
723 - """Mapa repo_url → fingerprint klucza podpisującego (baza zaufania)."""
724 - try:
725 - with open(TRUST_DB) as f:
726 - return json.load(f)
727 - except (FileNotFoundError, json.JSONDecodeError):
728 - return {}
729 -
730 -
731 -def _save_trust_db(db: dict):
732 - os.makedirs(os.path.dirname(TRUST_DB), exist_ok=True)
733 - with open(TRUST_DB, "w") as f:
734 - json.dump(db, f, indent=2)
735 -
736 -
737 -def _gpg_verify_fp(sig_path: str, data_path: str, timeout: int = 30):
738 - """Weryfikuje podpis i odczytuje fingerprint podpisującego.
739 -
740 - Używa --status-fd=1 i linii VALIDSIG <fingerprint>. Zwraca (ok, fingerprint).
741 -
742 - FAIL-CLOSED: OK tylko gdy GPG zwrócił 0 ORAZ w statusie maszynowym jest
743 - linia VALIDSIG. Nie zakładamy sukcesu na podstawie samego kodu wyjścia –
744 - gdyby format --status-fd się zmienił, wolimy odrzucić podpis niż przyjąć
745 - niezaufany pakiet (wywołujący traktuje fp=None jako brak potwierdzenia).
746 - """
747 - env = os.environ.copy()
748 - res = _gpg_run("--verify", "--status-fd", "1", sig_path, data_path,
749 - capture_output=True, text=True, timeout=timeout, env=env)
750 - out = res.stdout or ""
751 - m = re.search(r"\[GNUPG:\]\s+VALIDSIG\s+([0-9A-Fa-f]{16,})", out)
752 - if not m:
753 - m = re.search(r"\bVALIDSIG\s+([0-9A-Fa-f]{16,})", out)
754 - if res.returncode != 0 or not m:
755 - return False, None
756 - return True, m.group(1).upper()
757 -
758 -
759 -def _verify_local_pkg_signature(pkg_path: str) -> bool:
760 - """Weryfikuje lokalny .pag tym samym kluczem co zaufane repo."""
761 - # PAG_INSECURE=1 – spójnie z _verify_repo_sig() i _verify_pkg_signature().
762 - # Potrzebne w środowisku BUILDA: instalator buduje własne .pag (np. `kernel`)
763 - # lokalnie, nie ma dla nich pliku .asc, a klucza prywatnego repo celowo NIE ma
764 - # na maszynie budującej. Wcześniej ta funkcja jako jedyna ignorowała
765 - # PAG_INSECURE, więc obejście używane przez resztę builda tu nie działało.
766 - if os.environ.get("PAG_INSECURE", "") == "1":
767 - print(_(' ⚠ PAG_INSECURE=1 – skipping local package signature verification'))
768 - return True
769 - sig_path = next((pkg_path + ext for ext in (".asc", ".sig")
770 - if os.path.isfile(pkg_path + ext)), "")
771 - if not sig_path:
772 - print(_(' ❌ No signature for package: {arg1}', arg1=(pkg_path)))
773 - print(_(' A .pag.asc/.pag.sig file from the same source is required.'))
774 - return False
775 - ok, fingerprint = _gpg_verify_fp(sig_path, pkg_path)
776 - if not ok or not fingerprint:
777 - print(_(' ❌ Invalid package signature: {arg1}', arg1=(pkg_path)))
778 - return False
779 - expected = _repo_pinned_fp(DEFAULT_REPOS[0])
780 - if not expected:
781 - print(_(' ❌ No pinned repo key for the local package.'))
782 - print(_(' Run first: sudo pag sync'))
783 - return False
784 - if fingerprint != expected.upper():
785 - print(_(' ❌ [SECURITY ERROR] Package was signed with a different repo key.'))
786 - print(_(' Expected: {arg1}', arg1=(expected)))
787 - print(_(' Received: {arg1}', arg1=(fingerprint)))
788 - return False
789 - print(_(' 🔐 Package signature OK ({arg1})', arg1=(fingerprint)))
790 - return True
791 -
792 -
793 -# =============================================================================
794 -# i18n – WIELOJĘZYCZNOŚĆ
795 -# =============================================================================
796 -
797 -LANG = os.environ.get("LANG", "en_US.UTF-8")[:2] # pl, en, de...
798 -COLOR = os.environ.get("NO_COLOR", "") == "" and sys.stdout.isatty()
799 -
800 -def _c(code: str, text: str) -> str:
801 - """Dodaje kody ANSI jeśli kolor jest włączony."""
802 - if not COLOR:
803 - return text
804 - colors = {
805 - "green": "\033[32m", "red": "\033[31m", "yellow": "\033[33m",
806 - "cyan": "\033[36m", "bold": "\033[1m", "dim": "\033[2m",
807 - "reset": "\033[0m",
808 - }
809 - return f"{colors.get(code,'')}{text}{colors['reset']}"
810 -
811 -T = {
812 - "en": {
813 - "root_required": "pag requires root privileges (sudo).",
814 - "db_locked": "Another pag instance is running.",
815 - "db_lock_hint": "If no other pag process is running, wait a moment and retry.",
816 - "no_index": "Cannot fetch repository indexes. Run 'pag update'.",
817 - "cache_ro": "Repo cache is read-only ({cache}) – using local index (may be outdated).\n Refresh as root: sudo pag sync",
818 - "all_installed": "All packages are already installed.",
819 - "to_install": "To install: {} packages ({:.2f} MB)",
820 - "new": "NEW",
821 - "continue_q": "Continue? [Y/n] ",
822 - "no_tty": "No TTY / stdin closed (EOF) – cancelling.",
823 - "cancelled": "Cancelled.",
824 - "not_found": "not found in repos",
825 - "pkg_not_found": "Package not found: {} (not in any repo)",
826 - "not_found_hint": "Check the spelling or run 'pag search <query>'.",
827 - "downloading": "Downloading",
828 - "done": "done",
829 - "wroom_terminal": "PAG WROOM needs an interactive terminal – run: pag wroom",
830 - "wroom_too_small": "Enlarge the terminal (min. {arg1}x{arg2})",
831 - "wroom_tagline": "PAGAN RACING 4.2.0 · 38911 BYTES FREE",
832 - "wroom_controls": "←/→ lane ↑/↓ gas/brake P pause Q quit",
833 - "wroom_press": "PRESS SPACE TO RACE",
834 - "wroom_over": "RACE OVER",
835 - "wroom_score": "Score: {arg1}",
836 - "wroom_best": "Best: {arg1}",
837 - "wroom_restart": "R / SPACE – race again Q – quit",
838 - "wroom_paused": "PAUSED",
839 - "wroom_hud": "SCORE {arg1:06d} SPEED {arg2:3d} km/h LIVES {arg3}",
840 - "download_fail": "download failed",
841 - "gpg_fail": "GPG verification failed",
842 - "sha256_mismatch": "SHA256 mismatch",
843 - "install_failed": "installation failed",
844 - "installed": "Installed {} packages.",
845 - "rollback_restored": "Restored previous state from snapshot.",
846 - "rollback_files": "Rolled back {} files.",
847 - "no_history": "No transaction history.",
848 - "pinned_list": "Pinned packages ({}):",
849 - "no_pinned": "No pinned packages.",
850 - "pinned_to": "pinned to",
851 - "unpinned": "unpinned.",
852 - "not_pinned": "was not pinned.",
853 - "repo_added": "Added repository: {}",
854 - "repo_exists": "Repository already exists: {}",
855 - "updated_done": "Index refresh complete. {} packages cached.",
856 - "indexes_refreshed": "Indexes refreshed.",
857 - "updates_available": "⚠ {} packages have updates – run: pag update",
858 - "upgrading": "Upgrading: {} packages",
859 - "all_up_to_date": "All packages are up to date.",
860 - "removing": "Removing",
861 - "orphans_found": "Orphaned dependencies ({}): {}",
862 - "flatpak_missing": "Flatpak is not installed.",
863 - "flatpak_adding": "Adding Flathub remote...",
864 - "flatpak_searching": "Searching Flathub for '{}'...",
865 - "flatpak_found": "Found {} results:",
866 - "flatpak_not_found": "not found on Flathub",
867 - "flatpak_install_prompt": "Install {}? [Y/n] ",
868 - "flatpak_installing": "Installing {}...",
869 - "flatpak_installed": "Flatpak {} installed.",
870 - "flatpak_removed": "Flatpak {} removed.",
871 - "flatpak_not_installed": "Flatpak {} is not installed.",
872 - "flatpak_info_id": "ID",
873 - "flatpak_info_version": "Version",
874 - "flatpak_info_branch": "Branch",
875 - "flatpak_info_origin": "Origin",
876 - "flatpak_info_size": "Installed size",
877 - "flatpak_info_desc": "Description",
878 - "flatpak_updated": "Flatpaks updated.",
879 - "flatpak_usage": "Usage: pag flatpak <search|install|remove|list|update|info> [args]",
880 - "flatpak_scope": "Installation",
881 - "flatpak_menu_hint": "Installed and verified, but this session may not show it in the menu: Flatpak exports are missing from XDG_DATA_DIRS.",
882 - "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.",
883 - "key_imported": "Key imported successfully.",
884 - "key_removed": "Key removed: {}",
885 - "no_keys": "No trusted GPG keys.",
886 - "gpg_missing": "GNUPG MISSING – install gnupg and retry",
887 - "ssl_broken": "Python has no working ssl module (HTTPS impossible) – fix the python/openssl packages (e.g. sudo pag install -f python).",
888 - "key_add_failed": "Key import failed (gpg error) – key was NOT added.",
889 - "verify_ok": "All {} files intact.",
890 - "verify_errors": "{} problems found:",
891 - "cache_cleared": "{} files ({:.2f} MB) cleared from cache.",
892 - "deployments_list": "Deployments ({}):",
893 - "no_deployments": "No deployments.",
894 - "active_deployment": "ACTIVE",
895 - "deploy_rollback_ok": "Switched to deployment: {}",
896 - "deploy_rollback_fail": "No previous deployment.",
897 - "deploy_cleanup_ok": "Removed {} old deployments.",
898 - "deploy_cleanup_none": "No deployments to clean (minimum {}).",
899 - "snapshot_none": "No system snapshots.",
900 - "snapshot_list": "System snapshots ({}):",
901 - "snapshot_created": "Snapshot created: {}.",
902 - "snapshot_deleted": "Snapshot removed: {}.",
903 - "snapshot_not_found": "Snapshot not found: {}",
904 - "snapshot_unsupported": "Snapshots unavailable: {}",
905 - "snapshot_rollback_next": "Next boot set to snapshot: {}",
906 - "snapshot_rollback_hint": "Select this entry in the GRUB menu: {}",
907 - "staging_prepare": "Preparing {} packages in staging (system unchanged)...",
908 - "staging_failed": "Staging failed – the system was NOT modified.",
909 - "staging_commit": "All packages prepared – applying changes...",
910 - "grub_refreshed": "GRUB menu refreshed.",
911 - "grub_failed": "GRUB: {}",
912 - "grub_no_initrd": "GRUB: boot entry has no initramfs – check /boot/initramfs-*.img",
913 - "crlf_fixed": "{}: CRLF removed (it broke grub-mkconfig).",
914 - "initramfs_links_fixed": "initramfs symlinks repaired.",
915 - "no_user_sessions": "no active user sessions – user units load at next login.",
916 - "dry_run_done": "Dry run – nothing was changed.",
917 - "dry_run_plan": "Dry run – transaction plan (no changes):",
918 - "why_explicit": "explicitly installed",
919 - "why_dependency": "dependency of",
920 - "why_not_installed": "not installed",
921 - "rdepends_title": "Reverse dependencies of {} ({}):",
922 - "rdepends_none": "nothing depends on it.",
923 - "optional_deps": "Optional dependencies (not installed automatically):",
924 - "autoremove_ok": "Removed {} orphaned packages.",
925 - "autoremove_none": "No orphaned packages.",
926 - "downloaded": "Downloaded {} to cache ({:.2f} MB).",
927 - "provides_mapped": "{} → {} (provides)",
928 - "stats_title": "PAG Statistics",
929 - "stats_packages": "Installed packages",
930 - "stats_files": "Tracked files",
931 - "stats_size": "Total size",
932 - "stats_cache": "Cache size",
933 - "stats_history": "Transactions",
934 - "stats_last_update": "Last update",
935 - # Komunikaty bezpieczeństwa (baza EN; PL w tabeli "pl" jako sec_*_pl)
936 - "sec_downgrade": "Downgrade blocked: {pkg} {new} < {old}",
937 - "sec_suid": "SUID stripped from {path}",
938 - "sec_https": "HTTPS required for repos",
939 - "sec_badname": "Invalid package name: {name}",
940 - "sec_toobig": "Package too large: {size_mb}MB > {max_mb}MB",
941 - "sec_conflict": "File conflict: {path} owned by {owner}",
942 - "sec_audit": "{pkg} installed by {user}",
943 - "sec_locked": "Another pag process is running",
944 - # Konfiguracja (/etc) – zachowanie zmian użytkownika
945 - "conf_pacnew": "Modified config kept; new version saved as {path}",
946 - "conf_pacsave": "Modified config kept as {path}",
947 - # Zależności wirtualne (provides)
948 - "provides_conflict": "Multiple providers for '{name}' ({providers}) – using '{chosen}'",
949 -
950 - # Base baked into the ISO image (pag base / base adopt)
951 - "base_title": "Base from the ISO image",
952 - "base_no_manifest": "This system carries no base manifest (/usr/share/pag/base.json) – nothing to adopt.",
953 - "base_iso_version": "Image version",
954 - "base_total": "Base packages (from image)",
955 - "base_tracked": "Managed by pag",
956 - "base_adoptable": "Adoptable from repo",
957 - "base_unmatched": "No counterpart in repo",
958 - "base_adopt_hint": "Adopt them (image files get replaced by repo packages): sudo pag base adopt",
959 - "base_unmatched_hint": "These stay at the image version (no such package in repo):",
960 - "base_more": "more",
961 - "base_nothing_selected": "None of the given names is on the adopt list.",
962 - "base_all_managed": "Every base package is already managed by pag.",
963 - "base_adopt_plan": "Adopting {} base packages from the repo (~{:.0f} MB):",
964 - "base_dry_run": "Dry run – nothing was installed.",
965 - "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).",
966 - "base_overwrite": "{} comes from the ISO image – its files will be replaced (backup kept for 'pag rollback').",
967 - "base_reboot_hint": "Base adopted from the repo – reboot before using the new libraries/toolchain.",
968 - "base_register_ok": "Registered {} base packages in the package DB ({} were already tracked).",
969 - "base_register_plan": "Dry run – would register {} base packages.",
970 - "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).",
971 - "base_register_renamed": "{} names were matched to their repo package names.",
972 - "stats_base": "Base (image) managed",
973 - },
974 - "pl": {
975 - "root_required": "pag wymaga uprawnień root (sudo).",
976 - "db_locked": "Inna instancja pag jest uruchomiona.",
977 - "db_lock_hint": "Jeśli żaden inny proces pag nie działa, poczekaj chwilę i spróbuj ponownie.",
978 - "no_index": "Nie można pobrać indeksów repozytoriów. Uruchom 'pag update'.",
979 - "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",
980 - "all_installed": "Wszystkie pakiety są już zainstalowane.",
981 - "to_install": "Do zainstalowania: {} pakietów ({:.2f} MB)",
982 - "new": "NOWY",
983 - "continue_q": "Kontynuować? [T/n] ",
984 - "no_tty": "Brak terminala (EOF) – anuluję.",
985 - "cancelled": "Anulowano.",
986 - "not_found": "brak w repozytoriach",
987 - "pkg_not_found": "Nie znaleziono pakietu: {} (brak w repozytoriach)",
988 - "not_found_hint": "Sprawdź pisownię lub uruchom 'pag search <fraza>'.",
989 - "downloading": "Pobieranie",
990 - "done": "gotowe",
991 - "wroom_terminal": "PAG WROOM wymaga terminala – uruchom: pag wroom",
992 - "wroom_too_small": "Powiększ terminal (min. {arg1}x{arg2})",
993 - "wroom_tagline": "PAGAN RACING 4.2.0 · 38911 BAJTÓW WOLNE",
994 - "wroom_controls": "←/→ pas ↑/↓ gaz/hamulec P pauza Q wyjście",
995 - "wroom_press": "NACIŚNIJ SPACJĘ, ABY RUSZYĆ",
996 - "wroom_over": "KONIEC WYŚCIGU",
997 - "wroom_score": "Wynik: {arg1}",
998 - "wroom_best": "Rekord: {arg1}",
999 - "wroom_restart": "R / SPACJA – jeszcze raz Q – wyjście",
1000 - "wroom_paused": "PAUZA",
1001 - "wroom_hud": "WYNIK {arg1:06d} PRĘDKOŚĆ {arg2:3d} km/h ŻYCIA {arg3}",
1002 - "download_fail": "błąd pobierania",
1003 - "gpg_fail": "błąd weryfikacji GPG",
1004 - "sha256_mismatch": "niezgodność SHA256",
1005 - "install_failed": "błąd instalacji",
1006 - "installed": "Zainstalowano {} pakietów.",
1007 - "rollback_restored": "Przywrócono poprzedni stan z migawki.",
1008 - "rollback_files": "Wycofano {} plików.",
1009 - "no_history": "Brak historii transakcji.",
1010 - "pinned_list": "Przypięte pakiety ({}):",
1011 - "no_pinned": "Brak przypiętych pakietów.",
1012 - "pinned_to": "przypięty do",
1013 - "unpinned": "odpięty.",
1014 - "not_pinned": "nie był przypięty.",
1015 - "repo_added": "Dodano repozytorium: {}",
1016 - "repo_exists": "Repozytorium już istnieje: {}",
1017 - "updated_done": "Odświeżanie zakończone. {} pakietów w cache.",
1018 - "indexes_refreshed": "Indeksy odświeżone.",
1019 - "updates_available": "⚠ jest {} pakietów do zaktualizowania – wpisz: pag update",
1020 - "upgrading": "Aktualizacje: {} pakietów",
1021 - "all_up_to_date": "Wszystkie pakiety są aktualne.",
1022 - "removing": "Usuwanie",
1023 - "orphans_found": "Osierocone zależności ({}): {}",
1024 - "flatpak_missing": "Flatpak nie jest zainstalowany.",
1025 - "flatpak_adding": "Dodaję zdalne repozytorium Flathub...",
1026 - "flatpak_searching": "Szukam '{}' we Flathub...",
1027 - "flatpak_found": "Znaleziono {} wyników:",
1028 - "flatpak_not_found": "nie znaleziono we Flathub",
1029 - "flatpak_install_prompt": "Zainstalować {}? [T/n] ",
1030 - "flatpak_installing": "Instalowanie {}...",
1031 - "flatpak_installed": "Flatpak {} zainstalowany.",
1032 - "flatpak_removed": "Flatpak {} usunięty.",
1033 - "flatpak_not_installed": "Flatpak {} nie jest zainstalowany.",
1034 - "flatpak_info_id": "ID",
1035 - "flatpak_info_version": "Wersja",
1036 - "flatpak_info_branch": "Gałąź",
1037 - "flatpak_info_origin": "Źródło",
1038 - "flatpak_info_size": "Rozmiar",
1039 - "flatpak_info_desc": "Opis",
1040 - "flatpak_updated": "Flapaki zaktualizowane.",
1041 - "flatpak_usage": "Użycie: pag flatpak <search|install|remove|list|update|info> [args]",
1042 - "flatpak_scope": "Instalacja",
1043 - "flatpak_menu_hint": "Zainstalowano i zweryfikowano, ale sesja może jej nie pokazać w menu: brak eksportów Flatpaka w XDG_DATA_DIRS.",
1044 - "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.",
1045 - "key_imported": "Klucz zaimportowany pomyślnie.",
1046 - "key_removed": "Klucz usunięty: {}",
1047 - "no_keys": "Brak zaufanych kluczy GPG.",
1048 - "gpg_missing": "BRAK GNUPG – zainstaluj gnupg i spróbuj ponownie",
1049 - "ssl_broken": "Python bez działającego modułu ssl (HTTPS niemożliwe) – napraw pakiety python/openssl (np. sudo pag install -f python).",
1050 - "key_add_failed": "Import klucza nie powiódł się (błąd gpg) – klucz NIE został dodany.",
1051 - "verify_ok": "Wszystkie {} plików sprawne.",
1052 - "verify_errors": "Znaleziono {} problemów:",
1053 - "cache_cleared": "{} plików ({:.2f} MB) usuniętych z cache.",
1054 - "deployments_list": "Deploymenty ({}):",
1055 - "no_deployments": "Brak deploymentów.",
1056 - "active_deployment": "AKTYWNY",
1057 - "deploy_rollback_ok": "Przełączono na deployment: {}",
1058 - "deploy_rollback_fail": "Brak poprzedniego deploymentu.",
1059 - "deploy_cleanup_ok": "Usunięto {} starych deploymentów.",
1060 - "deploy_cleanup_none": "Nie ma deploymentów do wyczyszczenia (minimum {}).",
1061 - "snapshot_none": "Brak snapshotów systemu.",
1062 - "snapshot_list": "Snapshoty systemu ({}):",
1063 - "snapshot_created": "Utworzono snapshot: {}.",
1064 - "snapshot_deleted": "Usunięto snapshot: {}.",
1065 - "snapshot_not_found": "Nie znaleziono snapshotu: {}",
1066 - "snapshot_unsupported": "Snapshoty niedostępne: {}",
1067 - "snapshot_rollback_next": "Następny start ustawiono na snapshot: {}",
1068 - "snapshot_rollback_hint": "Wybierz ten wpis w menu GRUB: {}",
1069 - "staging_prepare": "Przygotowuję {} pakietów w stagingu (system bez zmian)...",
1070 - "staging_failed": "Etap przygotowania nieudany – system NIE został zmieniony.",
1071 - "staging_commit": "Wszystkie pakiety przygotowane – nakładam zmiany...",
1072 - "grub_refreshed": "Menu GRUB odświeżone.",
1073 - "grub_failed": "GRUB: {}",
1074 - "grub_no_initrd": "GRUB: wpis startowy bez initramfs – sprawdź /boot/initramfs-*.img",
1075 - "crlf_fixed": "{}: usunięto CRLF (psuło grub-mkconfig).",
1076 - "initramfs_links_fixed": "Naprawiono dowiązania initramfs.",
1077 - "no_user_sessions": "brak aktywnych sesji użytkownika – jednostki wczytają się przy logowaniu.",
1078 - "dry_run_done": "Dry-run – nic nie zmieniono.",
1079 - "dry_run_plan": "Dry-run – plan transakcji (bez zmian):",
1080 - "why_explicit": "zainstalowany jawnie",
1081 - "why_dependency": "zależność od",
1082 - "why_not_installed": "niezainstalowany",
1083 - "rdepends_title": "Odwrotne zależności {} ({}):",
1084 - "rdepends_none": "nic od niego nie zależy.",
1085 - "optional_deps": "Opcjonalne zależności (nie są instalowane automatycznie):",
1086 - "autoremove_ok": "Usunięto {} osieroconych pakietów.",
1087 - "autoremove_none": "Brak osieroconych pakietów.",
1088 - "downloaded": "Pobrano {} do cache ({:.2f} MB).",
1089 - "sec_downgrade": "Downgrade blocked: {pkg} {new} < {old}",
1090 - "sec_suid": "SUID stripped from {path}",
1091 - "sec_https": "HTTPS required for repos",
1092 - "sec_badname": "Invalid package name: {name}",
1093 - "sec_toobig": "Package too large: {size_mb}MB > {max_mb}MB",
1094 - "sec_conflict": "File conflict: {path} owned by {owner}",
1095 - "sec_audit": "{pkg} installed by {user}",
1096 - "sec_locked": "Another pag process is running",
1097 - "sec_downgrade_pl": "Blokada downgrade: {pkg} {new} < {old}",
1098 - "sec_suid_pl": "SUID usuniety z {path}",
1099 - "sec_https_pl": "Repozytorium wymaga HTTPS",
1100 - "sec_badname_pl": "Nieprawidlowa nazwa pakietu: {name}",
1101 - "sec_toobig_pl": "Paczka za duza: {size_mb}MB > {max_mb}MB",
1102 - "sec_conflict_pl": "Konflikt plikow: {path} nalezy do {owner}",
1103 - "sec_audit_pl": "{pkg} zainstalowany przez {user}",
1104 - "sec_locked_pl": "Inny proces pag juz dziala",
1105 -
1106 - "provides_mapped": "{} → {} (provides)",
1107 - "stats_title": "Statystyki PAG",
1108 - "stats_packages": "Zainstalowane pakiety",
1109 - "stats_files": "Śledzone pliki",
1110 - "stats_size": "Całkowity rozmiar",
1111 - "stats_cache": "Rozmiar cache",
1112 - "stats_history": "Transakcje",
1113 - "stats_last_update": "Ostatnia aktualizacja",
1114 - "conf_pacnew": "Zmieniony plik konfiguracyjny zachowany; nowa wersja: {path}",
1115 - "conf_pacsave": "Zmieniony plik konfiguracyjny zachowany jako {path}",
1116 - "provides_conflict": "Wielu dostawców dla '{name}' ({providers}) – używam '{chosen}'",
1117 -
1118 - # Baza wypalona w obrazie ISO (pag base / base adopt)
1119 - "base_title": "Baza z obrazu ISO",
1120 - "base_no_manifest": "Ten system nie ma manifestu bazy (/usr/share/pag/base.json) – nie ma czego adoptować.",
1121 - "base_iso_version": "Wersja obrazu",
1122 - "base_total": "Pakiety bazy (z obrazu)",
1123 - "base_tracked": "Zarządzane przez pag",
1124 - "base_adoptable": "Do adoptowania z repo",
1125 - "base_unmatched": "Bez odpowiednika w repo",
1126 - "base_adopt_hint": "Adoptuj (pliki z obrazu zostaną zastąpione pakietami z repo): sudo pag base adopt",
1127 - "base_unmatched_hint": "Te zostaną w wersji z obrazu (brak takiego pakietu w repo):",
1128 - "base_more": "więcej",
1129 - "base_nothing_selected": "Żadna z podanych nazw nie jest na liście do adoptowania.",
1130 - "base_all_managed": "Wszystkie pakiety bazy są już zarządzane przez pag.",
1131 - "base_adopt_plan": "Adoptowanie {} pakietów bazy z repo (~{:.0f} MB):",
1132 - "base_dry_run": "Próba na sucho – nic nie zainstalowano.",
1133 - "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).",
1134 - "base_overwrite": "{} pochodzi z obrazu ISO – pliki zostaną zastąpione (kopia zapasowa dla 'pag rollback').",
1135 - "base_reboot_hint": "Baza zaadoptowana z repo – zrestartuj system, zanim zaczniesz używać nowych bibliotek/narzędzi.",
1136 - "base_register_ok": "Zarejestrowano {} pakietów bazy w bazie pakietów ({} już było).",
1137 - "base_register_plan": "Dry-run – zarejestrowałbym {} pakietów bazy.",
1138 - "base_register_nocache": "Brak cache indeksu repo – zostawiono nazwy z buildera (uruchom 'sudo pag sync' i ponownie 'pag base register', aby je zmapować).",
1139 - "base_register_renamed": "{} nazw dopasowano do nazw pakietów w repo.",
1140 - "stats_base": "Baza (obraz) zarządzana",
1141 - },
1142 -}
1143 -
1144 -# ── i18n: komunikaty CLI (msgid = tekst EN) ─────────────────────────────
1145 -_EXTRA_I18N = {
1146 - ' ⚠ PAG_INSECURE=1 – skipping local package signature verification': ' ⚠ PAG_INSECURE=1 – pomijam weryfikację podpisu pakietu lokalnego',
1147 - ' ❌ No signature for package: {arg1}': ' ❌ Brak podpisu dla pakietu: {arg1}',
1148 - ' 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.',
1149 - ' ❌ Invalid package signature: {arg1}': ' ❌ Nieprawidłowy podpis pakietu: {arg1}',
1150 - ' ❌ No pinned repo key for the local package.': ' ❌ Brak przypiętego klucza repo dla lokalnego pakietu.',
1151 - ' Run first: sudo pag sync': ' Uruchom najpierw: sudo pag sync',
1152 - ' ❌ [SECURITY ERROR] Package was signed with a different repo key.': ' ❌ [SECURITY ERROR] Pakiet podpisano innym kluczem repo.',
1153 - ' Expected: {arg1}': ' Oczekiwany: {arg1}',
1154 - ' Received: {arg1}': ' Otrzymany: {arg1}',
1155 - ' 🔐 Package signature OK ({arg1})': ' 🔐 Podpis pakietu OK ({arg1})',
1156 - ' ⚡ Copying the active deployment...': ' ⚡ Kopiowanie aktywnego deploymentu...',
1157 - ' ✅ Deployment: {arg1} ({arg2})': ' ✅ Deployment: {arg1} ({arg2})',
1158 - ' ✅ First deployment: {arg1}': ' ✅ Pierwszy deployment: {arg1}',
1159 - ' ⚠ Cannot create {arg1}: {arg2}': ' ⚠ Nie mogę utworzyć {arg1}: {arg2}',
1160 - ' ⚠ Failed to create snapshot: {arg1}': ' ⚠ Nie udało się utworzyć snapshotu: {arg1}',
1161 - ' ⚠ btrfs snapshot failed: {arg1}': ' ⚠ btrfs snapshot nie udał się: {arg1}',
1162 - ' 📸 System snapshot: {arg1} (subvol={arg2})': ' 📸 Snapshot systemu: {arg1} (subvol={arg2})',
1163 - ' ❌ Invalid snapshot path – refusing to delete.': ' ❌ Nieprawidłowa ścieżka snapshotu – odmawiam usunięcia.',
1164 - ' ⏪ Snapshot: {arg1}': ' ⏪ Snapshot: {arg1}',
1165 - ' 💡 Reboot the system – GRUB will boot the selected snapshot.': ' 💡 Zrestartuj system – GRUB uruchomi wybrany snapshot.',
1166 - ' 💡 At boot, choose an entry in the GRUB menu (snapshots section).': ' 💡 Przy starcie wybierz wpis w menu GRUB (sekcja snapshotów).',
1167 - '❌ Another pag update is in progress – try again later.': '❌ Inna aktualizacja pag jest w toku – spróbuj ponownie później.',
1168 - ' ⚠ Failed to extract {arg1}: {arg2}': ' ⚠ Nie rozpakowano {arg1}: {arg2}',
1169 - ' ⚠ Corrupted index cache {arg1}: {arg2}': ' ⚠ Uszkodzony cache indeksu {arg1}: {arg2}',
1170 - ' ❌ {arg1}: cannot refresh index – {arg2} is read-only': ' ❌ {arg1}: nie można odświeżyć indeksu – {arg2} jest tylko-do-odczytu',
1171 - ' ⚠ HTTP {arg1} for {arg2}': ' ⚠ HTTP {arg1} dla {arg2}',
1172 - ' ⚠ Failed to download index {arg1}: {arg2}': ' ⚠ Błąd pobierania indeksu {arg1}: {arg2}',
1173 - ' ⚠ Index downloaded, but failed to save cache ({arg1}): {arg2}': ' ⚠ Indeks pobrany, ale nie udało się zapisać cache ({arg1}): {arg2}',
1174 - ' ❌ {arg1}: no GPG keys – verification impossible!': ' ❌ {arg1}: brak kluczy GPG – weryfikacja niemożliwa!',
1175 - ' Set PAG_INSECURE=1 to skip (not recommended)': ' Ustaw PAG_INSECURE=1 aby pominąć (niezalecane)',
1176 - ' ❌ {arg1}: CANNOT DOWNLOAD SIGNATURE repo.json.asc/.sig!': ' ❌ {arg1}: NIE MOŻNA POBRAĆ PODPISU repo.json.asc/.sig!',
1177 - ' 🔑 Imported repo key from {arg1}/paganos.asc': ' 🔑 Importowano klucz repo z {arg1}/paganos.asc',
1178 - ' ⚠ {arg1}: invalid GPG signature (PAG_INSECURE – ignoring)': ' ⚠ {arg1}: nieprawidłowy podpis GPG (PAG_INSECURE – ignoruję)',
1179 - ' ❌ {arg1}: GPG is not installed – cannot verify the signature!': ' ❌ {arg1}: GPG nie jest zainstalowane – nie można zweryfikować podpisu!',
1180 - ' Install gnupg or set PAG_INSECURE=1 (not recommended)': ' Zainstaluj gnupg lub ustaw PAG_INSECURE=1 (niezalecane)',
1181 - ' ❌ {arg1}: INVALID GPG SIGNATURE of the repository index!': ' ❌ {arg1}: NIEPRAWIDŁOWY PODPIS GPG indeksu repozytorium!',
1182 - ' ⚠ {arg1}: cannot read signature fingerprint (PAG_INSECURE – ignoring)': ' ⚠ {arg1}: nie można odczytać fingerprintu (PAG_INSECURE – ignoruję)',
1183 - ' ❌ [SECURITY ERROR] {arg1}: cannot read signature fingerprint!': ' ❌ [SECURITY ERROR] {arg1}: nie można odczytać fingerprintu podpisu!',
1184 - ' Pinned key: {arg1} – rejecting the index.': ' Przypięty klucz: {arg1} – odrzucam indeks.',
1185 - ' ⚠ {arg1}: SIGNING KEY CHANGED (PAG_INSECURE – ignoring)': ' ⚠ {arg1}: ZMIENIONY KLUCZ PODPISU (PAG_INSECURE – ignoruję)',
1186 - ' ❌ [SECURITY ERROR] {arg1}: Repository signing key has changed!': ' ❌ [SECURITY ERROR] {arg1}: Klucz podpisujący repo uległ zmianie!',
1187 - ' If this is an intentional key rotation: pag key-trust {arg1}': ' Jeśli to celowa rotacja klucza: pag key-trust {arg1}',
1188 - ' 🔐 Pinned repo fingerprint {arg1}: {arg2}': ' 🔐 Przypięto fingerprint repo {arg1}: {arg2}',
1189 - ' (TOFU – first trust. If the key changes, pag will refuse updates.)': ' (TOFU – pierwsze zaufanie. Gdy klucz się zmieni, pag odmówi aktualizacji.)',
1190 - ' To avoid TOFU, add the fingerprint to /etc/pag/repos.conf.': ' Aby uniknąć TOFU, dopisz fingerprint w /etc/pag/repos.conf.',
1191 - '❌ Download error: {arg1}': '❌ Błąd pobierania: {arg1}',
1192 - '🔐 Pinning repo key {arg1}...': '🔐 Przypinam klucz repo {arg1}...',
1193 - ' ❌ Cannot read signature fingerprint (missing/failed).': ' ❌ Nie można odczytać fingerprintu podpisu (brak/nieudany).',
1194 - ' 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>).',
1195 - ' ✅ Pinned {arg1} for {arg2}': ' ✅ Przypięto {arg1} dla {arg2}',
1196 - ' From now on, a key change will be reported as SECURITY ERROR.': ' Od teraz zmiana klucza zostanie zgłoszona jako SECURITY ERROR.',
1197 - ' ℹ {arg1} has no pinned fingerprint.': ' ℹ {arg1} nie ma przypiętego fingerprintu.',
1198 - ' ✅ Removed pin for {arg1}.': ' ✅ Usunięto przypięcie dla {arg1}.',
1199 - ' ❌ {arg1}: preparation stage failed ({arg2})': ' ❌ {arg1}: etap przygotowania nieudany ({arg2})',
1200 - ' ❌ {arg1}: commit error – {arg2}': ' ❌ {arg1}: błąd commit – {arg2}',
1201 - ' ⚠ ldconfig not found — linker cache was not refreshed.': ' ⚠ Nie znaleziono ldconfig — cache linkera nie został odświeżony.',
1202 - ' ⚠ Failed to refresh ld.so cache: {arg1}': " ⚠ Nie udało się odświeżyć cache'a ld.so: {arg1}",
1203 - ' ⚠ {arg1} shared files preserved': ' ⚠ {arg1} plików współdzielonych zachowanych',
1204 - ' ⚠ {arg1} sensitive system files preserved': ' ⚠ {arg1} wrażliwych plików systemowych zachowanych',
1205 - ' 🧹 Removed {arg1} obsolete files ({arg2})': ' 🧹 Usunięto {arg1} nieaktualnych plików ({arg2})',
1206 - ' 🛠 Interrupted transaction detected – restored {arg1} missing files.': ' 🛠 Wykryto przerwana transakcje – przywrocono {arg1} brakujacych plikow.',
1207 - ' ⚠ Hook skipped (PAG_NO_HOOKS=1): {arg1} for {arg2}': ' ⚠ Hook pominięty (PAG_NO_HOOKS=1): {arg1} dla {arg2}',
1208 - ' ⚠ Hook {arg1} for {arg2} exited with code {arg3}': ' ⚠ Hook {arg1} dla {arg2} zakończony z kodem {arg3}',
1209 - ' ⚠ Hook {arg1} for {arg2} timed out ({arg3}s)': ' ⚠ Hook {arg1} dla {arg2} przekroczył timeout ({arg3}s)',
1210 - ' Increase PAG_HOOK_TIMEOUT (e.g. PAG_HOOK_TIMEOUT=1800) and retry.': ' Zwiększ PAG_HOOK_TIMEOUT (np. PAG_HOOK_TIMEOUT=1800) i spróbuj ponownie.',
1211 - ' ⚠ Hook {arg1} for {arg2}: {arg3}': ' ⚠ Hook {arg1} dla {arg2}: {arg3}',
1212 - 'Recent transactions ({arg1}):': 'Ostatnie transakcje ({arg1}):',
1213 - '❌ No snapshot to restore.': '❌ Brak snapshotu do przywrócenia.',
1214 - '⏪ Rolling back: {arg1} ({arg2})': '⏪ Wycofywanie: {arg1} ({arg2})',
1215 - ' Packages: {arg1}': ' Pakiety: {arg1}',
1216 - ' ❌ Package not found: {arg1}': ' ❌ Nie znaleziono pakietu: {arg1}',
1217 - ' ❌ {arg1}: missing metadata.json': ' ❌ {arg1}: brak metadata.json',
1218 - ' ❌ {arg1}: failed to read package ({arg2})': ' ❌ {arg1}: nie udało się odczytać pakietu ({arg2})',
1219 - ' ↩ Preparation stage failed – the system was NOT changed.': ' ↩ Etap przygotowania nieudany – system NIE został zmieniony.',
1220 - ' ↓ {arg1}-{arg2} (local) ... ': ' ↓ {arg1}-{arg2} (lokalny) ... ',
1221 - ' ❌ Not enough disk space: need ~{arg1} MB, free {arg2} MB ({arg3})': ' ❌ Za mało miejsca na dysku: potrzeba ~{arg1} MB, wolne {arg2} MB ({arg3})',
1222 - ' ⚠ 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)',
1223 - ' ❌ {arg1} is mounted read-only – cannot install.': ' ❌ {arg1} jest zamontowane tylko-do-odczytu – nie można instalować.',
1224 - '❌ Cannot continue – {arg1} missing dependencies.': '❌ Nie można kontynuować – {arg1} brakujących zależności.',
1225 - ' Install the missing packages or add repositories.': ' Zainstaluj brakujące pakiety lub dodaj repozytoria.',
1226 - ' Install the library provider or update the repository.': ' Zainstaluj dostawcę biblioteki lub zaktualizuj repozytorium.',
1227 - '\n 🏗️ Creating a new deployment...': '\n 🏗️ Tworzenie nowego deploymentu...',
1228 - '\n ⏬ Downloading {arg1} packages in parallel...': '\n ⏬ Pobieranie {arg1} pakietów równolegle...',
1229 - '\n 🐧 Finalizing kernel/driver update (DKMS → initramfs → GRUB)...': '\n 🐧 Finalizuję aktualizację jądra/sterowników (DKMS → initramfs → GRUB)...',
1230 - '\n 🐧 Finalizing kernel/driver update in deployment (initramfs)...': '\n 🐧 Finalizuję aktualizację jądra/sterowników w deploymencie (initramfs)...',
1231 - ' ↩ Aborted BEFORE installation – no package was changed.': ' ↩ Przerwano PRZED instalacją – żadna paczka nie została zmieniona.',
1232 - ' ❌ Failed to create snapshot (--snapshot mode) – aborting.': ' ❌ Nie udało się utworzyć snapshotu (tryb --snapshot) – przerywam.',
1233 - '\n ↩ Rolling back transaction ({arg1} errors)...': '\n ↩ Cofanie transakcji ({arg1} błędów)...',
1234 - '\n 🔄 Switching to deployment {arg1}...': '\n 🔄 Przełączanie na deployment {arg1}...',
1235 - ' ✅ Active deployment: {arg1}': ' ✅ Aktywny deployment: {arg1}',
1236 - ' 💡 Restart required to reload the system.': ' 💡 Restart wymagany do przeładowania systemu.',
1237 - ' ⚠ {arg1}: not installed': ' ⚠ {arg1}: nie zainstalowano',
1238 - '✅ ({arg1} files)': '✅ ({arg1} plików)',
1239 - '\n✅ Removed {arg1}.': '\n✅ Usunięto {arg1}.',
1240 - " 'pag remove-orphans' to clean up.": " Uruchom 'pag remove-orphans', aby posprzątać.",
1241 - ' ⚡ Trigger: {arg1} ({arg2})': ' ⚡ Wyzwalacz: {arg1} ({arg2})',
1242 - ' ⚠ trigger {arg1} timed out (120 s)': ' ⚠ trigger {arg1} przekroczył limit czasu (120 s)',
1243 - ' ⚠ trigger {arg1}: {arg2}': ' ⚠ wyzwalacz {arg1}: {arg2}',
1244 - '❌ No repositories configured.': '❌ Brak repozytoriów w konfiguracji.',
1245 - '🔄 Checking for pag update from {arg1}...': '🔄 Sprawdzam aktualizację pag z {arg1}...',
1246 - ' ❌ Cannot download pag: {arg1}': ' ❌ Nie można pobrać pag: {arg1}',
1247 - ' ⚠ Invalid update signature (PAG_INSECURE – ignoring)': ' ⚠ Nieprawidłowy podpis aktualizacji (PAG_INSECURE – ignoruję)',
1248 - ' ❌ Invalid update signature – not updating.': ' ❌ Nieprawidłowy podpis aktualizacji – nie aktualizuję.',
1249 - ' ❌ Cannot confirm the update signature fingerprint.': ' ❌ Nie można potwierdzić fingerprintu podpisu aktualizacji.',
1250 - ' ⚠ Update signed with a different key (PAG_INSECURE – ignoring)': ' ⚠ Podpis aktualizacji innym kluczem (PAG_INSECURE – ignoruję)',
1251 - ' ❌ [SECURITY ERROR] Update signed with a different key than the repo!': ' ❌ [SECURITY ERROR] Podpis aktualizacji innym kluczem niż repo!',
1252 - ' Expected: {arg1}, received: {arg2}': ' Oczekiwany: {arg1}, Otrzymany: {arg2}',
1253 - ' ❌ SHA256 mismatch! Expected {arg1}, got {arg2}': ' ❌ SHA256 niezgodny! Oczekiwano {arg1}, jest {arg2}',
1254 - ' ✅ SHA256 matches': ' ✅ SHA256 zgodny',
1255 - ' ❌ Syntax error in new pag: {arg1}': ' ❌ Błąd składni w nowym pag: {arg1}',
1256 - ' ✅ Downloaded pag {arg1} (current {arg2}), signature verified': ' ✅ Pobrano pag {arg1} (obecny {arg2}), podpis zweryfikowany',
1257 - ' ✅ Installed new pag. Old version kept as {arg1}': ' ✅ Zainstalowano nowy pag. Stary zachowany jako {arg1}',
1258 - ' ⚠ A different pag is first in PATH: {arg1} (updated {arg2})': ' ⚠ W PATH pierwszy jest inny pag: {arg1} (zaktualizowano {arg2})',
1259 - ' Remove the old copy: sudo rm {arg1}': ' Usuń starą kopię: sudo rm {arg1}',
1260 - ' Restart pag to use the new version.': ' Uruchom ponownie pag, aby użyć nowej wersji.',
1261 - '🔄 Refreshing indexes...': '🔄 Odświeżanie indeksów...',
1262 - ' {arg1} {arg2}: {arg3} packages {arg4}': ' {arg1} {arg2}: {arg3} pakietów {arg4}',
1263 - ' ⚠ New pag version {arg1} available – run: pag self-update': ' ⚠ Nowa wersja pag {arg1} dostępna – uruchom: pag self-update',
1264 - ' 🐧 Rebuilding initramfs (newer kernel)...': ' 🐧 Przebudowa initramfs (nowsze jądro)...',
1265 - 'No packages installed.': 'Brak zainstalowanych pakietów.',
1266 - 'Installed ({arg1}):': 'Zainstalowane ({arg1}):',
1267 - 'Available ({arg1}):': 'Dostępne ({arg1}):',
1268 - '❌ No results for: {arg1}': '❌ Brak wyników dla: {arg1}',
1269 - "Results for '{arg1}' ({arg2}):": "Wyniki dla '{arg1}' ({arg2}):",
1270 - "\n ❌ '{arg1}' — not found.": "\n ❌ '{arg1}' — nie znaleziono.",
1271 - ' PaganOS repo: pag search {arg1}': ' Repo PaganOS: pag search {arg1}',
1272 - ' Flathub: pag flatpak search {arg1}': ' Flathub: pag flatpak search {arg1}',
1273 - ' Add repo: pag repo-add <url>': ' Dodaj repo: pag repo-add <url>',
1274 - ' ... and {arg1} more (pag search {arg2})': ' ... i {arg1} więcej (pag search {arg2})',
1275 - ' ... and {arg1} more (pag flatpak search {arg2})': ' ... i {arg1} więcej (pag flatpak search {arg2})',
1276 - ' ✓ {arg1} is already installed ({arg2})': ' ✓ {arg1} jest już zainstalowany ({arg2})',
1277 - "❌ '{arg1}' not found.": "❌ Nie znaleziono '{arg1}'.",
1278 - ' Version (repo): {arg1}': ' Wersja (repo): {arg1}',
1279 - ' Description: {arg1}': ' Opis: {arg1}',
1280 - ' Size: {arg1:.1f} MB': ' Rozmiar: {arg1:.1f} MB',
1281 - ' SHA256: {arg1}...': ' SHA256: {arg1}...',
1282 - ' GPG: {arg1}': ' GPG: {arg1}',
1283 - ' Dependencies: {arg1}': ' Zależności: {arg1}',
1284 - ' Installed: {arg1} ({arg2})': ' Zainstalowany: {arg1} ({arg2})',
1285 - "❌ '{arg1}' not installed.": "❌ '{arg1}' nie jest zainstalowany.",
1286 - 'Files in {arg1} ({arg2}):': 'Pliki w {arg1} ({arg2}):',
1287 - 'Nothing to repair (no packages installed).': 'Nic do naprawy (brak zainstalowanych pakietow).',
1288 - '✅ All files are in place – nothing to repair.': '✅ Wszystkie pliki na miejscu – nic do naprawy.',
1289 - '🔧 Packages with missing files: {arg1} (total {arg2} files)': '🔧 Pakiety z brakujacymi plikami: {arg1} (lacznie {arg2} plikow)',
1290 - '\n(--dry-run: nothing is changed)': '\n(--dry-run: nic nie zmieniam)',
1291 - '\n🔧 repair: {arg1}': '\n🔧 naprawa: {arg1}',
1292 - '⚠ Repaired {arg1}/{arg2}. Failed: {arg3}': '⚠ Naprawiono {arg1}/{arg2}. Nie udalo sie: {arg3}',
1293 - '✅ Repaired {arg1} packages.': '✅ Naprawiono {arg1} pakietow.',
1294 - 'Nothing to verify.': 'Nie ma czego weryfikować.',
1295 - '✅ No orphans.': 'Brak osieroconych pakietów.',
1296 - 'Orphans ({arg1}):': 'Osierocone ({arg1}):',
1297 - ' ⚠ Search error: {arg1}': ' ⚠ Błąd wyszukiwania: {arg1}',
1298 - '\n Choose a number (1-{arg1}) or press Enter to cancel:': '\n Wybierz numer (1-{arg1}) lub Enter aby anulować: ',
1299 - " 📦 {arg1} – already installed (use 'pag flatpak info {arg2}' for details)": " 📦 {arg1} – już zainstalowany (szczegóły: 'pag flatpak info {arg2}')",
1300 - "\n Multiple matches for '{arg1}':": "\n Wiele dopasowań dla '{arg1}':",
1301 - '\n Choose a number (1-{arg1}) or press Enter:': '\n Wybierz numer (1-{arg1}) lub Enter: ',
1302 - ' ... and {arg1} more. Refine your query.': ' ... i {arg1} więcej. Doprecyzuj zapytanie.',
1303 - '\n Choose a number to install (1-{arg1}) or press Enter to cancel:': '\n Wybierz numer do zainstalowania (1-{arg1}) lub Enter aby anulować: ',
1304 - ' (no installed flatpaks)': ' (brak zainstalowanych flatpaków)',
1305 - 'Installed flatpaks ({arg1}):': ' Zainstalowane flatpaki ({arg1}):',
1306 - ' 🔄 Updating flatpaks...': ' 🔄 Aktualizacja flatpaków...',
1307 - '\n 💡 To install: pag flatpak install {arg1}': '\n 💡 Aby zainstalować: pag flatpak install {arg1}',
1308 - ' 🔧 DKMS: rebuilding out-of-tree modules (nvidia/vbox)...': ' 🔧 DKMS: przebudowa modułów out-of-tree (nvidia/vbox)...',
1309 - ' 🔧 Rebuilding initramfs (pagan-initramfs)...': ' 🔧 Przebudowa initramfs (pagan-initramfs)...',
1310 - ' 🔧 Rebuilding initramfs (dracut)...': ' 🔧 Przebudowa initramfs (dracut)...',
1311 - ' 🔧 Rebuilding initramfs (mkinitcpio)...': ' 🔧 Przebudowa initramfs (mkinitcpio)...',
1312 - ' ⚠ No dracut/mkinitcpio – initramfs was not rebuilt': ' ⚠ Brak dracut/mkinitcpio – initramfs nie został przebudowany',
1313 - ' 🔧 Building initramfs for the deployment...': ' 🔧 Budowanie initramfs dla deploymentu...',
1314 - ' ⚠ pag-initramfs-init not found – skipping initramfs build': ' ⚠ Nie znaleziono pag-initramfs-init – pomijam budowę initramfs',
1315 - " ⚠ No vmlinuz-* found in the deployment's /boot": ' ⚠ Nie znaleziono vmlinuz-* w /boot deploymentu',
1316 - ' 🐧 Kernel: {arg1}': ' 🐧 Jądro: {arg1}',
1317 - ' ⚠ Skipping unavailable files: {arg1}': ' ⚠ Pomijam niedostępne pliki: {arg1}',
1318 - ' ⚠ Skipping unavailable file: {arg1}': ' ⚠ Pomijam niedostępny plik: {arg1}',
1319 - ' ✅ initramfs.img ({arg1:.1f} MB) → {arg2}': ' ✅ initramfs.img ({arg1:.1f} MB) → {arg2}',
1320 - ' ❌ initramfs build error: {arg1}': ' ❌ Błąd budowy initramfs: {arg1}',
1321 - '🏗️ Deployment: {arg1}': '🏗️ Deployment: {arg1}',
1322 - '✅ Initramfs updated.': '✅ Initramfs zaktualizowany.',
1323 - '❌ Initramfs update failed.': '❌ Błąd aktualizacji initramfs.',
1324 - ' 📋 Regenerating GRUB (grub-mkconfig)...': ' 📋 Regeneracja GRUB (grub-mkconfig)...',
1325 - ' ⚠ Could not detect the root partition – GRUB entries will have no root=.': ' ⚠ Nie udało się wykryć partycji root – wpisy GRUB nie dostaną root=.',
1326 - ' Set PAG_ROOT_DEVICE=/dev/... (or PAG_GRUB_ROOT) and retry.': ' Ustaw PAG_ROOT_DEVICE=/dev/... (lub PAG_GRUB_ROOT) i powtórz.',
1327 - ' 📋 GRUB config updated – entries for each deployment': ' 📋 GRUB config zaktualizowany – wpisy dla każdego deploymentu',
1328 - '📋 Updating GRUB configuration...': '📋 Aktualizacja konfiguracji GRUB...',
1329 - '✅ GRUB updated.': '✅ GRUB zaktualizowany.',
1330 - ' +{arg1} more...': ' +{arg1} więcej...',
1331 - '❌ Deployment {arg1} does not exist on disk': '❌ Deployment {arg1} nie istnieje na dysku',
1332 - '⏪ Restoring deployment: {arg1}': '⏪ Przywracanie deploymentu: {arg1}',
1333 - '\n❌ {arg1} – cannot install:': '\n❌ {arg1} – nie można zainstalować:',
1334 - ' {arg1} → needs {arg2} (missing from repositories)': ' {arg1} → potrzebuje {arg2} (brak w repozytoriach)',
1335 - '\n⚠ {arg1} – will be installed as dependencies:': '\n⚠ {arg1} – zostaną doinstalowane:',
1336 - ' {arg1} → {arg2} ({arg3} – will be downloaded)': ' {arg1} → {arg2} ({arg3} – będzie pobrane)',
1337 - ' {arg1} → requires {arg2} – no package provides this version': ' {arg1} → wymaga {arg2} – żaden pakiet nie dostarcza tej wersji',
1338 - ' ↻ Retrying download of {arg1} ({arg2}/{arg3})...': ' ↻ Ponawiam pobieranie {arg1} ({arg2}/{arg3})...',
1339 - ' ⚠ Download error {arg1}: {arg2}': ' ⚠ Błąd pobierania {arg1}: {arg2}',
1340 - '❌ Format: spdx | cyclonedx': '❌ Format: spdx | cyclonedx',
1341 - ' ✓ {arg1} ({arg2} keys)': ' ✓ {arg1} ({arg2} kluczy)',
1342 - 'Usage: pag search <query>': 'Użycie: pag search <query>',
1343 - 'Usage: pag info <pkg>': 'Użycie: pag info <pkg>',
1344 - 'Usage: pag files <pkg>': 'Użycie: pag files <pkg>',
1345 - 'Usage: pag why <pkg>': 'Użycie: pag why <pkg>',
1346 - 'Usage: pag rdepends <pkg>': 'Użycie: pag rdepends <pkg>',
1347 - 'Usage: pag flatpak-search <query>': 'Użycie: pag flatpak-search <query>',
1348 - 'Usage: pag flatpak-info <id>': 'Użycie: pag flatpak-info <id>',
1349 - "❌ Unknown command: '{arg1}'. Did you mean '{arg2}'?": "❌ Nieznana komenda: '{arg1}'. Czy chodziło o '{arg2}'?",
1350 - " Run 'pag' without arguments to see the command list.": " Uruchom 'pag' bez argumentów, aby zobaczyć listę komend.",
1351 - 'Usage: pag unpin <pkg>': 'Użycie: pag unpin <pkg>',
1352 - 'Usage: pag repo-add <url> [name]': 'Użycie: pag repo-add <url> [name]',
1353 - 'Usage: pag key-add <url|file>': 'Użycie: pag key-add <url|file>',
1354 - 'Usage: pag key-remove <id>': 'Użycie: pag key-remove <id>',
1355 - 'Usage: pag key-trust <repo_url>': 'Użycie: pag key-trust <repo_url>',
1356 - 'Usage: pag key-untrust <repo_url>': 'Użycie: pag key-untrust <repo_url>',
1357 - 'Usage: pag flatpak-install <app>': 'Użycie: pag flatpak-install <app>',
1358 - 'Usage: pag flatpak-remove <app>': 'Użycie: pag flatpak-remove <app>',
1359 - 'Usage: pag snapshot-delete <id>': 'Użycie: pag snapshot-delete <id>',
1360 - '\n ⚠ Interrupted (Ctrl-C).': '\n ⚠ Przerwano (Ctrl-C).',
1361 -}
1362 -for _msgid, _pl in _EXTRA_I18N.items():
1363 - T["en"].setdefault(_msgid, _msgid)
1364 - T["pl"].setdefault(_msgid, _pl)
1365 -
1366 -_AUX_I18N = {
1367 - 'installed_marker': ('installed', 'zainstalowany'),
1368 - 'none_value': ('none', 'brak'),
1369 - 'none_parenthesized': ('(none)', '(brak)'),
1370 - 'stats_top': ('Top 5:', 'Największe 5:'),
1371 - 'never': ('never', 'nigdy'),
1372 - 'action_install': ('install', 'instalacja'),
1373 - 'action_upgrade': ('upgrade', 'aktualizacja'),
1374 - 'action_remove': ('remove', 'usunięcie'),
1375 - 'action_rollback': ('rollback', 'wycofanie'),
1376 - 'action_manual': ('manual', 'ręczny'),
1377 - 'action_repair': ('repair', 'naprawa'),
1378 - 'flatpak_searching_any': ('Searching Flathub...', 'Szukam we Flathub...'),
1379 - 'upgrade_marker': ('[upgrade]', '[aktualizacja]'),
1380 - 'hardlink_method': ('hardlinks', 'hardlinki'),
1381 - 'copy_method': ('full copy', 'pełna kopia'),
1382 - 'reflink_method': ('CoW (reflink)', 'CoW (reflink)'),
1383 - 'verify_missing_file': (' ❌ {}: missing {}', ' ❌ {}: brakuje {}'),
1384 - 'verify_sha_mismatch': (' ❌ {}: SHA256 mismatch {}', ' ❌ {}: niezgodność SHA256 {}'),
1385 - 'gpg_binary_not_found': ('GPG binary not found ({})', 'Nie znaleziono binarki GPG ({})'),
1386 - 'gpg_timeout': ('GPG operation timed out', 'Operacja GPG przekroczyła limit czasu'),
1387 - 'audio_services_reloaded': (' ⚡ audio services reloaded for sessions: {}', ' ⚡ przeładowano usługi audio dla sesji: {}'),
1388 - 'grub_fallback_label': ('Pagan Linux – fallback (plain root)', 'Pagan Linux – fallback (zwykły root)'),
1389 - 'done': ('done', 'gotowe'),
1390 - 'deploy_copy_failed': ('Failed to copy the deployment by any method', 'Nie udało się skopiować deploymentu żadną metodą'),
1391 - 'pkg_missing_data_tar': ('missing data.tar.xz in package', 'brak data.tar.xz w pakiecie'),
1392 - 'pkg_sha_mismatch': ('SHA256 mismatch: {}', 'niezgodność SHA256: {}'),
1393 - 'repo_index_invalid': ("missing 'packages' list", "brak listy 'packages'"),
1394 -}
1395 -for _k, (_en, _pl) in _AUX_I18N.items():
1396 - T["en"].setdefault(_k, _en)
1397 - T["pl"].setdefault(_k, _pl)
1398 -
1399 -# ── Tłumaczenia z PLIKÓW (nadpisują/rozszerzają wbudowane PL/EN) ─────────────
1400 -# Kolejność: PAG_LANG_DIR (env) → /etc/pag/lang → /usr/share/pag/lang →
1401 -# ./pag-lang obok binarki (dev). Brak plików NIE jest błędem – zostaje
1402 -# wbudowany słownik T (fallback), więc pag zawsze działa.
1403 -# Przykład pliku (pag-lang/pl.json): {"app_title": "...", "usage": "..."}.
1404 -def _load_lang_files() -> None:
1405 - # PAG_LANG_NO_FILES=1 → pomiń pliki (używane przy eksporcie --lang-extract,
1406 - # żeby wyeksportować CZYSTE wbudowane słowniki, bez starych nadpisań).
1407 - if os.environ.get("PAG_LANG_NO_FILES") == "1":
1408 - return
1409 - dirs = []
1410 - _env = os.environ.get("PAG_LANG_DIR")
1411 - if _env:
1412 - dirs.append(_env)
1413 - # __file__ bywa niedostępne, gdy moduł jest exec/frozen (np. harness
1414 - # instalacyjny) – liczymy wtedy od ścieżki programu, zamiast wywalać
1415 - # NameError przy samym imporcie.
1416 - _self = globals().get("__file__") or sys.argv[0] or "pag"
1417 - dirs += ["/etc/pag/lang", "/usr/share/pag/lang",
1418 - os.path.join(os.path.dirname(os.path.abspath(_self)), "pag-lang")]
1419 - for _d in dirs:
1420 - for _code in list(T.keys()) + ["pl", "en", "de"]:
1421 - _p = os.path.join(_d, f"{_code}.json")
1422 - try:
1423 - with open(_p, "r", encoding="utf-8") as _fh:
1424 - _data = json.load(_fh)
1425 - if isinstance(_data, dict):
1426 - # Merge (nie replace): klucze nieobecne w pliku zachowują
1427 - # wbudowane tłumaczenie. Puste wartości pomijamy, żeby
1428 - # niekompletny/uszkodzony plik nie wyczyścił komunikatu.
1429 - _clean = {str(k): str(v) for k, v in _data.items()
1430 - if str(v).strip()}
1431 - T.setdefault(_code, {}).update(_clean)
1432 - except (OSError, ValueError):
1433 - continue
1434 -
1435 -
1436 -_load_lang_files()
1437 -
1438 -def _(key: str, *args, **kwargs) -> str:
1439 - """Tłumaczy klucz i formatuje argumenty.
1440 -
1441 - Dla LANG=pl preferuje wariant „<key>_pl” (np. komunikaty bezpieczeństwa
1442 - mają krótkie wersje PL obok bazy EN), potem zwykły klucz, potem EN/klicz.
1443 - """
1444 - if LANG == "pl":
1445 - _pl = T.get("pl", {})
1446 - msg = _pl.get(key + "_pl") or _pl.get(key) or T["en"].get(key, key)
1447 - else:
1448 - msg = T.get(LANG, T["en"]).get(key, T["en"].get(key, key))
1449 - if args or kwargs:
1450 - return msg.format(*args, **kwargs)
1451 - return msg
1452 -
1453 -
1454 -def _ask_confirm() -> bool:
1455 - """Pytanie potwierdzające (T/n). PAG_YES=1 → zawsze tak.
1456 -
1457 - EOF/brak terminala (stdin zamknięty, np. ssh bez TTY, cron, subprocess
1458 - panelu webowego) → NIE – anuluj, nie wykonuj operacji bez potwierdzenia
1459 - (inaczej input() rzuca EOFError i pag pada tracebackiem).
1460 - Enter → tak (domyślne Y/n).
1461 - """
1462 - if os.environ.get("PAG_YES", "") == "1":
1463 - print(_("continue_q") + " t (--yes)")
1464 - return True
1465 - try:
1466 - ans = input(_("continue_q")).strip().lower()
1467 - except (EOFError, KeyboardInterrupt):
1468 - print(f"\n ⚠ {_('no_tty')}")
1469 - return False
1470 - return not ans or ans in ("t", "y")
1471 -
1472 -
1473 -# =============================================================================
1474 -# ŚCIEŻKI
1475 -# =============================================================================
1476 -PAG_ROOT = os.environ.get("PAG_ROOT", "/")
1477 -PAG_DB = "/var/lib/pag"
1478 -PAG_CACHE = "/var/cache/pag"
1479 -PAG_CONF = "/etc/pag"
1480 -REPO_CACHE = "/var/cache/pag/repos"
1481 -REPOS_CONF = "/etc/pag/repos.conf"
1482 -REPOS_DIR = PAG_CONF + "/repos" # drop-in: /etc/pag/repos/<nazwa>.conf
1483 -INSTALLED_DB = "/var/lib/pag/installed.json"
1484 -FILES_DB_SQL = "/var/lib/pag/files.db" # SQLite!
1485 -WORLD_FILE = "/var/lib/pag/world"
1486 -PINNED_FILE = "/var/lib/pag/pinned.json"
1487 -HISTORY_FILE = "/var/lib/pag/history.json"
1488 -LOCK_FILE = "/var/lib/pag/pag.lock"
1489 -STAGING_DIR = "/.pag_staging" # na tej samej partycji co / (unikamy EXDEV)
1490 -PKG_EXT = ".pag"
1491 -REPO_CACHE_TTL = 3600
1492 -MAX_PKG_SIZE = 2 * 1024 * 1024 * 1024 # 2 GB – maksymalny rozmiar paczki
1493 -BASE_MANIFEST = "/usr/share/pag/base.json" # baza z obrazu ISO (pag base/adopt)
1494 -
1495 -# ── UPRZYWILEJOWANE PLIKI ────────────────────────────────────────────────────
1496 -# Domyślnie pag zdejmuje bit SUID i wymusza właściciela root:root. Niektóre
1497 -# programy MUSZĄ jednak zachować setuid/setgid albo grupę inną niż root
1498 -# (/usr/bin/sudo, /usr/bin/passwd, /usr/bin/unix_chkpwd,
1499 -# /usr/lib/dbus-daemon-launch-helper). Bez tego tracą możliwość działania
1500 -# po aktualizacji przez pag (np. użytkownik nie zmieni hasła).
1501 -#
1502 -# Bezpieczeństwo: zawartość pakietu jest uwierzytelniona (podpis GPG repo +
1503 -# przypięty fingerprint + SHA256 całego pakietu), więc metadane w nim są
1504 -# zaufane tak samo jak same pliki. Zachowujemy uprawnienia WYŁĄCZNIE dla
1505 -# ścieżek z tej listy (albo z pola `privileged:` receptury, które pagbuild
1506 -# zapisuje w metadata.json).
1507 -PRIVILEGED_PATHS = frozenset({
1508 - "/usr/bin/cdda2wav", "/usr/bin/cdrecord",
1509 - "/usr/bin/chage", "/usr/bin/expiry",
1510 - "/usr/bin/fcrondyn", "/usr/bin/fcronsighup", "/usr/bin/fcrontab",
1511 - "/usr/bin/firejail", "/usr/bin/fping",
1512 - "/usr/bin/fusermount", "/usr/bin/fusermount3",
1513 - "/usr/bin/gpasswd", "/usr/bin/ksu", "/usr/bin/lockfile",
1514 - "/usr/bin/mount", "/usr/bin/mount.nfs",
1515 - "/usr/bin/newgidmap", "/usr/bin/newuidmap",
1516 - "/usr/bin/passwd", "/usr/bin/ping", "/usr/bin/ping6",
1517 - "/usr/bin/procmail", "/usr/bin/readcd", "/usr/bin/rscsi",
1518 - "/usr/bin/screen", "/usr/bin/screen-5.0.2",
1519 - "/usr/bin/sg", "/usr/bin/su", "/usr/bin/sudo", "/usr/bin/traceroute",
1520 - "/usr/bin/umount", "/usr/bin/unix_chkpwd", "/usr/bin/wall",
1521 - "/usr/lib/dbus-daemon-launch-helper",
1522 - "/usr/lib/httpd/suexec",
1523 - "/usr/lib/utempter/utempter",
1524 - "/usr/lib/xscreensaver/xscreensaver-auth",
1525 - "/usr/libexec/libgtop_server2",
1526 - "/usr/libexec/qemu-bridge-helper",
1527 - "/usr/libexec/ssh-keysign",
1528 - "/usr/libexec/xf86-video-intel-backlight-helper",
1529 - "/opt/google/chrome/chrome-sandbox",
1530 - "/opt/gitkraken/chrome-sandbox",
1531 - "/opt/VirtualBox/VBoxHeadless", "/opt/VirtualBox/VBoxNetAdpCtl",
1532 - "/opt/VirtualBox/VBoxNetDHCP", "/opt/VirtualBox/VBoxVolInfo",
1533 - "/opt/VirtualBox/VirtualBoxVM",
1534 -})
1535 -ALLOWED_PKG_RE = re.compile(r'^[a-zA-Z0-9][a-zA-Z0-9._+@-]*$')
1536 -
1537 -# Bezpieczeństwo / audyt
1538 -AUDIT_LOG = "/var/log/pag/audit.log" # dziennik operacji krytycznych (hooki, self-update)
1539 -TRUST_DB = "/etc/pag/trusted.json" # mapa repo_url → fingerprint klucza podpisującego
1540 -HOOK_API_VERSION = "1" # wersjonowane API hooków (env PKG_HOOK_API)
1541 -
1542 -# =============================================================================
1543 -# IMMUTABLE OS – DEPLOYMENTY
1544 -# =============================================================================
1545 -# Model: zamiast mutować /, każda operacja tworzy NOWY deployment.
1546 -# /var, /etc, /home są współdzielone między deploymentami.
1547 -#
1548 -# STRUKTURA:
1549 -# /.deployments/
1550 -# active → 20260723T120000 (symlink do aktywnego)
1551 -# 20260723T120000/
1552 -# usr/ bin/ lib/ lib64/ ... (pełny system)
1553 -# var → /var (symlink do współdzielonego)
1554 -# etc → /etc
1555 -# home → /home
1556 -# ...
1557 -#
1558 -# Jak to działa:
1559 -# 1. pag install → kopiuje active → nowy deployment + nakłada zmiany → switch symlinka
1560 -# 2. pag remove → kopiuje active → nowy deployment - usuwa pliki → switch symlinka
1561 -# 3. pag deploy-rollback → przełącza active symlink na poprzedni deployment
1562 -# 4. Przy starcie systemu: initrd montuje /.deployments/active jako /
1563 -# =============================================================================
1564 -
1565 -DEPLOYMENTS_DIR = "/.deployments"
1566 -ACTIVE_LINK = "/.deployments/active"
1567 -DEPLOYMENTS_DB = "/var/lib/pag/deployments.json"
1568 -
1569 -# Snapshoty systemu (CoW). Na btrfs każdy snapshot jest osobnym subwolumenem,
1570 -# więc zajmuje tylko zmienione bloki, a GRUB potrafi uruchomić system z wybranej
1571 -# migawki (rootflags=subvol=...). Na ext4/xfs nie ma snapshotów CoW – zostaje
1572 -# atomowy staging + backup nadpisywanych plików.
1573 -SNAPSHOTS_DIR = "/.pag_snapshots"
1574 -SNAPSHOTS_DB = "/var/lib/pag/snapshots.json"
1575 -GRUB_SNAPSHOT_SCRIPT = "/etc/grub.d/40_pagan_snapshots"
1576 -
1577 -# Ścieżki współdzielone – NIE wchodzą do deploymentu (są symlinkami do /...)
1578 -SHARED_PATHS = {
1579 - "/var", "/etc", "/home", "/root", "/tmp", "/run",
1580 - "/dev", "/proc", "/sys", "/mnt", "/media", "/srv",
1581 - # /boot współdzielone: jądro + initramfs są wspólne dla wszystkich
1582 - # deploymentów (inaczej każdy trzyma własną ~50-100 MB kopię). GRUB
1583 - # wskazuje na /.deployments/<id>/boot → symlink do /boot.
1584 - "/boot",
1585 - "/.deployments", "/.pag_staging",
1586 -}
1587 -
1588 -def _is_shared_path(rel: str) -> bool:
1589 - """Sprawdza czy ścieżka należy do katalogów współdzielonych (poza deploymentem)."""
1590 - for sp in SHARED_PATHS:
1591 - if rel == sp or rel.startswith(sp + "/"):
1592 - return True
1593 - return False
1594 -
1595 -def _is_config_path(rel: str) -> bool:
1596 - """Czy ścieżka to plik konfiguracyjny (/etc/...)?
1597 -
1598 - Dla takich plików stosujemy .pacnew/.pacsave (zachowanie zmian użytkownika)
1599 - zamiast bezwarunkowego nadpisania/usunięcia."""
1600 - p = rel.lstrip("/")
1601 - return p == "etc" or p.startswith("etc/")
1602 -
1603 -# Wrażliwa konfiguracja auth/systemowa – NIGDY nie nadpisujemy jej po cichu.
1604 -# Nadpisanie /etc/pam.d/system-* przez pakiet (np. shadow) potrafi zablokować
1605 -# logowanie/sudo („account validation failure”); dla tych ścieżek zawsze robimy
1606 -# .pacnew, gdy treść na dysku różni się od tej z pakietu.
1607 -_SENSITIVE_CONFIG_RE = re.compile(
1608 - r'^(pam\.d/|security/|sudoers$|sudoers\.d/|shadow$|gshadow$|passwd$|group$|'
1609 - r'login\.defs$|nsswitch\.conf$|default/useradd$)')
1610 -
1611 -def _is_sensitive_config(rel: str) -> bool:
1612 - """Czy rel to wrażliwy plik /etc (PAM, sudoers, shadow, login.defs…)?"""
1613 - p = rel.lstrip("/")
1614 - if not p.startswith("etc/"):
1615 - return False
1616 - return bool(_SENSITIVE_CONFIG_RE.match(p[4:]))
1617 -
1618 -def _get_deployment_root() -> str:
1619 - """Zwraca ścieżkę do aktywnego deploymentu, lub PAG_ROOT jeśli tryb niemutowalny wyłączony."""
1620 - if os.environ.get("PAG_IMMUTABLE", "") in ("0", "no", "false", ""):
1621 - return PAG_ROOT
1622 - if os.path.islink(ACTIVE_LINK):
1623 - return os.readlink(ACTIVE_LINK)
1624 - if os.path.isdir(ACTIVE_LINK):
1625 - return ACTIVE_LINK
1626 - # Brak deploymentów – użyj /
1627 - return PAG_ROOT
1628 -
1629 -def _load_deployments() -> List[dict]:
1630 - """Wczytuje historię deploymentów."""
1631 - if not os.path.exists(DEPLOYMENTS_DB):
1632 - return []
1633 - try:
1634 - return json.load(open(DEPLOYMENTS_DB))
1635 - except Exception:
1636 - return []
1637 -
1638 -def _save_deployments(deployments: List[dict]):
1639 - os.makedirs(os.path.dirname(DEPLOYMENTS_DB), exist_ok=True)
1640 - json.dump(deployments, open(DEPLOYMENTS_DB, "w"), indent=2)
1641 -
1642 -def _create_deployment(pkg_names: List[str], action: str) -> Tuple[str, str]:
1643 - """
1644 - Tworzy nowy deployment przez skopiowanie aktywnego (CoW) i zwraca jego ścieżkę.
1645 - Zwraca (deployment_dir, deployment_id).
1646 - """
1647 - deploy_id = datetime.now().strftime("%Y%m%dT%H%M%S")
1648 - deploy_dir = os.path.join(DEPLOYMENTS_DIR, deploy_id)
1649 - os.makedirs(DEPLOYMENTS_DIR, exist_ok=True)
1650 -
1651 - active = _get_deployment_root()
1652 -
1653 - if os.path.isdir(active) and active != PAG_ROOT:
1654 - # Trójstopniowa strategia kopiowania deploymentu:
1655 - # 1. reflink (CoW – btrfs, xfs) → 0 MB kopiowane
1656 - # 2. hardlink (linki twarde) → 0 MB kopiowane, tylko inody
1657 - # 3. zwykłe cp (ostateczność) → pełna kopia
1658 - print(_(' ⚡ Copying the active deployment...'))
1659 - copied = False
1660 - for method, cmd, label in [
1661 - ("reflink", ["cp", "--reflink=auto", "-a", active + "/.", deploy_dir + "/"], _("reflink_method")),
1662 - ("hardlink", ["cp", "-al", active + "/.", deploy_dir + "/"], _("hardlink_method")),
1663 - ("copy", ["cp", "-a", active + "/.", deploy_dir + "/"], _("copy_method")),
1664 - ]:
1665 - try:
1666 - subprocess.run(cmd, check=True, timeout=600, capture_output=True)
1667 - print(_(' ✅ Deployment: {arg1} ({arg2})', arg1=(deploy_id), arg2=(label)))
1668 - copied = True
1669 - break
1670 - except subprocess.CalledProcessError:
1671 - if method == "copy":
1672 - raise # ostatnia deska – niech leci wyjątek
1673 - continue
1674 - if not copied:
1675 - raise RuntimeError(_("deploy_copy_failed"))
1676 - else:
1677 - # Pierwszy deployment – tylko katalogi szkieletowe
1678 - # /boot celowo POMINIĘTE – jest współdzielone (SHARED_PATHS); poniższa
1679 - # pętla utworzy w deploymencie symlink boot → /boot.
1680 - for d in ["/usr", "/lib", "/lib64", "/bin", "/sbin", "/opt"]:
1681 - if os.path.isdir(d):
1682 - dest = os.path.join(deploy_dir, d.lstrip("/"))
1683 - os.makedirs(dest, exist_ok=True)
1684 - print(_(' ✅ First deployment: {arg1}', arg1=(deploy_id)))
1685 -
1686 - # Utwórz symlinki do współdzielonych katalogów
1687 - for sp in SHARED_PATHS:
1688 - link_dst = os.path.join(deploy_dir, sp.lstrip("/"))
1689 - if not os.path.lexists(link_dst) and os.path.isdir(sp):
1690 - os.symlink(sp, link_dst)
1691 -
1692 - # Zapisz w bazie deploymentów
1693 - deployments = _load_deployments()
1694 - deployments.append({
1695 - "id": deploy_id,
1696 - "action": action,
1697 - "packages": pkg_names,
1698 - "timestamp": datetime.now().isoformat(),
1699 - "active": True,
1700 - })
1701 - # Oznacz poprzednie jako nieaktywne
1702 - for d in deployments[:-1]:
1703 - d["active"] = False
1704 - _save_deployments(deployments)
1705 -
1706 - return deploy_dir, deploy_id
1707 -
1708 -def _switch_deployment(deploy_dir: str) -> bool:
1709 - """Atomowo przełącza aktywny deployment przez podmianę symlinka."""
1710 - tmp_link = ACTIVE_LINK + ".new"
1711 - if os.path.lexists(tmp_link):
1712 - os.remove(tmp_link)
1713 - os.symlink(deploy_dir, tmp_link)
1714 - os.rename(tmp_link, ACTIVE_LINK) # atomowe na tym samym FS
1715 - return True
1716 -
1717 -# =============================================================================
1718 -# SNAPSHOTY SYSTEMU (CoW – btrfs)
1719 -# =============================================================================
1720 -# Snapshot powstaje PRZED transakcją. Na btrfs to subwolumen (kilka KB
1721 -# metadanych, reszta to współdzielone bloki), więc nie kopiujemy całego
1722 -# systemu. Wpis GRUB pozwala uruchomić system z wybranej migawki.
1723 -# Na ext4/xfs nie ma CoW – instalacja nadal jest atomowa dzięki stagingowi,
1724 -# a rollback opiera się na backupie nadpisywanych plików.
1725 -
1726 -def _btrfs_bin() -> str:
1727 - """Ścieżka do btrfs (PATH bywa okrojony w chroocie/instalatorze)."""
1728 - found = shutil.which("btrfs")
1729 - if found:
1730 - return found
1731 - for cand in ("/usr/bin/btrfs", "/usr/sbin/btrfs", "/sbin/btrfs", "/bin/btrfs"):
1732 - if os.path.exists(cand):
1733 - return cand
1734 - return ""
1735 -
1736 -
1737 -def _root_fstype() -> str:
1738 - try:
1739 - r = subprocess.run(["findmnt", "-n", "-o", "FSTYPE", "/"],
1740 - capture_output=True, text=True, timeout=5)
1741 - fs = r.stdout.strip().splitlines()[0].strip() if r.stdout.strip() else ""
1742 - if fs:
1743 - return fs
1744 - except Exception:
1745 - pass
1746 - try:
1747 - r = subprocess.run(["stat", "-f", "-c", "%T", "/"],
1748 - capture_output=True, text=True, timeout=5)
1749 - return r.stdout.strip()
1750 - except Exception:
1751 - return ""
1752 -
1753 -
1754 -def _btrfs_root_path() -> str:
1755 - """Ścieżka aktywnego subwolumenu root względem top-level btrfs."""
1756 - btrfs = _btrfs_bin()
1757 - if btrfs:
1758 - try:
1759 - r = subprocess.run([btrfs, "subvolume", "show", "/"],
1760 - capture_output=True, text=True, timeout=5)
1761 - if r.returncode == 0:
1762 - for line in r.stdout.splitlines():
1763 - line = line.strip()
1764 - if line.lower().startswith("path:"):
1765 - p = line.split(":", 1)[1].strip()
1766 - if p in ("", "/"):
1767 - return "/"
1768 - return p.strip("/")
1769 - except Exception:
1770 - pass
1771 - try:
1772 - r = subprocess.run(["findmnt", "-n", "-o", "FSROOT", "/"],
1773 - capture_output=True, text=True, timeout=5)
1774 - p = r.stdout.strip()
1775 - if p and p != "/":
1776 - return p.strip("/")
1777 - except Exception:
1778 - pass
1779 - return "/"
1780 -
1781 -
1782 -def _snapshot_support() -> Tuple[bool, str]:
1783 - fs = _root_fstype()
1784 - if fs != "btrfs":
1785 - return False, (f"root jest na {fs or 'nieznanym systemie plików'} – "
1786 - f"snapshoty CoW wymagają btrfs")
1787 - if not _btrfs_bin():
1788 - return False, "brak narzędzia btrfs (zainstaluj pakiet btrfs-progs)"
1789 - return True, ""
1790 -
1791 -
1792 -def _load_snapshots() -> List[dict]:
1793 - if not os.path.exists(SNAPSHOTS_DB):
1794 - return []
1795 - try:
1796 - data = load_json(SNAPSHOTS_DB)
1797 - return data if isinstance(data, list) else []
1798 - except Exception:
1799 - return []
1800 -
1801 -
1802 -def _save_snapshots(items: List[dict]):
1803 - os.makedirs(os.path.dirname(SNAPSHOTS_DB), exist_ok=True)
1804 - save_json(SNAPSHOTS_DB, items)
1805 -
1806 -
1807 -def _snapshot_label(snap: dict) -> str:
1808 - """Czytelna etykieta GRUB (bez znaków, które psują menu)."""
1809 - pkgs = list(snap.get("packages") or [])
1810 - p = ", ".join(pkgs[:3])
1811 - if len(pkgs) > 3:
1812 - p += f" +{len(pkgs) - 3}"
1813 - base = f"Pagan Linux snapshot {snap.get('id', '?')}"
1814 - if snap.get("label"):
1815 - base += f" - {snap['label']}"
1816 - if p:
1817 - base += f" - {p}"
1818 - # GRUB: usuń apostrofy i znaki kontrolne.
1819 - return re.sub(r"[\x00-\x1f']", "", base)[:120]
1820 -
1821 -
1822 -def _root_boot_arg() -> str:
1823 - """`root=UUID=...` dla wpisu GRUB (stabilne po zmianie nazw urządzeń)."""
1824 - dev = _detect_root_device()
1825 - if not dev:
1826 - return ""
1827 - if dev.startswith(("UUID=", "PARTUUID=", "LABEL=", "PARTLABEL=")):
1828 - return f" root={dev}"
1829 - uuid = ""
1830 - try:
1831 - r = subprocess.run(["blkid", "-s", "UUID", "-o", "value", dev],
1832 - capture_output=True, text=True, timeout=5)
1833 - uuid = r.stdout.strip().splitlines()[0].strip() if r.stdout.strip() else ""
1834 - except Exception:
1835 - uuid = ""
1836 - return f" root=UUID={uuid}" if uuid else f" root={dev}"
1837 -
1838 -
1839 -def _initrd_for_kernel(boot_dir: str, kernel: str) -> str:
1840 - """Nazwa initramfs pasująca do jądra (initramfs.img / initramfs-<ver>.img…)."""
1841 - if not kernel or not os.path.isdir(boot_dir):
1842 - return ""
1843 - ver = kernel[len("vmlinuz-"):] if kernel.startswith("vmlinuz-") else ""
1844 - candidates = []
1845 - if ver:
1846 - candidates += [f"initramfs-{ver}.img", f"initrd.img-{ver}"]
1847 - candidates += ["initramfs.img", "initrd.img"]
1848 - for c in candidates:
1849 - if os.path.isfile(os.path.join(boot_dir, c)):
1850 - return c
1851 - for f in sorted(os.listdir(boot_dir)):
1852 - if f.startswith(("initramfs", "initrd")):
1853 - return f
1854 - return ""
1855 -
1856 -
1857 -def _pick_kernel_initrd(boot_dir: str) -> Tuple[str, str]:
1858 - kernels = sorted(
1859 - [f for f in os.listdir(boot_dir) if f.startswith("vmlinuz-")],
1860 - reverse=True,
1861 - ) if os.path.isdir(boot_dir) else []
1862 - if not kernels:
1863 - return "", ""
1864 - k = kernels[0]
1865 - return k, _initrd_for_kernel(boot_dir, k)
1866 -
1867 -
1868 -def _grub_snapshot_entries() -> List[str]:
1869 - """Wpisy menu GRUB dla snapshotów (dla `_update_grub_config` i grub.d)."""
1870 - snaps = _load_snapshots()
1871 - if not snaps:
1872 - return []
1873 -
1874 - root_arg = _root_boot_arg()
1875 - try:
1876 - separate_boot = os.path.isdir("/boot") and os.path.ismount("/boot")
1877 - except OSError:
1878 - separate_boot = False
1879 - bp = _boot_prefix()
1880 -
1881 - lines: List[str] = []
1882 - for snap in reversed(snaps):
1883 - path = snap.get("path") or ""
1884 - if not path or not os.path.isdir(path):
1885 - continue
1886 -
1887 - if separate_boot:
1888 - # Osobne /boot jest współdzielone: użyj jądra ZAPISANEGO przy
1889 - # tworzeniu snapshotu (o ile nadal leży w /boot), a nie zawsze
1890 - # najnowszego – nowe jądro mogło być właśnie przyczyną problemu.
1891 - kname = snap.get("kernel") or ""
1892 - if not kname or not os.path.isfile(os.path.join("/boot", kname)):
1893 - kname, _ = _pick_kernel_initrd("/boot")
1894 - iname = _initrd_for_kernel("/boot", kname) if kname else ""
1895 - kernel = f"{bp}/{kname}" if kname else ""
1896 - initrd = f"{bp}/{iname}" if iname else ""
1897 - else:
1898 - snap_boot = os.path.join(path, "boot")
1899 - kname, iname = _pick_kernel_initrd(snap_boot)
1900 - # Kopia zapasowa: jądro z bieżącego /boot (np. gdy /boot nie
1901 - # było częścią snapshotu lub jest to bardzo stara migawka).
1902 - if not kname:
1903 - kname, iname = _pick_kernel_initrd("/boot")
1904 - kernel = f"{bp}/{kname}" if kname else ""
1905 - initrd = f"{bp}/{iname}" if iname else ""
1906 - else:
1907 - kernel = f"{path}/boot/{kname}"
1908 - initrd = f"{path}/boot/{iname}" if iname else ""
1909 -
1910 - if not kernel:
1911 - continue
1912 -
1913 - subvol = snap.get("subvol") or ""
1914 - flags = f" rootflags=subvol={subvol} rootfstype=btrfs" if subvol else ""
1915 - label = _snapshot_label(snap)
1916 -
1917 - lines.append(f"menuentry '{label}' --class pagan --class gnu-linux --class os {{")
1918 - lines.append(f" linux {kernel}{root_arg}{flags} rw quiet")
1919 - if initrd:
1920 - lines.append(f" initrd {initrd}")
1921 - lines.append("}")
1922 - lines.append("")
1923 - return lines
1924 -
1925 -
1926 -def _ensure_snapshot_grub_script() -> bool:
1927 - """Instaluje /etc/grub.d/40_pagan_snapshots (integracja z grub-mkconfig)."""
1928 - if not os.path.isdir("/etc/grub.d"):
1929 - return False
1930 - # Preferuj BIEŻĄCĄ binarkę (np. testy z repo), a nie starszy /usr/bin/pag:
1931 - # stary pag nie zna `snapshot-grub` i uruchomiłby smart-search.
1932 - _self = os.path.abspath(sys.argv[0]) if sys.argv[0] else ""
1933 - exe = _self if _self and os.path.isfile(_self) else (shutil.which("pag") or "/usr/bin/pag")
1934 - if not exe or not os.path.exists(exe):
1935 - exe = "/usr/bin/pag"
1936 - quoted = exe.replace("'", "'\\''")
1937 - script = (
1938 - "#!/bin/sh\n"
1939 - "# Pagan Linux – wpisy GRUB dla snapshotów systemu (wygenerowane przez pag)\n"
1940 - "# Usuń ten plik, aby ukryć snapshoty w menu GRUB.\n"
1941 - f"PAG_BIN='{quoted}'\n"
1942 - 'if [ ! -x "$PAG_BIN" ]; then\n'
1943 - ' PAG_BIN="$(command -v pag 2>/dev/null || true)"\n'
1944 - "fi\n"
1945 - '[ -x "$PAG_BIN" ] || exit 0\n'
1946 - '# Tylko pag >= 4.1 zna komendę snapshot-grub (starszy zrobiłby\n'
1947 - '# smart-search i mógłby zawiesić grub-mkconfig na sieci).\n'
1948 - 'case "$("$PAG_BIN" --version 2>/dev/null)" in\n'
1949 - ' "pag 4."[1-9]*|"pag "[5-9]*|"pag "[1-9][0-9]*) ;;\n'
1950 - ' *) exit 0 ;;\n'
1951 - 'esac\n'
1952 - 'exec "$PAG_BIN" snapshot-grub\n'
1953 - )
1954 - try:
1955 - with open(GRUB_SNAPSHOT_SCRIPT, "w", encoding="utf-8") as fh:
1956 - fh.write(script)
1957 - os.chmod(GRUB_SNAPSHOT_SCRIPT, 0o755)
1958 - return True
1959 - except OSError:
1960 - return False
1961 -
1962 -
1963 -def _create_system_snapshot(packages: List[str], action: str,
1964 - label: str = "") -> Optional[dict]:
1965 - """Tworzy snapshot root (btrfs) i zapisuje go w bazie.
1966 -
1967 - Zwraca dict snapshotu albo None. Nie przerywa instalacji – o tym decyduje
1968 - wywołujący (tryb --snapshot wymaga sukcesu, tryb auto tylko ostrzega).
1969 - """
1970 - ok, why = _snapshot_support()
1971 - if not ok:
1972 - return None
1973 - btrfs = _btrfs_bin()
1974 - try:
1975 - os.makedirs(SNAPSHOTS_DIR, exist_ok=True)
1976 - except OSError as e:
1977 - print(_(' ⚠ Cannot create {arg1}: {arg2}', arg1=(SNAPSHOTS_DIR), arg2=(e)), file=sys.stderr)
1978 - return None
1979 -
1980 - base_id = datetime.now().strftime("%Y%m%dT%H%M%S")
1981 - snap_id = base_id
1982 - n = 1
1983 - while os.path.lexists(os.path.join(SNAPSHOTS_DIR, snap_id)):
1984 - snap_id = f"{base_id}-{n}"
1985 - n += 1
1986 - snap_path = os.path.join(SNAPSHOTS_DIR, snap_id)
1987 -
1988 - try:
1989 - r = subprocess.run([btrfs, "subvolume", "snapshot", "/", snap_path],
1990 - capture_output=True, text=True, timeout=600)
1991 - except Exception as e:
1992 - print(_(' ⚠ Failed to create snapshot: {arg1}', arg1=(e)), file=sys.stderr)
1993 - return None
1994 - if r.returncode != 0:
1995 - msg = (r.stderr or r.stdout or "").strip().splitlines()
1996 - print(_(' ⚠ btrfs snapshot failed: {arg1}', arg1=(msg[-1] if msg else r.returncode)),
1997 - file=sys.stderr)
1998 - return None
1999 -
2000 - rootp = _btrfs_root_path()
2001 - if rootp in ("", "/"):
2002 - subvol = f"/.pag_snapshots/{snap_id}"
2003 - else:
2004 - subvol = f"{rootp}/.pag_snapshots/{snap_id}"
2005 -
2006 - # Zapamiętaj jądro/initramfs z chwili snapshotu – przy osobnym /boot
2007 - # dzięki temu uruchomimy migawkę ze STARYM (działającym) jądrem.
2008 - _kn, _ir = _pick_kernel_initrd("/boot")
2009 - snap = {
2010 - "id": snap_id,
2011 - "path": snap_path,
2012 - "subvol": subvol,
2013 - "created": datetime.now().isoformat(),
2014 - "action": action,
2015 - "label": label,
2016 - "packages": list(packages)[:100],
2017 - "kernel": _kn,
2018 - "initrd": _ir,
2019 - }
2020 - items = _load_snapshots()
2021 - items.append(snap)
2022 - _save_snapshots(items)
2023 - _ensure_snapshot_grub_script()
2024 - print(_(' 📸 System snapshot: {arg1} (subvol={arg2})', arg1=(snap_id), arg2=(subvol)))
2025 - return snap
2026 -
2027 -
2028 -def _find_snapshot(snap_id: str) -> Optional[dict]:
2029 - items = _load_snapshots()
2030 - if not snap_id:
2031 - return items[-1] if items else None
2032 - for s in items:
2033 - if s.get("id") == snap_id:
2034 - return s
2035 - for s in items:
2036 - if str(s.get("id", "")).startswith(snap_id):
2037 - return s
2038 - return None
2039 -
2040 -
2041 -def cmd_snapshot_list():
2042 - items = _load_snapshots()
2043 - if not items:
2044 - print(_("snapshot_none"))
2045 - return 0
2046 - print(_("snapshot_list", len(items)))
2047 - for s in reversed(items):
2048 - pkgs = list(s.get("packages") or [])
2049 - listed = ", ".join(pkgs[:4])
2050 - if len(pkgs) > 4:
2051 - listed += f" +{len(pkgs) - 4}"
2052 - print(f" {s.get('id', '?')} [{_action_label(s.get('action', ''))}]")
2053 - if listed:
2054 - print(f" {listed}")
2055 - print(f" {s.get('created', '')}")
2056 - print(f" {s.get('path', '')}")
2057 - return 0
2058 -
2059 -
2060 -def cmd_snapshot_grub():
2061 - """Wypisuje menuentry dla grub-mkconfig (wywoływane z 40_pagan_snapshots)."""
2062 - for line in _grub_snapshot_entries():
2063 - print(line)
2064 - return 0
2065 -
2066 -
2067 -def cmd_snapshot_create(label: str = ""):
2068 - ok, why = _snapshot_support()
2069 - if not ok:
2070 - print(f" ❌ {_('snapshot_unsupported', why)}")
2071 - return 1
2072 - snap = _create_system_snapshot([], "manual", label=label)
2073 - if not snap:
2074 - return 1
2075 - _ensure_snapshot_grub_script()
2076 - _refresh_bootloader()
2077 - print(f" ✅ {_('snapshot_created', snap['id'])}")
2078 - return 0
2079 -
2080 -
2081 -def cmd_snapshot_delete(snap_id: str):
2082 - snap = _find_snapshot(snap_id)
2083 - if not snap:
2084 - print(f" ❌ {_('snapshot_not_found', snap_id)}")
2085 - return 1
2086 - path = snap.get("path") or ""
2087 - if not path.startswith(SNAPSHOTS_DIR + "/"):
2088 - print(_(' ❌ Invalid snapshot path – refusing to delete.'))
2089 - return 1
2090 - if os.path.isdir(path):
2091 - btrfs = _btrfs_bin()
2092 - if not btrfs:
2093 - print(f" ❌ {_('snapshot_unsupported', 'brak btrfs')}")
2094 - return 1
2095 - r = subprocess.run([btrfs, "subvolume", "delete", path],
2096 - capture_output=True, text=True, timeout=120)
2097 - if r.returncode != 0:
2098 - print(f" ❌ btrfs: {(r.stderr or '').strip()[:200]}")
2099 - return 1
2100 - _save_snapshots([s for s in _load_snapshots() if s.get("id") != snap.get("id")])
2101 - _refresh_bootloader()
2102 - print(f" ✅ {_('snapshot_deleted', snap.get('id', ''))}")
2103 - return 0
2104 -
2105 -
2106 -def cmd_snapshot_rollback(snap_id: str = ""):
2107 - """Ustawia snapshot jako następny start (albo pokazuje wybór w GRUB)."""
2108 - snap = _find_snapshot(snap_id)
2109 - if not snap:
2110 - print(f" ❌ {_('snapshot_not_found', snap_id or '(brak)' )}")
2111 - return 1
2112 - if not os.path.isdir(snap.get("path") or ""):
2113 - print(f" ❌ {_('snapshot_not_found', snap.get('id', ''))}")
2114 - return 1
2115 -
2116 - label = _snapshot_label(snap)
2117 - print(_(' ⏪ Snapshot: {arg1}', arg1=(snap.get('id', ''))))
2118 - print(f" {snap.get('created', '')}")
2119 - pkgs = list(snap.get("packages") or [])
2120 - if pkgs:
2121 - print(f" {', '.join(pkgs[:8])}{' …' if len(pkgs) > 8 else ''}")
2122 - if not _ask_confirm():
2123 - return 0
2124 -
2125 - _ensure_snapshot_grub_script()
2126 - _refresh_bootloader()
2127 -
2128 - grub_reboot = shutil.which("grub-reboot") or shutil.which("grub2-reboot")
2129 - if grub_reboot:
2130 - r = subprocess.run([grub_reboot, label], capture_output=True, text=True)
2131 - if r.returncode == 0:
2132 - print(f" ✅ {_('snapshot_rollback_next', label)}")
2133 - print(_(' 💡 Reboot the system – GRUB will boot the selected snapshot.'))
2134 - return 0
2135 - print(f" ℹ {_('snapshot_rollback_hint', label)}")
2136 - print(_(' 💡 At boot, choose an entry in the GRUB menu (snapshots section).'))
2137 - return 0
2138 -
2139 -
2140 -DEFAULT_REPOS = [
2141 - "https://repo.paganlinux.eu/stable/",
2142 -]
2143 -
2144 -# =============================================================================
2145 -# INICJALIZACJA
2146 -# =============================================================================
2147 -
2148 -def _require_dir(d: str) -> None:
2149 - """Utwórz katalog, a przy istniejącej NIE-katalogowej ścieżce podaj powód.
2150 -
2151 - `os.makedirs(..., exist_ok=True)` nie wystarcza: gdy `mkdir` zwróci EEXIST,
2152 - Python sprawdza `os.path.isdir(path)`, a dla MARTWEGO dowiązania to False –
2153 - wyjątek leci dalej. Objaw: `pag update` kończył się tracebackiem
2154 - `FileExistsError: /var/cache/pag -> /home/pagan-build/cache-pag` (cel
2155 - dowiązania został skasowany).
2156 - """
2157 - try:
2158 - os.makedirs(d, exist_ok=True)
2159 - return
2160 - except FileExistsError:
2161 - pass
2162 - except OSError as e:
2163 - print(f"❌ Nie mogę utworzyć {d}: {e}")
2164 - sys.exit(1)
2165 - if os.path.islink(d) and not os.path.exists(d):
2166 - print(f"❌ {d} jest martwym dowiązaniem → {os.readlink(d)}")
2167 - print(f" Usuń dowiązanie (rm {d}) albo utwórz katalog docelowy.")
2168 - else:
2169 - print(f"❌ {d} istnieje, ale nie jest katalogiem.")
2170 - sys.exit(1)
2171 -
2172 -
2173 -def ensure_dirs():
2174 - for d in [PAG_DB, PAG_CACHE, PAG_CONF, REPO_CACHE, REPOS_DIR, STAGING_DIR, DEPLOYMENTS_DIR]:
2175 - _require_dir(d)
2176 - for f, default in [
2177 - (REPOS_CONF, "\n".join(DEFAULT_REPOS) + "\n"),
2178 - (INSTALLED_DB, "{}"),
2179 - (PINNED_FILE, "{}"),
2180 - (HISTORY_FILE, "[]"),
2181 - ]:
2182 - if not os.path.exists(f):
2183 - with open(f, "w") as fh: fh.write(default)
2184 - if not os.path.exists(WORLD_FILE):
2185 - Path(WORLD_FILE).touch()
2186 - if not os.path.exists(GPG_HOME):
2187 - os.makedirs(GPG_HOME, exist_ok=True)
2188 - os.chmod(GPG_HOME, 0o700)
2189 - _gpg_run("--list-keys", capture_output=True)
2190 - # Inicjalizuj SQLite
2191 - _db_init()
2192 - # Wyczyść staging po poprzednim przerwanym buildzie/instalacji
2193 - if os.path.isdir(STAGING_DIR):
2194 - for entry in os.listdir(STAGING_DIR):
2195 - if entry == "backups":
2196 - continue # backupy starych wersji – potrzebne do `pag rollback`
2197 - path = os.path.join(STAGING_DIR, entry)
2198 - try:
2199 - if os.path.isfile(path) or os.path.islink(path):
2200 - os.unlink(path)
2201 - elif os.path.isdir(path):
2202 - shutil.rmtree(path, ignore_errors=True)
2203 - except OSError:
2204 - pass
2205 -
2206 -# =============================================================================
2207 -# SQLITE – BAZA PLIKÓW (poprawne zarządzanie połączeniami)
2208 -# =============================================================================
2209 -
2210 -from contextlib import contextmanager
2211 -
2212 -@contextmanager
2213 -def _db_session(readonly: Optional[bool] = None):
2214 - """Context manager – gwarantuje zamknięcie połączenia.
2215 -
2216 - Gdy katalog bazy nie jest zapisywalny (np. komenda read-only uruchomiona
2217 - jako zwykły user), otwieramy połączenie w trybie read-only. Inaczej
2218 - `PRAGMA journal_mode=WAL` próbuje pisać i kończy się błędem
2219 - „attempt to write a readonly database” zamiast zwrócić wynik.
2220 - """
2221 - if readonly is None:
2222 - readonly = not os.access(os.path.dirname(FILES_DB_SQL) or ".", os.W_OK)
2223 - if readonly:
2224 - # Katalog bazy nie jest zapisywalny (np. komenda read-only uruchomiona
2225 - # jako zwykły user). Baza jest w trybie WAL, więc SQLite przy `mode=ro`
2226 - # próbuje utworzyć plik `-shm` w katalogu – bez prawa zapisu kończy się
2227 - # to błędem „attempt to write a readonly database” nawet przy SELECT.
2228 - # Dlatego próbujemy zwykłego `mode=ro`, a gdy zawiedzie, otwieramy z
2229 - # `immutable=1` (SQLite pomija wtedy WAL/SHM i czyta ostatni
2230 - # checkpoint). Przy równoległym zapisie roota odczyt może być chwilowo
2231 - # nieaktualny – dla komend diagnostycznych (files/list/verify) to OK.
2232 - conn = sqlite3.connect(f"file:{FILES_DB_SQL}?mode=ro", uri=True, timeout=15)
2233 - try:
2234 - conn.execute("SELECT 1 FROM sqlite_master LIMIT 1")
2235 - except sqlite3.OperationalError:
2236 - conn.close()
2237 - conn = sqlite3.connect(
2238 - f"file:{FILES_DB_SQL}?mode=ro&immutable=1", uri=True, timeout=15)
2239 - else:
2240 - conn = sqlite3.connect(FILES_DB_SQL, timeout=15)
2241 - conn.execute("PRAGMA journal_mode=WAL")
2242 - conn.execute("PRAGMA synchronous=NORMAL")
2243 - conn.execute("PRAGMA foreign_keys=ON")
2244 - conn.execute("PRAGMA busy_timeout=15000")
2245 - conn.row_factory = sqlite3.Row
2246 - try:
2247 - yield conn
2248 - if not readonly:
2249 - conn.commit()
2250 - except Exception:
2251 - if not readonly:
2252 - conn.rollback()
2253 - raise
2254 - finally:
2255 - conn.close()
2256 -
2257 -
2258 -def _db_init():
2259 - """Tworzy tabele SQLite jeśli nie istnieją."""
2260 - with _db_session() as db:
2261 - db.execute("""
2262 - CREATE TABLE IF NOT EXISTS files (
2263 - id INTEGER PRIMARY KEY AUTOINCREMENT,
2264 - path TEXT NOT NULL,
2265 - package TEXT NOT NULL,
2266 - sha256 TEXT,
2267 - size INTEGER,
2268 - is_symlink INTEGER DEFAULT 0,
2269 - symlink_target TEXT,
2270 - UNIQUE(path, package)
2271 - )
2272 - """)
2273 - db.execute("CREATE INDEX IF NOT EXISTS idx_files_path ON files(path)")
2274 - db.execute("CREATE INDEX IF NOT EXISTS idx_files_pkg ON files(package)")
2275 - db.execute("""
2276 - CREATE TABLE IF NOT EXISTS file_checksums (
2277 - path TEXT PRIMARY KEY,
2278 - sha256 TEXT NOT NULL,
2279 - installed_at TEXT
2280 - )
2281 - """)
2282 - db.commit()
2283 -
2284 -def _db_record_files(pkg_name: str, files: List[dict]):
2285 - """Zapisuje pliki do SQLite (obsługuje symlinki)."""
2286 - with _db_session() as db:
2287 - # Jawna transakcja – atomowość obu zapisów i szybsze wykrycie blokady
2288 - try:
2289 - db.execute("BEGIN IMMEDIATE")
2290 - except sqlite3.OperationalError:
2291 - pass # transakcja już otwarta (implicit)
2292 - db.executemany(
2293 - "INSERT OR REPLACE INTO files (path, package, sha256, size, is_symlink, symlink_target) "
2294 - "VALUES (?,?,?,?,?,?)",
2295 - [(f["path"], pkg_name, f.get("sha256",""), f.get("size",0),
2296 - f.get("is_symlink", 0), f.get("symlink_target", ""))
2297 - for f in files]
2298 - )
2299 - db.executemany(
2300 - "INSERT OR REPLACE INTO file_checksums (path, sha256, installed_at) VALUES (?,?,?)",
2301 - [(f["path"], f.get("sha256",""), datetime.now().isoformat())
2302 - for f in files if f.get("sha256")]
2303 - )
2304 -
2305 -def _db_get_package_files(pkg_name: str) -> List[str]:
2306 - with _db_session() as db:
2307 - return [r["path"] for r in db.execute(
2308 - "SELECT DISTINCT path FROM files WHERE package=?", (pkg_name,)
2309 - )]
2310 -
2311 -def _db_get_file_owners(filepath: str) -> List[str]:
2312 - """Zwraca listę pakietów będących właścicielami pliku."""
2313 - with _db_session() as db:
2314 - return [r["package"] for r in db.execute(
2315 - "SELECT package FROM files WHERE path=?", (filepath,)
2316 - )]
2317 -
2318 -def _db_remove_package_files(pkg_name: str):
2319 - with _db_session() as db:
2320 - db.execute("DELETE FROM files WHERE package=?", (pkg_name,))
2321 - db.commit()
2322 -
2323 -def _db_get_all_file_checksums() -> Dict[str, str]:
2324 - with _db_session() as db:
2325 - return {r["path"]: r["sha256"] for r in db.execute("SELECT path, sha256 FROM file_checksums")}
2326 -
2327 -def _db_get_package_checksums(pkg_name: str) -> Dict[str, str]:
2328 - """Sumy SHA256 zapisane dla plików należących do pakietu.
2329 -
2330 - Używane do wykrycia, czy użytkownik zmodyfikował plik konfiguracyjny
2331 - (porównanie z sumą z chwili instalacji) – serce mechanizmu .pacnew/.pacsave.
2332 - """
2333 - with _db_session() as db:
2334 - return {r["path"]: r["sha256"] for r in db.execute(
2335 - "SELECT fc.path AS path, fc.sha256 AS sha256 FROM file_checksums fc "
2336 - "JOIN files f ON f.path = fc.path WHERE f.package=?", (pkg_name,))}
2337 -
2338 -
2339 -def _db_count_files() -> int:
2340 - with _db_session() as db:
2341 - return db.execute("SELECT COUNT(*) FROM files").fetchone()[0]
2342 -
2343 -# =============================================================================
2344 -# BLOKADA
2345 -# =============================================================================
2346 -
2347 -class DatabaseLock:
2348 - """Blokada plikowa (flock) – jądro zwalnia ją AUTOMATYCZNIE, gdy proces
2349 - ginie (kill -9, twardy reset). Stary PID-file miał race condition: po
2350 - śmierci pag PID mógł zostać przydzielony obcemu procesowi (PID reuse)
2351 - i pag odmawiał działania na zawsze („baza zablokowana”).
2352 - """
2353 - def __init__(self):
2354 - self._f = None
2355 - def __enter__(self):
2356 - os.makedirs(os.path.dirname(LOCK_FILE), exist_ok=True)
2357 - self._f = open(LOCK_FILE, "w")
2358 - try:
2359 - # LOCK_NB: rzuca wyjątek zamiast czekać w nieskończoność
2360 - fcntl.flock(self._f, fcntl.LOCK_EX | fcntl.LOCK_NB)
2361 - except BlockingIOError:
2362 - print(f"❌ {_('db_locked')}", file=sys.stderr)
2363 - print(f" {_('db_lock_hint', LOCK_FILE)}", file=sys.stderr)
2364 - sys.exit(1)
2365 - self._f.write(str(os.getpid()))
2366 - self._f.flush()
2367 - return self
2368 - def __exit__(self, *args):
2369 - if self._f:
2370 - try:
2371 - fcntl.flock(self._f, fcntl.LOCK_UN)
2372 - except OSError:
2373 - pass
2374 - self._f.close()
2375 - self._f = None
2376 - # Uwaga: NIE usuwamy pliku blokady. Stały plik + flock na inode to jedyny
2377 - # bezpieczny wzorzec – os.remove(), gdy inny proces trzyma blokadę na starym
2378 - # inode, otwiera wyścig (nowy proces blokowałby nowo utworzony inode).
2379 -
2380 -
2381 -class SelfUpdateLock:
2382 - """Blokada podmiany binarki pag podczas self-update.
2383 -
2384 - Niezależna od DatabaseLock (inny plik) – cmd_self_update może zostać
2385 - wywołane poza globalną blokadą (np. z zewnętrznego skryptu), a dwie
2386 - równoległe aktualizacje pisałyby do tego samego `dst.new`; `os.replace`
2387 - mógłby wtedy podmienić plik w trakcie wykonywania (uszkodzony pag).
2388 - """
2389 - def __init__(self):
2390 - self._f = None
2391 -
2392 - def __enter__(self):
2393 - lock_path = LOCK_FILE + ".self-update"
2394 - os.makedirs(os.path.dirname(lock_path), exist_ok=True)
2395 - self._f = open(lock_path, "w")
2396 - try:
2397 - fcntl.flock(self._f, fcntl.LOCK_EX | fcntl.LOCK_NB)
2398 - except BlockingIOError:
2399 - self._f.close()
2400 - self._f = None
2401 - print(_('❌ Another pag update is in progress – try again later.'),
2402 - file=sys.stderr)
2403 - sys.exit(1)
2404 - self._f.write(str(os.getpid()))
2405 - self._f.flush()
2406 - return self
2407 -
2408 - def __exit__(self, *args):
2409 - if self._f:
2410 - try:
2411 - fcntl.flock(self._f, fcntl.LOCK_UN)
2412 - except OSError:
2413 - pass
2414 - self._f.close()
2415 - self._f = None
2416 -
2417 -# =============================================================================
2418 -# POMOCNICZE
2419 -# =============================================================================
2420 -
2421 -
2422 -# Katalogi systemowe. /bin, /sbin i /lib64 to na usrmerge symlinki do
2423 -# /usr/bin, /usr/bin i /usr/lib64 – bez nich pag pomijał CAŁĄ zawartość
2424 -# pakietów, które pakują pliki „starymi” ścieżkami (np. busybox: 386 plików
2425 -# w ./bin/, w tym sam ./bin/busybox → "BLOCKED: ./bin/ls" i spółka).
2426 -_ALLOWED_PREFIXES = ("/usr/", "/etc/", "/var/", "/opt/",
2427 - "/boot/", "/lib/", "/lib64/", "/run/",
2428 - "/bin/", "/sbin/", # usrmerge: bin→usr/bin, sbin→usr/bin
2429 - # Pliki wewnętrzne paczki .pkg.tar.xz
2430 - "metadata.json", "data.tar.xz", "hooks/",
2431 - "sums.json")
2432 -
2433 -def _check_path_safety(name: str) -> bool:
2434 - # Normalizuj – usuń leading ./
2435 - if name.startswith("./"):
2436 - name = name[2:]
2437 - if name in (".", ""):
2438 - return True
2439 - # Porównuj z prefiksami BEZ wiodącego '/', by zarówno "/usr/bin/ls", jak i
2440 - # wewnętrzne pliki pakietu ("hooks/pre-install", "data.tar.xz") przechodziły.
2441 - norm = name.lstrip("/")
2442 - for prefix in _ALLOWED_PREFIXES:
2443 - p = prefix.lstrip("/").rstrip("/")
2444 - if norm == p or norm.startswith(p + "/"):
2445 - return True
2446 - return False
2447 -
2448 -
2449 -def _validate_pkg_name(name):
2450 - return bool(ALLOWED_PKG_RE.match(name))
2451 -
2452 -
2453 -
2454 -def _audit(msg):
2455 - from datetime import datetime, timezone
2456 - os.makedirs(os.path.dirname(AUDIT_LOG), exist_ok=True)
2457 - with open(AUDIT_LOG, "a") as f:
2458 - f.write(datetime.now(timezone.utc).isoformat() + " " + msg + "\n")
2459 -
2460 -def _strip_suid(path):
2461 - try:
2462 - st = os.stat(path)
2463 - if st.st_mode & 0o4000:
2464 - os.chmod(path, st.st_mode & ~0o4000)
2465 - print(f" {_("sec_suid", path=path)}")
2466 - except OSError:
2467 - pass
2468 -
2469 -def _check_downgrade(pkg_name, new_ver, installed_db):
2470 - if pkg_name in installed_db:
2471 - old = installed_db[pkg_name].get("version", "0")
2472 - if new_ver < old:
2473 - print(f" {_("sec_downgrade", pkg=pkg_name, new=new_ver, old=old)}")
2474 - return False
2475 - return True
2476 -
2477 -def _safe_extractall(tar: tarfile.TarFile, dest: str, *, preserve_perms: bool = True,
2478 - privileged=frozenset()):
2479 - """
2480 - Bezpieczne rozpakowanie archiwum tar z ochroną przed Directory Traversal.
2481 -
2482 - Działa na Python < 3.12 (gdzie parametr 'filter' w extractall nie istnieje)
2483 - oraz na Python 3.12+. W przeciwieństwie do filtra 'data' z Pythona 3.12,
2484 - zachowuje bity uprawnień POSIX (SUID, SGID, sticky) – preserve_perms=True.
2485 -
2486 - Ochrona oparta jest na FINALNEJ ścieżce (os.path.realpath), nie tylko na
2487 - prostym sprawdzaniu stringa:
2488 - - Blokuje ścieżki absolutne i z '..' (path traversal)
2489 - - Blokuje symlinki/hardlinki, których cel wychodzi poza dest
2490 - - Blokuje zapis "przez" złośliwy symlink, który został wcześniej
2491 - rozpakowany (np. katalog → /etc, potem zapis katalog/plik)
2492 - - Zachowuje oryginalne uprawnienia plików
2493 - """
2494 - dest_real = os.path.realpath(dest)
2495 - os.makedirs(dest_real, exist_ok=True)
2496 -
2497 - def _target_within(path: str) -> bool:
2498 - try:
2499 - return os.path.commonpath([dest_real, os.path.realpath(path)]) == dest_real
2500 - except ValueError:
2501 - # różne napędy / ścieżki nie da się wspólnie porównać → odrzuć
2502 - return False
2503 -
2504 - for member in tar.getmembers():
2505 - name = member.name
2506 -
2507 - # --- Ochrona przed Directory Traversal (szybkie string-checki) ---
2508 - if name.startswith('/'):
2509 - continue
2510 - if '..' in name.split('/'):
2511 - continue
2512 - # Zablokuj bajt NUL i backslash (bugi/obejścia tarfile na niektórych platformach)
2513 - if '\x00' in name or '\\' in name:
2514 - continue
2515 - if not _check_path_safety(name):
2516 - print(f" BLOCKED: {name}")
2517 - continue
2518 -
2519 - target = os.path.join(dest, name)
2520 -
2521 - # --- Ochrona na podstawie finalnej ścieżki ---
2522 - # Jeśli którykolwiek komponent nadrzędny jest (złośliwym) symlinkiem
2523 - # wskazującym poza dest, realpath to wykryje – zablokuj zapis.
2524 - if not _target_within(target):
2525 - print(f" BLOCKED (escape): {name}")
2526 - continue
2527 -
2528 - # --- Ochrona dla symlinków i hardlinków ---
2529 - if member.issym() or member.islnk():
2530 - link = member.linkname
2531 - if '\x00' in link:
2532 - continue
2533 - # Link absolutny jest POPRAWNY, gdy cel jest ścieżką systemową
2534 - # (np. usr/bin/librewolf -> /usr/lib/librewolf/librewolf). Wcześniej
2535 - # odrzucaliśmy wszystkie takie linki po cichu, przez co w systemie
2536 - # brakowalo np. /usr/bin/librewolf — a wpis .desktop z TryExec nie
2537 - # pojawiał się w menu. Odrzucamy tylko cele spoza dozwolonych prefiksów.
2538 - if link.startswith('/'):
2539 - if not _check_path_safety(link):
2540 - print(f" BLOCKED (link target): {name} -> {link}")
2541 - continue
2542 - # Cel absolutny zostaje bez zmian – po instalacji wskazuje
2543 - # właściwą ścieżkę w systemie (sprawdzenie _target_within
2544 - # dotyczy ścieżki RELATYWNEJ i tutaj nie ma zastosowania).
2545 - else:
2546 - # UWAGA: '..' w relatywnym celu linku jest POPRAWNE i częste
2547 - # (np. busybox: bin/ls -> ../usr/bin/busybox). Wcześniej taki
2548 - # link byl po cichu pomijany, przez co busybox instalowal
2549 - # 3 pliki zamiast 388. Decyduje realny cel — _target_within().
2550 - link_target = os.path.join(os.path.dirname(target), link)
2551 - if not _target_within(link_target):
2552 - print(f" BLOCKED (link escape): {name} -> {link}")
2553 - continue
2554 -
2555 - # Rozpakuj z zachowaniem metadanych. Python 3.12+ wymaga jawnego
2556 - # `filter=` (inaczej DeprecationWarning, a w 3.14+ błąd).
2557 - # UWAGA: 'fully_trusted' CELOWO pomija wbudowane filtry bezpieczeństwa
2558 - # Pythona – to nie przeoczenie. Nasza walidacja powyżej (path traversal,
2559 - # NUL/backslash, escape przez symlink, linki wychodzące poza dest) jest
2560 - # równoważna lub ostrzejsza, a 'fully_trusted' pozwala zachować bity
2561 - # SUID/SGID/sticky, które filtr 'data' by usunął (np. /usr/bin/sudo).
2562 - # SUID jest i tak zdejmowany przez _strip_suid() tuż po rozpakowaniu.
2563 - try:
2564 - if hasattr(tarfile, 'data_filter'):
2565 - # Python 3.12+
2566 - tar.extract(member, dest, set_attrs=preserve_perms, numeric_owner=False,
2567 - filter='fully_trusted')
2568 - else:
2569 - tar.extract(member, dest, set_attrs=preserve_perms, numeric_owner=False)
2570 - except Exception as e:
2571 - print(_(' ⚠ Failed to extract {arg1}: {arg2}', arg1=(name), arg2=(e)))
2572 - continue
2573 - # Pliki z listy uprzywilejowanej zachowują SUID/SGID; reszta jest
2574 - # czyszczona (ochrona przed SUID niespodziewanym w pakiecie).
2575 - if "/" + os.path.relpath(target, dest_real) not in privileged:
2576 - _strip_suid(target)
2577 -
2578 -
2579 -def _sha256_file(path: str) -> str:
2580 - """SHA256 pliku. Na Python ≥3.11 używa hashlib.file_digest (pętla w C);
2581 - starsze wersje mają fallback z pętlą chunków."""
2582 - with open(path, "rb") as f:
2583 - if hasattr(hashlib, "file_digest"):
2584 - return hashlib.file_digest(f, "sha256").hexdigest()
2585 - h = hashlib.sha256()
2586 - for chunk in iter(lambda: f.read(65536), b""):
2587 - h.update(chunk)
2588 - return h.hexdigest()
2589 -
2590 -def _split_version(v: str):
2591 - """Rozdziela wersję na (release_parts, prerelease_parts).
2592 -
2593 - Przykład: '1.2.0-rc1' → ([1,2,0], ['rc','1']).
2594 - """
2595 - v = v.strip().lower().lstrip("v")
2596 - # build metadata po '+' jest ignorowane przy porównywaniu (semver)
2597 - v = v.split("+", 1)[0]
2598 - # prerelease po '-' lub '_' (np. 1.2.0-rc1, 1.2.0_rc1)
2599 - if "-" in v:
2600 - rel, pre = v.split("-", 1)
2601 - elif "_" in v:
2602 - rel, pre = v.split("_", 1)
2603 - else:
2604 - rel, pre = v, ""
2605 - nums = []
2606 - for part in rel.split("."):
2607 - m = re.match(r"(\d+)", part)
2608 - nums.append(int(m.group(1)) if m else 0)
2609 - pre_parts = [p for p in pre.split(".") if p]
2610 - return nums, pre_parts
2611 -
2612 -
2613 -def _cmp_pre(a, b):
2614 - """Porównuje ciągi identyfikatorów prerelease (reguły semver)."""
2615 - for i in range(max(len(a), len(b))):
2616 - if i >= len(a):
2617 - return -1 # krótszy prerelease jest niższy
2618 - if i >= len(b):
2619 - return 1
2620 - ia, ib = a[i], b[i]
2621 - if ia == ib:
2622 - continue
2623 - na, nb = ia.isdigit(), ib.isdigit()
2624 - if na and nb:
2625 - return 1 if int(ia) > int(ib) else -1
2626 - if na != nb:
2627 - return -1 if na else 1 # identyfikator liczbowy < alfanumeryczny
2628 - return 1 if ia > ib else -1
2629 - return 0
2630 -
2631 -
2632 -def _cmp_version(a: str, b: str) -> int:
2633 - """Porównuje dwie wersje; zwraca -1/0/1. Obsługuje prerelease (rc1, beta...)."""
2634 - a_rel, a_pre = _split_version(a)
2635 - b_rel, b_pre = _split_version(b)
2636 - # Porównaj część release (brakujące komponenty traktuj jako 0)
2637 - for i in range(max(len(a_rel), len(b_rel))):
2638 - xa = a_rel[i] if i < len(a_rel) else 0
2639 - xb = b_rel[i] if i < len(b_rel) else 0
2640 - if xa != xb:
2641 - return 1 if xa > xb else -1
2642 - # Część release równa → decyduje prerelease.
2643 - # Wersja finalna (bez prerelease) jest ZAWSZE nowsza od prerelease.
2644 - if not a_pre and not b_pre:
2645 - return 0
2646 - if not a_pre:
2647 - return 1
2648 - if not b_pre:
2649 - return -1
2650 - return _cmp_pre(a_pre, b_pre)
2651 -
2652 -
2653 -def _version_newer(a: str, b: str) -> bool:
2654 - """True gdy wersja a jest nowsza od b (z poprawną obsługą prerelease)."""
2655 - try:
2656 - return _cmp_version(a, b) > 0
2657 - except Exception:
2658 - return a != b
2659 -
2660 -def load_json(path):
2661 - try:
2662 - with open(path) as f:
2663 - return json.load(f)
2664 - except (FileNotFoundError, json.JSONDecodeError):
2665 - return {}
2666 -
2667 -def save_json(path, data):
2668 - with open(path, "w") as f:
2669 - json.dump(data, f, indent=2)
2670 -
2671 -class PackageInfo:
2672 - __slots__ = ("name","version","release","description","dependencies",
2673 - "optdepends","size_bytes","sha256","gpg_fp","repo_url","filename",
2674 - "provides","license","provides_so","requires_so","privileged")
2675 - def __init__(self, d, repo=""):
2676 - self.name = d.get("name","?")
2677 - self.version = d.get("version","0")
2678 - self.release = d.get("release", 1)
2679 - self.description = d.get("description","")
2680 - self.dependencies = d.get("dependencies", d.get("depends", []))
2681 - # Opcjonalne zależności (flatpak, btrfs-progs, grub, ...) – tylko
2682 - # informacyjne; `pag install` NIE instaluje ich automatycznie.
2683 - self.optdepends = d.get("optdepends", []) or []
2684 - self.size_bytes = d.get("size",0)
2685 - self.sha256 = d.get("sha256","")
2686 - self.gpg_fp = d.get("gpg_fingerprint","")
2687 - self.repo_url = repo
2688 - self.filename = d.get("filename", f"{self.name}-{self.version}{PKG_EXT}")
2689 - self.provides = d.get("provides", []) or []
2690 - self.license = d.get("license", []) or []
2691 - self.provides_so = d.get("provides_so", []) or []
2692 - self.requires_so = d.get("requires_so", []) or []
2693 - # Ścieżki, którym wolno zachować setuid/setgid i grupę (z receptury).
2694 - self.privileged = d.get("privileged", []) or []
2695 -
2696 -# =============================================================================
2697 -# REPOZYTORIA (cache, ETag, GPG)
2698 -# =============================================================================
2699 -
2700 -def _parse_repos_config():
2701 - """Parsuje repozytoria z /etc/pag/repos.conf oraz /etc/pag/repos/*.conf.
2702 -
2703 - Format linii: <url> [fingerprint]
2704 - Opcjonalny `fingerprint` (40 znaków hex) pozwala przypiąć klucz
2705 - podpisujący repo do konkretnego adresu – wtedy TOFU (auto-zaufanie przy
2706 - pierwszym użyciu) nie jest potrzebne, a zmiana klucza = błąd bezpieczeństwa.
2707 -
2708 - Drop-iny (np. stable.conf) są czytane alfabetycznie – pozwalają na
2709 - wygodne dodawanie repo bez dotykania głównego repos.conf
2710 - (np. `echo 'https://repo.paganlinux.eu/stable' > /etc/pag/repos/stable.conf`).
2711 - """
2712 - entries = []
2713 -
2714 - def _read_lines(path):
2715 - if not os.path.exists(path):
2716 - return
2717 - for line in open(path):
2718 - line = line.strip()
2719 - if not line or line.startswith("#"):
2720 - continue
2721 - parts = line.split()
2722 - url = parts[0].rstrip("/")
2723 - fp = parts[1].lower() if len(parts) > 1 else ""
2724 - entries.append({"url": url, "fingerprint": fp or None})
2725 -
2726 - # 1) Legacy: pojedynczy plik /etc/pag/repos.conf
2727 - _read_lines(REPOS_CONF)
2728 - # 2) Drop-in: /etc/pag/repos/<nazwa>.conf (sortowane, stabilna kolejność)
2729 - if os.path.isdir(REPOS_DIR):
2730 - for drop in sorted(os.listdir(REPOS_DIR)):
2731 - if drop.endswith(".conf"):
2732 - _read_lines(os.path.join(REPOS_DIR, drop))
2733 -
2734 - # Dedupe po URL (zachowaj pierwszy wpis – może mieć fingerprint)
2735 - seen, unique = set(), []
2736 - for e in entries:
2737 - if e["url"] not in seen:
2738 - seen.add(e["url"])
2739 - unique.append(e)
2740 -
2741 - if not unique:
2742 - for url in DEFAULT_REPOS:
2743 - # rstrip: get_repos()/_repo_pinned_fp() kluczują URL-e bez ukośnika
2744 - unique.append({"url": url.rstrip("/"), "fingerprint": None})
2745 - return unique
2746 -
2747 -
2748 -def get_repos():
2749 - return [e["url"] for e in _parse_repos_config()]
2750 -
2751 -
2752 -def _repo_pinned_fp(repo_url):
2753 - """Zwraca przypięty fingerprint klucza dla repo (z konfiguracji lub trust DB)."""
2754 - # Normalizacja ukośnika: _parse_repos_config() i trust DB kluczują URL-e BEZ
2755 - # końcowego „/”, a wywołujący podają często DEFAULT_REPOS[0] Z ukośnikiem.
2756 - # Bez tego przypięty klucz nie był znajdowany i lokalny .pag dostawał
2757 - # fałszywe „Brak przypiętego klucza repo” mimo poprawnego wpisu w trusted.json.
2758 - repo_url = repo_url.rstrip("/")
2759 - by_url = {e["url"]: e["fingerprint"] for e in _parse_repos_config()}
2760 - if by_url.get(repo_url):
2761 - return by_url[repo_url]
2762 - db = _load_trust_db()
2763 - fp = db.get(repo_url)
2764 - return fp.lower() if fp else None
2765 -
2766 -def _repo_cache_path(url):
2767 - return os.path.join(REPO_CACHE, url.replace("://","_").replace("/","_").replace(".","_") + ".json")
2768 -
2769 -def _repo_etag_path(url): return _repo_cache_path(url) + ".etag"
2770 -def _repo_ts_path(url): return _repo_cache_path(url) + ".ts"
2771 -
2772 -# Informacja (raz na uruchomienie), gdy cache repozytoriów jest tylko-do-odczytu –
2773 -# np. komendy read-only (`pag info`, `pag search`…) jako zwykły user: nie ma sensu
2774 -# ani prawa odświeżać /var/cache/pag/repos, więc używamy lokalnej kopii indeksu.
2775 -_cache_ro_notice_done = False
2776 -
2777 -def _cache_ro_notice():
2778 - global _cache_ro_notice_done
2779 - if _cache_ro_notice_done:
2780 - return
2781 - _cache_ro_notice_done = True
2782 - print(f" ⚠ {_('cache_ro', cache=REPO_CACHE)}", file=sys.stderr)
2783 -
2784 -def _load_repo_cache(cp: str) -> Optional[list]:
2785 - """Wczytuje cache indeksu repo; zwraca None gdy brak albo uszkodzony.
2786 -
2787 - Partial write (crash w trakcie zapisu) mógł zostawić obcięty JSON. Zamiast
2788 - zwracać pustą listę pakietów (użytkownik myśli, że repo jest puste)
2789 - sygnalizujemy None – wywołujący ponowi pobranie albo pokaże ostrzeżenie."""
2790 - if not os.path.exists(cp):
2791 - return None
2792 - try:
2793 - with open(cp, "r", encoding="utf-8") as fh:
2794 - data = json.load(fh)
2795 - pkgs = data.get("packages")
2796 - if not isinstance(pkgs, list):
2797 - raise ValueError(_("repo_index_invalid"))
2798 - return pkgs
2799 - except (OSError, ValueError) as e:
2800 - print(_(' ⚠ Corrupted index cache {arg1}: {arg2}', arg1=(cp), arg2=(e)), file=sys.stderr)
2801 - return None
2802 -
2803 -
2804 -def fetch_repo_index(repo_url, force=False):
2805 - cp = _repo_cache_path(repo_url)
2806 - ep = _repo_etag_path(repo_url)
2807 - tp = _repo_ts_path(repo_url)
2808 -
2809 - if not force and os.path.exists(cp) and os.path.exists(tp):
2810 - try:
2811 - if time.time() - float(open(tp).read().strip()) < REPO_CACHE_TTL:
2812 - cached = _load_repo_cache(cp)
2813 - if cached is not None:
2814 - return cached
2815 - # uszkodzony cache – spróbuj odświeżyć z sieci
2816 - except (OSError, ValueError):
2817 - pass
2818 -
2819 - # --- Cache tylko-do-odczytu (np. `pag info` jako zwykły user) ---
2820 - # /var/cache/pag/repos należy do roota. Nie próbuj odświeżać ani pisać –
2821 - # zwykły user i tak nie zapisze indeksu; użyj lokalnej kopii (może być
2822 - # nieaktualna). Pełne odświeżenie indeksu: sudo pag sync
2823 - if not (os.path.isdir(REPO_CACHE) and os.access(REPO_CACHE, os.W_OK)):
2824 - if force:
2825 - print(_(' ❌ {arg1}: cannot refresh index – {arg2} is read-only', arg1=(repo_url), arg2=(REPO_CACHE)),
2826 - file=sys.stderr)
2827 - return None
2828 - _cache_ro_notice()
2829 - cached = _load_repo_cache(cp)
2830 - if cached is not None:
2831 - return cached
2832 - return None
2833 -
2834 - headers = {"User-Agent": "pag/3.0"}
2835 - if os.path.exists(tp) and not force:
2836 - try:
2837 - lm = datetime.fromtimestamp(float(open(tp).read().strip()), tz=timezone.utc)
2838 - # Wymuś lokalizację C/POSIX dla nagłówków HTTP, aby unikać problemów z nazwami dni/miesięcy
2839 - try:
2840 - old_locale = locale.setlocale(locale.LC_TIME)
2841 - locale.setlocale(locale.LC_TIME, 'C')
2842 - headers["If-Modified-Since"] = lm.strftime("%a, %d %b %Y %H:%M:%S GMT")
2843 - locale.setlocale(locale.LC_TIME, old_locale)
2844 - except (locale.Error, ValueError):
2845 - # Jeśli ustawienie lokalizacji się nie powiedzie, użyj domyślnej
2846 - headers["If-Modified-Since"] = lm.strftime("%a, %d %b %Y %H:%M:%S GMT")
2847 - except: pass
2848 - if os.path.exists(ep) and not force:
2849 - try: headers["If-None-Match"] = open(ep).read().strip()
2850 - except: pass
2851 -
2852 - # --- Pobranie indeksu (błędy SIECI nie są błędami zapisu cache) ---
2853 - try:
2854 - req = Request(f"{repo_url}/repo.json", headers=headers)
2855 - with urlopen(req, timeout=30) as resp:
2856 - etag = resp.headers.get("ETag","")
2857 - raw = resp.read()
2858 - data = json.loads(raw.decode())
2859 - except HTTPError as e:
2860 - if e.code == 304:
2861 - # Serwer: indeks bez zmian – odśwież tylko znacznik czasu (best-effort)
2862 - try:
2863 - open(tp,"w").write(str(time.time()))
2864 - except OSError:
2865 - pass
2866 - cached = _load_repo_cache(cp)
2867 - if cached is not None:
2868 - return cached
2869 - # uszkodzona kopia – potraktuj jak brak (ostrzeżenie niżej)
2870 - print(_(' ⚠ HTTP {arg1} for {arg2}', arg1=(e.code), arg2=(repo_url)), file=sys.stderr)
2871 - return None
2872 - except Exception as e:
2873 - print(_(' ⚠ Failed to download index {arg1}: {arg2}', arg1=(repo_url), arg2=(e)), file=sys.stderr)
2874 - return _load_repo_cache(cp)
2875 -
2876 - # Indeks pobrany – zapisz SUROWE bajty (nie re-serializuj! podpis GPG jest
2877 - # nad oryginalnymi bajtami repo.json z serwera) i zweryfikuj podpis.
2878 - # Najpierw zapis tymczasowy + weryfikacja GPG, dopiero potem podmiana cp:
2879 - # błąd zapisu (np. pełny dysk) nie niszczy starej, zweryfikowanej kopii
2880 - # i NIGDY nie zwracamy danych, które nie przeszły weryfikacji.
2881 - tmp_path = cp + ".tmp"
2882 - try:
2883 - with open(tmp_path, "wb") as f:
2884 - f.write(raw)
2885 - if not _verify_repo_sig(repo_url, tmp_path):
2886 - return None # weryfikacja nie powiodła się – stary cache zostaje
2887 - os.replace(tmp_path, cp)
2888 - # przenieś podpis obok docelowego pliku (marker „repo ma podpis")
2889 - for _ext in (".asc", ".sig"):
2890 - if os.path.exists(tmp_path + _ext):
2891 - try:
2892 - os.replace(tmp_path + _ext, cp + _ext)
2893 - except OSError:
2894 - pass
2895 - break
2896 - if etag:
2897 - try:
2898 - open(ep,"w").write(etag)
2899 - except OSError:
2900 - pass
2901 - try:
2902 - open(tp,"w").write(str(time.time()))
2903 - except OSError:
2904 - pass
2905 - return data.get("packages",[])
2906 - except OSError as e:
2907 - print(_(' ⚠ Index downloaded, but failed to save cache ({arg1}): {arg2}', arg1=(REPO_CACHE), arg2=(e)),
2908 - file=sys.stderr)
2909 - # cp nie został podmieniony (podmiana jest po weryfikacji) – lokalna kopia
2910 - # to wciąż stare, zweryfikowane dane
2911 - return _load_repo_cache(cp)
2912 - finally:
2913 - for _p in (tmp_path, tmp_path + ".asc", tmp_path + ".sig"):
2914 - try:
2915 - os.unlink(_p)
2916 - except OSError:
2917 - pass
2918 -
2919 -def _verify_repo_sig(repo_url, cache_path) -> bool:
2920 - """Weryfikuje podpis GPG indeksu repozytorium i przypina fingerprint.
2921 -
2922 - FAIL-CLOSED: brak/nieprawidłowy podpis = False (chyba że PAG_INSECURE=1).
2923 - Zwraca True jeśli indeks jest zaufany, False jeśli należy go odrzucić.
2924 -
2925 - Model zaufania (TOFU + pinning):
2926 - - Pierwszy raz (brak przypiętego fingerprintu) → klucz jest importowany,
2927 - a fingerprint zapisywany w /etc/pag/trusted.json z JAWNYM ostrzeżeniem.
2928 - To świadomy kompromis wygody i bezpieczeństwa.
2929 - - Kolejne uruchomienia: fingerprint jest porównywany z przypiętym.
2930 - Zmiana klucza = ❌ SECURITY ERROR (fail-closed), wymagane ręczne:
2931 - pag key-trust <repo_url> (po weryfikacji nowego klucza)
2932 - """
2933 - insecure = os.environ.get("PAG_INSECURE", "") == "1"
2934 -
2935 - if not os.path.exists(GPG_HOME):
2936 - if insecure:
2937 - return True # brak GPG home – tryb insecure, akceptuj
2938 - print(_(' ❌ {arg1}: no GPG keys – verification impossible!', arg1=(repo_url)))
2939 - print(_(' Set PAG_INSECURE=1 to skip (not recommended)'))
2940 - os.remove(cache_path)
2941 - return False
2942 -
2943 - sig_path = cache_path + ".sig"
2944 - # Podpisy generowane jako .asc (armored) – próbuj .asc, potem .sig
2945 - sig_data = None
2946 - sig_ext = ""
2947 - for ext in (".asc", ".sig"):
2948 - try:
2949 - req = Request(f"{repo_url}/repo.json{ext}", headers={"User-Agent":"pag/3.0"})
2950 - with urlopen(req, timeout=15) as resp:
2951 - sig_data = resp.read()
2952 - sig_ext = ext
2953 - break
2954 - except Exception:
2955 - continue
2956 - if not sig_data:
2957 - if insecure:
2958 - return True # tryb insecure – akceptuj bez podpisu
2959 - print(_(' ❌ {arg1}: CANNOT DOWNLOAD SIGNATURE repo.json.asc/.sig!', arg1=(repo_url)))
2960 - print(_(' Set PAG_INSECURE=1 to skip (not recommended)'))
2961 - os.remove(cache_path)
2962 - return False
2963 - sig_path = cache_path + sig_ext
2964 - with open(sig_path, "wb") as f:
2965 - f.write(sig_data)
2966 -
2967 - ok, fingerprint = _gpg_verify_fp(sig_path, cache_path)
2968 - if not ok:
2969 - # Automatyczny import klucza repo przy pierwszym uruchomieniu (TOFU,
2970 - # jak apt) – gdy w keyringu brakuje klucza (No public key).
2971 - res = _gpg_run("--verify", sig_path, cache_path,
2972 - capture_output=True, text=True, timeout=30)
2973 - _stderr = res.stderr.decode(errors="replace") if isinstance(res.stderr, bytes) else (res.stderr or "")
2974 - if "public key" in _stderr.lower() and "no public key" in _stderr.lower():
2975 - try:
2976 - with urlopen(Request(f"{repo_url}/paganos.asc", headers={"User-Agent": "pag/3.0"}), timeout=20) as r:
2977 - keydata = r.read()
2978 - with tempfile.NamedTemporaryFile(delete=False, suffix=".asc") as tmp:
2979 - tmp.write(keydata)
2980 - tmp.flush()
2981 - _gpg_run("--import", tmp.name, capture_output=True, timeout=30)
2982 - os.unlink(tmp.name)
2983 - print(_(' 🔑 Imported repo key from {arg1}/paganos.asc', arg1=(repo_url)))
2984 - ok, fingerprint = _gpg_verify_fp(sig_path, cache_path)
2985 - except Exception:
2986 - pass
2987 - if not ok:
2988 - if insecure:
2989 - print(_(' ⚠ {arg1}: invalid GPG signature (PAG_INSECURE – ignoring)', arg1=(repo_url)))
2990 - return True
2991 - os.remove(cache_path)
2992 - if not shutil.which(GPG_BINARY):
2993 - print(_(' ❌ {arg1}: GPG is not installed – cannot verify the signature!', arg1=(repo_url)))
2994 - print(_(' Install gnupg or set PAG_INSECURE=1 (not recommended)'))
2995 - else:
2996 - print(_(' ❌ {arg1}: INVALID GPG SIGNATURE of the repository index!', arg1=(repo_url)))
2997 - return False
2998 -
2999 - # --- Wymuś przypięty fingerprint (TOFU + pinning) ---
3000 - pinned = _repo_pinned_fp(repo_url)
3001 - if pinned:
3002 - if not fingerprint:
3003 - if insecure:
3004 - print(_(' ⚠ {arg1}: cannot read signature fingerprint (PAG_INSECURE – ignoring)', arg1=(repo_url)))
3005 - return True
3006 - os.remove(cache_path)
3007 - print(_(' ❌ [SECURITY ERROR] {arg1}: cannot read signature fingerprint!', arg1=(repo_url)))
3008 - print(_(' Pinned key: {arg1} – rejecting the index.', arg1=(pinned)))
3009 - return False
3010 - if fingerprint != pinned.upper():
3011 - if insecure:
3012 - print(_(' ⚠ {arg1}: SIGNING KEY CHANGED (PAG_INSECURE – ignoring)', arg1=(repo_url)))
3013 - return True
3014 - os.remove(cache_path)
3015 - print(_(' ❌ [SECURITY ERROR] {arg1}: Repository signing key has changed!', arg1=(repo_url)))
3016 - print(_(' Expected: {arg1}', arg1=(pinned)))
3017 - print(_(' Received: {arg1}', arg1=(fingerprint)))
3018 - print(_(' If this is an intentional key rotation: pag key-trust {arg1}', arg1=(repo_url)))
3019 - return False
3020 - return True
3021 -
3022 - if fingerprint:
3023 - # Brak przypiętego fingerprintu → TOFU: zapisz go w bazie zaufania.
3024 - db = _load_trust_db()
3025 - if db.get(repo_url) != fingerprint:
3026 - _save_trust_db({**db, repo_url: fingerprint})
3027 - print(_(' 🔐 Pinned repo fingerprint {arg1}: {arg2}', arg1=(repo_url), arg2=(fingerprint)))
3028 - print(_(' (TOFU – first trust. If the key changes, pag will refuse updates.)'))
3029 - print(_(' To avoid TOFU, add the fingerprint to /etc/pag/repos.conf.'))
3030 - return True
3031 -
3032 -def fetch_all_packages(force=False):
3033 - all_pkgs = {}
3034 - for repo_url in get_repos():
3035 - pkgs = fetch_repo_index(repo_url, force)
3036 - if pkgs:
3037 - for pdata in pkgs:
3038 - name = pdata.get("name", pdata.get("filename","?").split("-")[0])
3039 - pkg = PackageInfo(pdata, repo_url)
3040 - if name not in all_pkgs or _version_newer(pkg.version, all_pkgs[name].version):
3041 - all_pkgs[name] = pkg
3042 - return all_pkgs
3043 -
3044 -# =============================================================================
3045 -# GPG
3046 -# =============================================================================
3047 -
3048 -def _verify_pkg_gpg(pkg_path, repo_url=None):
3049 - """Weryfikuje podpis GPG pakietu i (jeśli znamy repo) przypięty fingerprint.
3050 -
3051 - FAIL-CLOSED: brak podpisu = odrzucenie (chyba że PAG_INSECURE=1).
3052 - Zwraca (passed: bool, message: str).
3053 - """
3054 - insecure = os.environ.get("PAG_INSECURE", "") == "1"
3055 - # Brak gnupg = weryfikacja niemożliwa. Bez tej gałęzi użytkownik dostawał
3056 - # mylące „NIEPRAWIDŁOWY PODPIS GPG”, mimo że paczka i podpis są w porządku.
3057 - if not shutil.which(GPG_BINARY):
3058 - if insecure:
3059 - return True, "(gpg missing – PAG_INSECURE)"
3060 - return False, _("gpg_missing")
3061 - sig_path = pkg_path + ".sig"
3062 - if not os.path.exists(sig_path) and os.path.exists(pkg_path + ".asc"):
3063 - sig_path = pkg_path + ".asc"
3064 -
3065 - if not os.path.exists(sig_path):
3066 - if insecure:
3067 - return True, "(no signature – PAG_INSECURE)"
3068 - return False, "BRAK PODPISU – pakiet odrzucony (ustaw PAG_INSECURE=1 aby pominąć)"
3069 -
3070 - ok, fp = _gpg_verify_fp(sig_path, pkg_path)
3071 - if not ok:
3072 - if insecure:
3073 - return True, "(invalid signature – PAG_INSECURE)"
3074 - return False, "NIEPRAWIDŁOWY PODPIS GPG"
3075 -
3076 - # Opcjonalnie: sprawdź, czy podpis pochodzi od klucza przypiętego dla repo.
3077 - if repo_url:
3078 - pinned = _repo_pinned_fp(repo_url)
3079 - if pinned and fp and fp != pinned.upper():
3080 - if insecure:
3081 - return True, "(pkg signer mismatch – PAG_INSECURE)"
3082 - return False, f"PAKIET PODPISANY INNYM KLUCZEM niż repo (oczekiwano {pinned})"
3083 -
3084 - return True, "GPG verified"
3085 -
3086 -def cmd_key_add(source):
3087 - ensure_dirs()
3088 - if not shutil.which(GPG_BINARY):
3089 - print(f"❌ {_('gpg_missing')}"); return 1
3090 - if source.startswith("http"):
3091 - try:
3092 - with urlopen(Request(source, headers={"User-Agent":"pag/3.0"}), timeout=30) as resp:
3093 - keydata = resp.read()
3094 - with tempfile.NamedTemporaryFile(delete=False, suffix=".gpg") as tmp:
3095 - tmp.write(keydata); tmp.flush()
3096 - res = _gpg_run("--import", tmp.name, capture_output=True, timeout=30)
3097 - os.unlink(tmp.name)
3098 - if res.returncode != 0:
3099 - print(f"❌ {_('key_add_failed')}"); return 1
3100 - except Exception as e:
3101 - print(_('❌ Download error: {arg1}', arg1=(e))); return 1
3102 - else:
3103 - res = _gpg_run("--import", source, capture_output=True, timeout=30)
3104 - if res.returncode != 0:
3105 - print(f"❌ {_('key_add_failed')}"); return 1
3106 - print(f"✅ {_('key_imported')}")
3107 -
3108 -def cmd_key_list():
3109 - if not shutil.which(GPG_BINARY):
3110 - print(f"❌ {_('gpg_missing')}"); return
3111 - if not os.path.exists(GPG_HOME):
3112 - print(_("no_keys")); return
3113 - result = _gpg_run("--list-keys", "--keyid-format", "LONG",
3114 - capture_output=True, text=True, timeout=30)
3115 - if result.returncode != 0:
3116 - print(f"❌ {_('gpg_missing')}"); return
3117 - print(result.stdout or _("no_keys"))
3118 -
3119 -def cmd_key_remove(key_id):
3120 - _gpg_run("--batch", "--yes", "--delete-key", key_id,
3121 - capture_output=True, timeout=30)
3122 - print(f"✅ {_('key_removed', key_id)}")
3123 -
3124 -def _repo_signer_fp(repo_url):
3125 - """Pobiera repo.json + podpis i zwraca fingerprint podpisującego (bez pinningu)."""
3126 - repo_url = repo_url.rstrip("/")
3127 - try:
3128 - with urlopen(Request(f"{repo_url}/repo.json", headers={"User-Agent":"pag/3.0"}), timeout=30) as r:
3129 - data = r.read()
3130 - except Exception:
3131 - return None
3132 - sig = None
3133 - sig_ext = ".asc"
3134 - for ext in (".asc", ".sig"):
3135 - try:
3136 - with urlopen(Request(f"{repo_url}/repo.json{ext}", headers={"User-Agent":"pag/3.0"}), timeout=20) as r:
3137 - sig = r.read()
3138 - sig_ext = ext
3139 - break
3140 - except Exception:
3141 - continue
3142 - if not sig:
3143 - return None
3144 - with tempfile.NamedTemporaryFile(delete=False, suffix=".json") as tf:
3145 - tf.write(data); tf.flush()
3146 - data_path = tf.name
3147 - sig_path = data_path + sig_ext
3148 - try:
3149 - with open(sig_path, "wb") as f:
3150 - f.write(sig)
3151 - ok, fp = _gpg_verify_fp(sig_path, data_path)
3152 - finally:
3153 - for p in (data_path, sig_path):
3154 - try: os.unlink(p)
3155 - except OSError: pass
3156 - return fp if ok else None
3157 -
3158 -
3159 -def cmd_key_trust(repo_url):
3160 - """Przypina fingerprint klucza podpisującego repo (koniec z TOFU dla tego repo)."""
3161 - repo_url = repo_url.rstrip("/")
3162 - print(_('🔐 Pinning repo key {arg1}...', arg1=(repo_url)))
3163 - fp = _repo_signer_fp(repo_url)
3164 - if not fp:
3165 - print(_(' ❌ Cannot read signature fingerprint (missing/failed).'))
3166 - print(_(' Make sure the repo key is in the keyring (pag key-add <url|file>).'))
3167 - return 1
3168 - db = _load_trust_db()
3169 - _save_trust_db({**db, repo_url: fp})
3170 - print(_(' ✅ Pinned {arg1} for {arg2}', arg1=(fp), arg2=(repo_url)))
3171 - print(_(' From now on, a key change will be reported as SECURITY ERROR.'))
3172 - return 0
3173 -
3174 -
3175 -def cmd_key_untrust(repo_url):
3176 - """Usuwa przypięcie fingerprintu dla repo (wraca do TOFU)."""
3177 - repo_url = repo_url.rstrip("/")
3178 - db = _load_trust_db()
3179 - if repo_url not in db:
3180 - print(_(' ℹ {arg1} has no pinned fingerprint.', arg1=(repo_url)))
3181 - return 0
3182 - del db[repo_url]
3183 - _save_trust_db(db)
3184 - print(_(' ✅ Removed pin for {arg1}.', arg1=(repo_url)))
3185 - return 0
3186 -
3187 -
3188 -def cmd_key_trusted():
3189 - """Listuje przypięte fingerprinty repozytoriów."""
3190 - db = _load_trust_db()
3191 - if not db:
3192 - print(_("no_keys"))
3193 - return
3194 - for url, fp in sorted(db.items()):
3195 - print(f" {url}\n {fp}")
3196 -
3197 -# =============================================================================
3198 -# ATOMOWA INSTALACJA (STAGING)
3199 -# =============================================================================
3200 -
3201 -def _safe_rename(src: str, dst: str) -> bool:
3202 - """
3203 - Atomowe przeniesienie pliku. Jeśli src i dst są na różnych
3204 - systemach plików (EXDEV), kopiuje + usuwa źródło.
3205 - """
3206 - try:
3207 - os.rename(src, dst)
3208 - return True
3209 - except OSError as e:
3210 - if e.errno == 18: # EXDEV – cross-device link
3211 - shutil.copy2(src, dst)
3212 - os.remove(src)
3213 - return True
3214 - raise
3215 -
3216 -
3217 -def _install_file(src: str, rel: str, data_staging: str, sums: dict,
3218 - staging: str, journal: list, installed_files: list,
3219 - deploy_dir: str = "", backup_dir: str = "",
3220 - backup_journal: Optional[list] = None,
3221 - old_checksums: Optional[dict] = None,
3222 - privileged=frozenset()) -> bool:
3223 - """
3224 - Instaluje pojedynczy plik (zwykły lub symlink).
3225 - Obsługuje: cross-device rename, symlinki, weryfikację SHA256.
3226 -
3227 - Jeśli deploy_dir jest podany (tryb immutable), pliki systemowe trafiają
3228 - do deploymentu, a współdzielone (/var, /etc, ...) bezpośrednio do /.
3229 -
3230 - Jeśli backup_dir jest podany, a pod dst istnieje już plik (upgrade/reinstall),
3231 - stara wersja jest przenoszona do backup_dir, by rollback mógł ją przywrócić.
3232 -
3233 - old_checksums: {ścieżka: sha256 z chwili instalacji}. Gdy podane i plik /etc
3234 - został zmodyfikowany przez użytkownika, nowa wersja ląduje jako .pacnew
3235 - (stary plik NIE jest ruszany) – wzorzec jak w pacmanie.
3236 - """
3237 - # W trybie immutable: pliki współdzielone idą do /, reszta do deploymentu
3238 - if deploy_dir and _is_shared_path("/" + rel):
3239 - dst_root = PAG_ROOT
3240 - elif deploy_dir:
3241 - dst_root = deploy_dir
3242 - else:
3243 - dst_root = PAG_ROOT
3244 -
3245 - dst = os.path.join(dst_root, rel)
3246 -
3247 - # --- SYMLINK ---
3248 - if os.path.islink(src):
3249 - link_target = os.readlink(src)
3250 - # Weryfikuj sums.json dla symlinka (hash ścieżki docelowej)
3251 - expected = sums.get("/" + rel, "")
3252 - if expected:
3253 - link_hash = hashlib.sha256(link_target.encode()).hexdigest()
3254 - if expected and link_hash != expected:
3255 - return False
3256 -
3257 - os.makedirs(os.path.dirname(dst), exist_ok=True)
3258 - # Backup istniejącego symlinka (upgrade) – dla poprawnego rollbacku
3259 - if backup_dir and backup_journal is not None and os.path.lexists(dst):
3260 - try:
3261 - backup_path = os.path.join(backup_dir, rel)
3262 - os.makedirs(os.path.dirname(backup_path), exist_ok=True)
3263 - os.replace(dst, backup_path)
3264 - backup_journal.append((backup_path, "/" + rel))
3265 - journal.append(("backup", backup_path, dst))
3266 - except OSError:
3267 - pass
3268 - # Jeśli docelowy symlink już istnieje, usuń go
3269 - if os.path.islink(dst) or os.path.exists(dst):
3270 - os.remove(dst)
3271 - os.symlink(link_target, dst)
3272 - journal.append(("symlink", "", dst))
3273 - installed_files.append({
3274 - "path": "/" + rel,
3275 - "sha256": hashlib.sha256(link_target.encode()).hexdigest(),
3276 - "size": len(link_target),
3277 - "is_symlink": True,
3278 - "symlink_target": link_target,
3279 - })
3280 - return True
3281 -
3282 - # --- ZWYKŁY PLIK ---
3283 - # Oblicz SHA256
3284 - try:
3285 - file_sha = _sha256_file(src)
3286 - except Exception:
3287 - file_sha = ""
3288 -
3289 - # Weryfikuj sums.json
3290 - expected = sums.get("/" + rel, "")
3291 - if expected and file_sha and file_sha != expected:
3292 - return False
3293 -
3294 - # --- .pacnew: NIE nadpisuj pliku konfiguracyjnego, którego nie wolno zgubić ---
3295 - # Robimy `<plik>.pacnew`, gdy:
3296 - # a) plik jest śledzony i użytkownik go zmodyfikował (hash != zapisanej sumy),
3297 - # b) to wrażliwa konfiguracja (/etc/pam.d, /etc/security, sudoers, shadow…),
3298 - # a treść na dysku różni się od tej z pakietu – chroni auth przed
3299 - # cichym nadpisaniem przez `install`/`upgrade` (np. przez shadow).
3300 - # NIE robimy .pacnew, jeśli plik na dysku jest identyczny z nowym albo był
3301 - # niezmieniony od instalacji (wtedy nadpisanie jest bezpieczne).
3302 - old_sha = (old_checksums or {}).get("/" + rel, "")
3303 - if file_sha and _is_config_path(rel) and os.path.isfile(dst) and not os.path.islink(dst):
3304 - tracked_modified = bool(old_sha) and file_sha != old_sha
3305 - if tracked_modified or _is_sensitive_config(rel):
3306 - try:
3307 - cur_sha = _sha256_file(dst)
3308 - except OSError:
3309 - cur_sha = ""
3310 - if cur_sha and cur_sha != file_sha and not (old_sha and cur_sha == old_sha):
3311 - pacnew = dst + ".pacnew"
3312 - try:
3313 - _safe_rename(src, pacnew)
3314 - try:
3315 - os.chown(pacnew, 0, 0)
3316 - except (OSError, PermissionError):
3317 - pass
3318 - # Journal (do cofnięcia przy nieudanej transakcji) – ale NIE
3319 - # zapisujemy .pacnew w bazie plików: to artefakt użytkownika.
3320 - journal.append(("file", src, pacnew))
3321 - print(f" ⚠ {_('conf_pacnew', path=pacnew)}")
3322 - return True
3323 - except OSError:
3324 - pass # nie udało się – kontynuuj normalną instalację
3325 -
3326 - # Utwórz katalog docelowy
3327 - os.makedirs(os.path.dirname(dst), exist_ok=True)
3328 -
3329 - # Backup istniejącego pliku (upgrade) – dla poprawnego rollbacku
3330 - if backup_dir and backup_journal is not None and os.path.lexists(dst):
3331 - try:
3332 - backup_path = os.path.join(backup_dir, rel)
3333 - os.makedirs(os.path.dirname(backup_path), exist_ok=True)
3334 - os.replace(dst, backup_path)
3335 - backup_journal.append((backup_path, "/" + rel))
3336 - journal.append(("backup", backup_path, dst))
3337 - except OSError:
3338 - pass
3339 -
3340 - # Atomowe przeniesienie (z fallbackiem dla cross-device).
3341 - # Zachowuje bity uprawnień (SUID/SGID/sticky) – NIE używamy filter='data'.
3342 - _safe_rename(src, dst)
3343 -
3344 - if "/" + rel in privileged:
3345 - # Plik uprzywilejowany: zostaw właściciela, grupę i bity z pakietu
3346 - # (np. sudo 4755 root:root, qemu-bridge-helper 4750 root:kvm).
3347 - try:
3348 - st = os.stat(dst)
3349 - if st.st_mode & 0o6000:
3350 - _audit(f"privileged {dst} mode={oct(st.st_mode & 0o7777)} "
3351 - f"uid={st.st_uid} gid={st.st_gid}")
3352 - except OSError:
3353 - pass
3354 - else:
3355 - # Wymuś właściciela root:root. UWAGA: os.chown() NIE czyści bitów SUID/SGID.
3356 - try:
3357 - os.chown(dst, 0, 0)
3358 - except (OSError, PermissionError):
3359 - # Na niektórych systemach plików (tmpfs, fat) chown może się nie powieść
3360 - pass
3361 -
3362 - journal.append(("file", src, dst))
3363 - installed_files.append({
3364 - "path": "/" + rel,
3365 - "sha256": file_sha,
3366 - "size": os.path.getsize(dst),
3367 - "is_symlink": False,
3368 - })
3369 - return True
3370 -
3371 -
3372 -
3373 -def _stage_package(pkg_path: str, pkg: PackageInfo) -> Optional[dict]:
3374 - """Rozpakowuje pakiet do stagingu, NIE dotykając systemu.
3375 -
3376 - Zwraca dict: staging, data, sums, hooks. None przy błędzie.
3377 -
3378 - To pierwsza faza transakcji grupowej: najpierw przygotowujemy WSZYSTKIE
3379 - pakiety (np. całe GNOME – 50 paczek). Dopiero gdy każda się rozpakuje i
3380 - przejdzie weryfikację SHA256, przechodzimy do fazy commit. Błąd jednej
3381 - paczki nie zostawia więc systemu w połowie instalacji.
3382 - """
3383 - staging = tempfile.mkdtemp(dir=STAGING_DIR, prefix=f".stage-{pkg.name}-")
3384 - try:
3385 - with tarfile.open(pkg_path, "r:xz") as tf:
3386 - _safe_extractall(tf, staging)
3387 -
3388 - data_tar = os.path.join(staging, "data.tar.xz")
3389 - if not os.path.exists(data_tar):
3390 - raise RuntimeError(_("pkg_missing_data_tar"))
3391 -
3392 - data_staging = os.path.join(staging, "data")
3393 - os.makedirs(data_staging, exist_ok=True)
3394 - priv = PRIVILEGED_PATHS | frozenset(pkg.privileged or ())
3395 - with tarfile.open(data_tar, "r:xz") as tf:
3396 - _safe_extractall(tf, data_staging, privileged=priv)
3397 -
3398 - sums_path = os.path.join(data_staging, "sums.json")
3399 - sums = json.load(open(sums_path)) if os.path.exists(sums_path) else {}
3400 -
3401 - # Weryfikacja SHA256 JUŻ w stagingu – uszkodzona paczka nie dojdzie
3402 - # do fazy commit, więc nie zdąży nadpisać żadnego pliku w systemie.
3403 - _bad: List[str] = []
3404 - for _root, _dirs, _files in os.walk(data_staging):
3405 - for _name in list(_dirs) + _files:
3406 - if _name == "sums.json":
3407 - continue
3408 - _fp = os.path.join(_root, _name)
3409 - _rel = "/" + os.path.relpath(_fp, data_staging)
3410 - _expected = sums.get(_rel, "")
3411 - if not _expected:
3412 - continue
3413 - try:
3414 - if os.path.islink(_fp):
3415 - _actual = hashlib.sha256(
3416 - os.readlink(_fp).encode()).hexdigest()
3417 - elif os.path.isfile(_fp):
3418 - _actual = _sha256_file(_fp)
3419 - else:
3420 - continue
3421 - except OSError:
3422 - _actual = ""
3423 - if _actual != _expected:
3424 - _bad.append(_rel)
3425 - if len(_bad) >= 5:
3426 - break
3427 - if len(_bad) >= 5:
3428 - break
3429 - if _bad:
3430 - raise RuntimeError(_("pkg_sha_mismatch", ", ".join(_bad[:5])))
3431 -
3432 - return {
3433 - "staging": staging,
3434 - "data": data_staging,
3435 - "sums": sums,
3436 - "hooks": os.path.join(staging, "hooks"),
3437 - }
3438 - except Exception as e:
3439 - shutil.rmtree(staging, ignore_errors=True)
3440 - print(_(' ❌ {arg1}: preparation stage failed ({arg2})', arg1=(pkg.name), arg2=(e)))
3441 - return None
3442 -
3443 -
3444 -def _discard_staged(staged: Optional[dict]):
3445 - """Usuwa katalog stagingu przygotowanego pakietu (bez zmian w systemie)."""
3446 - if staged and staged.get("staging"):
3447 - shutil.rmtree(staged["staging"], ignore_errors=True)
3448 -
3449 -
3450 -def _apply_staged_package(staged: dict, pkg: PackageInfo, deploy_dir: str = "",
3451 - backup_dir: str = "",
3452 - old_checksums: Optional[dict] = None
3453 - ) -> Tuple[bool, List[dict], List[Tuple[str, str]]]:
3454 - """Faza commit: przenosi przygotowany pakiet do systemu.
3455 -
3456 - Hooki pre/post-install uruchamiane są tutaj – dopiero po tym, jak cała
3457 - grupa pakietów została poprawnie rozpakowana w stagingu.
3458 - """
3459 - staging = staged["staging"]
3460 - data_staging = staged["data"]
3461 - sums = staged["sums"]
3462 - hooks_dir = staged["hooks"]
3463 - priv = PRIVILEGED_PATHS | frozenset(pkg.privileged or ())
3464 - journal: List[tuple] = []
3465 - installed_files: List[dict] = []
3466 - backup_journal: List[Tuple[str, str]] = []
3467 -
3468 - try:
3469 - # Hook pre-install (przed przeniesieniem plików do systemu)
3470 - _run_hook(hooks_dir, "pre-install", pkg)
3471 -
3472 - # Przenieś pliki: staging/data/* → /
3473 - for root, dirs, files in os.walk(data_staging):
3474 - # Symlink do katalogu (np. /lib → usr/lib) os.walk zwraca w `dirs`.
3475 - # Nie wolno tworzyć z niego prawdziwego katalogu – przekieruj do
3476 - # pętli plików, gdzie _install_file odtworzy symlink.
3477 - for _d in list(dirs):
3478 - if os.path.islink(os.path.join(root, _d)):
3479 - dirs.remove(_d)
3480 - files.append(_d)
3481 -
3482 - # Odtwórz katalogi z pakietu – w tym PUSTE (np. /etc/pulse/default.pa.d).
3483 - for d in dirs:
3484 - src_dir = os.path.join(root, d)
3485 - rel_dir = os.path.relpath(src_dir, data_staging)
3486 - if deploy_dir and _is_shared_path("/" + rel_dir):
3487 - dst_root = PAG_ROOT
3488 - elif deploy_dir:
3489 - dst_root = deploy_dir
3490 - else:
3491 - dst_root = PAG_ROOT
3492 - dst_dir = os.path.join(dst_root, rel_dir)
3493 - if not os.path.isdir(dst_dir):
3494 - try:
3495 - os.makedirs(dst_dir, exist_ok=True)
3496 - except OSError:
3497 - pass
3498 - for fname in files:
3499 - if fname == "sums.json":
3500 - continue
3501 - src = os.path.join(root, fname)
3502 - rel = os.path.relpath(src, data_staging)
3503 -
3504 - ok = _install_file(src, rel, data_staging, sums,
3505 - staging, journal, installed_files, deploy_dir,
3506 - backup_dir, backup_journal,
3507 - old_checksums=old_checksums,
3508 - privileged=priv)
3509 - if not ok:
3510 - # Cofnij wszystkie operacje
3511 - _rollback_journal(journal, staging)
3512 - return False, [], backup_journal
3513 -
3514 - # Odbuduj cache ikon GTK dla motywów dotkniętych instalacją.
3515 - _icon_dirs = set()
3516 - for f in installed_files:
3517 - fp = f.get("path", "") or ""
3518 - if fp.startswith("/usr/share/icons/"):
3519 - _rest = fp[len("/usr/share/icons/"):]
3520 - _theme = _rest.split("/", 1)[0]
3521 - if _theme:
3522 - _icon_dirs.add(os.path.join(PAG_ROOT, "usr/share/icons", _theme))
3523 - if _icon_dirs:
3524 - try:
3525 - subprocess.run(["gtk-update-icon-cache", "--version"],
3526 - capture_output=True, timeout=10)
3527 - for _d in sorted(_icon_dirs):
3528 - if os.path.isdir(_d):
3529 - subprocess.run(["gtk-update-icon-cache", "-f", "-q", _d],
3530 - capture_output=True, timeout=300)
3531 - except Exception:
3532 - pass
3533 -
3534 - # Uruchom hooki post-install
3535 - _run_hook(hooks_dir, "post-install", pkg)
3536 -
3537 - # Zachowaj hooki na wypadek usunięcia pakietu (pre/post-remove)
3538 - try:
3539 - if os.path.isdir(hooks_dir):
3540 - persisted = os.path.join(PAG_DB, "hooks", pkg.name)
3541 - shutil.rmtree(persisted, ignore_errors=True)
3542 - shutil.copytree(hooks_dir, persisted)
3543 - except Exception:
3544 - pass
3545 -
3546 - # Zapisz do SQLite
3547 - _db_record_files(pkg.name, installed_files)
3548 -
3549 - shutil.rmtree(staging, ignore_errors=True)
3550 - return True, installed_files, backup_journal
3551 -
3552 - except Exception as e:
3553 - _rollback_journal(journal, staging)
3554 - print(_(' ❌ {arg1}: commit error – {arg2}', arg1=(pkg.name), arg2=(e)))
3555 - return False, [], backup_journal
3556 -
3557 -
3558 -def _atomic_install(pkg_path: str, pkg: PackageInfo, deploy_dir: str = "",
3559 - backup_dir: str = "",
3560 - old_checksums: Optional[dict] = None
3561 - ) -> Tuple[bool, List[dict], List[Tuple[str, str]]]:
3562 - """Instaluje pojedynczy pakiet dwufazowo: staging → commit.
3563 -
3564 - Zachowane jako publiczny wrapper dla instalacji pojedynczych plików
3565 - lokalnych; transakcja grupowa w cmd_install przygotowuje staging dla
3566 - całej grupy i wywołuje _apply_staged_package bezpośrednio.
3567 - """
3568 - staged = _stage_package(pkg_path, pkg)
3569 - if not staged:
3570 - return False, [], []
3571 - return _apply_staged_package(staged, pkg, deploy_dir, backup_dir, old_checksums)
3572 -
3573 -def _refresh_dynamic_linker_cache(deploy_dir: str = "") -> bool:
3574 - """Odświeża cache ld.so po udanej instalacji pakietów."""
3575 - ldconfig = shutil.which("ldconfig")
3576 - if not ldconfig:
3577 - print(_(' ⚠ ldconfig not found — linker cache was not refreshed.'),
3578 - file=sys.stderr)
3579 - return False
3580 -
3581 - target_root = deploy_dir or PAG_ROOT
3582 - command = [ldconfig]
3583 - if target_root != "/":
3584 - command.extend(["-r", target_root])
3585 -
3586 - try:
3587 - subprocess.run(command, check=True, timeout=60,
3588 - stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
3589 - text=True)
3590 - return True
3591 - except (OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc:
3592 - detail = getattr(exc, "stderr", None) or str(exc)
3593 - print(_(' ⚠ Failed to refresh ld.so cache: {arg1}', arg1=(detail.strip())),
3594 - file=sys.stderr)
3595 - return False
3596 -
3597 -
3598 -def _rollback_journal(journal: list, staging_path: str):
3599 - """Cofa wszystkie operacje z journala (odwrotna kolejność)."""
3600 - for entry in reversed(journal):
3601 - op = entry[0]
3602 - if op == "file":
3603 - _, src, dst = entry
3604 - try:
3605 - if os.path.exists(dst) or os.path.islink(dst):
3606 - _safe_rename(dst, src)
3607 - except Exception:
3608 - pass
3609 - elif op == "symlink":
3610 - _, _, dst = entry
3611 - try:
3612 - if os.path.islink(dst) or os.path.exists(dst):
3613 - os.remove(dst)
3614 - except Exception:
3615 - pass
3616 - elif op == "backup":
3617 - # Przywróć starą wersję pliku z backupu (upgrade)
3618 - _, bpath, dst = entry
3619 - try:
3620 - if os.path.lexists(bpath):
3621 - os.replace(bpath, dst)
3622 - except Exception:
3623 - pass
3624 - shutil.rmtree(staging_path, ignore_errors=True)
3625 -
3626 -# =============================================================================
3627 -# BEZPIECZNE USUWANIE
3628 -# =============================================================================
3629 -
3630 -def _safe_remove_files(pkg_name: str, installed_db: dict) -> Tuple[int, List[str]]:
3631 - """
3632 - Usuwa pliki pakietu, ale tylko jeśli NIE są współdzielone z innym pakietem.
3633 - Zwraca (liczba usuniętych, [lista usuniętych ścieżek]).
3634 - """
3635 - pkg_files = _db_get_package_files(pkg_name)
3636 - recorded = _db_get_package_checksums(pkg_name)
3637 - removed = []
3638 - skipped_shared = []
3639 - skipped_sensitive = []
3640 -
3641 - for fpath in pkg_files:
3642 - owners = _db_get_file_owners(fpath)
3643 - # Sprawdź czy inny ZAINSTALOWANY pakiet też jest właścicielem
3644 - other_owners = [o for o in owners if o != pkg_name and o in installed_db]
3645 -
3646 - if other_owners:
3647 - # Plik współdzielony – tylko usuń wpis w DB, nie kasuj pliku
3648 - skipped_shared.append(fpath)
3649 - continue
3650 -
3651 - full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
3652 - if os.path.isfile(full) or os.path.islink(full):
3653 - # Wrażliwej konfiguracji systemowej (/etc/pam.d, sudoers, shadow…)
3654 - # NIE kasujemy przy `remove` – jej brak potrafi zablokować logowanie
3655 - # i sudo (np. usunięcie system-auth/system-account). Zostaje wpis w bazie.
3656 - if _is_sensitive_config(fpath):
3657 - skipped_sensitive.append(fpath)
3658 - continue
3659 - # .pacsave: zachowaj ZMIENIONY plik konfiguracyjny zamiast kasować
3660 - # (porównanie z sumą z chwili instalacji), wzorzec jak w pacmanie.
3661 - if not os.path.islink(full) and _is_config_path(fpath):
3662 - old_sha = recorded.get(fpath, "")
3663 - if old_sha:
3664 - try:
3665 - cur_sha = _sha256_file(full)
3666 - except OSError:
3667 - cur_sha = ""
3668 - if cur_sha and cur_sha != old_sha:
3669 - pacsave = full + ".pacsave"
3670 - try:
3671 - os.replace(full, pacsave)
3672 - print(f" ⚠ {_('conf_pacsave', path=pacsave)}")
3673 - removed.append(fpath)
3674 - continue
3675 - except OSError:
3676 - pass
3677 - os.remove(full)
3678 - removed.append(fpath)
3679 -
3680 - # Usuń puste katalogi (od najgłębszych)
3681 - dirs = set()
3682 - for fpath in removed + skipped_shared:
3683 - parent = os.path.dirname(fpath)
3684 - while parent and parent != "/":
3685 - dirs.add(parent)
3686 - parent = os.path.dirname(parent)
3687 -
3688 - for d in sorted(dirs, key=len, reverse=True):
3689 - full_d = os.path.join(PAG_ROOT, d.lstrip("/"))
3690 - if os.path.isdir(full_d):
3691 - try:
3692 - os.rmdir(full_d)
3693 - except OSError:
3694 - pass # nie jest pusty – OK
3695 -
3696 - # Usuń z SQLite
3697 - _db_remove_package_files(pkg_name)
3698 -
3699 - if skipped_shared:
3700 - print(_(' ⚠ {arg1} shared files preserved', arg1=(len(skipped_shared))))
3701 - if skipped_sensitive:
3702 - print(_(' ⚠ {arg1} sensitive system files preserved', arg1=(len(skipped_sensitive))))
3703 -
3704 - return len(removed) + len(skipped_shared) + len(skipped_sensitive), removed
3705 -
3706 -
3707 -def _remove_stale_files(pkg_name: str, old_files: List[str], new_paths: List[str],
3708 - installed_db: dict, deploy_dir: str = "",
3709 - backup_dir: str = "", backup_journal: Optional[list] = None) -> Tuple[int, List[str]]:
3710 - """
3711 - Po upgrade usuwa pliki starej wersji, których nie ma w nowej.
3712 -
3713 - - Pliki współdzielone z innym zainstalowanym pakietem są ZACHOWYWANE
3714 - (usuwany jest tylko wpis z bazy `files` dla tego pakietu).
3715 - - Sprząta puste katalogi i wpisy SQLite starej wersji.
3716 - Zwraca (liczba usuniętych, [usunięte ścieżki]).
3717 - """
3718 - new_set = set(new_paths)
3719 - # Warianty /usr/lib <-> /usr/lib64: plik obecny w nowej wersji pod równoważną
3720 - # ścieżką NIE jest przestarzały. Bez tego upgrade kasował właśnie
3721 - # zainstalowany plik, gdy stara i nowa wersja używały różnych libdir
3722 - # (kolizja lib/lib64).
3723 - new_effective = set()
3724 - for _p in new_set:
3725 - new_effective.add(_p)
3726 - if _p.startswith("/usr/lib64/"):
3727 - new_effective.add("/usr/lib/" + _p[len("/usr/lib64/"):])
3728 - elif _p.startswith("/usr/lib/"):
3729 - new_effective.add("/usr/lib64/" + _p[len("/usr/lib/"):])
3730 - stale = [f for f in old_files if f not in new_effective]
3731 - if not stale:
3732 - return 0, []
3733 -
3734 - root = deploy_dir or PAG_ROOT
3735 - removed = []
3736 - skipped = 0
3737 - for fpath in stale:
3738 - owners = _db_get_file_owners(fpath)
3739 - other_owners = [o for o in owners if o != pkg_name and o in installed_db]
3740 - if other_owners:
3741 - # Współdzielony z innym pakietem – tylko usuń wpis z DB dla tego pakietu
3742 - skipped += 1
3743 - else:
3744 - # Wrażliwych plików systemowych NIE kasujemy, gdy nowy pakiet ich już
3745 - # nie dostarcza (np. shadow przestaje pakować system-*). Ich brak
3746 - # blokuje login/sudo; usuwamy więc tylko wpis w bazie.
3747 - if _is_sensitive_config(fpath):
3748 - skipped += 1
3749 - else:
3750 - # Gdy nowa wersja pliku /etc trafiła do .pacnew, plik użytkownika
3751 - # MUSI zostać – nie jest „przestarzały”. Zachowujemy też wpis w bazie
3752 - # (stara suma), by kolejny upgrade dalej wykrywał zmiany użytkownika.
3753 - if _is_config_path(fpath):
3754 - _cfg_full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
3755 - if os.path.lexists(_cfg_full + ".pacnew"):
3756 - skipped += 1
3757 - continue
3758 - full = os.path.join(root, fpath.lstrip("/"))
3759 - if os.path.isfile(full) or os.path.islink(full):
3760 - try:
3761 - if backup_dir and backup_journal is not None:
3762 - backup_path = os.path.join(backup_dir, fpath.lstrip("/"))
3763 - os.makedirs(os.path.dirname(backup_path), exist_ok=True)
3764 - os.replace(full, backup_path) # przenieś do backupu (rollback)
3765 - backup_journal.append((backup_path, fpath))
3766 - else:
3767 - os.remove(full)
3768 - removed.append(fpath)
3769 - except OSError:
3770 - pass
3771 - # Usuń wpis `files` dla tego pakietu (stara wersja już go nie zawiera)
3772 - with _db_session() as db:
3773 - db.execute("DELETE FROM files WHERE package=? AND path=?", (pkg_name, fpath))
3774 -
3775 - # Usuń puste katalogi (od najgłębszych)
3776 - dirs = set()
3777 - for fpath in removed:
3778 - parent = os.path.dirname(fpath)
3779 - while parent and parent != "/":
3780 - dirs.add(parent)
3781 - parent = os.path.dirname(parent)
3782 - for d in sorted(dirs, key=len, reverse=True):
3783 - full_d = os.path.join(root, d.lstrip("/"))
3784 - if os.path.isdir(full_d):
3785 - try:
3786 - os.rmdir(full_d)
3787 - except OSError:
3788 - pass # nie jest pusty – OK
3789 -
3790 - if removed:
3791 - print(_(' 🧹 Removed {arg1} obsolete files ({arg2})', arg1=(len(removed)), arg2=(pkg_name)))
3792 - if skipped:
3793 - print(_(' ⚠ {arg1} shared files preserved', arg1=(skipped)))
3794 -
3795 - return len(removed), removed
3796 -
3797 -
3798 -def _new_transaction_backup_root() -> str:
3799 - """Katalog na backupy NADPISYWANYCH plików dla bieżącej transakcji.
3800 -
3801 - Tworzony dla KAŻDEJ transakcji, nie tylko upgrade: „świeża” instalacja
3802 - pakietu też potrafi nadpisać pliki spoza bazy pag (baza rootfs/ISO).
3803 - Gdy transakcja padnie, rollback MUSI mieć co przywrócić – inaczej kasuje
3804 - te pliki (tak zniknął m.in. libpam.so.0 i przestał działać sudo)."""
3805 - txn = datetime.now().strftime("%Y%m%dT%H%M%S") + "-" + str(os.getpid())
3806 - root = os.path.join(STAGING_DIR, "backups", txn)
3807 - os.makedirs(root, exist_ok=True)
3808 - return root
3809 -
3810 -
3811 -def _purge_old_backups(keep_root: str = ""):
3812 - """Usuwa backupy starszych transakcji (zostawia bieżący – dla `pag rollback`)."""
3813 - base = os.path.join(STAGING_DIR, "backups")
3814 - if not os.path.isdir(base):
3815 - return
3816 - for entry in os.listdir(base):
3817 - p = os.path.join(base, entry)
3818 - if p != keep_root and os.path.isdir(p):
3819 - shutil.rmtree(p, ignore_errors=True)
3820 -
3821 -
3822 -def _recover_interrupted_transactions(verbose=True) -> int:
3823 - """Przywraca pliki po transakcji PRZERWANEJ w polowie (crash / kill -9).
3824 -
3825 - Backup transakcji (/.pag_staging/backups/<txn>) powstaje, ZANIM pliki zostana
3826 - podmienione. Jesli pag zginie w trakcie, czesc plikow jest juz przeniesiona do
3827 - backupu, a nowych jeszcze nie ma -> system zostaje bez pliku.
3828 -
3829 - Dla kazdego katalogu backupu, ktory NIE jest zapisany w historii jako UDANA
3830 - transakcja (`upgrade_backup_root` przy `success=true`; takie zostawiamy dla
3831 - `pag rollback`), przywracamy pliki nieobecne w systemie. Potem odswiezamy
3832 - cache linkera.
3833 - """
3834 - base = os.path.join(STAGING_DIR, "backups")
3835 - if not os.path.isdir(base):
3836 - return 0
3837 - try:
3838 - history = load_json(HISTORY_FILE) or []
3839 - except Exception:
3840 - history = []
3841 - done_roots = {
3842 - e.get("upgrade_backup_root") for e in history
3843 - if isinstance(e, dict) and e.get("success") and e.get("upgrade_backup_root")
3844 - }
3845 - restored = 0
3846 - for txn in sorted(os.listdir(base)):
3847 - root = os.path.join(base, txn)
3848 - if not os.path.isdir(root) or root in done_roots:
3849 - continue
3850 - for dirpath, _dirs, files in os.walk(root):
3851 - for fn in files:
3852 - src = os.path.join(dirpath, fn)
3853 - rel = os.path.relpath(src, root)
3854 - dst = os.path.join(PAG_ROOT, rel)
3855 - if os.path.lexists(dst):
3856 - continue
3857 - try:
3858 - os.makedirs(os.path.dirname(dst), exist_ok=True)
3859 - if os.path.islink(src):
3860 - os.symlink(os.readlink(src), dst)
3861 - else:
3862 - shutil.copy2(src, dst)
3863 - restored += 1
3864 - except OSError:
3865 - pass
3866 - if restored:
3867 - try:
3868 - subprocess.run(["ldconfig"], capture_output=True, timeout=120)
3869 - except Exception:
3870 - pass
3871 - if verbose:
3872 - print(_(' 🛠 Interrupted transaction detected – restored {arg1} missing files.', arg1=(restored)))
3873 - return restored
3874 -
3875 -
3876 -# =============================================================================
3877 -# HOOKI
3878 -# =============================================================================
3879 -# Hooki uruchamiają dowolny plik z pakietu jako root — to naturalna cecha
3880 -# menedżera pakietów (apt/pacman też tak mają), dlatego MUSISZ ufać repozytorium.
3881 -# Aby ograniczyć ryzyko:
3882 -# - hook dostaje minimalne, "czyste" środowisko (bez LD_PRELOAD, BASH_ENV itp.)
3883 -# - hooki można wyłączyć (PAG_NO_HOOKS=1) i ustawić timeout (PAG_HOOK_TIMEOUT)
3884 -# - każde uruchomienie jest logowane do /var/log/pag/audit.log
3885 -# - hook ma wersjonowane API (PKG_HOOK_API)
3886 -# =============================================================================
3887 -
3888 -# Lista wykonanych hooków — trafia do wpisu transakcji (informacja w rejestrze).
3889 -_HOOKS_RUN: List[str] = []
3890 -
3891 -
3892 -def _hook_env(pkg: PackageInfo, hook_name: str) -> dict:
3893 - """Buduje minimalne środowisko dla hooka (bez niebezpiecznych zmiennych)."""
3894 - return {
3895 - "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
3896 - "HOME": "/root",
3897 - "LANG": "C.UTF-8",
3898 - "LC_ALL": "C.UTF-8",
3899 - "PKG_NAME": pkg.name,
3900 - "PKG_VERSION": pkg.version,
3901 - "PKG_ACTION": hook_name,
3902 - "PKG_HOOK_API": HOOK_API_VERSION,
3903 - }
3904 -
3905 -
3906 -def _hook_timeout() -> int:
3907 - """Timeout hooka w sekundach.
3908 -
3909 - Domyślnie 900 s, bo hooki jądra/NVIDIA budują moduły DKMS i initramfs –
3910 - na wolniejszych maszynach to kilka minut. Krótszy limit (dawniej 60 s)
3911 - zabijał hook w połowie i zostawiał /boot bez aktualnego initramfs.
3912 - Nadpisz przez `PAG_HOOK_TIMEOUT`.
3913 - """
3914 - try:
3915 - return max(1, int(os.environ.get("PAG_HOOK_TIMEOUT", "900")))
3916 - except Exception:
3917 - return 900
3918 -
3919 -
3920 -def _run_hook(hooks_dir: str, hook_name: str, pkg: PackageInfo) -> bool:
3921 - """Uruchamia skrypt hooka jeśli istnieje.
3922 -
3923 - Zwraca True jeśli hook został WYKONANY (istniał i uruchomiono go), False w
3924 - pozostałych przypadkach (brak pliku, wyłączone hooki, błąd). Obsługuje
3925 - ograniczone środowisko, timeout, logowanie do audytu i rejestr w transakcji.
3926 - """
3927 - hook_path = os.path.join(hooks_dir, hook_name)
3928 - if not os.path.exists(hook_path):
3929 - return False
3930 -
3931 - if os.environ.get("PAG_NO_HOOKS", "") == "1":
3932 - print(_(' ⚠ Hook skipped (PAG_NO_HOOKS=1): {arg1} for {arg2}', arg1=(hook_name), arg2=(pkg.name)))
3933 - _audit(f"hook SKIP {hook_name} {pkg.name}-{pkg.version} (PAG_NO_HOOKS=1)")
3934 - return False
3935 -
3936 - os.chmod(hook_path, 0o755)
3937 - env = _hook_env(pkg, hook_name)
3938 - tag = f"{hook_name} {pkg.name}-{pkg.version}"
3939 - try:
3940 - result = subprocess.run([hook_path], env=env, timeout=_hook_timeout(),
3941 - check=False, capture_output=True, text=True,
3942 - cwd="/")
3943 - _HOOKS_RUN.append(tag)
3944 - if result.returncode != 0:
3945 - print(_(' ⚠ Hook {arg1} for {arg2} exited with code {arg3}', arg1=(hook_name), arg2=(pkg.name), arg3=(result.returncode)))
3946 - if result.stderr:
3947 - print(f" {result.stderr.strip()[-200:]}")
3948 - _audit(f"hook FAIL {tag} rc={result.returncode}")
3949 - else:
3950 - _audit(f"hook OK {tag}")
3951 - return True
3952 - except subprocess.TimeoutExpired:
3953 - print(_(' ⚠ Hook {arg1} for {arg2} timed out ({arg3}s)', arg1=(hook_name), arg2=(pkg.name), arg3=(_hook_timeout())))
3954 - print(_(' Increase PAG_HOOK_TIMEOUT (e.g. PAG_HOOK_TIMEOUT=1800) and retry.'))
3955 - _audit(f"hook TIMEOUT {tag}")
3956 - return False
3957 - except Exception as e:
3958 - print(_(' ⚠ Hook {arg1} for {arg2}: {arg3}', arg1=(hook_name), arg2=(pkg.name), arg3=(e)))
3959 - _audit(f"hook ERROR {tag}: {e}")
3960 - return False
3961 -
3962 -# =============================================================================
3963 -# TRANSAKCJE I ROLLBACK
3964 -# =============================================================================
3965 -
3966 -def _record_transaction(action, packages, success, snapshot, file_journal=None, hooks=None,
3967 - upgrade_backups=None, upgrade_backup_root="", snapshot_id=""):
3968 - history = load_json(HISTORY_FILE) if os.path.exists(HISTORY_FILE) else []
3969 - # Rejestr wykonanych hooków – informacja o tym, że uruchomiono kod pakietu
3970 - # jako root. Trafia do historii, by dało się później sprawdzić, co się działo.
3971 - executed_hooks = list(_HOOKS_RUN) if hooks is None else hooks
3972 - _HOOKS_RUN.clear()
3973 - entry = {
3974 - "action": action, "packages": packages, "success": success,
3975 - "timestamp": datetime.now().isoformat(),
3976 - "snapshot": snapshot,
3977 - "file_journal": file_journal, # lista plików do wycofania
3978 - "hooks": executed_hooks, # wykonane hooki (pre/post-install/remove)
3979 - }
3980 - if snapshot_id:
3981 - # Snapshot systemu (btrfs) z chwili PRZED transakcją – można z niego
3982 - # uruchomić system z menu GRUB albo podejrzeć `pag snapshot-list`.
3983 - entry["snapshot_id"] = snapshot_id
3984 - if upgrade_backups:
3985 - entry["upgrade_backups"] = upgrade_backups # {dst: backup_path}
3986 - entry["upgrade_backup_root"] = upgrade_backup_root
3987 - history.append(entry)
3988 - if len(history) > 50:
3989 - history = history[-50:]
3990 - save_json(HISTORY_FILE, history)
3991 -
3992 -def _action_label(action):
3993 - key = "action_" + str(action)
3994 - return _(key) if key in T.get("en", {}) else str(action)
3995 -
3996 -def cmd_history():
3997 - if not os.path.exists(HISTORY_FILE):
3998 - print(_("no_history")); return
3999 - history = load_json(HISTORY_FILE)
4000 - if not history:
4001 - print(_("no_history")); return
4002 - print(_('Recent transactions ({arg1}):', arg1=(len(history))))
4003 - for i, e in enumerate(reversed(history), 1):
4004 - icon = "✅" if e["success"] else "❌"
4005 - pkgs = ", ".join(e["packages"][:5])
4006 - if len(e["packages"]) > 5: pkgs += f" (+{len(e['packages'])-5})"
4007 - print(f" {i}. {icon} {_action_label(e['action'])}: {pkgs}")
4008 - print(f" {e['timestamp']}")
4009 -
4010 -def cmd_rollback():
4011 - if not os.path.exists(HISTORY_FILE):
4012 - print(_("no_history")); return 1
4013 - history = load_json(HISTORY_FILE)
4014 - if not history:
4015 - print(_("no_history")); return 1
4016 -
4017 - last = None
4018 - for e in reversed(history):
4019 - if e["success"] and e.get("snapshot"):
4020 - last = e; break
4021 -
4022 - if not last:
4023 - print(_('❌ No snapshot to restore.')); return 1
4024 -
4025 - print(_('⏪ Rolling back: {arg1} ({arg2})', arg1=(_action_label(last['action'])), arg2=(last['timestamp'])))
4026 - print(_(' Packages: {arg1}', arg1=(', '.join(last['packages'][:10]))))
4027 -
4028 - if not _ask_confirm():
4029 - return 0
4030 -
4031 - # Przywróć installed.json
4032 - save_json(INSTALLED_DB, last["snapshot"])
4033 -
4034 - # Wycofaj fizyczne pliki (jeśli zapisano journal)
4035 - # Deduplikacja: pakiet może zgłosić ten sam plik więcej niż raz (np. przez
4036 - # `provides` lub wspólną ścieżkę), a journal z historii mógł zostać zapisany
4037 - # przed dodaniem deduplikacji.
4038 - file_journal = list(dict.fromkeys(last.get("file_journal", [])))
4039 - upgrade_backups = last.get("upgrade_backups", {}) or {}
4040 - backup_root = last.get("upgrade_backup_root", "")
4041 -
4042 - # Przywróć stare wersje z backupów (upgrade) – nadpisane i usunięte stale pliki
4043 - for dst, bpath in upgrade_backups.items():
4044 - full = os.path.join(PAG_ROOT, dst.lstrip("/"))
4045 - if bpath and os.path.lexists(bpath):
4046 - try:
4047 - os.makedirs(os.path.dirname(full), exist_ok=True)
4048 - os.replace(bpath, full)
4049 - except OSError:
4050 - pass
4051 -
4052 - # Usuń nowe pliki (które nie miały poprzedniej wersji)
4053 - backed = set(upgrade_backups)
4054 - if file_journal:
4055 - for fpath in reversed(file_journal):
4056 - if fpath in backed:
4057 - continue
4058 - full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
4059 - if os.path.exists(full) or os.path.islink(full):
4060 - os.remove(full)
4061 - print(f" {_('rollback_files', len(file_journal))}")
4062 -
4063 - # Sprzątanie pustych katalogów + katalogu backupów
4064 - dirs = set()
4065 - for fpath in file_journal:
4066 - parent = os.path.dirname(fpath)
4067 - while parent and parent != "/":
4068 - dirs.add(parent)
4069 - parent = os.path.dirname(parent)
4070 - for d in sorted(dirs, key=len, reverse=True):
4071 - full_d = os.path.join(PAG_ROOT, d.lstrip("/"))
4072 - if os.path.isdir(full_d):
4073 - try:
4074 - os.rmdir(full_d)
4075 - except OSError:
4076 - pass
4077 - if backup_root:
4078 - shutil.rmtree(backup_root, ignore_errors=True)
4079 -
4080 - print(f"✅ {_('rollback_restored')}")
4081 - _record_transaction("rollback", last["packages"], True, None)
4082 - return 0
4083 -
4084 -# =============================================================================
4085 -# INSTALACJA
4086 -# =============================================================================
4087 -
4088 -def _install_local_pkg_files(paths, install_succeeded):
4089 - """Instaluje lokalne pliki .pag (bez repozytorium).
4090 -
4091 - Najpierw przygotowuje WSZYSTKIE paczki w stagingu, potem je nakłada.
4092 - Dzięki temu uszkodzony plik w środku grupy nie zostawia systemu
4093 - w połowie instalacji. Zwraca (failed_count, installed_files).
4094 - """
4095 - failed = 0
4096 - prepared = []
4097 - for p in paths:
4098 - p = os.path.abspath(p)
4099 - if not os.path.isfile(p):
4100 - print(_(' ❌ Package not found: {arg1}', arg1=(p)))
4101 - failed += 1
4102 - break
4103 - if not _verify_local_pkg_signature(p):
4104 - failed += 1
4105 - break
4106 - try:
4107 - with tarfile.open(p, "r:xz") as tf:
4108 - meta = tf.extractfile("metadata.json")
4109 - if meta is None:
4110 - print(_(' ❌ {arg1}: missing metadata.json', arg1=(p)))
4111 - failed += 1
4112 - break
4113 - data = json.loads(meta.read())
4114 - except Exception as e:
4115 - print(_(' ❌ {arg1}: failed to read package ({arg2})', arg1=(p), arg2=(e)))
4116 - failed += 1
4117 - break
4118 - pkg = PackageInfo(data, repo="local")
4119 - staged = _stage_package(p, pkg)
4120 - if not staged:
4121 - failed += 1
4122 - break
4123 - prepared.append((pkg, staged))
4124 -
4125 - if failed:
4126 - for _pkg, _st in prepared:
4127 - _discard_staged(_st)
4128 - print(_(' ↩ Preparation stage failed – the system was NOT changed.'))
4129 - return failed, []
4130 -
4131 - all_files = []
4132 - for pkg, staged in prepared:
4133 - print(_(' ↓ {arg1}-{arg2} (local) ... ', arg1=(pkg.name), arg2=(pkg.version)), end="", flush=True)
4134 - ok, files, _ = _apply_staged_package(staged, pkg)
4135 - if ok:
4136 - install_succeeded(pkg, files)
4137 - all_files.extend(f["path"] for f in files)
4138 - print("✅")
4139 - else:
4140 - print("❌")
4141 - failed += 1
4142 - return failed, all_files
4143 -
4144 -
4145 -def _preflight_disk(total_bytes: int) -> bool:
4146 - """Pre-flight przed transakcją: wolne miejsce + mount read-only.
4147 -
4148 - Zwraca False (przerywa instalację) gdy na partycji docelowej brakuje
4149 - miejsca na pakiety albo katalog stagingu jest zamontowany read-only
4150 - (inaczej instalacja rwałaby się w połowie, zostawiając uszkodzony system).
4151 - """
4152 - target = PAG_ROOT or "/"
4153 - try:
4154 - st = os.statvfs(target)
4155 - free = st.f_bavail * st.f_frsize
4156 - except OSError:
4157 - return True # nie da się sprawdzić – nie blokuj
4158 - need_mb = total_bytes // 1048576
4159 - free_mb = free // 1048576
4160 - if free < total_bytes:
4161 - print(_(' ❌ Not enough disk space: need ~{arg1} MB, free {arg2} MB ({arg3})', arg1=(need_mb), arg2=(free_mb), arg3=(target)))
4162 - return False
4163 - if free < total_bytes * 3:
4164 - print(_(' ⚠ Low disk space: {arg1} MB free, packages ~{arg2} MB (extracted will take more)', arg1=(free_mb), arg2=(need_mb)))
4165 - # Wykryj mount read-only (test zapisu w stagingu)
4166 - try:
4167 - probe = os.path.join(STAGING_DIR, ".pag-probe")
4168 - with open(probe, "w") as f:
4169 - f.write("x")
4170 - os.remove(probe)
4171 - except OSError:
4172 - print(_(' ❌ {arg1} is mounted read-only – cannot install.', arg1=(target)))
4173 - return False
4174 - return True
4175 -
4176 -
4177 -def cmd_install(package_names, as_dep=False, upgrade=False):
4178 - ensure_dirs()
4179 - installed_db = load_json(INSTALLED_DB)
4180 - world = load_world()
4181 - pinned = load_json(PINNED_FILE)
4182 -
4183 - # Obsługa lokalnych plików .pkg.tar.xz (zbudowanych przez pagbuild) –
4184 - # nie wymaga repozytorium ani GPG.
4185 - local_files = [p for p in package_names if p.endswith(PKG_EXT) or
4186 - (os.sep in p and os.path.isfile(os.path.abspath(p)))]
4187 - if local_files:
4188 - _local_need = sum(
4189 - os.path.getsize(os.path.abspath(p))
4190 - for p in local_files if os.path.isfile(os.path.abspath(p))
4191 - )
4192 - if not _preflight_disk(_local_need):
4193 - return 1
4194 -
4195 - def _ok(pkg, files):
4196 - installed_db[pkg.name] = {
4197 - "version": pkg.version, "release": pkg.release, "description": pkg.description,
4198 - "dependencies": pkg.dependencies, "size_bytes": pkg.size_bytes,
4199 - "sha256": pkg.sha256, "installed_at": datetime.now().isoformat(),
4200 - "repo": "local",
4201 - "provides": getattr(pkg, "provides", None) or [],
4202 - "provides_so": getattr(pkg, "provides_so", None) or [],
4203 - "requires_so": getattr(pkg, "requires_so", None) or [],
4204 - }
4205 - world.add(pkg.name)
4206 - failed_local, _fl = _install_local_pkg_files(local_files, _ok)
4207 - save_json(INSTALLED_DB, installed_db)
4208 - save_world(world)
4209 - if failed_local:
4210 - return 1
4211 - _refresh_dynamic_linker_cache()
4212 - package_names = [n for n in package_names if n not in
4213 - [os.path.abspath(x) for x in local_files] and
4214 - n not in local_files]
4215 - to_install = []
4216 - if not package_names:
4217 - return 0
4218 - # pozostałe argumenty to nazwy pakietów z repo – kontynuuj
4219 -
4220 - repo_pkgs = fetch_all_packages()
4221 -
4222 - if not repo_pkgs:
4223 - print(f"❌ {_('no_index')}"); return 1
4224 -
4225 - for name in list(package_names):
4226 - if name in pinned:
4227 - print(f"⚠ {name} {_('pinned_to')} {pinned[name]} – skipping")
4228 - package_names.remove(name)
4229 -
4230 - to_install, missing_deps = _resolve_deps(package_names, repo_pkgs, installed_db)
4231 -
4232 - # ── Pakiety, których NIE MA w repo ani nie są zainstalowane ──
4233 - # Zgłoś od razu zamiast mylącego „Do zainstalowania: N (0.00 MB)”
4234 - # i prośby o potwierdzenie (np. `pag install steam` gdy steam nie istnieje).
4235 - not_found = []
4236 - for n in package_names:
4237 - real = _resolve_provides(n, repo_pkgs, installed_db)
4238 - if real not in repo_pkgs and real not in installed_db \
4239 - and not os.path.exists(os.path.abspath(n)):
4240 - not_found.append(n)
4241 - if not_found:
4242 - print(f"\n ❌ {_('pkg_not_found', ', '.join(not_found))}")
4243 - print(f" {_('not_found_hint')}")
4244 - return 1
4245 -
4246 - # --- Tryb upgrade: pakiety już zainstalowane MUSZĄ zostać ponownie
4247 - # zainstalowane z nowszej wersji (zastąpienie w tej samej transakcji).
4248 - if upgrade:
4249 - # `pag update` przekazuje tu tylko pakiety z NOWSZĄ wersją (już
4250 - # przefiltrowane w _pending_updates), a `pag install -f` wymusza
4251 - # reinstalację nawet tej SAMEJ wersji – dlatego nie filtrujemy po
4252 - # _version_newer.
4253 - upgrade_targets = [
4254 - name for name in package_names
4255 - if name in repo_pkgs
4256 - and name in installed_db
4257 - and name not in pinned
4258 - ]
4259 - for name in upgrade_targets:
4260 - if name not in to_install:
4261 - to_install.append(name)
4262 -
4263 - if not to_install and not missing_deps:
4264 - print(f"✅ {_('all_installed')}"); return 0
4265 -
4266 - # ── WERYFIKACJA ZALEŻNOŚCI ──────────────────────────────────────────
4267 - fatal_missing = _verify_dependencies(to_install, repo_pkgs, installed_db)
4268 -
4269 - if fatal_missing > 0:
4270 - print(_('❌ Cannot continue – {arg1} missing dependencies.', arg1=(fatal_missing)))
4271 - print(_(' Install the missing packages or add repositories.'))
4272 - return 1
4273 -
4274 - so_missing = _verify_so_deps(to_install, repo_pkgs, installed_db)
4275 - if so_missing > 0:
4276 - print(_(' Install the library provider or update the repository.'))
4277 - return 1
4278 -
4279 - if not to_install:
4280 - print(f"✅ {_('all_installed')}"); return 0
4281 -
4282 - MAX_MB = MAX_PKG_SIZE // 1048576
4283 - for n in to_install:
4284 - if not _validate_pkg_name(n):
4285 - print(f" {_("sec_badname", name=n)}")
4286 - return 1
4287 - sz = repo_pkgs[n].size_bytes if n in repo_pkgs else 0
4288 - if sz > MAX_PKG_SIZE:
4289 - mb = sz // 1048576
4290 - print(f" {_("sec_toobig", size_mb=mb, max_mb=MAX_MB)}")
4291 - return 1
4292 - total_size = sum(repo_pkgs[n].size_bytes for n in to_install if n in repo_pkgs)
4293 - if not _preflight_disk(total_size):
4294 - return 1
4295 - print(f"\n📦 {_('to_install', len(to_install), total_size/1048576)}")
4296 - for name in to_install:
4297 - p = repo_pkgs.get(name)
4298 - if p:
4299 - if name in installed_db:
4300 - marker = f" {_('upgrade_marker')}" if upgrade else ""
4301 - else:
4302 - marker = f" [{_('new')}]"
4303 - print(f" {name}-{p.version}{marker}")
4304 -
4305 - # Pakiet z bazy obrazu ISO (nie w installed.json) → ostrzeż, że pliki z ISO
4306 - # zostaną zastąpione pakietem z repo (kopia do `pag rollback`).
4307 - _base_warn_overwrite(to_install)
4308 -
4309 - if not as_dep and not upgrade:
4310 - if not _ask_confirm():
4311 - print(_("cancelled")); return 0
4312 -
4313 - # `--dry-run`: pokaż plan i wyjdź. Nic nie jest pobierane, rozpakowywane
4314 - # ani zmieniane – bezpieczne sprawdzenie, co zrobiłaby transakcja.
4315 - if os.environ.get("PAG_DRY_RUN", "") == "1":
4316 - print(f"\n 🧪 {_('dry_run_plan')}")
4317 - for _n in to_install:
4318 - _p = repo_pkgs.get(_n)
4319 - if _p:
4320 - _mark = f" {_('upgrade_marker')}" if _n in installed_db else f" [{_('new')}]"
4321 - print(f" {_n}-{_p.version}{_mark}")
4322 - print(f" {_('dry_run_done')}")
4323 - return 0
4324 -
4325 - snapshot = copy.deepcopy(installed_db)
4326 - all_installed_files = []
4327 - failed = []
4328 - # Pary (pkg, stare_pliki, nowe_pliki) do usunięcia martwych plików po upgrade
4329 - stale_candidates = []
4330 - # Katalog backupów nadpisywanych plików – dla poprawnego rollbacku.
4331 - # Dla KAŻDEJ transakcji: instalacja „nowego” pakietu także nadpisuje pliki
4332 - # spoza bazy pag (baza rootfs/ISO), a rollback bez backupu by je skasował.
4333 - backup_root = ""
4334 - all_backups: List[Tuple[str, str]] = [] # (backup_path, dst)
4335 - if to_install:
4336 - backup_root = _new_transaction_backup_root()
4337 -
4338 - # --- Dziennik transakcji (dla pełnej atomowości) ---
4339 - # Jeśli którykolwiek pakiet zawiedzie, cofamy WSZYSTKIE zainstalowane
4340 - # w tej transakcji przez _rollback_transaction().
4341 - transaction_journal: List[Tuple[str, str, str]] = [] # (op, src, dst)
4342 -
4343 - # --- Tryb immutable: utwórz nowy deployment ---
4344 - immutable = os.environ.get("PAG_IMMUTABLE", "") == "1"
4345 - deploy_dir = ""
4346 - deploy_id = ""
4347 - if immutable:
4348 - print(_('\n 🏗️ Creating a new deployment...'))
4349 - deploy_dir, deploy_id = _create_deployment(to_install, "upgrade" if upgrade else "install")
4350 - target_root = deploy_dir
4351 - else:
4352 - target_root = ""
4353 -
4354 - # --- Faza 1: Równoległe pobieranie wszystkich pakietów ---
4355 - to_download = [repo_pkgs[name] for name in to_install if name in repo_pkgs]
4356 - if len(to_download) > 1:
4357 - print(_('\n ⏬ Downloading {arg1} packages in parallel...', arg1=(len(to_download))))
4358 - downloaded = _download_packages_parallel(to_download)
4359 - else:
4360 - downloaded = {}
4361 -
4362 - # --- Faza 1b: WERYFIKACJA WSZYSTKICH paczek PRZED instalacją ---
4363 - # KLUCZOWE: GPG i SHA256 sprawdzamy dla WSZYSTKICH paczek, ZANIM
4364 - # zainstalujemy choćby jedną. Inaczej instalowany pakiet może podmienić
4365 - # bibliotekę używaną przez sam gpg (np. libassuan 3.0.1 zmienił namespace
4366 - # symboli LIBASSUAN_1.0 -> LIBASSUAN_2.0) i wtedy weryfikacja kolejnych
4367 - # paczek w tej samej transakcji pada, dając fałszywe
4368 - # „NIEPRAWIDŁOWY PODPIS GPG".
4369 - verified = {}
4370 - _vfail = []
4371 - for _name in to_install:
4372 - _pkg = repo_pkgs.get(_name)
4373 - if not _pkg:
4374 - _vfail.append((_name, _('not_found')))
4375 - continue
4376 - _pp = downloaded.get(_name)
4377 - if not _pp:
4378 - _pp = _download_pkg(_pkg)
4379 - if not _pp:
4380 - _vfail.append((_name, _('download_fail')))
4381 - continue
4382 - _gok, _gmsg = _verify_pkg_gpg(_pp, repo_url=_pkg.repo_url)
4383 - if not _gok:
4384 - _vfail.append((_name, f"{_('gpg_fail')}: {_gmsg[:60]}"))
4385 - continue
4386 - if _pkg.sha256 and _sha256_file(_pp) != _pkg.sha256:
4387 - _vfail.append((_name, _('sha256_mismatch')))
4388 - continue
4389 - verified[_name] = _pp
4390 - if _vfail:
4391 - for _n, _m in _vfail:
4392 - print(f" ❌ {_n}: {_m}")
4393 - print(_(' ↩ Aborted BEFORE installation – no package was changed.'))
4394 - return 1
4395 -
4396 - # --- Snapshot systemu PRZED transakcją (btrfs CoW) ---
4397 - # Tworzymy go PO pobraniu i weryfikacji paczek, ale PRZED rozpakowaniem
4398 - # czegokolwiek do systemu. Domyślnie `auto`: tylko na btrfs. `--snapshot`
4399 - # wymusza migawkę (i przerywa, gdy się nie uda), `--no-snapshot` wyłącza.
4400 - snapshot_mode = (os.environ.get("PAG_SNAPSHOT") or "auto").strip().lower()
4401 - sys_snap: Optional[dict] = None
4402 - if to_install and snapshot_mode not in ("never", "no", "0", "off"):
4403 - _snap_ok, _snap_why = _snapshot_support()
4404 - if _snap_ok:
4405 - sys_snap = _create_system_snapshot(
4406 - to_install, "upgrade" if upgrade else "install")
4407 - if sys_snap:
4408 - _refresh_bootloader()
4409 - elif snapshot_mode in ("always", "require", "1", "yes"):
4410 - print(_(' ❌ Failed to create snapshot (--snapshot mode) – aborting.'))
4411 - return 1
4412 - elif snapshot_mode in ("always", "require", "1", "yes"):
4413 - print(f" ❌ {_('snapshot_unsupported', _snap_why)}")
4414 - return 1
4415 - else:
4416 - print(f" ℹ {_('snapshot_unsupported', _snap_why)}")
4417 -
4418 - # --- Faza 1c: PRZYGOTOWANIE CAŁEJ GRUPY W STAGINGU ---
4419 - # Rozpakowujemy WSZYSTKIE pakiety do `/.pag_staging/.stage-*`, zanim
4420 - # dotkniemy systemu. Jeśli jedna z 50 paczek (np. GNOME) jest uszkodzona,
4421 - # transakcja kończy się tutaj – na dysku nie ma żadnych zmian.
4422 - atomic = os.environ.get("PAG_ATOMIC", "1") != "0"
4423 - staged_pkgs: List[Tuple[str, PackageInfo, Optional[dict]]] = []
4424 - if atomic and to_install:
4425 - print(f"\n 🧰 {_('staging_prepare', len(to_install))}")
4426 - _sbar = _StepBar(len(to_install), icon="🧰 ", width=25)
4427 - _stage_failed: List[str] = []
4428 - for _si, _name in enumerate(to_install, 1):
4429 - _pkg = repo_pkgs.get(_name)
4430 - _pp = verified.get(_name)
4431 - if not _pkg or not _pp:
4432 - _stage_failed.append(_name)
4433 - break
4434 - _sbar.step(_si, f"{_name}-{_pkg.version}")
4435 - _st = _stage_package(_pp, _pkg)
4436 - if not _st:
4437 - _stage_failed.append(_name)
4438 - break
4439 - staged_pkgs.append((_name, _pkg, _st))
4440 - _sbar.end()
4441 - if _stage_failed:
4442 - for _n, _p, _st in staged_pkgs:
4443 - _discard_staged(_st)
4444 - print(f" ↩ {_('staging_failed')}")
4445 - if backup_root:
4446 - shutil.rmtree(backup_root, ignore_errors=True)
4447 - _record_transaction("upgrade" if upgrade else "install", to_install, False,
4448 - snapshot,
4449 - snapshot_id=sys_snap["id"] if sys_snap else "")
4450 - return 1
4451 - print(f" ✅ {_('staging_commit')}")
4452 - elif to_install:
4453 - staged_pkgs = [(n, repo_pkgs[n], None) for n in to_install]
4454 -
4455 - # --- Faza 2: Instalacja – JEDNA nadpisywana linia postępu (jak przy
4456 - # pobieraniu), bez ściany tekstu na każdy pakiet. W trybie
4457 - # nieinteraktywnym (logi, netinstall instalatora) wypisujemy linię na
4458 - # pakiet – tam to pożądane do logu.
4459 - t0 = time.time()
4460 - stdout_tty = sys.stdout.isatty()
4461 -
4462 - # Animowany pasek postępu („drakkar”) – jedna nadpisywana linia; morze
4463 - # faluje nawet wtedy, gdy pojedynczy pakiet instaluje się długo.
4464 - _pbar = _StepBar(len(to_install), icon="📦 ", width=25)
4465 -
4466 - def _bar_draw(idx: int, name: str) -> None:
4467 - _pbar.step(idx, name)
4468 -
4469 - def _bar_end() -> None:
4470 - _pbar.end()
4471 -
4472 - for _pkg_i, (name, pkg, _staged) in enumerate(staged_pkgs, 1):
4473 - if not pkg:
4474 - _bar_end()
4475 - print(f" ❌ {name}: {_('not_found')}")
4476 - failed.append(name)
4477 - break
4478 -
4479 - _bar_draw(_pkg_i, f"{name}-{pkg.version}")
4480 -
4481 - # Przed instalacją zapamiętaj pliki starej wersji (potrzebne w upgrade)
4482 - old_files = _db_get_package_files(name) if name in installed_db else []
4483 - # Stare sumy SHA256 – do wykrycia zmian użytkownika w plikach /etc (.pacnew)
4484 - old_checksums = _db_get_package_checksums(name) if name in installed_db else None
4485 -
4486 - # Commit przygotowanego pakietu (w upgrade backupuje nadpisywane pliki).
4487 - # Tryb `PAG_ATOMIC=0` zachowuje starą ścieżkę pojedynczą (staging per pakiet).
4488 - if _staged is not None:
4489 - ok, files, backup_j = _apply_staged_package(
4490 - _staged, pkg, deploy_dir,
4491 - backup_dir=backup_root,
4492 - old_checksums=old_checksums)
4493 - else:
4494 - # Ścieżka pobrana i ZWERYFIKOWANA w fazie 1b.
4495 - pkg_path = verified.get(name)
4496 - if not pkg_path:
4497 - _bar_end()
4498 - print(f" ❌ {name}: {_('download_fail')}")
4499 - failed.append(name)
4500 - break # przerwij transakcję
4501 - ok, files, backup_j = _atomic_install(
4502 - pkg_path, pkg, deploy_dir,
4503 - backup_dir=backup_root,
4504 - old_checksums=old_checksums)
4505 - if ok:
4506 - installed_db[name] = {
4507 - "version": pkg.version, "release": pkg.release, "description": pkg.description,
4508 - "dependencies": pkg.dependencies, "size_bytes": pkg.size_bytes,
4509 - "sha256": pkg.sha256, "installed_at": datetime.now().isoformat(),
4510 - "repo": pkg.repo_url,
4511 - "provides": getattr(pkg, "provides", None) or [],
4512 - "provides_so": getattr(pkg, "provides_so", None) or [],
4513 - "requires_so": getattr(pkg, "requires_so", None) or [],
4514 - }
4515 - if not as_dep and name in package_names:
4516 - world.add(name)
4517 - if not stdout_tty:
4518 - print(f" ✓ {name}-{pkg.version}", flush=True)
4519 - all_installed_files.extend(f["path"] for f in files)
4520 - all_backups.extend(backup_j)
4521 -
4522 - # Upgrade: zapamiętaj stare pliki, by po sukcesie usunąć te,
4523 - # których nie ma już w nowej wersji.
4524 - if upgrade and old_files:
4525 - stale_candidates.append((name, old_files, [f["path"] for f in files]))
4526 - else:
4527 - _bar_end()
4528 - print(f" ❌ {name}: {_('install_failed')}")
4529 - failed.append(name)
4530 - break # PRZERWIJ – błąd instalacji
4531 -
4532 - # Deduplikacja journalu – ten sam plik może trafić tu dwukrotnie (np. przez
4533 - # `provides`); rollback i historia nie potrzebują duplikatów.
4534 - all_installed_files = list(dict.fromkeys(all_installed_files))
4535 -
4536 - # --- Rollback całej transakcji jeśli cokolwiek zawiodło ---
4537 - if failed:
4538 - _bar_end()
4539 - print(_('\n ↩ Rolling back transaction ({arg1} errors)...', arg1=(len(failed))))
4540 - for _n, _p, _st in staged_pkgs:
4541 - _discard_staged(_st)
4542 - _rollback_transaction(installed_db, snapshot, all_installed_files,
4543 - deploy_dir, immutable, backups=all_backups)
4544 - if backup_root:
4545 - shutil.rmtree(backup_root, ignore_errors=True)
4546 - _record_transaction("upgrade" if upgrade else "install", to_install, False,
4547 - snapshot,
4548 - snapshot_id=sys_snap["id"] if sys_snap else "")
4549 - return 1
4550 -
4551 - save_json(INSTALLED_DB, installed_db)
4552 - save_world(world)
4553 -
4554 - # --- Po ZAPISANIU bazy: usuń nieaktualne pliki starych wersji (upgrade).
4555 - # Kolejność ma znaczenie: najpierw utrwalamy stan nowej wersji w bazie, a
4556 - # dopiero potem kasujemy pliki, których nowa wersja nie zawiera. Odwrotna
4557 - # kolejność (kasowanie przed zapisem) przy przerwaniu zostawiała system bez
4558 - # plików. Usunięte pliki trafiają do backupu, aby `pag rollback` mógł je
4559 - # przywrócić.
4560 - for pkg_name, old_files, new_paths in stale_candidates:
4561 - _remove_stale_files(pkg_name, old_files, new_paths, installed_db, deploy_dir,
4562 - backup_root, all_backups)
4563 - _record_transaction("upgrade" if upgrade else "install", to_install, True, snapshot,
4564 - file_journal=all_installed_files,
4565 - upgrade_backups={dst: bp for bp, dst in all_backups} if all_backups else None,
4566 - upgrade_backup_root=backup_root,
4567 - snapshot_id=sys_snap["id"] if sys_snap else "")
4568 -
4569 - # Zachowaj backupy bieżącej transakcji (dla `pag rollback`), usuń starsze.
4570 - if backup_root:
4571 - _purge_old_backups(keep_root=backup_root)
4572 -
4573 - _bar_end()
4574 -
4575 - # --- Tryb immutable: przełącz na nowy deployment ---
4576 - if immutable and not failed:
4577 - _refresh_dynamic_linker_cache(deploy_dir)
4578 - # Initramfs dla deploymentu budujemy RAZ – po wszystkich pakietach,
4579 - # żeby zawierał też moduły nvidia/vbox dołożone w tej transakcji.
4580 - if any(_needs_initramfs_refresh(_n) for _n in to_install):
4581 - print(_('\n 🐧 Finalizing kernel/driver update in deployment (initramfs)...'))
4582 - _rebuild_initramfs(deploy_dir)
4583 - print(_('\n 🔄 Switching to deployment {arg1}...', arg1=(deploy_id)))
4584 - _switch_deployment(deploy_dir)
4585 - print(_(' ✅ Active deployment: {arg1}', arg1=(deploy_id)))
4586 - _update_grub_config()
4587 - cmd_deploy_cleanup(keep=5) # Zostawia 5 najnowszych deploymentów
4588 - print(_(' 💡 Restart required to reload the system.'))
4589 - else:
4590 - _refresh_dynamic_linker_cache()
4591 - # Hooki zbiorcze – raz na transakcję (fc-cache itp.), tylko gdy pliki
4592 - # trafiły do realnego systemu (nie do deploymentu).
4593 - _process_triggers(all_installed_files)
4594 - # Jądro/sterowniki zmienione na ZWYKŁEJ instalacji → DKMS + initramfs +
4595 - # GRUB, dokładnie RAZ i po wszystkich pakietach. Hook pakietu nie może
4596 - # odświeżyć GRUB-a (trzymany lock PAG-a), a wcześniejsza przebudowa
4597 - # initramfs w pętli dawała fałszywe ETA i dublowała pracę.
4598 - if any(_needs_initramfs_refresh(_n) for _n in to_install):
4599 - print(_('\n 🐧 Finalizing kernel/driver update (DKMS → initramfs → GRUB)...'))
4600 - _post_kernel_hooks()
4601 - elif sys_snap:
4602 - # Snapshot istnieje, ale nie było zmiany jądra – odśwież menu GRUB,
4603 - # żeby wpis migawki był widoczny przy najbliższym starcie.
4604 - _ensure_snapshot_grub_script()
4605 - _refresh_bootloader()
4606 -
4607 - print(f"\n✅ {_('installed', len(to_install))} ({(time.time()-t0):.0f}s)")
4608 - return 0
4609 -
4610 -
4611 -def _rollback_transaction(installed_db: dict, snapshot: dict,
4612 - installed_files: List[str],
4613 - deploy_dir: str, is_immutable: bool,
4614 - backups: Optional[List[Tuple[str, str]]] = None):
4615 - """
4616 - Cofa WSZYSTKIE pakiety zainstalowane w bieżącej transakcji.
4617 - Przywraca installed_db do stanu sprzed transakcji.
4618 - Usuwa fizyczne pliki z systemu (lub deploymentu w trybie immutable).
4619 - Jeśli podano `backups` (upgrade) – przywraca stare wersje nadpisanych plików.
4620 - """
4621 - # Przywróć installed_db
4622 - installed_db.clear()
4623 - installed_db.update(snapshot)
4624 -
4625 - root = deploy_dir if is_immutable else PAG_ROOT
4626 - backup_map = {dst: src for src, dst in (backups or [])}
4627 -
4628 - # Przywróć stare wersje z backupów (upgrade)
4629 - for dst, bpath in backup_map.items():
4630 - full = os.path.join(root, dst.lstrip("/"))
4631 - if os.path.lexists(bpath):
4632 - try:
4633 - os.makedirs(os.path.dirname(full), exist_ok=True)
4634 - os.replace(bpath, full)
4635 - except OSError:
4636 - pass
4637 -
4638 - # Usuń nowe pliki (które nie miały poprzedniej wersji)
4639 - for fpath in reversed(installed_files):
4640 - if fpath in backup_map:
4641 - continue
4642 - full = os.path.join(root, fpath.lstrip("/"))
4643 - if os.path.isfile(full) or os.path.islink(full):
4644 - try:
4645 - os.remove(full)
4646 - except OSError:
4647 - pass
4648 -
4649 - # Wyczyść puste katalogi
4650 - dirs_to_check = set()
4651 - for fpath in installed_files:
4652 - parent = os.path.dirname(fpath)
4653 - while parent and parent != "/":
4654 - dirs_to_check.add(parent)
4655 - parent = os.path.dirname(parent)
4656 - for d in sorted(dirs_to_check, key=len, reverse=True):
4657 - full_d = os.path.join(root, d.lstrip("/"))
4658 - if os.path.isdir(full_d):
4659 - try:
4660 - os.rmdir(full_d)
4661 - except OSError:
4662 - pass
4663 -
4664 - # W trybie immutable: usuń nieudany deployment
4665 - if is_immutable and deploy_dir:
4666 - shutil.rmtree(deploy_dir, ignore_errors=True)
4667 -
4668 - save_json(INSTALLED_DB, snapshot)
4669 -
4670 -
4671 -# =============================================================================
4672 -# USUWANIE
4673 -# =============================================================================
4674 -
4675 -def cmd_remove(package_names):
4676 - installed_db = load_json(INSTALLED_DB)
4677 - world = load_world()
4678 - snapshot = copy.deepcopy(installed_db)
4679 - removed = []
4680 - removed_files = []
4681 -
4682 - total = len(package_names)
4683 - for i, name in enumerate(package_names, 1):
4684 - if name not in installed_db:
4685 - print(_(' ⚠ {arg1}: not installed', arg1=(name))); continue
4686 -
4687 - # Pasek postępu (animowany „drakkar” na TTY)
4688 - pct = (i - 1) / total * 100
4689 - bar = _pagan_bar(pct, 25, time.time(), animated=sys.stderr.isatty())
4690 - print(f" 🗑 [{bar}] {i}/{total} ({pct:.0f}%) ", end="\r", file=sys.stderr, flush=True)
4691 -
4692 - print(f"🗑 {name}-{installed_db[name]['version']} ...", end=" ", flush=True)
4693 -
4694 - # Pre-remove hook (jeśli dostępny w staging)
4695 - _run_hook_for_installed(name, "pre-remove")
4696 -
4697 - count, rm_files = _safe_remove_files(name, installed_db)
4698 - del installed_db[name]
4699 - world.discard(name)
4700 - removed.append(name)
4701 - removed_files.extend(rm_files)
4702 - print(_('✅ ({arg1} files)', arg1=(count)))
4703 -
4704 - # Post-remove hook + sprzątanie zapisanych hooków
4705 - _run_hook_for_installed(name, "post-remove")
4706 - shutil.rmtree(os.path.join(PAG_DB, "hooks", name), ignore_errors=True)
4707 -
4708 - save_json(INSTALLED_DB, installed_db)
4709 - save_world(world)
4710 - _record_transaction("remove", removed, True, snapshot)
4711 -
4712 - print(file=sys.stderr) # wyczyść linię paska postępu
4713 -
4714 - if not removed: return 0
4715 - print(_('\n✅ Removed {arg1}.', arg1=(len(removed))))
4716 - _process_triggers(removed_files)
4717 -
4718 - orphans = _find_orphans(installed_db, world)
4719 - if orphans:
4720 - print(f"\n💡 {_('orphans_found', len(orphans), ', '.join(sorted(orphans)[:10]))}")
4721 - print(_(" 'pag remove-orphans' to clean up."))
4722 - return 0
4723 -
4724 -def _run_hook_for_installed(pkg_name, hook_name):
4725 - """Próbuje uruchomić hook z katalogu pakietu (jeśli został zapisany)."""
4726 - hook_dir = os.path.join(PAG_DB, "hooks", pkg_name)
4727 - if os.path.isdir(hook_dir):
4728 - ver = load_json(INSTALLED_DB).get(pkg_name, {}).get("version", "")
4729 - _run_hook(hook_dir, hook_name, PackageInfo({"name": pkg_name, "version": ver}))
4730 -
4731 -
4732 -# =============================================================================
4733 -# TRIGGERS – hooki zbiorcze (raz na transakcję, nie per pakiet)
4734 -# =============================================================================
4735 -# Wzorem pacman/dpkg: pakiet/administrator deklaruje zainteresowanie ścieżkami,
4736 -# a pasujący trigger uruchamia się DOKŁADNIE RAZ na końcu transakcji
4737 -# (np. fc-cache, glib-compile-schemas, update-desktop-database) zamiast po
4738 -# każdym pakiecie z osobna.
4739 -
4740 -TRIGGERS_DIR = PAG_CONF + "/triggers"
4741 -
4742 -DEFAULT_TRIGGERS = [
4743 - {"name": "font-cache", "paths": ["/usr/share/fonts/", "/usr/local/share/fonts/"],
4744 - "run": "fc-cache -fs"},
4745 - {"name": "glib-schemas", "paths": ["/usr/share/glib-2.0/schemas/"],
4746 - "run": "glib-compile-schemas /usr/share/glib-2.0/schemas"},
4747 - {"name": "desktop-database", "paths": ["/usr/share/applications/"],
4748 - "run": "update-desktop-database -q /usr/share/applications"},
4749 - {"name": "mime-database", "paths": ["/usr/share/mime/"],
4750 - "run": "update-mime-database /usr/share/mime"},
4751 - {"name": "systemd-daemon-reload", "paths": ["/usr/lib/systemd/system/"],
4752 - "run": "systemctl daemon-reload"},
4753 - # `systemctl --global daemon-reload` NIE istnieje – --global dotyczy tylko
4754 - # enable/disable jednostek. Przeładowanie robi _user_daemon_reload()
4755 - # (per zalogowany użytkownik), a "run" zostaje jako opis/cel audytu.
4756 - {"name": "systemd-user-daemon-reload", "paths": ["/usr/lib/systemd/user/"],
4757 - "internal": "user-daemon-reload",
4758 - "run": "systemctl --user daemon-reload"},
4759 - {"name": "udev-reload", "paths": ["/usr/lib/udev/rules.d/"],
4760 - "run": "udevadm control --reload-rules"},
4761 -]
4762 -
4763 -def _load_triggers() -> List[dict]:
4764 - """Ładuje triggery: domyślne (tylko gdy binarka istnieje) + /etc/pag/triggers/*.json."""
4765 - out = []
4766 - for t in DEFAULT_TRIGGERS:
4767 - bin_name = t["run"].split()[0]
4768 - if shutil.which(bin_name):
4769 - out.append(dict(t))
4770 - if os.path.isdir(TRIGGERS_DIR):
4771 - for fn in sorted(os.listdir(TRIGGERS_DIR)):
4772 - if not fn.endswith(".json"):
4773 - continue
4774 - try:
4775 - with open(os.path.join(TRIGGERS_DIR, fn)) as f:
4776 - data = json.load(f)
4777 - except (OSError, json.JSONDecodeError):
4778 - continue
4779 - if isinstance(data, dict):
4780 - data = [data]
4781 - for t in data:
4782 - if isinstance(t, dict) and t.get("name") and t.get("paths") and t.get("run"):
4783 - out.append(t)
4784 - return out
4785 -
4786 -def _logged_in_users() -> List[tuple]:
4787 - """[(uid, user)] aktywnych logowań wg loginctl. Best-effort."""
4788 - try:
4789 - r = subprocess.run(["loginctl", "list-users", "--no-legend"],
4790 - capture_output=True, text=True, timeout=30)
4791 - except Exception:
4792 - return []
4793 - out = []
4794 - for ln in (r.stdout or "").splitlines():
4795 - parts = ln.split()
4796 - if len(parts) < 2 or not parts[0].isdigit():
4797 - continue
4798 - out.append((parts[0], parts[1]))
4799 - return out
4800 -
4801 -
4802 -def _user_daemon_reload() -> int:
4803 - """Przeładowuje menedżery systemd ZALOGOWANYCH użytkowników.
4804 -
4805 - `systemctl --user` działa tylko w kontekście danego użytkownika (sesyjny
4806 - D-Bus), więc dla roota trzeba wejść w jego sesję. Zwraca liczbę udanych
4807 - przeładowań; brak sesji to nie błąd – jednostki wczytają się przy logowaniu.
4808 - """
4809 - done = 0
4810 - for uid, user in _logged_in_users():
4811 - rt = f"/run/user/{uid}"
4812 - if not os.path.isdir(rt):
4813 - continue
4814 - try:
4815 - if shutil.which("runuser"):
4816 - r = subprocess.run(
4817 - ["runuser", "-u", user, "--", "env", f"XDG_RUNTIME_DIR={rt}",
4818 - "systemctl", "--user", "daemon-reload"],
4819 - capture_output=True, timeout=60)
4820 - else:
4821 - r = subprocess.run(
4822 - ["su", "-", user, "-c",
4823 - f"XDG_RUNTIME_DIR={rt} systemctl --user daemon-reload"],
4824 - capture_output=True, timeout=60)
4825 - if r.returncode == 0:
4826 - done += 1
4827 - except Exception:
4828 - pass
4829 - return done
4830 -
4831 -
4832 -def _reload_user_media_services(touched_paths: List[str]) -> None:
4833 - """Po aktualizacji multimediow przeladuj uslugi UZYTKOWNIKA (pipewire/wireplumber).
4834 -
4835 - Nowe binarki/moduly sa juz na dysku, ale dzialajace sesje maja stare w
4836 - pamieci i probuja ladowac nieistniejace wersje modulow. Best-effort:
4837 - przeladowanie menedzerow systemd uzytkownikow + try-restart w sesjach.
4838 - """
4839 - if os.environ.get("PAG_NO_HOOKS", "") == "1":
4840 - return
4841 - _pfx = ("/usr/lib/systemd/user/pipewire", "/usr/lib/systemd/user/wireplumber",
4842 - "/usr/bin/pipewire", "/usr/bin/wireplumber",
4843 - "/usr/lib/pipewire-0.3/", "/usr/lib64/pipewire-0.3/",
4844 - "/usr/lib/wireplumber-0.5/", "/usr/lib64/wireplumber-0.5/")
4845 - if not any(_p.startswith(_x) for _x in _pfx for _p in touched_paths):
4846 - return
4847 - _user_daemon_reload()
4848 - try:
4849 - _r = subprocess.run(["loginctl", "list-users", "--no-legend"],
4850 - capture_output=True, text=True, timeout=30)
4851 - _users = [ln.split()[1] for ln in (_r.stdout or "").splitlines()
4852 - if len(ln.split()) >= 2]
4853 - except Exception:
4854 - _users = []
4855 - _done = []
4856 - for _u in _users:
4857 - try:
4858 - _rr = subprocess.run(
4859 - ["su", "-", _u, "-c",
4860 - "systemctl --user try-restart pipewire.socket pipewire.service "
4861 - "wireplumber.service"],
4862 - capture_output=True, timeout=60)
4863 - if _rr.returncode == 0:
4864 - _done.append(_u)
4865 - except Exception:
4866 - pass
4867 - if _done:
4868 - print(_("audio_services_reloaded", ", ".join(sorted(set(_done)))))
4869 -
4870 -def _process_triggers(touched_paths: List[str]):
4871 - """Uruchamia pasujące triggery RAZ na końcu transakcji (best-effort)."""
4872 - if not touched_paths:
4873 - return
4874 - if os.environ.get("PAG_NO_HOOKS", "") == "1":
4875 - return
4876 - import shlex as _shlex
4877 - matched = []
4878 - for trig in _load_triggers():
4879 - if any(path.startswith(p) for p in trig["paths"] for path in touched_paths):
4880 - matched.append(trig)
4881 - for trig in matched:
4882 - run = trig["run"]
4883 - print(_(' ⚡ Trigger: {arg1} ({arg2})', arg1=(trig['name']), arg2=(run)))
4884 - if trig.get("internal") == "user-daemon-reload":
4885 - _n = _user_daemon_reload()
4886 - _audit(f"TRIGGER {trig['name']}: user-daemon-reload ok={_n}")
4887 - if not _n:
4888 - print(" ℹ " + _('no_user_sessions'))
4889 - continue
4890 - try:
4891 - r = subprocess.run(_shlex.split(run), capture_output=True, text=True, timeout=120)
4892 - _audit(f"TRIGGER {trig['name']}: {run} rc={r.returncode}")
4893 - if r.returncode != 0:
4894 - print(f" ⚠ rc={r.returncode}: {(r.stderr or r.stdout or '').strip()[:160]}")
4895 - except subprocess.TimeoutExpired:
4896 - print(_(' ⚠ trigger {arg1} timed out (120 s)', arg1=(trig['name'])))
4897 - _audit(f"TRIGGER {trig['name']} TIMEOUT")
4898 - except Exception as e:
4899 - print(_(' ⚠ trigger {arg1}: {arg2}', arg1=(trig['name']), arg2=(e)))
4900 - _reload_user_media_services(touched_paths)
4901 -
4902 -
4903 -# =============================================================================
4904 -# UPDATE / UPGRADE / LIST / SEARCH / INFO / VERIFY
4905 -# =============================================================================
4906 -
4907 -def _cleanup_tmp_files(*paths):
4908 - """Usuwa tymczasowe pliki (np. .pag.new) po nieudanej operacji."""
4909 - for p in paths:
4910 - try:
4911 - if os.path.isfile(p):
4912 - os.remove(p)
4913 - except OSError:
4914 - pass
4915 -
4916 -
4917 -def cmd_self_update():
4918 - """Aktualizuje samego klienta pag z repo (podpisany /stable/pag).
4919 -
4920 - Kolejność: pobierz → weryfikacja GPG (+ fingerprint repo) → SHA256 →
4921 - kontrola składni (compile) → backup → atomowe os.replace.
4922 -
4923 - Podmieniamy plik, z którego pag ZOSTAŁ URUCHOMIONY (a nie hardkodowane
4924 - /usr/local/bin/pag): gdy pakiet instaluje /usr/bin/pag, a self-update
4925 - pisał do /usr/local/bin/pag, powstawały DWIE kopie o różnych wersjach
4926 - i zależnie od PATH `pag --version` pokazywał raz jedną, raz drugą."""
4927 - # Dedykowana blokada – patrz SelfUpdateLock. Chroni zapis dst.new oraz
4928 - # os.replace przed równoległą aktualizacją (np. cron + ręcznie).
4929 - with SelfUpdateLock():
4930 - return _self_update_impl()
4931 -
4932 -
4933 -def _self_update_impl():
4934 - repos = get_repos()
4935 - if not repos:
4936 - print(_('❌ No repositories configured.'))
4937 - return 1
4938 - # Aktualizuj bieżący plik (Python ≥3.9 ustawia __file__ jako ścieżkę
4939 - # bezwzględną). Poza /usr|/usr/local (np. uruchomienie z checkoutu)
4940 - # nie nadpisujemy niczego – wracamy do domyślnej lokalizacji instalacji.
4941 - dst = "/usr/local/bin/pag"
4942 - try:
4943 - cand = os.path.realpath(__file__)
4944 - if cand.startswith(("/usr/", "/usr/local/")):
4945 - dst = cand
4946 - except Exception:
4947 - pass
4948 - base = repos[0]
4949 - dst_new = dst + ".new"
4950 - dst_bak = dst + ".bak"
4951 - print(_('🔄 Checking for pag update from {arg1}...', arg1=(base)))
4952 - try:
4953 - with urlopen(Request(f"{base}/pag", headers={"User-Agent": "pag/3.0"}), timeout=20) as r:
4954 - data = r.read()
4955 - with urlopen(Request(f"{base}/pag.asc", headers={"User-Agent": "pag/3.0"}), timeout=20) as r:
4956 - sig = r.read()
4957 - except Exception as e:
4958 - print(_(' ❌ Cannot download pag: {arg1}', arg1=(e)))
4959 - return 1
4960 -
4961 - # Zapisz nową wersję w katalogu docelowym (ta sama partycja → atomowy rename)
4962 - with open(dst_new, "wb") as f:
4963 - f.write(data)
4964 - with open(dst_new + ".asc", "wb") as f:
4965 - f.write(sig)
4966 -
4967 - # --- 1. Weryfikacja podpisu GPG – bez tego nie instalujemy ---
4968 - insecure = os.environ.get("PAG_INSECURE", "") == "1"
4969 - ok, fp = _gpg_verify_fp(dst_new + ".asc", dst_new)
4970 - if not ok:
4971 - # Automatyczny import klucza (TOFU) – jak w _verify_repo_sig
4972 - res = _gpg_run("--verify", dst_new + ".asc", dst_new,
4973 - capture_output=True, text=True)
4974 - _stderr = res.stderr.decode(errors="replace") if isinstance(res.stderr, bytes) else (res.stderr or "")
4975 - if "public key" in _stderr.lower() and "no public key" in _stderr.lower():
4976 - try:
4977 - with urlopen(Request(f"{base}/paganos.asc", headers={"User-Agent": "pag/3.0"}), timeout=20) as r:
4978 - keydata = r.read()
4979 - with tempfile.NamedTemporaryFile(delete=False, suffix=".asc") as tmp:
4980 - tmp.write(keydata); tmp.flush()
4981 - _gpg_run("--import", tmp.name, capture_output=True, timeout=30)
4982 - os.unlink(tmp.name)
4983 - print(_(' 🔑 Imported repo key from {arg1}/paganos.asc', arg1=(base)))
4984 - ok, fp = _gpg_verify_fp(dst_new + ".asc", dst_new)
4985 - except Exception:
4986 - pass
4987 - if not ok:
4988 - if insecure:
4989 - print(_(' ⚠ Invalid update signature (PAG_INSECURE – ignoring)'))
4990 - else:
4991 - print(_(' ❌ Invalid update signature – not updating.'))
4992 - _cleanup_tmp_files(dst_new, dst_new + ".asc")
4993 - return 1
4994 - # Sprawdź fingerprint względem przypiętego klucza repo
4995 - pinned = _repo_pinned_fp(base)
4996 - if pinned:
4997 - if not fp:
4998 - print(_(' ❌ Cannot confirm the update signature fingerprint.'))
4999 - _cleanup_tmp_files(dst_new, dst_new + ".asc")
5000 - return 1
5001 - if fp != pinned.upper():
5002 - if insecure:
5003 - print(_(' ⚠ Update signed with a different key (PAG_INSECURE – ignoring)'))
5004 - else:
5005 - print(_(' ❌ [SECURITY ERROR] Update signed with a different key than the repo!'))
5006 - print(_(' Expected: {arg1}, received: {arg2}', arg1=(pinned), arg2=(fp)))
5007 - _cleanup_tmp_files(dst_new, dst_new + ".asc")
5008 - return 1
5009 -
5010 - # --- 2. Weryfikacja SHA256 (jeśli repo publikuje pag.sha256) ---
5011 - try:
5012 - with urlopen(Request(f"{base}/pag.sha256", headers={"User-Agent": "pag/3.0"}), timeout=15) as r:
5013 - sha = r.read().decode().strip().split()[0]
5014 - if sha:
5015 - actual = hashlib.sha256(data).hexdigest()
5016 - if actual.lower() != sha.lower():
5017 - print(_(' ❌ SHA256 mismatch! Expected {arg1}, got {arg2}', arg1=(sha), arg2=(actual)))
5018 - _cleanup_tmp_files(dst_new, dst_new + ".asc")
5019 - return 1
5020 - print(_(' ✅ SHA256 matches'))
5021 - except Exception:
5022 - # Brak pag.sha256 w repo – opcjonalne; nie blokuj aktualizacji.
5023 - pass
5024 -
5025 - # --- 3. Kontrola składni (nie uruchamiaj uszkodzonego/poddanego edycji pliku) ---
5026 - try:
5027 - compile(data, "pag", "exec")
5028 - except SyntaxError as e:
5029 - print(_(' ❌ Syntax error in new pag: {arg1}', arg1=(e)))
5030 - _cleanup_tmp_files(dst_new, dst_new + ".asc")
5031 - return 1
5032 -
5033 - m = (re.search(rb'PAG_VERSION\s*=\s*"(\d+\.\d+\.\d+[a-z]?)"', data[:3000])
5034 - or re.search(rb"v(\d+\.\d+\.\d+[a-z]?)", data[:3000]))
5035 - new_ver = m.group(1).decode() if m else "?"
5036 - print(_(' ✅ Downloaded pag {arg1} (current {arg2}), signature verified', arg1=(new_ver), arg2=(PAG_VERSION)))
5037 -
5038 - # --- 4. Backup + atomowa podmiana ---
5039 - if os.path.exists(dst):
5040 - shutil.copy2(dst, dst_bak)
5041 - os.chmod(dst_new, 0o755)
5042 - os.replace(dst_new, dst) # atomowe na tym samym FS
5043 - try:
5044 - if os.path.exists(dst_new + ".asc"):
5045 - os.remove(dst_new + ".asc")
5046 - except OSError:
5047 - pass
5048 - print(_(' ✅ Installed new pag. Old version kept as {arg1}', arg1=(dst_bak)))
5049 - # Ostrzeż, gdy w PATH pierwsza jest INNA kopia `pag` – inaczej
5050 - # `pag --version` dalej pokaże starą wersję i wygląda to jak brak update.
5051 - other = shutil.which("pag")
5052 - if other and os.path.realpath(other) != os.path.realpath(dst):
5053 - print(_(' ⚠ A different pag is first in PATH: {arg1} (updated {arg2})', arg1=(other), arg2=(dst)))
5054 - print(_(' Remove the old copy: sudo rm {arg1}', arg1=(other)))
5055 - print(_(' Restart pag to use the new version.'))
5056 - return 0
5057 -
5058 -
5059 -def _candidate_newer(rp, inst):
5060 - """Czy pakiet z repo jest nowszy od zainstalowanego.
5061 - Porównuje (version, release): sam bump pkgrel (np. auto-rebuild modułów
5062 - po aktualizacji jądra: nvidia-kernel-618 610.57.04-1 -> -2) też musi być
5063 - widziany przez `pag update`. Stare rekordy instalacji (bez pola release)
5064 - traktujemy jak release=1 – nie generują churnu, dopóki nie wrócą do
5065 - reinstalacji/zmiany wersji."""
5066 - rv = getattr(rp, "version", "0")
5067 - iv = inst.get("version", "0")
5068 - if _version_newer(rv, iv):
5069 - return True
5070 - if rv != iv:
5071 - return False
5072 - rr = int(getattr(rp, "release", 1) or 1)
5073 - ir = int(inst.get("release", 1) or 1)
5074 - return rr > ir
5075 -
5076 -
5077 -def _pending_updates() -> List[str]:
5078 - """Zainstalowane pakiety z nowszą wersją/release w repo (bez przypiętych)."""
5079 - installed = load_json(INSTALLED_DB)
5080 - pinned = load_json(PINNED_FILE)
5081 - repo = fetch_all_packages()
5082 - if not repo:
5083 - return []
5084 - return [n for n, i in installed.items()
5085 - if n not in pinned and (rp := repo.get(n)) and _candidate_newer(rp, i)]
5086 -
5087 -# =============================================================================
5088 -# BAZA Z OBRAZU ISO → REPO (`pag base`) – pełny rolling
5089 -# =============================================================================
5090 -# ISO jest zbudowane ZE ŹRÓDEŁ (glibc, gcc, gtk, XFCE, …) – pag tych pakietów
5091 -# nie instalował, więc nie ma ich w installed.json/files.db. Skutki:
5092 -# • `pag upgrade` ich NIE dotyka (nie ma o nich pojęcia),
5093 -# • mimo to `pag install <nazwa>` je NADPISZE – pag robi kopię plików spoza
5094 -# swojej bazy (patrz _new_transaction_backup_root), więc nie są nietykalne.
5095 -#
5096 -# /usr/share/pag/base.json (wypalany przez build-pagan.sh) mówi, co jest w bazie
5097 -# obrazu i w jakiej wersji. `pag base` pokazuje stan, a `pag base adopt` dogrywa
5098 -# te pakiety z repo – po tym zabiegu pag zarządza nimi normalnie, więc
5099 -# `pag upgrade` aktualizuje CAŁY system (rolling), a nie tylko to, co sam
5100 -# wcześniej zainstalował.
5101 -#
5102 -# Nazwy z buildera różnią się od nazw pakietów w repo (builder buduje „libX11”,
5103 -# repo ma pakiet „xorg-libx11”), stąd aliasy poniżej. Nazwy bez odpowiednika
5104 -# w repo zostają w wersji z obrazu – raport mówi o tym wprost, zamiast udawać,
5105 -# że są aktualne.
5106 -BASE_NAME_ALIASES = {
5107 - "atk": "at-spi2-core",
5108 - "dejavu-fonts": "dejavu-ttf",
5109 - "fontconfig": "xorg-fontconfig",
5110 - "gtk": "gtk3",
5111 - "iceauth": "xorg-iceauth",
5112 - "libX11": "xorg-libx11",
5113 - "libXau": "xorg-libxau",
5114 - "libXdmcp": "xorg-libxdmcp",
5115 - "libXext": "xorg-libxext",
5116 - "libXft": "xorg-libxft",
5117 - "libdrm": "xorg-libdrm",
5118 - "libnspr": "nspr",
5119 - "libxkbfile": "xorg-libxkbfile",
5120 - "libxklavier": "xorg-libxklavier",
5121 - "linux-pam": "pam",
5122 - "pixman": "xorg-pixman",
5123 - "sdl2": "sdl",
5124 - "setxkbmap": "xorg-setxkbmap",
5125 - "xauth": "xorg-xauth",
5126 - "xf86-input-libinput": "xorg-xf86-input-libinput",
5127 - "xf86-video-fbdev": "xorg-xf86-video-fbdev",
5128 - "xinit": "xorg-xinit",
5129 - "xkbcomp": "xorg-xkbcomp",
5130 - "xkeyboard-config": "xorg-xkeyboard-config",
5131 - # Builder buduje wpa_supplicant (z podkreślnikiem), a repo ma wpa-supplicant
5132 - # (z myślnikiem) – bez tego aliasu pakiet nie dostawał aktualizacji z repo,
5133 - # mimo że repo.json zna DOKŁADNIE tę samą wersję.
5134 - "wpa_supplicant": "wpa-supplicant",
5135 -}
5136 -
5137 -
5138 -def _base_manifest() -> dict:
5139 - """Manifest bazy z obrazu ({} gdy obraz go nie dostarcza)."""
5140 - _d = load_json(os.path.join(PAG_ROOT, BASE_MANIFEST.lstrip("/")))
5141 - return _d if isinstance(_d, dict) else {}
5142 -
5143 -
5144 -def _base_entries() -> list:
5145 - """[(nazwa_z_buildera, wersja_z_obrazu), ...] z manifestu."""
5146 - _out = []
5147 - for _e in (_base_manifest().get("packages") or []):
5148 - if isinstance(_e, str):
5149 - if _e:
5150 - _out.append((_e, "?"))
5151 - elif isinstance(_e, dict) and _e.get("name"):
5152 - _out.append((str(_e["name"]), str(_e.get("version") or "?")))
5153 - return _out
5154 -
5155 -
5156 -def _base_repo_name(name: str, repo: dict, installed: dict) -> str:
5157 - """Nazwa pakietu w repo dla nazwy z buildera (alias → provides → brak)."""
5158 - if name in repo:
5159 - return name
5160 - _alias = BASE_NAME_ALIASES.get(name)
5161 - if _alias and _alias in repo:
5162 - return _alias
5163 - _real = _resolve_provides(name, repo, installed)
5164 - return _real if _real in repo else ""
5165 -
5166 -
5167 -def _base_summary(repo: Optional[dict] = None) -> dict:
5168 - """Klasyfikacja pakietów bazy z obrazu wobec repo.
5169 -
5170 - repo=None → pobiera indeks repo (potrzebny do listy „do adoptowania”).
5171 - repo={} → bez sieci: rozpoznaje tylko to, czym pag już zarządza.
5172 - """
5173 - _entries = _base_entries()
5174 - if not _entries:
5175 - return {"total": 0, "tracked": 0, "adoptable": [], "unmatched": []}
5176 - if repo is None:
5177 - repo = fetch_all_packages()
5178 - installed = load_json(INSTALLED_DB)
5179 - tracked, adoptable, unmatched = 0, [], []
5180 - for _n, _v in _entries:
5181 - _real = _base_repo_name(_n, repo, installed)
5182 - if _n in installed or (_real and _real in installed):
5183 - tracked += 1
5184 - elif _real:
5185 - adoptable.append((_n, _real, _v))
5186 - else:
5187 - unmatched.append(_n)
5188 - return {"total": len(_entries), "tracked": tracked,
5189 - "adoptable": adoptable, "unmatched": unmatched}
5190 -
5191 -
5192 -def _base_hint_unmanaged() -> None:
5193 - """Jednozdaniowa informacja dla `pag sync/update/upgrade`."""
5194 - try:
5195 - _s = _base_summary()
5196 - except Exception:
5197 - return
5198 - if _s["adoptable"]:
5199 - print(f"\n ℹ {_('base_unmanaged_hint', len(_s['adoptable']))}")
5200 -
5201 -
5202 -def _base_warn_overwrite(names) -> None:
5203 - """Ostrzeżenie w `pag install`, gdy pakiet pochodzi z bazy obrazu ISO."""
5204 - _entries = _base_entries()
5205 - if not _entries:
5206 - return
5207 - _known = set()
5208 - for _n, _v in _entries:
5209 - _known.add(_n)
5210 - _al = BASE_NAME_ALIASES.get(_n)
5211 - if _al:
5212 - _known.add(_al)
5213 - _hit = [n for n in names if n in _known]
5214 - if _hit:
5215 - _listed = ", ".join(_hit[:5]) + (" …" if len(_hit) > 5 else "")
5216 - print(f" ℹ {_('base_overwrite', _listed)}")
5217 -
5218 -
5219 -def cmd_base_status():
5220 - """`pag base` / `pag base status` – co w systemie pochodzi z obrazu,
5221 - czym pag już zarządza i co da się zaadoptować z repo."""
5222 - _man = _base_manifest()
5223 - if not _man:
5224 - print(f" ℹ {_('base_no_manifest')}")
5225 - return 0
5226 - _s = _base_summary()
5227 - print(f"\n {_c('bold', _('base_title'))}")
5228 - print(f" {'─' * 46}")
5229 - _de = _man.get("de") or ""
5230 - print(f" {_('base_iso_version'):<34} {_man.get('iso_version', '?')}" + (f" ({_de})" if _de else ""))
5231 - print(f" {_('base_total'):<34} {_s['total']}")
5232 - print(f" {_('base_tracked'):<34} {_s['tracked']}")
5233 - print(f" {_('base_adoptable'):<34} {len(_s['adoptable'])}")
5234 - print(f" {_('base_unmatched'):<34} {len(_s['unmatched'])}")
5235 - if _s["adoptable"]:
5236 - print(f"\n {_('base_adopt_hint')}")
5237 - for _iso_n, _real, _v in _s["adoptable"][:10]:
5238 - _m = "" if _iso_n == _real else f" ({_iso_n})"
5239 - print(f" {_real}-{_v}{_m}")
5240 - if len(_s["adoptable"]) > 10:
5241 - print(f" … {len(_s['adoptable']) - 10} {_('base_more')}")
5242 - if _s["unmatched"]:
5243 - print(f"\n {_('base_unmatched_hint')}")
5244 - print(" " + ", ".join(_s["unmatched"][:12])
5245 - + (f" … +{len(_s['unmatched']) - 12}" if len(_s["unmatched"]) > 12 else ""))
5246 - return 0
5247 -
5248 -
5249 -def cmd_base_adopt(args):
5250 - """`pag base adopt [pkg...] [--dry-run]` – dograj bazę z obrazu z repo.
5251 -
5252 - Pakiety bazy nie ma w installed.json, więc pag traktuje je jak NOWĄ
5253 - instalację: pliki z obrazu trafiają do kopii transakcji (działa
5254 - `pag rollback`), a po sukcesie pag zarządza nimi jak każdym innym pakietem.
5255 - """
5256 - if not _base_manifest():
5257 - print(f" ℹ {_('base_no_manifest')}")
5258 - return 1
5259 - repo = fetch_all_packages()
5260 - if not repo:
5261 - print(f"❌ {_('no_index')}")
5262 - return 1
5263 - _want = [a for a in args if not a.startswith("-") and a != "adopt"]
5264 - _s = _base_summary(repo)
5265 - plan = _s["adoptable"]
5266 - if _want:
5267 - _sel = set(_want)
5268 - plan = [p for p in plan if p[0] in _sel or p[1] in _sel]
5269 - if not plan:
5270 - print(f" ℹ {_('base_nothing_selected')}")
5271 - return 0
5272 - if not plan:
5273 - print(f"✅ {_('base_all_managed')}")
5274 - return 0
5275 - _size = sum(repo[r].size_bytes for _i, r, _v in plan if r in repo)
5276 - print(f"\n {_('base_adopt_plan', len(plan), _size / 1048576)}")
5277 - for _iso_n, _real, _v in plan[:20]:
5278 - _p = repo.get(_real)
5279 - _rv = _p.version if _p else "?"
5280 - _rr = (getattr(_p, "release", "") or "") if _p else ""
5281 - _rvr = f"{_rv}-{_rr}" if _rr else _rv
5282 - _m = "" if _iso_n == _real else f" ({_iso_n} → {_real})"
5283 - print(f" {_real}: {_v} → {_rvr}{_m}")
5284 - if len(plan) > 20:
5285 - print(f" … {len(plan) - 20} {_('base_more')}")
5286 - if "-n" in args or "--dry-run" in args:
5287 - print(f" {_('base_dry_run')}")
5288 - return 0
5289 - _rc = cmd_install([r for _i, r, _v in plan])
5290 - if _rc == 0:
5291 - # Wymienione biblioteki/narzędzia (glibc, gcc, GTK…) są już nowe na dysku,
5292 - # ale działające procesy wciąż mają stare w pamięci – restart domyka.
5293 - print(f"\n ℹ {_('base_reboot_hint')}")
5294 - return _rc
5295 -
5296 -
5297 -def _base_cached_index() -> dict:
5298 - """Indeks repo TYLKO z lokalnego cache (zero sieci) – do mapowania nazw.
5299 -
5300 - Potrzebne dla `pag base register`: rejestracja bazy obrazu nie może zależeć
5301 - od sieci (odpala się w buildzie, w chroocie, bez DNS). Cache indeksu powstaje
5302 - przy okazji `pag sync`/`pag install` i po nim wystarcza.
5303 - """
5304 - _out = {}
5305 - try:
5306 - for _r in get_repos():
5307 - _cp = _repo_cache_path(_r)
5308 - if not os.path.exists(_cp):
5309 - continue
5310 - for _pdata in (_load_repo_cache(_cp) or []):
5311 - _n = _pdata.get("name") or _pdata.get("filename", "?").split("-")[0]
5312 - _pkg = PackageInfo(_pdata, _r)
5313 - if _n not in _out or _version_newer(_pkg.version, _out[_n].version):
5314 - _out[_n] = _pkg
5315 - except Exception:
5316 - return _out
5317 - return _out
5318 -
5319 -
5320 -def cmd_base_register(args):
5321 - """`pag base register [--force] [--dry-run]` – wpisz bazę obrazu do installed.json.
5322 -
5323 - PO CO: pakietów zbudowanych przez builder (glibc, gcc, GTK, XFCE…) nie ma
5324 - w installed.json, więc `pag upgrade` ich NIE widzi i system nie da się
5325 - prowadzić w trybie rolling – trzeba by najpierw `pag base adopt`, czyli
5326 - ponownie ŚCIĄGNĄĆ całą bazę z repo. Rejestracja zamiast tego zapisuje je
5327 - jako zainstalowane **z wersją z obrazu** (to ona leży na dysku), więc
5328 - `pag upgrade` porówna ją z repo i podniesie tylko to, co nowsze.
5329 -
5330 - Offline: nic nie pobiera. Cache indeksu repo (jeśli jest) służy WYŁĄCZNIE do
5331 - mapowania nazw builder → repo (BASE_NAME_ALIASES/provides) i metadanych
5332 - (release/opis/zależności). Nazwy bez odpowiednika w repo zostają jak są.
5333 -
5334 - OGRANICZENIE: rejestracja nie zna listy plików pakietu (files.db), więc
5335 - dopóki pakiet nie zostanie zaktualizowany z repo, `pag verify`/`pag remove`
5336 - go nie obejmą (`pag base adopt` nadal jest drogą do pełnego przejęcia).
5337 - """
5338 - _force = "-f" in args or "--force" in args
5339 - _dry = "-n" in args or "--dry-run" in args
5340 -
5341 - _entries = _base_entries()
5342 - if not _entries:
5343 - print(f" ℹ {_('base_no_manifest')}")
5344 - return 1
5345 -
5346 - _repo = _base_cached_index()
5347 - installed = load_json(INSTALLED_DB)
5348 - world = load_world()
5349 - _now = datetime.now().isoformat()
5350 -
5351 - added, skipped, renamed = [], 0, 0
5352 - for _n, _v in _entries:
5353 - _real = _base_repo_name(_n, _repo, installed) if _repo else ""
5354 - _key = _real or _n
5355 - if _real and _real != _n:
5356 - renamed += 1
5357 - if _key in installed and not _force:
5358 - skipped += 1
5359 - continue
5360 - _pkg = _repo.get(_key)
5361 - installed[_key] = {
5362 - "version": _v or (getattr(_pkg, "version", "") or "?"),
5363 - "release": getattr(_pkg, "release", "") or "1",
5364 - "description": (getattr(_pkg, "description", "") or "")
5365 - or "Pagan Linux – pakiet bazy obrazu",
5366 - "dependencies": list(getattr(_pkg, "dependencies", []) or []),
5367 - "size_bytes": getattr(_pkg, "size_bytes", 0) or 0,
5368 - "sha256": "",
5369 - "installed_at": _now,
5370 - "repo": "base",
5371 - "provides": list(getattr(_pkg, "provides", []) or []),
5372 - "provides_so": list(getattr(_pkg, "provides_so", []) or []),
5373 - "requires_so": list(getattr(_pkg, "requires_so", []) or []),
5374 - }
5375 - world.add(_key)
5376 - added.append(_key)
5377 -
5378 - if _dry:
5379 - print(f" ℹ {_('base_register_plan', len(added))}")
5380 - return 0
5381 - if added:
5382 - save_json(INSTALLED_DB, installed)
5383 - save_world(world)
5384 - print(f" ✅ {_('base_register_ok', len(added), skipped)}")
5385 - if renamed:
5386 - print(f" ℹ {_('base_register_renamed', renamed)}")
5387 - if not _repo:
5388 - print(f" ℹ {_('base_register_nocache')}")
5389 - return 0
5390 -
5391 -
5392 -def cmd_update(do_upgrade: bool = False):
5393 - """`pag sync` / `pag update` – odświeżenie indeksów + raport aktualizacji.
5394 -
5395 - sync → tylko odświeżenie indeksów + info: „jest X pakietów do
5396 - zaktualizowania – wpisz: pag update".
5397 - update → odświeżenie indeksów + AKTUALIZACJA PAKIETÓW (pakiety, nie system).
5398 - Pomijamy cache TTL (inaczej nowe pakiety/aktualizacje są niewidoczne nawet
5399 - przez godzinę). Pełne pobranie + weryfikacja GPG przy każdym odświeżeniu.
5400 - """
5401 - force = True
5402 - print(_('🔄 Refreshing indexes...'))
5403 - for repo_url in get_repos():
5404 - pkgs = fetch_repo_index(repo_url, force=force)
5405 - cp = _repo_cache_path(repo_url)
5406 - has_sig = os.path.exists(cp + ".sig")
5407 - 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 '⚠')))
5408 - print(f"✅ {_('indexes_refreshed')}")
5409 -
5410 - # Powiadomienie o nowszej wersji pag (repo.json["pag_version"])
5411 - try:
5412 - for r in get_repos():
5413 - cp = _repo_cache_path(r)
5414 - if os.path.exists(cp):
5415 - d = json.load(open(cp))
5416 - rv = d.get("pag_version", "")
5417 - if rv and rv != PAG_VERSION:
5418 - print(_(' ⚠ New pag version {arg1} available – run: pag self-update', arg1=(rv)))
5419 - except Exception:
5420 - pass
5421 -
5422 - # Raport: pakiety do aktualizacji
5423 - pending = _kernel_group_updates(_pending_updates())
5424 - if not pending:
5425 - print(f"✅ {_('all_up_to_date')}")
5426 - _base_hint_unmanaged()
5427 - return 0
5428 - print(f"{_('updates_available', len(pending))}")
5429 - installed = load_json(INSTALLED_DB)
5430 - repo = fetch_all_packages()
5431 - for n in pending:
5432 - _i = installed.get(n, {})
5433 - _ir = _i.get("release")
5434 - _nr = getattr(repo[n], "release", "") or ""
5435 - _old = f"{_i.get('version', '?')}-{_ir}" if _ir else _i.get("version", "?")
5436 - _new = f"{repo[n].version}-{_nr}" if _nr else repo[n].version
5437 - print(f" {n}: {_old} → {_new}")
5438 - if not do_upgrade:
5439 - _base_hint_unmanaged()
5440 - return 0 # sync: tylko informacja
5441 - if not _ask_confirm():
5442 - return 0
5443 - _rc = cmd_install(pending, upgrade=True)
5444 - _base_hint_unmanaged()
5445 - return _rc
5446 -
5447 -def _versioned_kernels(boot: str = "/boot") -> list:
5448 - """Wersjonowane obrazy jąder z /boot (bez aliasu `vmlinuz-linux`)."""
5449 - try:
5450 - out = []
5451 - for n in os.listdir(boot):
5452 - if not n.startswith("vmlinuz-"):
5453 - continue
5454 - ver = n[len("vmlinuz-"):]
5455 - if not ver or not ver[0].isdigit():
5456 - continue # vmlinuz-linux to alias, nie wersja
5457 - if os.path.islink(os.path.join(boot, n)):
5458 - continue
5459 - out.append(ver)
5460 - return out
5461 - except Exception:
5462 - return []
5463 -
5464 -
5465 -def _initramfs_stale() -> bool:
5466 - """Czy initramfs najnowszego (wersjonowanego) jądra wymaga przebudowy.
5467 -
5468 - Uwaga: aliasy `initramfs.img` / `initramfs-linux.img` bywają martwymi
5469 - symlinkami — `os.path.exists()` zwraca wtedy False, co wcześniej kończyło
5470 - się wiecznym „stale” i przebudową w pętli. Patrzymy na KONKRETNY plik
5471 - `initramfs-<wersja>.img`.
5472 - """
5473 - try:
5474 - if not os.path.isdir("/boot"):
5475 - return False
5476 - vers = _versioned_kernels()
5477 - if not vers:
5478 - return False
5479 - newest = max(vers, key=lambda v: os.path.getmtime(f"/boot/vmlinuz-{v}"))
5480 - img = f"/boot/initramfs-{newest}.img"
5481 - if not os.path.isfile(img):
5482 - return True
5483 - return os.path.getmtime(img) < os.path.getmtime(f"/boot/vmlinuz-{newest}")
5484 - except Exception:
5485 - return False
5486 -
5487 -def cmd_upgrade():
5488 - """`pag upgrade` – aktualizacja SYSTEMU: pakiety + kernel/initramfs/GRUB."""
5489 - rc = cmd_update(do_upgrade=True)
5490 - if rc != 0:
5491 - return rc
5492 - # System: dopilnuj initramfs (gdyby kernel był nowszy) + GRUB.
5493 - if _initramfs_stale():
5494 - print(_(' 🐧 Rebuilding initramfs (newer kernel)...'))
5495 - _rebuild_initramfs()
5496 - _refresh_bootloader()
5497 - return 0
5498 -
5499 -def cmd_list(installed_only=False):
5500 - if installed_only:
5501 - db = load_json(INSTALLED_DB)
5502 - pinned = load_json(PINNED_FILE)
5503 - if not db: print(_('No packages installed.')); return
5504 - print(_('Installed ({arg1}):', arg1=(len(db))))
5505 - for n, i in sorted(db.items()):
5506 - pin = " 📌" if n in pinned else ""
5507 - print(f" {n}-{i['version']}{pin} – {i.get('description','')}")
5508 - else:
5509 - pkgs = fetch_all_packages()
5510 - installed = load_json(INSTALLED_DB)
5511 - pinned = load_json(PINNED_FILE)
5512 - print(_('Available ({arg1}):', arg1=(len(pkgs))))
5513 - for n, p in sorted(pkgs.items()):
5514 - m = "✓" if n in installed else " "
5515 - extra = f" [{_('installed_marker')}: {installed[n]['version']}]" if n in installed else ""
5516 - if n in pinned: extra += " 📌"
5517 - print(f" [{m}] {n}-{p.version} – {p.description}{extra}")
5518 -
5519 -def cmd_search(query):
5520 - pkgs = fetch_all_packages()
5521 - results = [(n,p) for n,p in pkgs.items() if query.lower() in n.lower() or query.lower() in p.description.lower()]
5522 - if not results: print(_('❌ No results for: {arg1}', arg1=(query))); return
5523 - installed = load_json(INSTALLED_DB)
5524 - print(_("Results for '{arg1}' ({arg2}):", arg1=(query), arg2=(len(results))))
5525 - for n,p in sorted(results):
5526 - print(f" [{'✓' if n in installed else ' '}] {n}-{p.version}")
5527 - print(f" {p.description}")
5528 -
5529 -
5530 -def _smart_search(query: str) -> int:
5531 - """
5532 - Inteligentne wyszukiwanie: repo PaganOS + Flathub.
5533 - Uruchamiane gdy użytkownik wpisze `pag <nazwa>` zamiast `pag install <nazwa>`.
5534 - Pokazuje dostępne źródła i sugeruje komendy instalacji.
5535 - """
5536 - # 1. Repo PaganOS
5537 - try:
5538 - pkgs = fetch_all_packages()
5539 - except Exception:
5540 - pkgs = {}
5541 - repo_lower = [(n, p) for n, p in pkgs.items()
5542 - if query.lower() in n.lower() or query.lower() in p.description.lower()]
5543 -
5544 - # 2. Flathub (jeśli dostępny)
5545 - flat = _flatpak_search_raw(query) if _check_flatpak(quiet=True) else []
5546 -
5547 - if not repo_lower and not flat:
5548 - print(_("\n ❌ '{arg1}' — not found.", arg1=(query)))
5549 - print(_(' PaganOS repo: pag search {arg1}', arg1=(query)))
5550 - if _check_flatpak(quiet=True):
5551 - print(_(' Flathub: pag flatpak search {arg1}', arg1=(query)))
5552 - print(_(' Add repo: pag repo-add <url>'))
5553 - return 1
5554 -
5555 - installed = load_json(INSTALLED_DB)
5556 -
5557 - # ── Repo PaganOS ──
5558 - if repo_lower:
5559 - exact = [(n, p) for n, p in repo_lower if n.lower() == query.lower()]
5560 - show = (exact or repo_lower)[:6]
5561 - print(f"\n 📦 PaganOS — '{query}':")
5562 - for n, p in sorted(show):
5563 - mark = "✓" if n in installed else " "
5564 - desc = p.description[:70] if len(p.description) > 75 else p.description
5565 - print(f" [{mark}] {n}-{p.version}")
5566 - if desc:
5567 - print(f" {desc}")
5568 - if len(repo_lower) > 6:
5569 - print(_(' ... and {arg1} more (pag search {arg2})', arg1=(len(repo_lower) - 6), arg2=(query)))
5570 -
5571 - # ── Flathub ──
5572 - if flat:
5573 - print(f"\n 📦 Flathub — '{query}':")
5574 - for r in flat[:5]:
5575 - mark = "✓" if r.get("installed") else " "
5576 - name = r.get("name") or r.get("application", "?")
5577 - desc = (r.get("description") or "")[:65]
5578 - print(f" [{mark}] {name}")
5579 - if desc:
5580 - print(f" {desc}")
5581 - if len(flat) > 5:
5582 - print(_(' ... and {arg1} more (pag flatpak search {arg2})', arg1=(len(flat) - 5), arg2=(query)))
5583 -
5584 - # ── Sugestie instalacji ──
5585 - print()
5586 - if repo_lower:
5587 - 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]
5588 - if best in installed:
5589 - print(_(' ✓ {arg1} is already installed ({arg2})', arg1=(best), arg2=(installed[best]['version'])))
5590 - else:
5591 - print(f" 💡 sudo pag install {best}")
5592 - if flat:
5593 - best_fp = flat[0].get("application") or flat[0].get("name", query)
5594 - print(f" 💡 pag flatpak install {best_fp}")
5595 -
5596 - return 0
5597 -
5598 -def cmd_info(name):
5599 - pkgs = fetch_all_packages()
5600 - p = pkgs.get(name)
5601 - info = load_json(INSTALLED_DB).get(name)
5602 - if not p and not info: print(_("❌ '{arg1}' not found.", arg1=(name))); return 1
5603 - print(f"📦 {name}")
5604 - if p:
5605 - print(_(' Version (repo): {arg1}', arg1=(p.version)))
5606 - print(_(' Description: {arg1}', arg1=(p.description)))
5607 - print(_(' Size: {arg1:.1f} MB', arg1=(p.size_bytes/1048576)))
5608 - print(_(' SHA256: {arg1}...', arg1=(p.sha256[:32])))
5609 - print(_(' GPG: {arg1}', arg1=(p.gpg_fp or _('none_value'))))
5610 - print(_(' Dependencies: {arg1}', arg1=((', '.join(p.dependencies)) if p.dependencies else _('none_parenthesized'))))
5611 - if p.optdepends:
5612 - print(f" {_('optional_deps')}")
5613 - for _od in p.optdepends:
5614 - print(f" - {_od}")
5615 - if info:
5616 - print(_(' Installed: {arg1} ({arg2})', arg1=(info['version']), arg2=(info.get('installed_at','?'))))
5617 -
5618 -def cmd_files(name):
5619 - if name not in load_json(INSTALLED_DB):
5620 - print(_("❌ '{arg1}' not installed.", arg1=(name))); return 1
5621 - files = _db_get_package_files(name)
5622 - print(_('Files in {arg1} ({arg2}):', arg1=(name), arg2=(len(files))))
5623 - for f in sorted(files): print(f" {f}")
5624 -
5625 -def cmd_repair(dry_run=False):
5626 - """Naprawia system: reinstaluje pakiety, ktorych pliki zginely.
5627 -
5628 - Przechodzi po bazie plikow (jak `verify`), zbiera pakiety z brakujacymi
5629 - plikami i dla kazdego robi REINSTALACJE z repozytorium (staging + GPG).
5630 - Reinstalacja nie rusza konfiguracji uzytkownika (.pacnew), a przywraca
5631 - brakujace pliki pakietu (np. qt6-declarative, accountsservice).
5632 - """
5633 - installed = load_json(INSTALLED_DB)
5634 - if not installed:
5635 - print(_('Nothing to repair (no packages installed).'))
5636 - return 0
5637 - missing = {}
5638 - for name in installed:
5639 - cnt = 0
5640 - for fpath in _db_get_package_files(name):
5641 - full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
5642 - if not (os.path.exists(full) or os.path.islink(full)):
5643 - cnt += 1
5644 - if cnt:
5645 - missing[name] = cnt
5646 - if not missing:
5647 - print(_('✅ All files are in place – nothing to repair.'))
5648 - return 0
5649 - total = sum(missing.values())
5650 - print(_('🔧 Packages with missing files: {arg1} (total {arg2} files)', arg1=(len(missing)), arg2=(total)))
5651 - for n, c in sorted(missing.items(), key=lambda kv: (-kv[1], kv[0])):
5652 - print(f" {n}: {c}")
5653 - if dry_run:
5654 - print(_('\n(--dry-run: nothing is changed)'))
5655 - return 0
5656 - if not _ask_confirm():
5657 - print(_("cancelled")); return 0
5658 - # Jedna migawka na całą naprawę – nie tworzymy snapshotu per pakiet.
5659 - _snap_ok, _ = _snapshot_support()
5660 - if _snap_ok:
5661 - _create_system_snapshot(list(missing), "repair")
5662 - _refresh_bootloader()
5663 - _prev_snap = os.environ.get("PAG_SNAPSHOT")
5664 - os.environ["PAG_SNAPSHOT"] = "never"
5665 - failed = []
5666 - try:
5667 - for n in sorted(missing, key=lambda x: (-missing[x], x)):
5668 - print(_('\n🔧 repair: {arg1}', arg1=(n)))
5669 - try:
5670 - rc = cmd_install([n], upgrade=True)
5671 - except SystemExit as e:
5672 - rc = e.code
5673 - except Exception as e:
5674 - print(f" ❌ {n}: {e}")
5675 - rc = 1
5676 - if rc:
5677 - failed.append(n)
5678 - finally:
5679 - if _prev_snap is None:
5680 - os.environ.pop("PAG_SNAPSHOT", None)
5681 - else:
5682 - os.environ["PAG_SNAPSHOT"] = _prev_snap
5683 - print()
5684 - ok = len(missing) - len(failed)
5685 - if failed:
5686 - print(_('⚠ Repaired {arg1}/{arg2}. Failed: {arg3}', arg1=(ok), arg2=(len(missing)), arg3=(', '.join(failed))))
5687 - return 1
5688 - print(_('✅ Repaired {arg1} packages.', arg1=(ok)))
5689 - return 0
5690 -
5691 -
5692 -def cmd_verify(deep=False):
5693 - installed = load_json(INSTALLED_DB)
5694 - if not installed: print(_('Nothing to verify.')); return
5695 - errors = []
5696 -
5697 - # Wczytaj WSZYSTKIE sumy RAZ (nie w pętli!) – przy 50k plików wywołanie
5698 - # _db_get_all_file_checksums() per-plik dawało O(n²) i godziny zamiast sekund.
5699 - all_checksums = _db_get_all_file_checksums() if deep else {}
5700 - for name in installed:
5701 - for fpath in _db_get_package_files(name):
5702 - full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
5703 - if not (os.path.exists(full) or os.path.islink(full)):
5704 - errors.append(_("verify_missing_file", name, fpath))
5705 - elif deep:
5706 - expected = all_checksums.get(fpath, "")
5707 - if expected:
5708 - actual = _sha256_file(full)
5709 - if actual != expected:
5710 - errors.append(_("verify_sha_mismatch", name, fpath))
5711 -
5712 - if errors:
5713 - print(f"❌ {_('verify_errors', len(errors))}")
5714 - for e in errors: print(e)
5715 - return 1
5716 - total = _db_count_files()
5717 - print(f"✅ {_('verify_ok', total)}")
5718 -
5719 -# =============================================================================
5720 -# PINNING / CLEAN / ORPHANS / REPO / FLATPAK
5721 -# =============================================================================
5722 -
5723 -def cmd_pin(name, version=""):
5724 - pinned = load_json(PINNED_FILE)
5725 - if version:
5726 - pinned[name] = version
5727 - else:
5728 - info = load_json(INSTALLED_DB).get(name, {})
5729 - pinned[name] = info.get("version", "?")
5730 - save_json(PINNED_FILE, pinned)
5731 - print(f"📌 {name} {_('pinned_to')} {pinned[name]}")
5732 -
5733 -def cmd_unpin(name):
5734 - pinned = load_json(PINNED_FILE)
5735 - if name in pinned:
5736 - del pinned[name]; save_json(PINNED_FILE, pinned)
5737 - print(f"🔓 {name} {_('unpinned')}")
5738 - else:
5739 - print(f"⚠ {name} {_('not_pinned')}")
5740 -
5741 -def cmd_pinned():
5742 - pinned = load_json(PINNED_FILE)
5743 - if not pinned: print(_("no_pinned")); return
5744 - print(_("pinned_list", len(pinned)))
5745 - for n,v in sorted(pinned.items()): print(f" 📌 {n} = {v}")
5746 -
5747 -def cmd_clean():
5748 - if os.path.isdir(PAG_CACHE):
5749 - count = size = 0
5750 - for f in os.listdir(PAG_CACHE):
5751 - fp = os.path.join(PAG_CACHE, f)
5752 - if os.path.isfile(fp):
5753 - size += os.path.getsize(fp); os.remove(fp); count += 1
5754 - print(f"✅ {_('cache_cleared', count, size/1048576)}")
5755 -
5756 -def cmd_remove_orphans():
5757 - installed = load_json(INSTALLED_DB)
5758 - world = load_world()
5759 - orphans = _find_orphans(installed, world)
5760 - if not orphans: print(_('✅ No orphans.')); return
5761 - print(_('Orphans ({arg1}):', arg1=(len(orphans))))
5762 - for n in sorted(orphans): print(f" {n}-{installed[n]['version']}")
5763 - if not _ask_confirm():
5764 - return
5765 - cmd_remove(list(orphans))
5766 -
5767 -
5768 -# =============================================================================
5769 -# PROVIDES – PAKIETY WIRTUALNE
5770 -# =============================================================================
5771 -
5772 -PROVIDES_MAP = {
5773 - "pkgconfig(glib-2.0)": "glib",
5774 - "pkgconfig(gobject-introspection-1.0)": "gobject-introspection",
5775 - "pkgconfig(gtk+-3.0)": "gtk",
5776 - "pkgconfig(gtk4)": "gtk",
5777 - "pkgconfig(zlib)": "zlib",
5778 - "pkgconfig(libffi)": "libffi",
5779 - "pkgconfig(expat)": "expat",
5780 - "pkgconfig(libsystemd)": "systemd",
5781 - "pkgconfig(dbus-1)": "dbus",
5782 - "pkgconfig(mount)": "util-linux",
5783 - "pkgconfig(blkid)": "util-linux",
5784 - "pkgconfig(libcap)": "libcap",
5785 - "pkgconfig(liblzma)": "xz",
5786 - "pkgconfig(libzstd)": "zstd",
5787 - "pkgconfig(bzip2)": "bzip2",
5788 - "pkgconfig(libcurl)": "curl",
5789 - "pkgconfig(openssl)": "openssl",
5790 - "pkgconfig(libpcre2-8)": "pcre2",
5791 - "pkgconfig(libxml-2.0)": "libxml2",
5792 - "pkgconfig(libxslt)": "libxslt",
5793 - "pkgconfig(freetype2)": "freetype",
5794 - "pkgconfig(fontconfig)": "fontconfig",
5795 - "pkgconfig(harfbuzz)": "harfbuzz",
5796 - "pkgconfig(cairo)": "cairo",
5797 - "pkgconfig(pango)": "pango",
5798 - "pkgconfig(xt)": "xorg-libxt",
5799 - "pkgconfig(xmu)": "xorg-libxmu",
5800 - "pkgconfig(ice)": "xorg-libice",
5801 - "pkgconfig(sm)": "xorg-libsm",
5802 - "pkgconfig(x11)": "xorg-libx11",
5803 - "pkgconfig(xext)": "xorg-libxext",
5804 - "pkgconfig(xrandr)": "xorg-libxrandr",
5805 - "pkgconfig(xfixes)": "xorg-libxfixes",
5806 - "pkgconfig(xcursor)": "xorg-libxcursor",
5807 - "pkgconfig(xinerama)": "xorg-libxinerama",
5808 - "pkgconfig(xrender)": "xorg-libxrender",
5809 - "pkgconfig(xau)": "xorg-libxau",
5810 - "pkgconfig(xcb)": "xorg-libxcb",
5811 - "pkgconfig(xdamage)": "xorg-libxdamage",
5812 - "pkgconfig(xcomposite)": "xorg-libxcomposite",
5813 - "pkgconfig(xft)": "xorg-libxft",
5814 - "pkgconfig(xss)": "xorg-libxss",
5815 - "pkgconfig(libsoup-3.0)": "libsoup3",
5816 - "pkgconfig(libsoup-2.4)": "libsoup2",
5817 - "pkgconfig(gdk-pixbuf-2.0)": "gdk-pixbuf2",
5818 - "pkgconfig(libpng)": "libpng",
5819 - "pkgconfig(libjpeg)": "libjpeg-turbo",
5820 - "pkgconfig(libtiff-4)": "libtiff",
5821 - "pkgconfig(ffi)": "libffi",
5822 - # ── system / baza ──
5823 - "pkgconfig(libcrypto)": "openssl",
5824 - "pkgconfig(libssl)": "openssl",
5825 - "pkgconfig(libudev)": "systemd",
5826 - "pkgconfig(libmount)": "util-linux",
5827 - "pkgconfig(libblkid)": "util-linux",
5828 - "pkgconfig(uuid)": "util-linux",
5829 - "pkgconfig(libexpat)": "expat",
5830 - "pkgconfig(libpcre)": "pcre",
5831 - "pkgconfig(ncursesw)": "ncurses",
5832 - "pkgconfig(tinfo)": "ncurses",
5833 - "pkgconfig(panel)": "ncurses",
5834 - "pkgconfig(readline)": "readline",
5835 - "pkgconfig(libseccomp)": "libseccomp",
5836 - "pkgconfig(pam)": "linux-pam",
5837 - "pkgconfig(libxcrypt)": "libxcrypt",
5838 - "pkgconfig(libcrypt)": "libxcrypt",
5839 - "pkgconfig(libnsl)": "libnsl",
5840 - "pkgconfig(liblz4)": "lz4",
5841 - "pkgconfig(libevent)": "libevent",
5842 - "pkgconfig(libarchive)": "libarchive",
5843 - "pkgconfig(sqlite3)": "sqlite",
5844 - "pkgconfig(libpq)": "postgresql",
5845 - "pkgconfig(mysqlclient)": "mariadb",
5846 - "pkgconfig(json-c)": "json-c",
5847 - "pkgconfig(json-glib-1.0)": "json-glib",
5848 - "pkgconfig(libunistring)": "libunistring",
5849 - "pkgconfig(libidn2)": "libidn2",
5850 - "pkgconfig(libpsl)": "libpsl",
5851 - "pkgconfig(icu-uc)": "icu",
5852 - "pkgconfig(icu-i18n)": "icu",
5853 - "pkgconfig(icu-io)": "icu",
5854 - "pkgconfig(gnutls)": "gnutls",
5855 - "pkgconfig(nettle)": "nettle",
5856 - "pkgconfig(hogweed)": "nettle",
5857 - "pkgconfig(libgcrypt)": "libgcrypt",
5858 - "pkgconfig(libgpg-error)": "libgpg-error",
5859 - "pkgconfig(libassuan)": "libassuan",
5860 - "pkgconfig(libusb-1.0)": "libusb",
5861 - "pkgconfig(libusb)": "libusb",
5862 - "pkgconfig(libgudev-1.0)": "libgudev",
5863 - "pkgconfig(gudev-1.0)": "libgudev",
5864 - "pkgconfig(polkit-gobject-1)": "polkit",
5865 - "pkgconfig(polkit-agent-1)": "polkit",
5866 - "pkgconfig(libpciaccess)": "libpciaccess",
5867 - "pkgconfig(pixman-1)": "pixman",
5868 - "pkgconfig(libdrm)": "libdrm",
5869 - "pkgconfig(libva)": "libva",
5870 - "pkgconfig(libva-drm)": "libva",
5871 - "pkgconfig(libva-x11)": "libva",
5872 - "pkgconfig(libva-wayland)": "libva",
5873 - "pkgconfig(vdpau)": "libvdpau",
5874 - "pkgconfig(libvdpau)": "libvdpau",
5875 - "pkgconfig(libinput)": "libinput",
5876 - "pkgconfig(libevdev)": "libevdev",
5877 - "pkgconfig(mtdev)": "mtdev",
5878 - # ── grafika / GL / multimedia ──
5879 - "pkgconfig(gbm)": "mesa",
5880 - "pkgconfig(gl)": "libglvnd",
5881 - "pkgconfig(egl)": "libglvnd",
5882 - "pkgconfig(glesv2)": "libglvnd",
5883 - "pkgconfig(glx)": "libglvnd",
5884 - "pkgconfig(vulkan)": "vulkan-loader",
5885 - "pkgconfig(libxkbcommon)": "libxkbcommon",
5886 - "pkgconfig(xkbcommon)": "libxkbcommon",
5887 - "pkgconfig(xkbcommon-x11)": "libxkbcommon",
5888 - "pkgconfig(xcb)": "xorg-libxcb",
5889 - "pkgconfig(xcb-util)": "xcb-util",
5890 - "pkgconfig(xcb-keysyms)": "xcb-util-keysyms",
5891 - "pkgconfig(xcb-icccm)": "xcb-util-wm",
5892 - "pkgconfig(xcb-cursor)": "xcb-util-cursor",
5893 - "pkgconfig(xcb-renderutil)": "xcb-util-renderutil",
5894 - "pkgconfig(xcb-image)": "xcb-util-image",
5895 - "pkgconfig(xcb-errors)": "xcb-util-errors",
5896 - "pkgconfig(wayland-client)": "wayland",
5897 - "pkgconfig(wayland-server)": "wayland",
5898 - "pkgconfig(wayland-cursor)": "wayland",
5899 - "pkgconfig(wayland-egl)": "wayland",
5900 - "pkgconfig(wayland-protocols)": "wayland-protocols",
5901 - "pkgconfig(gstreamer-1.0)": "gstreamer",
5902 - "pkgconfig(gstreamer-base-1.0)": "gstreamer",
5903 - "pkgconfig(gstreamer-check-1.0)": "gstreamer",
5904 - "pkgconfig(gstreamer-controller-1.0)": "gstreamer",
5905 - "pkgconfig(gstreamer-app-1.0)": "gst-plugins-base",
5906 - "pkgconfig(gstreamer-video-1.0)": "gst-plugins-base",
5907 - "pkgconfig(gstreamer-audio-1.0)": "gst-plugins-base",
5908 - "pkgconfig(gstreamer-pbutils-1.0)": "gst-plugins-base",
5909 - "pkgconfig(gstreamer-fft-1.0)": "gst-plugins-base",
5910 - "pkgconfig(gstreamer-riff-1.0)": "gst-plugins-base",
5911 - "pkgconfig(gstreamer-rtp-1.0)": "gst-plugins-base",
5912 - "pkgconfig(gstreamer-rtsp-1.0)": "gst-plugins-base",
5913 - "pkgconfig(gstreamer-sdp-1.0)": "gst-plugins-base",
5914 - "pkgconfig(gstreamer-net-1.0)": "gst-plugins-base",
5915 - "pkgconfig(gstreamer-gl-1.0)": "gst-plugins-base",
5916 - "pkgconfig(libpulse)": "libpulse",
5917 - "pkgconfig(libpulse-simple)": "libpulse",
5918 - "pkgconfig(libpulse-mainloop-glib)": "libpulse",
5919 - "pkgconfig(alsa)": "alsa-lib",
5920 - "pkgconfig(jack)": "jack2",
5921 - "pkgconfig(libsamplerate)": "libsamplerate",
5922 - "pkgconfig(sndfile)": "libsndfile",
5923 - "pkgconfig(libavcodec)": "ffmpeg",
5924 - "pkgconfig(libavformat)": "ffmpeg",
5925 - "pkgconfig(libavutil)": "ffmpeg",
5926 - "pkgconfig(libavfilter)": "ffmpeg",
5927 - "pkgconfig(libswscale)": "ffmpeg",
5928 - "pkgconfig(libswresample)": "ffmpeg",
5929 - "pkgconfig(libpostproc)": "ffmpeg",
5930 - "pkgconfig(SDL2)": "sdl2",
5931 - "pkgconfig(SDL)": "sdl",
5932 - "pkgconfig(SDL2_image)": "sdl2-image",
5933 - "pkgconfig(SDL2_ttf)": "sdl2-ttf",
5934 - "pkgconfig(SDL2_mixer)": "sdl2-mixer",
5935 - "pkgconfig(SDL2_net)": "sdl2-net",
5936 - "pkgconfig(libpng16)": "libpng",
5937 - "pkgconfig(libwebp)": "libwebp",
5938 - "pkgconfig(libwebpmux)": "libwebp",
5939 - "pkgconfig(libwebpdemux)": "libwebp",
5940 - "pkgconfig(libopenjp2)": "openjpeg2",
5941 - "pkgconfig(lcms2)": "lcms2",
5942 - "pkgconfig(libheif)": "libheif",
5943 - "pkgconfig(libde265)": "libde265",
5944 - "pkgconfig(x264)": "x264",
5945 - "pkgconfig(x265)": "x265",
5946 - # ── glib / gio ──
5947 - "pkgconfig(gio-unix-2.0)": "glib",
5948 - "pkgconfig(gmodule-2.0)": "glib",
5949 - "pkgconfig(gthread-2.0)": "glib",
5950 - "pkgconfig(girepository-2.0)": "gobject-introspection",
5951 - "pkgconfig(girepository-1.0)": "gobject-introspection",
5952 - "pkgconfig(libglib-2.0)": "glib",
5953 - "pkgconfig(libgobject-2.0)": "glib",
5954 -}
5955 -
5956 -# Ostrzeżenia o wielu dostawcach tej samej wirtualnej nazwy – raz na proces.
5957 -_PROVIDES_WARNED = set()
5958 -# Cache indeksu provides dla danego obiektu repo: (repo_obj, {virtual: [pkg,...]}).
5959 -# Trzymamy referencję do repo, by uniknąć pomyłki przy ponownym użyciu id().
5960 -_provides_cache = (None, {})
5961 -
5962 -def _provides_index(repo: dict) -> dict:
5963 - """Buduje (i cache’uje) mapę wirtualna nazwa → lista dostawców w repo.
5964 -
5965 - Pozwala wybrać dostawcę DETERMINISTYCZNIE (posortowanego) zamiast zależeć
5966 - od kolejności wstawiania w repo.json, oraz ostrzec o konflikcie provides."""
5967 - global _provides_cache
5968 - cached_repo, idx = _provides_cache
5969 - if cached_repo is repo:
5970 - return idx
5971 - idx = {}
5972 - for _pn, _p in repo.items():
5973 - for _prov in (getattr(_p, "provides", None) or []):
5974 - idx.setdefault(_prov, []).append(_pn)
5975 - for _prov, _pns in idx.items():
5976 - if len(_pns) > 1 and _prov not in _PROVIDES_WARNED:
5977 - _PROVIDES_WARNED.add(_prov)
5978 - _sorted = sorted(_pns)
5979 - print(f" ⚠ {_('provides_conflict', name=_prov, providers=', '.join(_sorted), chosen=_sorted[0])}",
5980 - file=sys.stderr)
5981 - _provides_cache = (repo, idx)
5982 - return idx
5983 -
5984 -
5985 -def _resolve_provides(name: str, repo: dict, installed: Optional[dict] = None) -> str:
5986 - """Rozwija wirtualną nazwę pakietu do rzeczywistej nazwy.
5987 -
5988 - Kolejność: repo → PROVIDES_MAP → wzorce → provides z repo.json →
5989 - provides ZAINSTALOWANYCH pakietów (lokalnie zbudowane poza repo też
5990 - dostarczają wirtualne zależności) → fallback pkgconfig (czyszczenie nazwy).
5991 - """
5992 - if name in repo:
5993 - return name
5994 - if name in PROVIDES_MAP:
5995 - real = PROVIDES_MAP[name]
5996 - if real in repo:
5997 - return real
5998 - # Wzorce: moduły Qt (Qt5Core/Qt6Widgets) i GStreamer (gstreamer-video-1.0)
5999 - if name.startswith("pkgconfig(Qt5"):
6000 - real = "qt5"
6001 - if real in repo:
6002 - return real
6003 - if name.startswith("pkgconfig(Qt6"):
6004 - real = "qt6"
6005 - if real in repo:
6006 - return real
6007 - if name.startswith("pkgconfig(gstreamer-") and name.endswith("-1.0)"):
6008 - real = "gstreamer"
6009 - if real in repo:
6010 - return real
6011 - if name.startswith("pkgconfig(gst-"):
6012 - real = "gst-plugins-base"
6013 - if real in repo:
6014 - return real
6015 - # Dynamiczne provides z repo.json (sekcja provides: w PAGBUILD.yaml)
6016 - # Determinizm: przy wielu dostawcach wybieramy posortowanego pierwszego
6017 - # (i ostrzegamy raz), zamiast zależeć od kolejności w repo.json.
6018 - _idx = _provides_index(repo)
6019 - if name in _idx:
6020 - return min(_idx[name])
6021 - # provides ZAINSTALOWANYCH pakietów – lokalnie zbudowane (pagbuild, poza
6022 - # repo) też dostarczają wirtualne zależności i muszą być rozpoznawane.
6023 - if installed:
6024 - _inst_cands = [pn for pn, meta in installed.items()
6025 - if isinstance(meta, dict) and name in (meta.get("provides") or [])]
6026 - if _inst_cands:
6027 - return min(_inst_cands)
6028 - clean = name
6029 - if name.startswith("pkgconfig(") and ")" in name:
6030 - clean = name.split("(", 1)[1].rstrip(")")
6031 - elif name.startswith("pkgconfig32(") and ")" in name:
6032 - clean = name.split("(", 1)[1].rstrip(")")
6033 - if clean != name and clean in repo:
6034 - return clean
6035 - return name
6036 -
6037 -
6038 -def cmd_why(pkg_name: str):
6039 - """Pokazuje dlaczego pakiet jest zainstalowany."""
6040 - installed = load_json(INSTALLED_DB)
6041 - world = load_world()
6042 - if pkg_name not in installed:
6043 - print(f" {pkg_name}: {_('why_not_installed')}"); return 1
6044 - if pkg_name in world:
6045 - print(f" {pkg_name}-{installed[pkg_name]['version']}: {_('why_explicit')}")
6046 - return 0
6047 - parents = set()
6048 - for w in world:
6049 - _find_dep_path(w, pkg_name, installed, set(), [], parents)
6050 - if parents:
6051 - for pp in sorted(parents):
6052 - print(f" {pkg_name}: {_('why_dependency')} {' → '.join(pp)}")
6053 - else:
6054 - print(f" {pkg_name}: {_('why_dependency')} (unknown/orphan)")
6055 - return 0
6056 -
6057 -
6058 -def _find_dep_path(cur, target, installed, visited, path, results):
6059 - if cur in visited: return
6060 - visited.add(cur); path.append(cur)
6061 - if cur == target:
6062 - results.add(tuple(path))
6063 - else:
6064 - for dep in installed.get(cur, {}).get("dependencies", []):
6065 - _find_dep_path(dep, target, installed, visited, path, results)
6066 - path.pop(); visited.discard(cur)
6067 -
6068 -
6069 -def cmd_rdepends(pkg_name: str):
6070 - """Pokazuje które pakiety zależą od danego pakietu (reverse dependencies).
6071 -
6072 - Odwrotność `pag why`: dla każdego zainstalowanego pakietu sprawdza, czy
6073 - któraś z jego zależności (także wirtualna, przez provides) wskazuje na
6074 - pkg_name. Przydatne przed `pag remove` – pokazuje, co przestanie działać.
6075 - """
6076 - installed = load_json(INSTALLED_DB)
6077 - if pkg_name not in installed:
6078 - print(f" {pkg_name}: {_('why_not_installed')}"); return 1
6079 - world = load_world()
6080 - # Nazwy, które zależą od pkg_name – sama nazwa plus jej wirtualne provides.
6081 - provided = {pkg_name} | set(installed[pkg_name].get("provides") or [])
6082 - rev = []
6083 - for name, meta in installed.items():
6084 - if name == pkg_name:
6085 - continue
6086 - for dep in (meta.get("dependencies") or []):
6087 - if dep in provided or _resolve_provides(dep, {}, installed) == pkg_name:
6088 - rev.append(name); break
6089 - if not rev:
6090 - print(f" {pkg_name}: {_('rdepends_none')}")
6091 - return 0
6092 - print(f"🔗 {_('rdepends_title', pkg_name, len(rev))}")
6093 - for n in sorted(rev):
6094 - kind = _("why_explicit") if n in world else _("why_dependency")
6095 - print(f" {n}-{installed[n].get('version', '?')} ({kind})")
6096 - return 0
6097 -
6098 -
6099 -def cmd_autoremove():
6100 - """Automatycznie usuwa osierocone zależności bez pytania."""
6101 - installed = load_json(INSTALLED_DB)
6102 - world = load_world()
6103 - orphans = _find_orphans(installed, world)
6104 - if not orphans: print(f"✅ {_('autoremove_none')}"); return 0
6105 - print(f"🗑 {_('orphans_found', len(orphans), ', '.join(sorted(orphans)[:10]))}")
6106 - return cmd_remove(list(orphans))
6107 -
6108 -
6109 -def cmd_download(package_names):
6110 - """Pobiera pakiety do cache bez instalowania."""
6111 - ensure_dirs()
6112 - repo = fetch_all_packages()
6113 - if not repo: print(f"❌ {_('no_index')}"); return 1
6114 - total_size = 0; downloaded = []
6115 - for name in package_names:
6116 - pkg = repo.get(name)
6117 - if not pkg:
6118 - print(f" ❌ {name}: {_('not_found')}"); continue
6119 - print(f" ↓ {name}-{pkg.version} ...", end=" ", flush=True)
6120 - path = _download_pkg(pkg)
6121 - if path:
6122 - total_size += os.path.getsize(path)
6123 - downloaded.append(name)
6124 - print(_c("green", "✓"))
6125 - else:
6126 - print(_c("red", "✗"))
6127 - if downloaded:
6128 - print(f"\n✅ {_('downloaded', len(downloaded), total_size/1048576)}")
6129 - return 0 if len(downloaded) == len(package_names) else 1
6130 -
6131 -
6132 -def cmd_stats():
6133 - """Wyświetla statystyki PAG."""
6134 - installed = load_json(INSTALLED_DB)
6135 - history = load_json(HISTORY_FILE) if os.path.exists(HISTORY_FILE) else []
6136 - total_size = sum(i.get("size_bytes", 0) for i in installed.values())
6137 - total_files = _db_count_files()
6138 - cache_size = sum(
6139 - os.path.getsize(os.path.join(PAG_CACHE, f))
6140 - for f in os.listdir(PAG_CACHE)
6141 - if os.path.isfile(os.path.join(PAG_CACHE, f))
6142 - ) if os.path.isdir(PAG_CACHE) else 0
6143 - last_update = _("never")
6144 - for e in reversed(history):
6145 - if e.get("action") in ("install", "upgrade") and e.get("success"):
6146 - last_update = e.get("timestamp", "?")[:19]; break
6147 - print(f"\n {_c('bold', _('stats_title'))}")
6148 - print(f" {'─' * 40}")
6149 - print(f" {_('stats_packages'):<30} {len(installed)}")
6150 - print(f" {_('stats_files'):<30} {total_files}")
6151 - print(f" {_('stats_size'):<30} {total_size/1048576:.1f} MB")
6152 - print(f" {_('stats_cache'):<30} {cache_size/1048576:.1f} MB")
6153 - print(f" {_('stats_history'):<30} {len(history)}")
6154 - print(f" {_('stats_last_update'):<30} {last_update}")
6155 - _bs = _base_summary(repo={}) # bez sieci – tylko stan zarządzania bazą
6156 - if _bs["total"]:
6157 - _bt = f"{_bs['tracked']}/{_bs['total']}"
6158 - if _bs["tracked"] < _bs["total"]:
6159 - _bt += " (sudo pag base adopt)"
6160 - print(f" {_('stats_base'):<30} {_bt}")
6161 - by_size = sorted(installed.items(), key=lambda x: x[1].get("size_bytes", 0), reverse=True)[:5]
6162 - if by_size:
6163 - print(f"\n {_c('dim', _('stats_top'))}")
6164 - for n, i in by_size:
6165 - print(f" {n}-{i['version']} {i.get('size_bytes',0)/1048576:.1f} MB")
6166 - return 0
6167 -
6168 -
6169 -def cmd_repo_add(url, name=None):
6170 - if not url.startswith("https://") and not os.environ.get("PAG_INSECURE"):
6171 - print(f" {_('sec_https')}"); return 1
6172 - ensure_dirs()
6173 - url = url.rstrip("/")
6174 - repos = get_repos()
6175 - if url in repos: print(f"⚠ {_('repo_exists', url)}"); return
6176 - if name:
6177 - # Drop-in: /etc/pag/repos/<nazwa>.conf (jak `echo url > .../stable.conf`)
6178 - os.makedirs(REPOS_DIR, exist_ok=True)
6179 - target = os.path.join(REPOS_DIR, name.rstrip("/").replace("/", "_") + ".conf")
6180 - with open(target, "w") as f: f.write(f"{url}\n")
6181 - print(f"✅ {_('repo_added', url)} → {target}")
6182 - return
6183 - with open(REPOS_CONF, "a") as f: f.write(f"{url}\n")
6184 - print(f"✅ {_('repo_added', url)}")
6185 -
6186 -def cmd_repo_list():
6187 - for i, url in enumerate(get_repos(), 1): print(f" {i}. {url}")
6188 -
6189 -FLATPAK_REMOTE_URL = "https://flathub.org/repo/flathub.flatpakrepo"
6190 -
6191 -def _check_flatpak(quiet: bool = False):
6192 - if not shutil.which("flatpak"):
6193 - if not quiet:
6194 - print(f"❌ {_('flatpak_missing')}")
6195 - return False
6196 - r = subprocess.run(["flatpak", "remotes"], capture_output=True, text=True)
6197 - if "flathub" not in r.stdout:
6198 - print(f"⚠ {_('flatpak_adding')}")
6199 - # Jako root dodajemy remote systemowy; bez roota – w instalacji użytkownika,
6200 - # żeby remote i miejsce instalacji były spójne (patrz _flatpak_do_install).
6201 - add = ["flatpak", "remote-add", "--if-not-exists"]
6202 - if os.geteuid() != 0:
6203 - add.append("--user")
6204 - subprocess.run(add + ["flathub", FLATPAK_REMOTE_URL], check=False)
6205 - return True
6206 -
6207 -def _spinner(msg: str):
6208 - """Prosty spinner „myślenia” w osobnym wątku. Zwraca funkcję stop()."""
6209 - stop = threading.Event()
6210 - def _spin():
6211 - for c in itertools.cycle("|/-\\"):
6212 - if stop.is_set():
6213 - break
6214 - sys.stdout.write(f"\r {msg} {c}")
6215 - sys.stdout.flush()
6216 - time.sleep(0.1)
6217 - t = threading.Thread(target=_spin, daemon=True)
6218 - t.start()
6219 - def _stop():
6220 - stop.set()
6221 - t.join(timeout=0.3)
6222 - sys.stdout.write("\r" + " " * (len(msg) + 4) + "\r")
6223 - sys.stdout.flush()
6224 - return _stop
6225 -
6226 -
6227 -def _flatpak_search_raw(query: str) -> List[dict]:
6228 - """Szuka we Flathub i zwraca listę wyników jako słowniki."""
6229 - if not _check_flatpak():
6230 - return []
6231 - stop = _spinner(_("flatpak_searching_any"))
6232 - try:
6233 - try:
6234 - r = subprocess.run(
6235 - ["flatpak", "search", "--columns=name,description,application,version,branch,remotes", query],
6236 - capture_output=True, text=True, timeout=120
6237 - )
6238 - finally:
6239 - stop()
6240 - if r.returncode != 0 and "No matches found" not in r.stdout and not r.stdout.strip():
6241 - print(f" ⚠ flatpak search: {r.stderr.strip()[:150]}")
6242 - results = []
6243 - for line in r.stdout.strip().split("\n"):
6244 - parts = line.split("\t")
6245 - if len(parts) >= 3:
6246 - results.append({
6247 - "name": parts[0].strip(),
6248 - "description": parts[1].strip() if len(parts) > 1 else "",
6249 - "app_id": parts[2].strip() if len(parts) > 2 else "",
6250 - "version": parts[3].strip() if len(parts) > 3 else "",
6251 - "branch": parts[4].strip() if len(parts) > 4 else "stable",
6252 - "origin": parts[5].strip() if len(parts) > 5 else "flathub",
6253 - })
6254 - return results
6255 - except Exception as e:
6256 - print(_(' ⚠ Search error: {arg1}', arg1=(e)), file=sys.stderr)
6257 - return []
6258 -
6259 -def _flatpak_find_best(query: str) -> Optional[dict]:
6260 - """
6261 - Szuka we Flathub i próbuje znaleźć najlepsze dopasowanie.
6262 - - Jeśli query dokładnie pasuje do app_id → zwraca od razu
6263 - - Jeśli query pasuje do nazwy → zwraca pierwsze
6264 - - Jeśli wiele wyników → wyświetla listę i pyta użytkownika
6265 - - Jeśli brak → zwraca None
6266 - """
6267 - results = _flatpak_search_raw(query)
6268 - if not results:
6269 - return None
6270 -
6271 - # Dokładne dopasowanie app_id
6272 - exact = [r for r in results if r["app_id"].lower() == query.lower()]
6273 - if exact:
6274 - return exact[0]
6275 -
6276 - # Dokładne dopasowanie nazwy
6277 - exact_name = [r for r in results if r["name"].lower() == query.lower()]
6278 - if exact_name:
6279 - return exact_name[0]
6280 -
6281 - # Jednoznaczne dopasowanie (tylko 1 wynik)
6282 - if len(results) == 1:
6283 - return results[0]
6284 -
6285 - # Wiele wyników – pokaż użytkownikowi
6286 - print(f"\n {_('flatpak_found', len(results))}")
6287 - for i, r in enumerate(results):
6288 - print(f" {i+1}. {_c('bold', r['name'])} ({r['app_id']})")
6289 - if r["version"]:
6290 - print(f" {_('flatpak_info_version')}: {r['version']}")
6291 - if r["description"]:
6292 - desc = r["description"][:80] + ("..." if len(r["description"]) > 80 else "")
6293 - print(f" {desc}")
6294 -
6295 - try:
6296 - choice = input(_('\n Choose a number (1-{arg1}) or press Enter to cancel:', arg1=(len(results)))).strip()
6297 - if not choice:
6298 - return None
6299 - idx = int(choice) - 1
6300 - if 0 <= idx < len(results):
6301 - return results[idx]
6302 - except (EOFError, ValueError, IndexError):
6303 - pass
6304 - return None
6305 -
6306 -def _flatpak_get_installed_info(app_id: str) -> Optional[dict]:
6307 - """Zwraca info o zainstalowanym flatpaku lub None."""
6308 - try:
6309 - r = subprocess.run(
6310 - ["flatpak", "info", "--columns=name,version,branch,origin,installed-size,description", app_id],
6311 - capture_output=True, text=True, timeout=10
6312 - )
6313 - if r.returncode != 0:
6314 - return None
6315 - parts = r.stdout.strip().split("\t")
6316 - if len(parts) < 3:
6317 - return None
6318 - return {
6319 - "name": parts[0].strip(),
6320 - "version": parts[1].strip() if len(parts) > 1 else "",
6321 - "branch": parts[2].strip() if len(parts) > 2 else "",
6322 - "origin": parts[3].strip() if len(parts) > 3 else "",
6323 - "size": parts[4].strip() if len(parts) > 4 else "",
6324 - "description": parts[5].strip() if len(parts) > 5 else "",
6325 - }
6326 - except Exception:
6327 - return None
6328 -
6329 -def _flatpak_is_installed(app_id: str) -> bool:
6330 - """Sprawdza czy flatpak o danym ID jest zainstalowany."""
6331 - try:
6332 - r = subprocess.run(
6333 - ["flatpak", "info", app_id],
6334 - capture_output=True, text=True, timeout=10
6335 - )
6336 - return r.returncode == 0
6337 - except Exception:
6338 - return False
6339 -
6340 -# =============================================================================
6341 -# FLATPAK – KOMENDY GŁÓWNE (zunifikowany interfejs)
6342 -# =============================================================================
6343 -# pag flatpak <query> → szuka i proponuje instalację (jeśli nie zainstalowany)
6344 -# pag flatpak search <query> → tylko szuka
6345 -# pag flatpak install <query> → instaluje
6346 -# pag flatpak remove <id> → usuwa
6347 -# pag flatpak list → lista zainstalowanych
6348 -# pag flatpak update → aktualizuje wszystkie
6349 -# pag flatpak info <id> → szczegóły flatpaka
6350 -
6351 -def cmd_flatpak(args: list):
6352 - """
6353 - Główna komenda flatpak – inteligentnie rozpoznaje intencję:
6354 - pag flatpak firefox → szuka i instaluje (jeśli nieznaleziony → szuka)
6355 - pag flatpak search firefox → tylko wyszukiwanie
6356 - pag flatpak install ... → bezpośrednia instalacja
6357 - pag flatpak remove ... → odinstalowanie
6358 - pag flatpak list → lista
6359 - pag flatpak update → aktualizacja
6360 - pag flatpak info ... → szczegóły
6361 - """
6362 - if not _check_flatpak():
6363 - return 1
6364 -
6365 - if not args:
6366 - # Bez argumentów – domyślnie lista
6367 - return cmd_flatpak_list()
6368 -
6369 - subcmd = args[0].lower()
6370 - rest = args[1:]
6371 -
6372 - # ── Podkomendy jawne ────────────────────────────────────────────────
6373 - if subcmd == "search":
6374 - if not rest:
6375 - print(_("flatpak_usage")); return 1
6376 - return cmd_flatpak_search(" ".join(rest))
6377 -
6378 - elif subcmd == "install":
6379 - if not rest:
6380 - print(_("flatpak_usage")); return 1
6381 - return _flatpak_smart_install(rest)
6382 -
6383 - elif subcmd == "remove" or subcmd == "uninstall":
6384 - if not rest:
6385 - print(_("flatpak_usage")); return 1
6386 - return _flatpak_smart_remove(rest)
6387 -
6388 - elif subcmd == "list":
6389 - return cmd_flatpak_list()
6390 -
6391 - elif subcmd == "update":
6392 - return cmd_flatpak_update()
6393 -
6394 - elif subcmd == "info":
6395 - if not rest:
6396 - print(_("flatpak_usage")); return 1
6397 - return cmd_flatpak_info(rest[0])
6398 -
6399 - else:
6400 - # ── Inteligentne wykrywanie: pag flatpak <nazwa> ────────────────
6401 - # Sprawdź czy to zainstalowany flatpak → pokaż info
6402 - # Jeśli nie → szukaj i zaproponuj instalację
6403 - query = " ".join(args)
6404 -
6405 - # Najpierw sprawdź czy już zainstalowany
6406 - if _flatpak_is_installed(query):
6407 - print(_(" 📦 {arg1} – already installed (use 'pag flatpak info {arg2}' for details)", arg1=(_c('green', query)), arg2=(query)))
6408 - return cmd_flatpak_info(query)
6409 -
6410 - # Szukaj we Flathub
6411 - print(f" {_('flatpak_searching', query)}")
6412 - best = _flatpak_find_best(query)
6413 - if not best:
6414 - print(f" ❌ '{query}' – {_('flatpak_not_found')}")
6415 - return 1
6416 -
6417 - print(f"\n {_c('cyan', best['name'])} ({best['app_id']})")
6418 - if best["version"]:
6419 - print(f" {_('flatpak_info_version')}: {best['version']}")
6420 - if best["description"]:
6421 - print(f" {best['description']}")
6422 -
6423 - try:
6424 - ans = input(f"\n {_('flatpak_install_prompt', best['name'])}").strip().lower()
6425 - except (EOFError, KeyboardInterrupt):
6426 - print(f"\n ⚠ {_('no_tty')}")
6427 - return 0
6428 - if ans and ans not in ("t", "y"):
6429 - print(_("cancelled"))
6430 - return 0
6431 -
6432 - return _flatpak_do_install(best["app_id"])
6433 -
6434 -def _flatpak_smart_install(names: list) -> int:
6435 - """Instaluje flatpaki – obsługuje nazwy częściowe (wyszukuje przed instalacją)."""
6436 - failed = 0
6437 - for name in names:
6438 - if "." in name and "/" not in name:
6439 - # Wygląda na pełne app_id (np. org.mozilla.firefox)
6440 - app_id = name
6441 - else:
6442 - # Szukaj najlepszego dopasowania
6443 - best = _flatpak_find_best(name)
6444 - if not best:
6445 - print(f" ❌ '{name}' – {_('flatpak_not_found')}")
6446 - failed += 1
6447 - continue
6448 - app_id = best["app_id"]
6449 - print(f" → {best['name']} ({app_id})")
6450 -
6451 - if _flatpak_do_install(app_id) != 0:
6452 - failed += 1
6453 - return 1 if failed else 0
6454 -
6455 -def _flatpak_export_dirs() -> List[str]:
6456 - """Katalogi eksportów Flatpaka (system + użytkownika) obecne na dysku.
6457 -
6458 - Instalacja użytkownika roota (/root/.local/share/flatpak) jest świadomie
6459 - POMIJANA – to wewnętrzny artefakt roota, którego sesja użytkownika nigdy
6460 - nie zobaczy (patrz _flatpak_do_install)."""
6461 - dirs = ["/var/lib/flatpak/exports"]
6462 - home = os.path.expanduser("~")
6463 - if home and home not in ("/root", "/"):
6464 - dirs.append(os.path.join(home, ".local", "share", "flatpak", "exports"))
6465 - return [d for d in dirs if os.path.isdir(d)]
6466 -
6467 -
6468 -def _flatpak_refresh_caches() -> None:
6469 - """Odświeża cache pulpitu i ikon po zmianie w Flatpaku (best-effort).
6470 -
6471 - Flatpak robi to sam, ale tylko gdy `update-desktop-database` jest w PATH.
6472 - Bez tego nowo zainstalowana aplikacja bywa nieobecna w menu."""
6473 - for exports in _flatpak_export_dirs():
6474 - apps = os.path.join(exports, "share", "applications")
6475 - if os.path.isdir(apps) and shutil.which("update-desktop-database"):
6476 - subprocess.run(["update-desktop-database", apps],
6477 - capture_output=True, check=False, timeout=60)
6478 - icons = os.path.join(exports, "share", "icons", "hicolor")
6479 - if os.path.isdir(icons) and shutil.which("gtk-update-icon-cache"):
6480 - subprocess.run(["gtk-update-icon-cache", "-q", "-t", "-f", icons],
6481 - capture_output=True, check=False, timeout=120)
6482 -
6483 -
6484 -def _flatpak_session_sees_exports() -> bool:
6485 - """Czy bieżąca sesja ma eksporty Flatpaka w XDG_DATA_DIRS."""
6486 - raw = os.environ.get("XDG_DATA_DIRS", "")
6487 - dirs = {d for d in raw.split(":") if d} or {"/usr/local/share", "/usr/share"}
6488 - return any(os.path.join(e, "share") in dirs for e in _flatpak_export_dirs())
6489 -
6490 -
6491 -def _flatpak_warn_if_invisible() -> None:
6492 - """Ostrzega, gdy sesja nie widzi eksportów – inaczej wygląda to jak
6493 - „zainstalowało się, ale nie ma go w menu / na PC”."""
6494 - if not _flatpak_session_sees_exports():
6495 - print(f" ⚠ {_('flatpak_menu_hint')}")
6496 - print(f" {_('flatpak_menu_fix')}")
6497 -
6498 -
6499 -def _flatpak_do_install(app_id: str) -> int:
6500 - """Wykonuje właściwą instalację flatpaka.
6501 -
6502 - Jako root wymuszamy instalację SYSTEMOWĄ (--system). Bez tego `flatpak`
6503 - uruchomiony jako root potrafi zainstalować aplikację w instalacji
6504 - użytkownika roota (/root/.local/share/flatpak) – widocznej dla roota, ale
6505 - nie dla zalogowanego użytkownika. To dokładnie efekt „instaluje, ale nie
6506 - mam tego na PC”. Bez roota próbujemy instalacji systemowej (polkit),
6507 - a w razie niepowodzenia cofamy się do instalacji użytkownika (--user).
6508 -
6509 - Zakres (scope) ma znaczenie: instalacja SYSTEMOWA (--system) jest widoczna
6510 - dla wszystkich użytkowników, a --user tylko dla bieżącego (dla roota:
6511 - /root/.local/... → niewidoczna dla sesji). `flatpak list` bez flag pokazuje
6512 - oba zakresy, więc systemowa instalacja roota jest widoczna też dla
6513 - zwykłego użytkownika."""
6514 - print(f" {_('flatpak_installing', app_id)}")
6515 - if os.geteuid() == 0:
6516 - result = subprocess.run(
6517 - ["flatpak", "install", "-y", "--system", "flathub", app_id],
6518 - check=False, timeout=600)
6519 - else:
6520 - result = subprocess.run(
6521 - ["flatpak", "install", "-y", "flathub", app_id],
6522 - check=False, timeout=600)
6523 - if result.returncode != 0:
6524 - # Flathub tylko dla użytkownika / brak agenta polkit – instalacja
6525 - # lokalna użytkownika jest lepsza niż twardy błąd.
6526 - subprocess.run(
6527 - ["flatpak", "remote-add", "--if-not-exists", "--user",
6528 - "flathub", FLATPAK_REMOTE_URL], check=False, timeout=60)
6529 - result = subprocess.run(
6530 - ["flatpak", "install", "-y", "--user", "flathub", app_id],
6531 - check=False, timeout=600)
6532 - if result.returncode != 0:
6533 - print(f" ❌ {_('download_fail')}: {app_id}")
6534 - return 1
6535 - _flatpak_refresh_caches()
6536 - print(f" ✅ {_('flatpak_installed', app_id)}")
6537 - _flatpak_warn_if_invisible()
6538 - return 0
6539 -
6540 -def _flatpak_smart_remove(names: list) -> int:
6541 - """Usuwa flatpaki – obsługuje nazwy częściowe."""
6542 - # Pobierz listę zainstalowanych
6543 - try:
6544 - r = subprocess.run(
6545 - ["flatpak", "list", "--columns=application,name"],
6546 - capture_output=True, text=True, timeout=10
6547 - )
6548 - installed = {}
6549 - for line in r.stdout.strip().split("\n"):
6550 - parts = line.split("\t")
6551 - if len(parts) >= 2:
6552 - installed[parts[0].strip()] = parts[1].strip()
6553 - except Exception:
6554 - installed = {}
6555 -
6556 - failed = 0
6557 - for name in names:
6558 - app_id = name
6559 -
6560 - # Jeśli nie podano pełnego ID – spróbuj dopasować
6561 - if name not in installed:
6562 - matches = {aid: aname for aid, aname in installed.items()
6563 - if name.lower() in aid.lower() or name.lower() in aname.lower()}
6564 - if len(matches) == 0:
6565 - print(f" ❌ '{name}' – {_('flatpak_not_installed', name)}")
6566 - failed += 1
6567 - continue
6568 - elif len(matches) == 1:
6569 - app_id = list(matches.keys())[0]
6570 - print(f" → {matches[app_id]} ({app_id})")
6571 - else:
6572 - print(_("\n Multiple matches for '{arg1}':", arg1=(name)))
6573 - for i, (aid, aname) in enumerate(sorted(matches.items()), 1):
6574 - print(f" {i}. {aname} ({aid})")
6575 - try:
6576 - choice = input(_('\n Choose a number (1-{arg1}) or press Enter:', arg1=(len(matches)))).strip()
6577 - if not choice:
6578 - failed += 1
6579 - continue
6580 - aid_list = sorted(matches.keys())
6581 - app_id = aid_list[int(choice) - 1]
6582 - except (EOFError, ValueError, IndexError):
6583 - failed += 1
6584 - continue
6585 -
6586 - print(f" 🗑 {app_id} ...", end=" ", flush=True)
6587 - result = subprocess.run(
6588 - ["flatpak", "uninstall", "-y", app_id],
6589 - capture_output=True, text=True, timeout=120
6590 - )
6591 - if result.returncode == 0:
6592 - print("✅")
6593 - print(f" {_('flatpak_removed', app_id)}")
6594 - else:
6595 - print("❌")
6596 - failed += 1
6597 - if not failed:
6598 - _flatpak_refresh_caches()
6599 - return 1 if failed else 0
6600 -
6601 -def cmd_flatpak_search(q: str):
6602 - """Wyszukuje we Flathub i wyświetla wyniki (z możliwością wyboru do instalacji)."""
6603 - if not _check_flatpak():
6604 - return 1
6605 - results = _flatpak_search_raw(q)
6606 - if not results:
6607 - print(f" ❌ '{q}' – {_('flatpak_not_found')}")
6608 - return 1
6609 - print(f"\n {_('flatpak_found', len(results))}")
6610 - shown = results[:30] # max 30 wyników
6611 - for i, r in enumerate(shown, 1):
6612 - installed = "📦 " if _flatpak_is_installed(r["app_id"]) else " "
6613 - print(f" {i:>2}. {installed}{_c('bold', r['name'])} ({r['app_id']})")
6614 - if r["version"]:
6615 - print(f" {_('flatpak_info_version')}: {r['version']} | {_('flatpak_info_branch')}: {r['branch']}")
6616 - if r["description"]:
6617 - desc = r["description"][:100] + ("..." if len(r["description"]) > 100 else "")
6618 - print(f" {_c('dim', desc)}")
6619 - if len(results) > 30:
6620 - print(_(' ... and {arg1} more. Refine your query.', arg1=(len(results) - 30)))
6621 -
6622 - # Interaktywny wybór – wpisz numer, aby zainstalować (Enter = anuluj)
6623 - try:
6624 - ans = input(_('\n Choose a number to install (1-{arg1}) or press Enter to cancel:', arg1=(len(shown)))).strip()
6625 - except (EOFError, KeyboardInterrupt):
6626 - return 0
6627 - if ans:
6628 - try:
6629 - idx = int(ans) - 1
6630 - if 0 <= idx < len(shown):
6631 - return _flatpak_do_install(shown[idx]["app_id"])
6632 - print(_("cancelled"))
6633 - except (ValueError, IndexError):
6634 - print(_("cancelled"))
6635 - return 0
6636 -
6637 -def cmd_flatpak_list():
6638 - """Wyświetla zainstalowane flatpaki."""
6639 - if not _check_flatpak():
6640 - return 1
6641 - r = subprocess.run(
6642 - ["flatpak", "list", "--columns=application,name,version,origin,installation,installed-size"],
6643 - capture_output=True, text=True, timeout=10
6644 - )
6645 - lines = [l for l in r.stdout.strip().split("\n") if l.strip()]
6646 - if not lines:
6647 - print(_(' (no installed flatpaks)'))
6648 - return 0
6649 - print(_('Installed flatpaks ({arg1}):', arg1=(len(lines))))
6650 - for line in lines:
6651 - parts = line.split("\t")
6652 - if len(parts) >= 3:
6653 - app_id, name, version = parts[0], parts[1], parts[2]
6654 - scope = parts[4] if len(parts) > 4 else ""
6655 - size = parts[5] if len(parts) > 5 else ""
6656 - size_str = f" ({size})" if size else ""
6657 - scope_str = f" [{scope}]" if scope else ""
6658 - print(f" 📦 {_c('bold', name)} {version}{scope_str}{size_str}")
6659 - print(f" {_c('dim', app_id)}")
6660 - return 0
6661 -
6662 -def cmd_flatpak_update():
6663 - """Aktualizuje wszystkie flatpaki."""
6664 - if not _check_flatpak():
6665 - return 1
6666 - print(_(' 🔄 Updating flatpaks...'))
6667 - result = subprocess.run(["flatpak", "update", "-y"], check=False, timeout=600)
6668 - if result.returncode == 0:
6669 - _flatpak_refresh_caches()
6670 - print(f" ✅ {_('flatpak_updated')}")
6671 - return result.returncode
6672 -
6673 -def cmd_flatpak_info(app_id: str):
6674 - """Wyświetla szczegóły flatpaka (zainstalowanego lub z Flathub)."""
6675 - if not _check_flatpak():
6676 - return 1
6677 -
6678 - # Najpierw sprawdź zainstalowany
6679 - info = _flatpak_get_installed_info(app_id)
6680 - if info:
6681 - print(f"\n 📦 {_c('bold', info['name'])} {_c('green', '[zainstalowany]')}")
6682 - print(f" {'─' * 45}")
6683 - print(f" {_('flatpak_info_id'):<16} {app_id}")
6684 - print(f" {_('flatpak_info_version'):<16} {info['version']}")
6685 - print(f" {_('flatpak_info_branch'):<16} {info['branch']}")
6686 - print(f" {_('flatpak_info_origin'):<16} {info['origin']}")
6687 - if info["size"]:
6688 - print(f" {_('flatpak_info_size'):<16} {info['size']}")
6689 - if info["description"]:
6690 - print(f" {_('flatpak_info_desc'):<16} {info['description']}")
6691 - return 0
6692 -
6693 - # Szukaj we Flathub
6694 - results = _flatpak_search_raw(app_id)
6695 - exact = [r for r in results if r["app_id"].lower() == app_id.lower()]
6696 - if not exact:
6697 - # Spróbuj częściowego dopasowania
6698 - if results:
6699 - exact = [results[0]]
6700 - else:
6701 - print(f" ❌ '{app_id}' – {_('flatpak_not_found')}")
6702 - return 1
6703 -
6704 - r = exact[0]
6705 - print(f"\n 📦 {_c('bold', r['name'])} (Flathub)")
6706 - print(f" {'─' * 45}")
6707 - print(f" {_('flatpak_info_id'):<16} {r['app_id']}")
6708 - print(f" {_('flatpak_info_version'):<16} {r['version']}")
6709 - if r["description"]:
6710 - print(f" {_('flatpak_info_desc'):<16} {r['description']}")
6711 - print(_('\n 💡 To install: pag flatpak install {arg1}', arg1=(r['app_id'])))
6712 - return 0
6713 -
6714 -# =============================================================================
6715 -# IMMUTABLE OS – KOMENDY DEPLOYMENTOWE
6716 -# =============================================================================
6717 -
6718 -# Pakiety jądra – po ich instalacji trzeba przebudować initramfs
6719 -KERNEL_PACKAGE_PATTERNS = ["linux", "kernel", "linux-kernel", "linux-lts"]
6720 -
6721 -# Pakiety, po których initramfs MUSI zostać przebudowany: jądra oraz moduły
6722 -# out-of-tree (NVIDIA/VirtualBox). `pag` robi to raz, po całej transakcji.
6723 -INITRAMFS_PACKAGE_PATTERNS = tuple(KERNEL_PACKAGE_PATTERNS) + (
6724 - "nvidia-dkms", "nvidia-kernel",
6725 - "vboxhost-kernel", "virtualbox-host-modules", "virtualbox-guest-modules",
6726 -)
6727 -
6728 -def _is_kernel_package(name: str) -> bool:
6729 - """Sprawdza czy pakiet to jądro (wymaga przebudowy initramfs)."""
6730 - name_lower = name.lower()
6731 - return any(pattern in name_lower for pattern in KERNEL_PACKAGE_PATTERNS)
6732 -
6733 -
6734 -def _needs_initramfs_refresh(name: str) -> bool:
6735 - """Czy po tym pakiecie trzeba przebudować initramfs (jądro lub moduły)."""
6736 - name_lower = name.lower()
6737 - return any(pattern in name_lower
6738 - for pattern in INITRAMFS_PACKAGE_PATTERNS)
6739 -
6740 -# Towarzysze jądra – aktualizowani RAZEM z jądrem, jeśli są zainstalowani,
6741 -# żeby userspace i moduły jądra nie rozjechały się wersjami.
6742 -KERNEL_SIBLINGS = ("linux-headers", "nvidia-dkms", "nvidia-kernel", "dkms",
6743 - "virtualbox-host-modules", "virtualbox-guest-modules")
6744 -
6745 -
6746 -def _kernel_group_updates(pending):
6747 - """Gdy w transakcji jest jądro, dołóż jego towarzyszy (jeśli zainstalowani)."""
6748 - if not any(_is_kernel_package(n) for n in pending):
6749 - return pending
6750 - try:
6751 - installed = load_json(INSTALLED_DB)
6752 - repo = fetch_all_packages()
6753 - except Exception:
6754 - return pending
6755 - out = list(pending)
6756 - for sib in KERNEL_SIBLINGS:
6757 - if sib in installed and sib in repo and sib not in out:
6758 - out.append(sib)
6759 - return out
6760 -
6761 -
6762 -def _post_kernel_hooks():
6763 - """Po zmianie jądra na ZWYKŁEJ instalacji: DKMS → initramfs → GRUB.
6764 -
6765 - Kolejność ma znaczenie: najpierw moduły out-of-tree (DKMS) pod nowe jądro,
6766 - potem initramfs (żeby zawierał już przebudowane moduły), na końcu wpisy
6767 - GRUB. To JEDYNE miejsce, które buduje initramfs po transakcji – hooki
6768 - pakietów mogą pominąć własną przebudowę, gdy działają pod lockiem `pag`.
6769 - """
6770 - if shutil.which("dkms"):
6771 - try:
6772 - print(_(' 🔧 DKMS: rebuilding out-of-tree modules (nvidia/vbox)...'))
6773 - subprocess.run(["dkms", "autoinstall"],
6774 - capture_output=True, text=True, timeout=1800)
6775 - except Exception:
6776 - pass
6777 - try:
6778 - _rebuild_initramfs()
6779 - except Exception:
6780 - pass
6781 - _refresh_bootloader()
6782 -
6783 -def _rebuild_initramfs(deploy_dir: str = "") -> bool:
6784 - """
6785 - Przebudowuje initramfs dla aktywnego (lub podanego) deploymentu.
6786 - Używa skryptu pag-initramfs lub ręcznego cpio.
6787 - """
6788 - if deploy_dir:
6789 - root = deploy_dir
6790 - else:
6791 - root = _get_deployment_root()
6792 -
6793 - if root == PAG_ROOT:
6794 - # Zwykły system – NAJPIERW natywne narzędzie PaganOS (per-wersja +
6795 - # root=UUID/PARTUUID/LABEL), potem dracut/mkinitcpio.
6796 - if shutil.which("pagan-initramfs"):
6797 - print(_(' 🔧 Rebuilding initramfs (pagan-initramfs)...'))
6798 - try:
6799 - r = subprocess.run(["pagan-initramfs"], capture_output=True,
6800 - text=True, timeout=1800)
6801 - if r.returncode == 0:
6802 - return True
6803 - except Exception:
6804 - pass
6805 - # Zwykły system – użyj dracut jeśli dostępny
6806 - if shutil.which("dracut"):
6807 - print(_(' 🔧 Rebuilding initramfs (dracut)...'))
6808 - result = subprocess.run(
6809 - ["dracut", "--force", "/boot/initramfs.img"],
6810 - capture_output=True, text=True, timeout=600
6811 - )
6812 - return result.returncode == 0
6813 - elif shutil.which("mkinitcpio"):
6814 - print(_(' 🔧 Rebuilding initramfs (mkinitcpio)...'))
6815 - result = subprocess.run(
6816 - ["mkinitcpio", "-g", "/boot/initramfs.img"],
6817 - capture_output=True, text=True, timeout=600
6818 - )
6819 - return result.returncode == 0
6820 - else:
6821 - print(_(' ⚠ No dracut/mkinitcpio – initramfs was not rebuilt'))
6822 - return False
6823 -
6824 - # Tryb immutable – budujemy initramfs dla deploymentu
6825 - print(_(' 🔧 Building initramfs for the deployment...'))
6826 -
6827 - # Sprawdź czy mamy nasz skrypt init
6828 - pag_init_script = "/usr/share/pag/initramfs-init"
6829 - if not os.path.exists(pag_init_script):
6830 - # Szukaj w źródłach (developerski fallback)
6831 - alt_paths = [
6832 - os.path.join(os.path.dirname(os.path.abspath(__file__)), "scripts", "initramfs-init"),
6833 - "/usr/share/pag/init",
6834 - ]
6835 - for p in alt_paths:
6836 - if os.path.exists(p):
6837 - pag_init_script = p
6838 - break
6839 -
6840 - if not os.path.exists(pag_init_script):
6841 - print(_(' ⚠ pag-initramfs-init not found – skipping initramfs build'))
6842 - return False
6843 -
6844 - boot_dir = os.path.join(root, "boot")
6845 - os.makedirs(boot_dir, exist_ok=True)
6846 -
6847 - # Znajdź jądro (vmlinuz-*)
6848 - kernels = sorted(
6849 - [f for f in os.listdir(boot_dir) if f.startswith("vmlinuz-")],
6850 - reverse=True
6851 - ) if os.path.exists(boot_dir) else []
6852 - if not kernels:
6853 - print(_(" ⚠ No vmlinuz-* found in the deployment's /boot"))
6854 - return False
6855 -
6856 - kernel_ver = kernels[0].replace("vmlinuz-", "")
6857 - print(_(' 🐧 Kernel: {arg1}', arg1=(kernel_ver)))
6858 -
6859 - # Buduj initramfs ręcznie (cpio)
6860 - tmpdir = tempfile.mkdtemp(prefix="pag-initramfs-")
6861 - try:
6862 - # Podstawowa struktura
6863 - for d in ["bin", "sbin", "dev", "proc", "sys", "run", "new_root",
6864 - "usr/bin", "usr/sbin", "lib", "lib64", "etc"]:
6865 - os.makedirs(os.path.join(tmpdir, d), exist_ok=True)
6866 -
6867 - # Skopiuj init
6868 - shutil.copy2(pag_init_script, os.path.join(tmpdir, "init"))
6869 - os.chmod(os.path.join(tmpdir, "init"), 0o755)
6870 -
6871 - # Skopiuj niezbędne binaria (busybox lub podstawowe narzędzia)
6872 - busybox_paths = [
6873 - os.path.join(root, "usr/bin/busybox"),
6874 - os.path.join(root, "bin/busybox"),
6875 - "/usr/bin/busybox",
6876 - "/bin/busybox",
6877 - ]
6878 - busybox = None
6879 - for bp in busybox_paths:
6880 - if os.path.exists(bp):
6881 - busybox = bp
6882 - break
6883 -
6884 - if busybox:
6885 - shutil.copy2(busybox, os.path.join(tmpdir, "bin/busybox"))
6886 - # Utwórz symlinki dla podstawowych komend
6887 - for cmd in ["sh", "mount", "umount", "ls", "cat", "echo", "sleep",
6888 - "readlink", "mkdir", "switch_root", "cp", "rm"]:
6889 - link = os.path.join(tmpdir, "bin", cmd)
6890 - if not os.path.exists(link):
6891 - os.symlink("busybox", link)
6892 - # /bin/sh → busybox
6893 - if not os.path.exists(os.path.join(tmpdir, "bin/sh")):
6894 - os.symlink("busybox", os.path.join(tmpdir, "bin/sh"))
6895 - else:
6896 - # Bez busybox – kopiuj podstawowe narzędzia z deploymentu
6897 - for tool in ["bash", "mount", "umount", "readlink", "mkdir", "cat", "sleep", "cp", "rm"]:
6898 - src = os.path.join(root, "usr/bin", tool)
6899 - if not os.path.exists(src):
6900 - src = os.path.join(root, "bin", tool)
6901 - if os.path.exists(src):
6902 - dest = os.path.join(tmpdir, "bin", os.path.basename(tool))
6903 - shutil.copy2(src, dest)
6904 - # Kopiuj zależności .so
6905 - _copy_libs_for_binary(src, tmpdir, root)
6906 -
6907 - # Dodaj moduły jądra (opcjonalnie – dla sterowników dyskowych)
6908 - modules_src = os.path.join(root, "lib/modules", kernel_ver)
6909 - if os.path.isdir(modules_src):
6910 - modules_dst = os.path.join(tmpdir, "lib/modules", kernel_ver)
6911 - # Kopiuj tylko niezbędne (fs, block, drivers/ata, drivers/nvme)
6912 - for sub in ["kernel/fs", "kernel/drivers/ata", "kernel/drivers/nvme",
6913 - "kernel/drivers/scsi", "kernel/drivers/virtio",
6914 - "modules.order", "modules.builtin"]:
6915 - src_sub = os.path.join(modules_src, sub)
6916 - if os.path.exists(src_sub):
6917 - dst_sub = os.path.join(modules_dst, sub)
6918 - os.makedirs(os.path.dirname(dst_sub), exist_ok=True)
6919 - if os.path.isdir(src_sub):
6920 - try:
6921 - shutil.copytree(src_sub, dst_sub, dirs_exist_ok=True, symlinks=True,
6922 - ignore_dangling_symlinks=True)
6923 - except (FileNotFoundError, PermissionError):
6924 - print(_(' ⚠ Skipping unavailable files: {arg1}', arg1=(sub)))
6925 - else:
6926 - try:
6927 - shutil.copy2(src_sub, dst_sub)
6928 - except (FileNotFoundError, PermissionError):
6929 - print(_(' ⚠ Skipping unavailable file: {arg1}', arg1=(sub)))
6930 -
6931 - # Pakuj do initramfs.img
6932 - initramfs_path = os.path.join(boot_dir, "initramfs.img")
6933 - old_cwd = os.getcwd()
6934 - os.chdir(tmpdir)
6935 - try:
6936 - with open(initramfs_path + ".tmp", "wb") as out:
6937 - _run_cpio_pipeline(tmpdir, out)
6938 - os.rename(initramfs_path + ".tmp", initramfs_path)
6939 - finally:
6940 - os.chdir(old_cwd)
6941 -
6942 - size_mb = os.path.getsize(initramfs_path) / 1048576
6943 - print(_(' ✅ initramfs.img ({arg1:.1f} MB) → {arg2}', arg1=(size_mb), arg2=(initramfs_path)))
6944 - return True
6945 -
6946 - except Exception as e:
6947 - print(_(' ❌ initramfs build error: {arg1}', arg1=(e)))
6948 - return False
6949 - finally:
6950 - shutil.rmtree(tmpdir, ignore_errors=True)
6951 -
6952 -
6953 -def _run_cpio_pipeline(tmpdir: str, out):
6954 - """find . -print0 | cpio --null -oH newc | gzip — bez shell=True.
6955 -
6956 - Buduje pipeline przez subprocess.Popen, unikając pośrednika powłoki
6957 - (brak ryzyka injection i niepotrzebnego procesu sh). Wykonuje się w cwd=tmpdir.
6958 - Separatory NUL (\0): plik/katalog ze znakiem nowej linii w nazwie nie
6959 - rozjeżdża cpio (inaczej uszkodzone archiwum → kernel panic przy rozruchu).
6960 - """
6961 - find = subprocess.Popen(["find", ".", "-print0"], cwd=tmpdir, stdout=subprocess.PIPE)
6962 - cpio = subprocess.Popen(["cpio", "--null", "-oH", "newc"], cwd=tmpdir,
6963 - stdin=find.stdout, stdout=subprocess.PIPE)
6964 - find.stdout.close() # zwolnij uchwyt – cpio dostanie SIGPIPE po zakończeniu find
6965 - gzip = subprocess.Popen(["gzip"], stdin=cpio.stdout, stdout=out)
6966 - cpio.stdout.close()
6967 - try:
6968 - gzip.wait(timeout=120)
6969 - if gzip.returncode != 0:
6970 - raise subprocess.CalledProcessError(gzip.returncode, ["gzip"])
6971 - cpio.wait(timeout=30)
6972 - find.wait(timeout=30)
6973 - except subprocess.TimeoutExpired:
6974 - for p in (gzip, cpio, find):
6975 - p.kill()
6976 - raise
6977 - finally:
6978 - for p in (find, cpio, gzip):
6979 - if p.poll() is None:
6980 - p.kill()
6981 - # Skontroluj też kody procesów pośrednich (cpio/find mogą zawieść, a gzip zwrócić 0)
6982 - if cpio.returncode != 0:
6983 - raise subprocess.CalledProcessError(cpio.returncode, ["cpio"])
6984 - if find.returncode != 0:
6985 - raise subprocess.CalledProcessError(find.returncode, ["find"])
6986 -
6987 -
6988 -def _copy_libs_for_binary(binary: str, dest_dir: str, root: str):
6989 - """Kopiuje zależności .so dla binarki do initramfs (uproszczone ldd)."""
6990 - try:
6991 - result = subprocess.run(
6992 - ["ldd", binary], capture_output=True, text=True, timeout=10
6993 - )
6994 - for line in result.stdout.split("\n"):
6995 - m = re.search(r'=>\s+(/\S+)', line)
6996 - if m:
6997 - lib_path = m.group(1)
6998 - lib_rel = lib_path.lstrip("/")
6999 - lib_dest = os.path.join(dest_dir, lib_rel)
7000 - if not os.path.exists(lib_dest):
7001 - os.makedirs(os.path.dirname(lib_dest), exist_ok=True)
7002 - # Szukaj w deployment root lub systemie
7003 - if os.path.exists(lib_path):
7004 - shutil.copy2(lib_path, lib_dest)
7005 - else:
7006 - alt = os.path.join(root, lib_rel)
7007 - if os.path.exists(alt):
7008 - shutil.copy2(alt, lib_dest)
7009 - except Exception:
7010 - pass
7011 -
7012 -
7013 -def cmd_initramfs_update():
7014 - """Ręcznie przebudowuje initramfs dla bieżącego deploymentu."""
7015 - ensure_dirs()
7016 - deploy_dir = _get_deployment_root()
7017 - if deploy_dir != PAG_ROOT:
7018 - print(_('🏗️ Deployment: {arg1}', arg1=(os.path.basename(deploy_dir))))
7019 - ok = _rebuild_initramfs(deploy_dir)
7020 - if ok:
7021 - print(_('✅ Initramfs updated.'))
7022 - # Po initramfs – zaktualizuj też GRUB
7023 - _update_grub_config()
7024 - else:
7025 - print(_('❌ Initramfs update failed.'))
7026 - return 0 if ok else 1
7027 -
7028 -
7029 -def _boot_prefix() -> str:
7030 - """Prefiks ścieżek jądra/initrd w grub.cfg.
7031 -
7032 - Gdy /boot jest OSOBNYM punktem montowania, GRUB ma w `root` partycję
7033 - /boot (tam leży grub.cfg i jądra), więc ścieżki podajemy względem niej:
7034 - "/vmlinuz-…", "/initramfs.img" – BEZ przedrostka /boot. Gdy /boot leży
7035 - na roocie, wymagane jest "/boot/…". Zły przedrostek = "file not found".
7036 - """
7037 - try:
7038 - if os.path.isdir("/boot") and os.path.ismount("/boot"):
7039 - return ""
7040 - except OSError:
7041 - pass
7042 - return "/boot"
7043 -
7044 -
7045 -def _strip_crlf(path: str) -> bool:
7046 - """Usuwa CRLF/CR z pliku. True, jeśli coś zmieniono.
7047 -
7048 - /etc/default/grub z końcówkami Windows wywala `grub-mkconfig`
7049 - (line 2: bad command), a wtedy menu GRUB nie jest odświeżane po
7050 - aktualizacji jądra — zostaje stary wpis startowy.
7051 - """
7052 - try:
7053 - if not os.path.isfile(path):
7054 - return False
7055 - with open(path, "rb") as f:
7056 - data = f.read()
7057 - if b"\r" not in data:
7058 - return False
7059 - with open(path, "wb") as f:
7060 - f.write(data.replace(b"\r\n", b"\n").replace(b"\r", b"\n"))
7061 - return True
7062 - except Exception:
7063 - return False
7064 -
7065 -
7066 -def _repair_initramfs_links(boot: str = "/boot") -> bool:
7067 - """Doprowadza aliasy initramfs do stanu, w którym GRUB ma co podać.
7068 -
7069 - /etc/grub.d/10_linux dodaje linię `initrd` tylko jeśli istnieje
7070 - `initrd.img-<wersja>` lub `initramfs-<wersja>.img`. Dla wpisu z aliasu
7071 - `vmlinuz-linux` szuka `initrd.img-linux` / `initramfs-linux.img`.
7072 - Martwy łańcuch dowiązań = start BEZ initramfs, czyli panika
7073 - (VFS: Cannot open root device), gdy NVMe/LUKS są modułami.
7074 - """
7075 - changed = False
7076 - try:
7077 - if not os.path.isdir(boot):
7078 - return False
7079 - imgs = []
7080 - for n in os.listdir(boot):
7081 - if not (n.startswith("initramfs-") and n.endswith(".img")):
7082 - continue
7083 - ver = n[len("initramfs-"):-len(".img")]
7084 - if not ver or not ver[0].isdigit():
7085 - continue # initramfs-linux.img to alias
7086 - fp = os.path.join(boot, n)
7087 - if os.path.isfile(fp) and not os.path.islink(fp):
7088 - imgs.append((os.path.getmtime(fp), n))
7089 - if not imgs:
7090 - return False
7091 - newest = max(imgs)[1]
7092 -
7093 - def _link(alias: str, target: str, force: bool = False) -> None:
7094 - nonlocal changed
7095 - ap = os.path.join(boot, alias)
7096 - if os.path.islink(ap):
7097 - if os.readlink(ap) == target and os.path.exists(ap):
7098 - return
7099 - if os.path.exists(ap) and not force:
7100 - return # cel istnieje – nie ruszamy
7101 - os.remove(ap)
7102 - elif os.path.exists(ap):
7103 - return # prawdziwy plik – nie ruszamy
7104 - try:
7105 - os.symlink(target, ap)
7106 - changed = True
7107 - except OSError:
7108 - pass
7109 -
7110 - _link("initramfs.img", newest, force=True)
7111 - if os.path.exists(os.path.join(boot, "vmlinuz-linux")):
7112 - _link("initramfs-linux.img", "initramfs.img")
7113 - _link("initrd.img-linux", "initramfs.img")
7114 - return changed
7115 - except Exception:
7116 - return changed
7117 -
7118 -
7119 -def _grub_entry_lacks_initrd(grub_cfg: str = "/boot/grub/grub.cfg") -> bool:
7120 - """Czy pierwszy wpis menu nie ma linii `initrd` (start bez initramfs)."""
7121 - try:
7122 - with open(grub_cfg, encoding="utf-8", errors="replace") as f:
7123 - lines = f.read().splitlines()
7124 - except Exception:
7125 - return False
7126 - inside = False
7127 - for ln in lines:
7128 - st = ln.strip()
7129 - # Uwaga: `menuentry_id_option="..."` z nagłówka grub.cfg też zaczyna się
7130 - # od "menuentry" – wymagamy separatora, inaczej parser zgłasza fałszywy
7131 - # alarm „wpis startowy bez initramfs”.
7132 - if st.startswith("menuentry") and st[9:10] in (" ", "\t", "'", '"'):
7133 - if inside:
7134 - return True
7135 - inside = True
7136 - continue
7137 - if not inside:
7138 - continue
7139 - if st.startswith("initrd"):
7140 - return False
7141 - if st == "}":
7142 - return True
7143 - return False
7144 -
7145 -
7146 -def _refresh_bootloader():
7147 - """Odświeża wpisy bootloadera po zmianie jądra.
7148 -
7149 - Deploymenty (immutable OS): własny generator _update_grub_config().
7150 - Zwykła instalacja: standardowy `grub-mkconfig` – /etc/grub.d/10_linux
7151 - sam wygeneruje wpisy dla KAŻDEGO /boot/vmlinuz-* wraz z jego własnym
7152 - initrd. Bez tego `pag upgrade kernel` zostawiał w menu STARY wpis:
7153 - system startował ze starym jądrem, a nowe moduły leżały bezużyteczne
7154 - ("moduły 7.2.8 na jądrze 7.2.5" → zawieszenie na starcie).
7155 - """
7156 - try:
7157 - if _load_deployments():
7158 - _update_grub_config()
7159 - return
7160 - except Exception:
7161 - pass
7162 - grub_cfg = "/boot/grub/grub.cfg"
7163 - if not os.path.isdir("/boot/grub"):
7164 - return
7165 - # Zanim wygenerujemy menu: napraw dane wejściowe. Inaczej grub-mkconfig
7166 - # albo się wywali, albo wygeneruje wpis bez initramfs.
7167 - for _f in ("/etc/default/grub", "/boot/grub/grub.cfg.exemple"):
7168 - if _strip_crlf(_f):
7169 - print(" 🧹 " + _('crlf_fixed', _f))
7170 - if _repair_initramfs_links():
7171 - print(" 🔗 " + _('initramfs_links_fixed'))
7172 - for tool, cmd in ((
7173 - "grub-mkconfig", ["grub-mkconfig", "-o", grub_cfg]), (
7174 - "grub2-mkconfig", ["grub2-mkconfig", "-o", grub_cfg])):
7175 - if shutil.which(tool):
7176 - try:
7177 - print(_(' 📋 Regenerating GRUB (grub-mkconfig)...'))
7178 - r = subprocess.run(cmd, capture_output=True, text=True,
7179 - errors="replace", timeout=180)
7180 - if r.returncode != 0:
7181 - tail = [x for x in (r.stderr or r.stdout or "").splitlines() if x.strip()]
7182 - print(" ⚠ " + _('grub_failed', tail[-1] if tail else r.returncode))
7183 - elif _grub_entry_lacks_initrd(grub_cfg):
7184 - print(" ⚠ " + _('grub_no_initrd'))
7185 - else:
7186 - print(" ✅ " + _('grub_refreshed'))
7187 - except Exception:
7188 - pass
7189 - return
7190 -
7191 -
7192 -def _update_grub_config():
7193 - """
7194 - Generuje wpisy GRUB dla wszystkich deploymentów.
7195 - Każdy deployment dostaje własny wpis – rollback możliwy z bootloadera.
7196 - """
7197 - grub_cfg = "/boot/grub/grub.cfg"
7198 - if not os.path.exists(os.path.dirname(grub_cfg)):
7199 - return # brak GRUB
7200 -
7201 - deployments = _load_deployments()
7202 - root_dev = _detect_root_device()
7203 - if not root_dev:
7204 - print(_(' ⚠ Could not detect the root partition – GRUB entries will have no root=.'),
7205 - file=sys.stderr)
7206 - print(_(' Set PAG_ROOT_DEVICE=/dev/... (or PAG_GRUB_ROOT) and retry.'),
7207 - file=sys.stderr)
7208 - root_arg = f" root={root_dev}" if root_dev else ""
7209 -
7210 - lines = [
7211 - "# =====================================================================",
7212 - "# Pagan Linux – GRUB config (wygenerowane przez pag grub-update)",
7213 - f"# Data: {datetime.now().isoformat()}",
7214 - "# =====================================================================",
7215 - "",
7216 - ]
7217 -
7218 - # Domyślny – ostatni (najnowszy) deployment
7219 - if deployments:
7220 - latest = deployments[-1]["id"]
7221 - lines.append(f"set default=0")
7222 - lines.append(f"set timeout=5")
7223 - else:
7224 - lines.append("set default=0")
7225 - lines.append("set timeout=5")
7226 - lines.append("")
7227 -
7228 - # Wpisy dla każdego deploymentu (od najnowszego)
7229 - entry_num = 0
7230 - for d in reversed(deployments):
7231 - deploy_dir = os.path.join(DEPLOYMENTS_DIR, d["id"])
7232 - boot_dir = os.path.join(deploy_dir, "boot")
7233 - kernels = sorted(
7234 - [f for f in os.listdir(boot_dir) if f.startswith("vmlinuz-")],
7235 - reverse=True
7236 - ) if os.path.isdir(boot_dir) else []
7237 -
7238 - kernel_path = f"/.deployments/{d['id']}/boot/{kernels[0]}" if kernels else ""
7239 - initrd_path = f"/.deployments/{d['id']}/boot/initramfs.img"
7240 - initrd_line = f"initrd {initrd_path}" if os.path.exists(os.path.join(boot_dir, "initramfs.img")) else ""
7241 -
7242 - active_mark = f" [{_('active_deployment')}]" if d.get("active") else ""
7243 - pkg_list = ", ".join(d.get("packages", [])[:3])
7244 - label = f"Pagan Linux – {d['id']}{active_mark}"
7245 -
7246 - lines.append(f"menuentry '{label}' {{")
7247 - if kernel_path:
7248 - lines.append(f" linux {kernel_path}{root_arg} rw quiet")
7249 - else:
7250 - lines.append(f" # Brak jądra w tym deploymencie")
7251 - if initrd_line:
7252 - lines.append(f" {initrd_line}")
7253 - lines.append("}")
7254 - lines.append("")
7255 - entry_num += 1
7256 -
7257 - # Snapshoty systemu (btrfs) – każdy jako osobny wpis do uruchomienia.
7258 - _snap_lines = _grub_snapshot_entries()
7259 - if _snap_lines:
7260 - lines.append("# --- Snapshoty systemu (CoW) ---")
7261 - lines.extend(_snap_lines)
7262 -
7263 - # Wpis fallback: zwykły root (gdyby wszystko padło).
7264 - # Uwaga: GRUB NIE rozwija globów – trzeba podać KONKRETNY plik jądra
7265 - # (wcześniejsze `linux /boot/vmlinuz-*` było niepoprawne).
7266 - fallback_kernels = sorted(
7267 - [f for f in os.listdir("/boot") if f.startswith("vmlinuz-")],
7268 - reverse=True
7269 - ) if os.path.isdir("/boot") else []
7270 - # Osobna partycja /boot => GRUB ma ją w `root`, ścieżki BEZ /boot.
7271 - _bp = _boot_prefix()
7272 - lines.append(f"menuentry '{_('grub_fallback_label')}' {{")
7273 - if fallback_kernels:
7274 - lines.append(f" linux {_bp}/{fallback_kernels[0]}{root_arg} rw quiet")
7275 - _fi = _initrd_for_kernel("/boot", fallback_kernels[0])
7276 - if _fi:
7277 - lines.append(f" initrd {_bp}/{_fi}")
7278 - else:
7279 - lines.append(" # Brak jądra w /boot")
7280 - lines.append("}")
7281 - lines.append("")
7282 -
7283 - # Zapisz
7284 - os.makedirs(os.path.dirname(grub_cfg), exist_ok=True)
7285 - with open(grub_cfg, "w") as f:
7286 - f.write("\n".join(lines))
7287 -
7288 - print(_(' 📋 GRUB config updated – entries for each deployment'))
7289 -
7290 -
7291 -def _root_device_from_fstab(path: str = "/etc/fstab") -> str:
7292 - """Zwraca DEVICE z wpisu dla '/' w fstab (pomija komentarze)."""
7293 - try:
7294 - with open(path, "r", encoding="utf-8", errors="replace") as fh:
7295 - for line in fh:
7296 - line = line.split("#", 1)[0].strip()
7297 - if not line:
7298 - continue
7299 - parts = line.split()
7300 - if len(parts) >= 2 and parts[1] == "/":
7301 - return parts[0]
7302 - except OSError:
7303 - pass
7304 - return ""
7305 -
7306 -
7307 -def _in_chroot() -> bool:
7308 - """Heurystyka: czy działamy w chrocie (build ISO/IMG)?
7309 -
7310 - W chrocie /proc/1/root to root HOSTA – inny system plików niż nasz '/'.
7311 - Na zwykłym systemie PID 1 ma root równy '/'. PAGAN_ROOT ustawiają skrypty
7312 - budujące i jest dziedziczony przez chroot (dodatkowa wskazówka).
7313 - """
7314 - if os.environ.get("PAG_IN_CHROOT") == "1":
7315 - return True
7316 - if os.environ.get("PAGAN_ROOT"):
7317 - return True
7318 - try:
7319 - return os.stat("/").st_dev != os.stat("/proc/1/root").st_dev
7320 - except OSError:
7321 - return False
7322 -
7323 -
7324 -def _detect_root_device() -> str:
7325 - """Wykrywa urządzenie/identyfikator partycji root dla GRUB (root=...).
7326 -
7327 - Kolejność (od najbardziej wiarygodnego w danym kontekście):
7328 - 1) PAG_ROOT_DEVICE / PAG_GRUB_ROOT – jawny override (build ISO/IMG,
7329 - instalator); najpewniejszy, bo nie zgadujemy.
7330 - 2) /etc/fstab TARGETU – w chrocie findmnt '/' zwraca partycję HOSTA,
7331 - a fstab opisuje target (np. root=/dev/sda2 dla obrazu IMG).
7332 - 3) findmnt '/' – na żywym systemie (obsługuje UUID/LUKS/subvol).
7333 - Zwraca "" gdy nie da się ustalić – wtedy GRUB nie dostaje błędnego root=.
7334 - """
7335 - explicit = (os.environ.get("PAG_ROOT_DEVICE")
7336 - or os.environ.get("PAG_GRUB_ROOT") or "").strip()
7337 - if explicit:
7338 - return explicit
7339 -
7340 - fstab_dev = _root_device_from_fstab()
7341 - if _in_chroot() and fstab_dev:
7342 - return fstab_dev
7343 -
7344 - try:
7345 - result = subprocess.run(
7346 - ["findmnt", "-n", "-o", "SOURCE", "/"],
7347 - capture_output=True, text=True, timeout=5
7348 - )
7349 - if result.returncode == 0 and result.stdout.strip():
7350 - return result.stdout.strip()
7351 - except Exception:
7352 - pass
7353 -
7354 - # Ostatnia deska: fstab targetu (lepsze niż hardkodowane /dev/sda1,
7355 - # które na sprzęcie z NVMe dawało niebootowalny system).
7356 - return fstab_dev
7357 -
7358 -
7359 -def cmd_grub_update():
7360 - """Ręcznie regeneruje konfigurację GRUB (deploymenty + snapshoty)."""
7361 - ensure_dirs()
7362 - print(_('📋 Updating GRUB configuration...'))
7363 - _ensure_snapshot_grub_script()
7364 - # Deploymenty mają własny generator; zwykły system – grub-mkconfig,
7365 - # który uruchomi /etc/grub.d/40_pagan_snapshots i zachowa pozostałe wpisy.
7366 - _refresh_bootloader()
7367 - print(_('✅ GRUB updated.'))
7368 - return 0
7369 -
7370 -def cmd_deploy_list():
7371 - """Wyświetla listę wszystkich deploymentów."""
7372 - deployments = _load_deployments()
7373 - if not deployments:
7374 - print(_("no_deployments")); return
7375 -
7376 - print(_("deployments_list", len(deployments)))
7377 - active = os.readlink(ACTIVE_LINK) if os.path.islink(ACTIVE_LINK) else ""
7378 -
7379 - for d in reversed(deployments):
7380 - marker = f" ◀ {_('active_deployment')}" if d.get("active") or d["id"] == os.path.basename(active) else ""
7381 - print(f" {d['id']}{marker}")
7382 - print(f" {_action_label(d['action'])}: {', '.join(d['packages'][:5])}")
7383 - if len(d.get('packages', [])) > 5:
7384 - print(_(' +{arg1} more...', arg1=(len(d['packages']) - 5)))
7385 - print(f" {d['timestamp']}")
7386 -
7387 -
7388 -def cmd_deploy_rollback():
7389 - """Przełącza na poprzedni deployment."""
7390 - deployments = _load_deployments()
7391 - active_indices = [i for i, d in enumerate(deployments) if d.get("active")]
7392 -
7393 - if len(deployments) < 2:
7394 - print(f"❌ {_('deploy_rollback_fail')}"); return 1
7395 -
7396 - current_idx = active_indices[0] if active_indices else len(deployments) - 1
7397 - prev_idx = current_idx - 1 if current_idx > 0 else -1
7398 -
7399 - if prev_idx < 0:
7400 - print(f"❌ {_('deploy_rollback_fail')}"); return 1
7401 -
7402 - prev = deployments[prev_idx]
7403 - prev_dir = os.path.join(DEPLOYMENTS_DIR, prev["id"])
7404 -
7405 - if not os.path.isdir(prev_dir):
7406 - print(_('❌ Deployment {arg1} does not exist on disk', arg1=(prev['id']))); return 1
7407 -
7408 - print(_('⏪ Restoring deployment: {arg1}', arg1=(prev['id'])))
7409 - print(f" {prev['action']}: {', '.join(prev['packages'][:5])}")
7410 -
7411 - if not _ask_confirm():
7412 - return 0
7413 -
7414 - _switch_deployment(prev_dir)
7415 -
7416 - for d in deployments:
7417 - d["active"] = (d["id"] == prev["id"])
7418 - _save_deployments(deployments)
7419 -
7420 - _update_grub_config()
7421 - print(f"✅ {_('deploy_rollback_ok', prev['id'])}")
7422 - print(_(' 💡 Restart required to reload the system.'))
7423 - return 0
7424 -
7425 -
7426 -def cmd_deploy_cleanup(keep: int = 3):
7427 - """Usuwa stare deploymenty, zachowując ostatnie `keep`."""
7428 - deployments = _load_deployments()
7429 -
7430 - if len(deployments) <= keep:
7431 - print(f"✅ {_('deploy_cleanup_none', keep)}"); return 0
7432 -
7433 - to_remove = deployments[:-keep]
7434 - removed = 0
7435 -
7436 - for d in to_remove:
7437 - deploy_dir = os.path.join(DEPLOYMENTS_DIR, d["id"])
7438 - if os.path.isdir(deploy_dir):
7439 - shutil.rmtree(deploy_dir, ignore_errors=True)
7440 - removed += 1
7441 -
7442 - remaining = deployments[-keep:]
7443 - _save_deployments(remaining)
7444 -
7445 - print(f"✅ {_('deploy_cleanup_ok', removed)}")
7446 - return 0
7447 -
7448 -
7449 -# =============================================================================
7450 -# POMOCNICZE
7451 -# =============================================================================
7452 -
7453 -# Pakiety dostarczane przez bazowy system (zawsze "zainstalowane"). Wchodzą do
7454 -# rootfs z ISO przez data.tar.xz, więc NIE ma ich w repo.json ani w bazie pag –
7455 -# każda zależność od nich (glibc, bash, python3…) wyglądałaby na "brakującą".
7456 -# Współdzielone przez rozwijanie i weryfikację zależności.
7457 -SYSTEM_BASE = {
7458 - "glibc", "libc", "gcc", "g++", "make", "binutils", "coreutils", "bash",
7459 - "linux-api-headers", "kernel-headers", "zlib", "pkg-config", "pkgconf",
7460 - "tar", "gzip", "xz", "bzip2", "findutils", "grep", "sed", "gawk", "awk",
7461 - "diffutils", "patch", "file", "m4", "perl", "python3", "sh",
7462 -}
7463 -
7464 -
7465 -def _resolve_deps(names, repo, installed):
7466 - resolved, visited = [], set()
7467 - missing = [] # zależności których nie ma ani w repo ani zainstalowane
7468 -
7469 - def _is_base(dep):
7470 - """True, gdy zależność dostarcza bazowy system (także przez provides)."""
7471 - return dep in SYSTEM_BASE \
7472 - or _resolve_provides(dep, repo, installed) in SYSTEM_BASE
7473 -
7474 - def visit(name, explicit=False):
7475 - if name in visited: return
7476 -
7477 - # Rozwijanie wirtualnych zależności przez provides
7478 - target = _resolve_provides(name, repo, installed)
7479 -
7480 - # Zależność dostarczana przez bazowy system – nie ma jej w repo ani w
7481 - # bazie pag, więc nie "brakuje" jej i nie próbujemy jej instalować.
7482 - # Wyjątek: nazwa podana wprost przez użytkownika (explicit=True).
7483 - if not explicit and target in SYSTEM_BASE:
7484 - return
7485 -
7486 - if target in visited: return
7487 - visited.add(target)
7488 - if target in repo:
7489 - for dep in repo[target].dependencies:
7490 - real_dep = _resolve_provides(dep, repo, installed)
7491 - real_target = real_dep if real_dep in repo else dep
7492 -
7493 - if _is_base(dep):
7494 - continue
7495 -
7496 - # Sprawdź czy zależność jest dostępna
7497 - if real_target not in installed and real_target not in repo:
7498 - if dep not in missing:
7499 - missing.append(dep)
7500 -
7501 - if dep not in installed:
7502 - visit(real_target)
7503 - elif target not in installed:
7504 - # Pakiet nie istnieje ani w repo ani zainstalowany
7505 - if target not in missing:
7506 - missing.append(target)
7507 -
7508 - if target not in installed and target not in resolved:
7509 - resolved.append(target)
7510 -
7511 - for name in names:
7512 - visit(name, explicit=True)
7513 -
7514 - # Zwróć brakujące (do sprawdzenia przez wywołującego)
7515 - return resolved, missing
7516 -
7517 -def _verify_dependencies(to_install: list, repo: dict, installed: dict) -> int:
7518 - """
7519 - Sprawdza czy wszystkie zależności pakietów do instalacji są spełnione.
7520 - Zwraca liczbę brakujących zależności.
7521 - """
7522 - all_missing = []
7523 - all_warnings = []
7524 -
7525 - for pkg_name in to_install:
7526 - pkg = repo.get(pkg_name)
7527 - if not pkg:
7528 - continue
7529 -
7530 - for dep in pkg.dependencies:
7531 - if dep in SYSTEM_BASE:
7532 - continue # bazowy system dostarcza tę zależność
7533 - real_dep = _resolve_provides(dep, repo, installed)
7534 - # Sprawdź czy zależność jest dostępna (w repo lub już zainstalowana)
7535 - in_repo = real_dep in repo
7536 - in_installed = real_dep in installed
7537 - will_be_installed = real_dep in to_install
7538 -
7539 - if not in_repo and not in_installed and not will_be_installed:
7540 - if dep not in all_missing:
7541 - all_missing.append((pkg_name, dep))
7542 - elif in_repo and not in_installed and not will_be_installed:
7543 - if dep not in [w[1] for w in all_warnings]:
7544 - all_warnings.append((pkg_name, dep, real_dep))
7545 -
7546 - if all_missing:
7547 - print(_('\n❌ {arg1} – cannot install:', arg1=(_c('red', 'BRAKUJĄCE ZALEŻNOŚCI'))))
7548 - for pkg, dep in all_missing:
7549 - print(_(' {arg1} → needs {arg2} (missing from repositories)', arg1=(pkg), arg2=(_c('red', dep))))
7550 - print()
7551 -
7552 - if all_warnings:
7553 - print(_('\n⚠ {arg1} – will be installed as dependencies:', arg1=(_c('yellow', 'NIESPEŁNIONE ZALEŻNOŚCI'))))
7554 - for pkg, dep, real in all_warnings:
7555 - print(_(' {arg1} → {arg2} ({arg3} – will be downloaded)', arg1=(pkg), arg2=(dep), arg3=(_c('green', real))))
7556 - print()
7557 -
7558 - return len(all_missing)
7559 -
7560 -# Biblioteki bazowe (glibc/gcc runtime) – zawsze dostępne, nie wymagają pakietu
7561 -BASE_SO = {
7562 - "libc.so.6", "libm.so.6", "libpthread.so.0", "libdl.so.2", "librt.so.1",
7563 - "libutil.so.1", "libresolv.so.2", "libnsl.so.1", "libcrypt.so.1",
7564 - "ld-linux.so.2", "ld-linux-x86-64.so.2", "ld-linux-aarch64.so.1",
7565 - "libgcc_s.so.1", "linux-vdso.so.1",
7566 -}
7567 -
7568 -def _verify_so_deps(to_install: list, repo: dict, installed: dict) -> int:
7569 - """Sprawdza wymagania ABI (provides_so / requires_so z metadata.json).
7570 -
7571 - Fail-closed TYLKO gdy metadata jawnie deklaruje requires_so, a żaden pakiet
7572 - (bazowy, zainstalowany lub instalowany w tej transakcji) nie dostarcza
7573 - wymaganej wersji biblioteki. Stare pakiety bez tych pól są pomijane.
7574 - """
7575 - provided = set(BASE_SO)
7576 - for n in to_install:
7577 - p = repo.get(n)
7578 - if p:
7579 - provided.update(p.provides_so or [])
7580 - for n, info in installed.items():
7581 - provided.update(info.get("provides_so", []) or [])
7582 -
7583 - # NAPRAWA: soname faktycznie obecne w systemie (ldconfig -p). Metadane
7584 - # starych paczek (zbudowanych przed polem provides_so) ich nie deklaruja,
7585 - # a biblioteki sa na dysku - bez tego fail-closed check blokuje legalne
7586 - # aktualizacje (np. mesa -> libLLVM.so.22.1).
7587 - try:
7588 - import shutil as _sh, subprocess as _sp
7589 - _ld = _sh.which("ldconfig")
7590 - if _ld:
7591 - _o = _sp.run([_ld, "-p"], capture_output=True, text=True).stdout
7592 - for _ln in _o.splitlines():
7593 - _ln = _ln.strip()
7594 - if "=>" in _ln:
7595 - provided.add(_ln.split("=>")[0].strip().split()[0])
7596 - except Exception:
7597 - pass
7598 -
7599 - missing = []
7600 - for n in sorted(to_install):
7601 - p = repo.get(n)
7602 - if not p:
7603 - continue
7604 - for so in (p.requires_so or []):
7605 - if so not in provided:
7606 - missing.append((n, so))
7607 -
7608 - if missing:
7609 - print(f"\n❌ {_c('red', 'BRAK WYMAGANYCH BIBLIOTEK (ABI so-name)')}:")
7610 - for n, so in missing:
7611 - print(_(' {arg1} → requires {arg2} – no package provides this version', arg1=(n), arg2=(_c('red', so))))
7612 - print()
7613 - return len(missing)
7614 -
7615 -def _download_pkg(pkg, attempts: int = 3, progress: bool = True,
7616 - on_progress=None, on_log=None):
7617 - """Pobiera pakiet do cache.
7618 -
7619 - `progress=False` wycisza pojedynczy pasek (np. gdy równoległy pobierający
7620 - pokazuje własny panel zbiorczy). `on_progress(downloaded, total)` pozwala
7621 - takiemu panelowi śledzić postęp bez wypisywania własnych linii, a
7622 - `on_log(text)` przekierowuje komunikaty (ponowienia, błędy) do panelu,
7623 - żeby nie rozbijały jego wielolinijkowego układu.
7624 - """
7625 - def _log(msg: str) -> None:
7626 - if on_log is not None:
7627 - on_log(msg)
7628 - else:
7629 - print(msg, file=sys.stderr)
7630 -
7631 - url = f"{pkg.repo_url}/{pkg.filename}"
7632 - dest = os.path.join(PAG_CACHE, pkg.filename)
7633 - if os.path.exists(dest) and (not pkg.sha256 or _sha256_file(dest) == pkg.sha256):
7634 - _download_pkg_sig(pkg, dest) # upewnij się, że sygnatura jest w cache
7635 - return dest
7636 - last_err = None
7637 - for attempt in range(1, attempts + 1):
7638 - try:
7639 - req = Request(url, headers={"User-Agent":"pag/3.0"})
7640 - with urlopen(req, timeout=600) as resp:
7641 - total = int(resp.headers.get("Content-Length", 0))
7642 - bar = DownloadBar(pkg.filename, total) if progress else None
7643 - done = 0
7644 - try:
7645 - with open(dest, "wb") as f:
7646 - while True:
7647 - chunk = resp.read(65536)
7648 - if not chunk:
7649 - break
7650 - f.write(chunk)
7651 - done += len(chunk)
7652 - if bar is not None:
7653 - bar.update(len(chunk))
7654 - if on_progress is not None:
7655 - on_progress(done, total)
7656 - finally:
7657 - if bar is not None:
7658 - bar.close()
7659 - if pkg.sha256 and _sha256_file(dest) != pkg.sha256:
7660 - last_err = _("sha256_mismatch")
7661 - try:
7662 - os.remove(dest)
7663 - except OSError:
7664 - pass
7665 - if attempt < attempts:
7666 - _log(_(' ↻ Retrying download of {arg1} ({arg2}/{arg3})...', arg1=(pkg.filename), arg2=(attempt), arg3=(attempts - 1)))
7667 - time.sleep(attempt)
7668 - continue
7669 - return None
7670 - _download_pkg_sig(pkg, dest)
7671 - return dest
7672 - except Exception as e:
7673 - last_err = e
7674 - # Usuń częściowy plik – bez tego mógłby zostać użyty jako „cache”
7675 - # (gdy pakiet nie ma sha256) albo mylić kolejną próbę.
7676 - try:
7677 - if os.path.exists(dest):
7678 - os.remove(dest)
7679 - except OSError:
7680 - pass
7681 - if attempt < attempts:
7682 - _log(_(' ↻ Retrying download of {arg1} ({arg2}/{arg3})...', arg1=(pkg.filename), arg2=(attempt), arg3=(attempts - 1)))
7683 - time.sleep(attempt)
7684 - continue
7685 - _log(_(' ⚠ Download error {arg1}: {arg2}', arg1=(pkg.filename), arg2=(last_err)))
7686 - return None
7687 -
7688 -def _download_pkg_sig(pkg, dest):
7689 - """Zapewnia AKTUALNY podpis pakietu (.asc, fallback .sig) w cache.
7690 -
7691 - Istniejący podpis jest używany tylko wtedy, gdy faktycznie weryfikuje TĘ
7692 - paczkę. Inaczej po przebudowie tej samej wersji (ten sam plik, nowy sha256)
7693 - stary podpis zostawał obok nowej paczki i weryfikacja dawała fałszywe
7694 - „NIEPRAWIDŁOWY PODPIS GPG”.
7695 - """
7696 - for ext in (".asc", ".sig"):
7697 - sig_dest = dest + ext
7698 - if os.path.exists(sig_dest):
7699 - ok, _fp = _gpg_verify_fp(sig_dest, dest)
7700 - if ok:
7701 - return
7702 - for ext in (".asc", ".sig"):
7703 - sig_dest = dest + ext
7704 - try:
7705 - req = Request(f"{pkg.repo_url}/{pkg.filename}{ext}", headers={"User-Agent":"pag/3.0"})
7706 - with urlopen(req, timeout=30) as resp:
7707 - data = resp.read()
7708 - except Exception:
7709 - continue
7710 - # nie mieszaj rozszerzeń – zostaje tylko ten wariant podpisu
7711 - for other in (".asc", ".sig"):
7712 - if other != ext:
7713 - try:
7714 - os.remove(dest + other)
7715 - except OSError:
7716 - pass
7717 - with open(sig_dest, "wb") as f:
7718 - f.write(data)
7719 - return
7720 - # Nie udało się pobrać podpisu – usuń nieaktualny z cache, żeby weryfikacja
7721 - # nie porównywała paczki z podpisem od innej wersji (czytelny „BRAK PODPISU”).
7722 - for other in (".asc", ".sig"):
7723 - try:
7724 - os.remove(dest + other)
7725 - except OSError:
7726 - pass
7727 -
7728 -def _download_packages_parallel(pkgs: List[PackageInfo], max_workers: int = 4) -> Dict[str, Optional[str]]:
7729 - """
7730 - Równoległe pobieranie wielu pakietów przez ThreadPoolExecutor.
7731 - Znacząco przyspiesza przy dużych aktualizacjach (50+ pakietów).
7732 -
7733 - Każdy aktywny wątek ma własną linię w panelu: procent, nazwa pakietu,
7734 - pobrane/rozmiar i ETA (patrz `_ParallelDownloadDisplay`).
7735 - Zwraca słownik {nazwa_pakietu: ścieżka_lub_None}.
7736 - """
7737 - results = {}
7738 - display = _ParallelDownloadDisplay(len(pkgs))
7739 -
7740 - def _worker(pkg: PackageInfo):
7741 - sid = display.start(pkg.name, getattr(pkg, "size_bytes", 0) or 0)
7742 - path = None
7743 - try:
7744 - path = _download_pkg(
7745 - pkg, progress=False,
7746 - on_progress=lambda done, total: display.progress(sid, done, total),
7747 - on_log=display.log)
7748 - return path
7749 - finally:
7750 - display.finish(sid, ok=bool(path))
7751 -
7752 - try:
7753 - with ThreadPoolExecutor(max_workers=max_workers) as executor:
7754 - future_to_pkg = {executor.submit(_worker, pkg): pkg for pkg in pkgs}
7755 - for future in as_completed(future_to_pkg):
7756 - pkg = future_to_pkg[future]
7757 - try:
7758 - results[pkg.name] = future.result()
7759 - except Exception:
7760 - results[pkg.name] = None
7761 - finally:
7762 - display.close()
7763 - return results
7764 -
7765 -def load_world():
7766 - if not os.path.exists(WORLD_FILE): return set()
7767 - return {l.strip() for l in open(WORLD_FILE) if l.strip()}
7768 -
7769 -def save_world(w):
7770 - with open(WORLD_FILE,"w") as f:
7771 - for n in sorted(w): f.write(f"{n}\n")
7772 -
7773 -def _find_orphans(installed, world):
7774 - needed = set(world)
7775 - changed = True
7776 - while changed:
7777 - changed = False
7778 - for n in list(needed):
7779 - for dep in installed.get(n,{}).get("dependencies",[]):
7780 - if dep not in needed and dep in installed:
7781 - needed.add(dep); changed = True
7782 - return {n for n in installed if n not in needed}
7783 -
7784 -# =============================================================================
7785 -# MAIN
7786 -# =============================================================================
7787 -
7788 -def cmd_sbom(argv):
7789 - """pag sbom export [spdx|cyclonedx] – manifest SBOM zainstalowanych pakietów.
7790 -
7791 - Wypisuje na stdout JSON (SPDX 2.3 lub CycloneDX 1.5) z listą
7792 - zainstalowanych pakietów, wersji, licencji i sum SHA256.
7793 - """
7794 - fmt = (argv[0] if argv else "spdx").lower()
7795 - if fmt not in ("spdx", "cyclonedx"):
7796 - print(_('❌ Format: spdx | cyclonedx'))
7797 - return 1
7798 - installed = load_json(INSTALLED_DB)
7799 - if not installed:
7800 - print("{}") if fmt == "cyclonedx" else print("{\"packages\": []}")
7801 - return 0
7802 - # metadata repo (licencje) – best-effort
7803 - try:
7804 - repo = fetch_all_packages()
7805 - except Exception:
7806 - repo = {}
7807 - names = sorted(installed)
7808 - created = datetime.now().astimezone().isoformat(timespec="seconds")
7809 -
7810 - def _license_of(name):
7811 - p = repo.get(name)
7812 - lic = getattr(p, "license", None) or []
7813 - if isinstance(lic, list):
7814 - lic = ", ".join(x for x in lic if x)
7815 - return lic or "NOASSERTION"
7816 -
7817 - if fmt == "spdx":
7818 - doc = {
7819 - "spdxVersion": "SPDX-2.3",
7820 - "dataLicense": "CC0-1.0",
7821 - "SPDXID": "SPDXRef-DOCUMENT",
7822 - "name": "PaganOS-installed",
7823 - "documentNamespace": f"https://repo.paganlinux.eu/sbom/installed-{int(time.time())}",
7824 - "creationInfo": {
7825 - "created": created,
7826 - "creators": [f"Tool: pag-{PAG_VERSION}"],
7827 - },
7828 - "packages": [],
7829 - }
7830 - for i, n in enumerate(names):
7831 - info = installed[n]
7832 - doc["packages"].append({
7833 - "SPDXID": f"SPDXRef-Package-{i+1}",
7834 - "name": n,
7835 - "versionInfo": info.get("version", ""),
7836 - "downloadLocation": info.get("repo", "NOASSERTION"),
7837 - "filesAnalyzed": False,
7838 - "licenseConcluded": _license_of(n),
7839 - "checksums": [{"algorithm": "SHA256", "checksumValue": info.get("sha256", "")}],
7840 - })
7841 - else: # cyclonedx
7842 - doc = {
7843 - "bomFormat": "CycloneDX",
7844 - "specVersion": "1.5",
7845 - "serialNumber": f"urn:uuid:{str(uuid.uuid4())}",
7846 - "version": 1,
7847 - "metadata": {
7848 - "timestamp": created,
7849 - "tools": [{"vendor": "PaganOS", "name": "pag", "version": PAG_VERSION}],
7850 - },
7851 - "components": [],
7852 - }
7853 - for n in names:
7854 - info = installed[n]
7855 - lic = _license_of(n)
7856 - comp = {
7857 - "type": "library",
7858 - "name": n,
7859 - "version": info.get("version", ""),
7860 - "hashes": [{"alg": "SHA-256", "content": info.get("sha256", "")}],
7861 - }
7862 - if lic != "NOASSERTION":
7863 - comp["licenses"] = [{"license": {"id": lic}}]
7864 - doc["components"].append(comp)
7865 - print(json.dumps(doc, indent=2, ensure_ascii=False))
7866 - return 0
7867 -
7868 -
7869 -USAGE_EN = """pag v3 – Pagan Linux Package Manager
7870 -
7871 -BASIC:
7872 - pag install <pkg>... Install packages
7873 - pag remove <pkg>... Remove packages
7874 - pag update Update PACKAGES (refreshes indexes first)
7875 - pag sync Refresh indexes + show pending package updates
7876 - pag upgrade Update SYSTEM (packages + kernel/initramfs/GRUB)
7877 - pag list [--installed] List available / installed
7878 - pag search <query> Search packages
7879 - pag info <pkg> Package details
7880 - pag files <pkg> List package files
7881 - pag verify [--deep] Verify integrity (--deep = SHA256 per file)
7882 - pag clean Clear download cache
7883 - pag stats System statistics
7884 - pag download <pkg>... Download packages to cache (offline prep)
7885 -
7886 -ROLLING (base baked into the image):
7887 - pag base [status] Image packages vs. repo (what pag manages)
7888 - pag base adopt [pkg...] Adopt base packages from the repo (--dry-run = preview)
7889 -
7890 -SECURITY:
7891 - pag key-add <url|file> Import GPG key
7892 - pag key-list List trusted keys
7893 - pag key-remove <id> Remove key
7894 - pag key-trust <repo> Pin repo signing key fingerprint (no TOFU)
7895 - pag key-untrust <repo> Forget repo fingerprint (back to TOFU)
7896 - pag key-trusted List pinned repo fingerprints
7897 -
7898 -ADVANCED:
7899 - pag why <pkg> Show why a package is installed
7900 - pag rdepends <pkg> Show which packages depend on a package
7901 - pag autoremove Auto-remove orphaned dependencies
7902 - pag pin <pkg> [ver] Pin package version
7903 - pag unpin <pkg> Unpin
7904 - pag pinned List pinned
7905 - pag history Transaction history
7906 - pag rollback Rollback last transaction
7907 - pag repair [--dry-run] Reinstall packages with missing files
7908 - pag remove-orphans Remove orphaned deps
7909 - pag repo-add <url> [name] Add repository (drop-in /etc/pag/repos/)
7910 - pag repo-list List repositories
7911 - pag sbom export [fmt] SBOM manifest (spdx|cyclonedx)
7912 -
7913 -FLATPAK:
7914 - pag flatpak [<query>] Search & install (smart)
7915 - pag flatpak search <q> Search Flathub
7916 - pag flatpak install <id> Install flatpak
7917 - pag flatpak remove <id> Remove flatpak
7918 - pag flatpak list List installed flatpaks
7919 - pag flatpak update Update all flatpaks
7920 - pag flatpak info <id> Show flatpak details
7921 -
7922 -SNAPSHOTS (btrfs CoW):
7923 - pag snapshot-list List system snapshots
7924 - pag snapshot-create [label] Create a snapshot now
7925 - pag snapshot-rollback [id] Start from snapshot at next boot (GRUB)
7926 - pag snapshot-delete <id> Delete a snapshot
7927 -
7928 -IMMUTABLE OS (PAG_IMMUTABLE=1):
7929 - pag deploy-list List all deployments
7930 - pag deploy-rollback Switch to previous deployment
7931 - pag deploy-cleanup [N] Remove old deployments (keep last N, default 3)
7932 - pag initramfs-update Rebuild initramfs for current kernel/deployment
7933 - pag grub-update Regenerate GRUB entries for all deployments
7934 -"""
7935 -
7936 -USAGE_PL = """pag v3 – Pagan Linux Package Manager
7937 -
7938 -PODSTAWOWE:
7939 - pag install <pkg>... Instalacja pakietów
7940 - pag remove <pkg>... Usuwanie pakietów
7941 - pag update Aktualizacja PAKIETÓW (odświeża indeksy)
7942 - pag sync Odśwież indeksy + info o aktualizacjach
7943 - pag upgrade Aktualizacja SYSTEMU (pakiety + kernel/initramfs/GRUB)
7944 - pag list [--installed] Lista dostępnych / zainstalowanych
7945 - pag search <query> Szukaj pakietów
7946 - pag info <pkg> Szczegóły pakietu
7947 - pag files <pkg> Lista plików pakietu
7948 - pag verify [--deep] Weryfikacja integralności
7949 - pag clean Wyczyść cache pobierania
7950 - pag stats Statystyki systemu
7951 - pag download <pkg>... Pobierz do cache (offline)
7952 -
7953 -ROLLING (baza wypalona w obrazie):
7954 - pag base [status] Pakiety z obrazu vs repo (czym pag zarządza)
7955 - pag base adopt [pkg...] Adoptuj pakiety bazy z repo (--dry-run = podgląd)
7956 -
7957 -BEZPIECZEŃSTWO:
7958 - pag key-add <url|file> Importuj klucz GPG
7959 - pag key-list Lista zaufanych kluczy
7960 - pag key-remove <id> Usuń klucz
7961 - pag key-trust <repo> Przypnij fingerprint klucza repo (bez TOFU)
7962 - pag key-untrust <repo> Zapomnij fingerprint repo (powrót do TOFU)
7963 - pag key-trusted Lista przypiętych fingerprintów repo
7964 -
7965 -ZAAWANSOWANE:
7966 - pag why <pkg> Dlaczego pakiet jest zainstalowany
7967 - pag rdepends <pkg> Które pakiety zależą od pakietu
7968 - pag autoremove Usuń osierocone zależności
7969 - pag pin <pkg> [ver] Przypnij wersję pakietu
7970 - pag unpin <pkg> Odepnij
7971 - pag pinned Lista przypiętych
7972 - pag history Historia transakcji
7973 - pag rollback Cofnij ostatnią transakcję
7974 - pag repair [--dry-run] Napraw brakujące pliki pakietów (reinstalacja)
7975 - pag remove-orphans Usuń osierocone zależności
7976 - pag repo-add <url> [nazwa] Dodaj repozytorium (drop-in w /etc/pag/repos/)
7977 - pag repo-list Lista repozytoriów
7978 - pag sbom export [fmt] Manifest SBOM (spdx|cyclonedx)
7979 -
7980 -FLATPAK:
7981 - pag flatpak [<query>] Szukaj i instaluj
7982 - pag flatpak search <q> Szukaj na Flathub
7983 - pag flatpak install <id> Zainstaluj flatpak
7984 - pag flatpak remove <id> Usuń flatpak
7985 - pag flatpak list Lista zainstalowanych
7986 - pag flatpak update Aktualizuj wszystkie
7987 - pag flatpak info <id> Szczegóły flatpaka
7988 -
7989 -SNAPSHOTY (btrfs CoW):
7990 - pag snapshot-list Lista snapshotów systemu
7991 - pag snapshot-create [opis] Utwórz snapshot teraz
7992 - pag snapshot-rollback [id] Uruchom snapshot przy następnym starcie (GRUB)
7993 - pag snapshot-delete <id> Usuń snapshot
7994 -
7995 -IMMUTABLE OS (PAG_IMMUTABLE=1):
7996 - pag deploy-list Lista wdrożeń
7997 - pag deploy-rollback Przełącz na poprzednie wdrożenie
7998 - pag deploy-cleanup [N] Usuń stare wdrożenia (zachowaj N, domyślnie 3)
7999 - pag initramfs-update Przebuduj initramfs
8000 - pag grub-update Regeneruj wpisy GRUB"""
8001 -
8002 -def _get_usage():
8003 - # Plik językowy może dostarczyć klucz "usage" – wtedy wygrywa z wbudowanym.
8004 - _u = T.get(LANG, {}).get("usage")
8005 - if _u:
8006 - return _u
8007 - if LANG == "pl":
8008 - return USAGE_PL
8009 - return USAGE_EN
8010 -
8011 -
8012 -# =============================================================================
8013 -# EASTER EGG: PAG WROOM – wyścigi ASCII w stylu Commodore
8014 -# -----------------------------------------------------------------------------
8015 -
8016 -def cmd_wroom():
8017 - """Ukryta gra: `pag wroom`.
8018 -
8019 - Animowany top-down wyścig w ASCII: trzy pasy, ruszający się tor, przeciwnicy,
8020 - punkty, ETA niepotrzebne – liczy się rekord. Sterowanie strzałkami (lub
8021 - WSAD), P pauza, Q wyjście. Gra działa tylko na terminalu; poza TTY wypisuje
8022 - krótką podpowiedź, a po wyjściu przywraca ekran i ustawienia terminala.
8023 - """
8024 - if not (sys.stdin.isatty() and sys.stdout.isatty()):
8025 - print(_('wroom_terminal'))
8026 - return 1
8027 - if os.environ.get("TERM", "") == "dumb":
8028 - print(_('wroom_terminal'))
8029 - return 1
8030 - try:
8031 - import random
8032 - import select
8033 - import termios
8034 - import tty
8035 - except ImportError:
8036 - print(_('wroom_terminal'))
8037 - return 1
8038 -
8039 - ANSI_RE = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]")
8040 -
8041 - def _vlen(text):
8042 - return len(ANSI_RE.sub("", text))
8043 -
8044 - def _vcut(text, width):
8045 - """Przytnij linię do `width` WIDOCZNYCH kolumn (nie licząc ANSI)."""
8046 - if _vlen(text) <= width:
8047 - return text
8048 - out, vis, i = [], 0, 0
8049 - while i < len(text) and vis < width:
8050 - m = ANSI_RE.match(text, i)
8051 - if m:
8052 - out.append(m.group(0))
8053 - i = m.end()
8054 - continue
8055 - out.append(text[i])
8056 - vis += 1
8057 - i += 1
8058 - return "".join(out)
8059 -
8060 - def _center(text, width):
8061 - v = _vlen(text)
8062 - if v >= width:
8063 - return _vcut(text, width)
8064 - pad = width - v
8065 - return " " * (pad // 2) + text + " " * (pad - pad // 2)
8066 -
8067 - # --- geometria toru i sprite'y (każdy znak = 1 kolumna) -------------------
8068 - SPR_ROOF = " ▄█▄ "
8069 - SPR_BODY = "▐███▌"
8070 - LANE_W = 8
8071 - N_LANES = 3
8072 - ROAD_W = LANE_W * N_LANES + 2
8073 - MIN_W, MIN_H = 56, 16
8074 -
8075 - GLYPHS = {
8076 - "P": ("████ ", "█ █", "████ ", "█ ", "█ "),
8077 - "A": (" ███ ", "█ █", "█████", "█ █", "█ █"),
8078 - "G": (" ████", "█ ", "█ ██", "█ █", " ████"),
8079 - "W": ("█ █", "█ █", "█ █ █", "██ ██", "█ █"),
8080 - "R": ("████ ", "█ █", "████ ", "█ █ ", "█ █ "),
8081 - "O": (" ███ ", "█ █", "█ █", "█ █", " ███ "),
8082 - "M": ("█ █", "██ ██", "█ █ █", "█ █", "█ █"),
8083 - }
8084 -
8085 - def _logo():
8086 - rows = []
8087 - for r in range(5):
8088 - line = ""
8089 - for ch in "PAG WROOM":
8090 - if ch == " ":
8091 - line += " "
8092 - else:
8093 - line += GLYPHS[ch][r] + " "
8094 - rows.append(line.rstrip())
8095 - return rows
8096 -
8097 - LOGO = _logo()
8098 -
8099 - state = {
8100 - "phase": "title", "best": 0, "paused": False,
8101 - "lane": 1, "x": 1.0, "speed": 90.0, "boost": 0.0,
8102 - "distance": 0.0, "lives": 3, "opponents": [],
8103 - "spawn": 0.8, "invuln": 1.0, "flash": 0.0,
8104 - "scroll": 0.0, "time": 0.0, "road_h": 12,
8105 - }
8106 -
8107 - def _new_game():
8108 - state.update(phase="play", paused=False, lane=1, x=1.0,
8109 - speed=90.0, boost=0.0, distance=0.0, lives=3,
8110 - opponents=[], spawn=0.8, invuln=1.0, flash=0.0,
8111 - scroll=0.0, time=0.0)
8112 -
8113 - # --- wejście (bez blokowania) --------------------------------------------
8114 - ARROWS = {"\x1b[D": "LEFT", "\x1b[C": "RIGHT",
8115 - "\x1b[A": "UP", "\x1b[B": "DOWN",
8116 - "\x1bOD": "LEFT", "\x1bOC": "RIGHT",
8117 - "\x1bOA": "UP", "\x1bOB": "DOWN"}
8118 - fd = sys.stdin.fileno()
8119 - pending = ""
8120 -
8121 - def _keys():
8122 - nonlocal pending
8123 - keys = []
8124 - try:
8125 - ready, _, _ = select.select([fd], [], [], 0)
8126 - if not ready:
8127 - return keys
8128 - data = pending + os.read(fd, 64).decode("utf-8", "ignore")
8129 - pending = ""
8130 - except (OSError, UnicodeDecodeError):
8131 - return keys
8132 - i = 0
8133 - while i < len(data):
8134 - if data[i] == "\x1b":
8135 - # Niekompletna sekwencja strzałki – dokończymy w następnej
8136 - # klatce. Sam ESC (bez reszty) nie wychodzi z gry: wyjściem
8137 - # jest Q, więc przypadkowy Alt/strzałka nie zabija wyścigu.
8138 - if i + 1 >= len(data):
8139 - pending = data[i:]
8140 - break
8141 - if data[i + 1] not in "[O":
8142 - i += 1
8143 - continue
8144 - if i + 2 >= len(data):
8145 - pending = data[i:]
8146 - break
8147 - seq = data[i:i + 3]
8148 - key = ARROWS.get(seq)
8149 - if key:
8150 - keys.append(key)
8151 - i += 3
8152 - continue
8153 - ch = data[i]
8154 - i += 1
8155 - if ch in "qQ":
8156 - keys.append("QUIT")
8157 - elif ch in "aA":
8158 - keys.append("LEFT")
8159 - elif ch in "dD":
8160 - keys.append("RIGHT")
8161 - elif ch in "wW":
8162 - keys.append("UP")
8163 - elif ch in "sS":
8164 - keys.append("DOWN")
8165 - elif ch in "pP":
8166 - keys.append("PAUSE")
8167 - elif ch in " \r\n rR":
8168 - keys.append("START")
8169 - return keys
8170 -
8171 - # --- rysowanie toru -------------------------------------------------------
8172 - def _paint(row, start, text, color):
8173 - cells, cols = row
8174 - for i, ch in enumerate(text):
8175 - pos = start + i
8176 - if 0 <= pos < len(cells) and ch != " ":
8177 - cells[pos] = ch
8178 - cols[pos] = color
8179 -
8180 - def _render_cells(row):
8181 - cells, cols = row
8182 - parts, i = [], 0
8183 - while i < len(cells):
8184 - j = i
8185 - while j + 1 < len(cells) and cols[j + 1] == cols[i]:
8186 - j += 1
8187 - seg = "".join(cells[i:j + 1])
8188 - parts.append(_c(cols[i], seg) if cols[i] else seg)
8189 - i = j + 1
8190 - return "".join(parts)
8191 -
8192 - def _road_row(r, phase):
8193 - cells = [" "] * ROAD_W
8194 - cols = [None] * ROAD_W
8195 - cells[0] = "║"
8196 - cols[0] = "yellow"
8197 - cells[-1] = "║"
8198 - cols[-1] = "yellow"
8199 - for sep in (LANE_W, LANE_W * 2):
8200 - if (r + phase) % 4 < 2:
8201 - cells[1 + sep] = "│"
8202 - cols[1 + sep] = "dim"
8203 - return cells, cols
8204 -
8205 - def _lane_start(pos, width):
8206 - return int(round(1 + pos * LANE_W + (LANE_W - width) / 2))
8207 -
8208 - def _play_lines(W, H):
8209 - road_h = max(6, H - 4)
8210 - rows = [_center(_c("cyan", "PAG WROOM"), W)]
8211 - hud = _('wroom_hud', arg1=(int(state["distance"])),
8212 - arg2=(int(state["speed"])), arg3=(state["lives"]))
8213 - rows.append(_center(hud, W))
8214 -
8215 - board = [_road_row(r, int(state["scroll"])) for r in range(road_h)]
8216 - for o in state["opponents"]:
8217 - base = int(round(o["y"]))
8218 - for dy, spr in ((0, SPR_ROOF), (1, SPR_BODY)):
8219 - rr = base + dy
8220 - if 0 <= rr < road_h:
8221 - _paint(board[rr], _lane_start(o["lane"], len(spr)),
8222 - spr, o["color"])
8223 -
8224 - if not (state["invuln"] > 0 and int(state["time"] * 10) % 2):
8225 - for dy, spr in ((0, SPR_ROOF), (1, SPR_BODY)):
8226 - rr = road_h - 2 + dy
8227 - _paint(board[rr], _lane_start(state["x"], len(spr)),
8228 - spr, "cyan")
8229 -
8230 - if state["flash"] > 0:
8231 - _paint(board[road_h - 2], ROAD_W // 2 - 2, "BUM!", "red")
8232 -
8233 - left = max(0, (W - ROAD_W) // 2)
8234 - right = max(0, W - ROAD_W - left)
8235 - for r in range(road_h):
8236 - rows.append(" " * left + _render_cells(board[r]) + " " * right)
8237 -
8238 - rows.append("")
8239 - rows.append(_center(_c("dim", _('wroom_controls')), W))
8240 - if state["paused"]:
8241 - rows[H // 2] = _center(_c("yellow", _('wroom_paused')), W)
8242 - return rows[:H]
8243 -
8244 - def _menu_lines(W, H, blink):
8245 - block = []
8246 - if W >= len(LOGO[0]) + 2:
8247 - block.extend(_c("cyan", ln) for ln in LOGO)
8248 - else:
8249 - block.append(_c("cyan", "P A G W R O O M"))
8250 - block.append("")
8251 - block.append(_c("dim", _('wroom_tagline')))
8252 - if H >= 18:
8253 - block.append("")
8254 - block.append(" " + _c("cyan", "▄███▄") + " " +
8255 - _c("red", "▄███▄") + " " +
8256 - _c("yellow", "▄███▄"))
8257 - if H >= 22:
8258 - block.extend(["", _c("dim", 'LOAD "WROOM",8,1'),
8259 - _c("dim", "READY."), _c("dim", "RUN")])
8260 - block.append("")
8261 - if state["phase"] == "over":
8262 - block.append(_c("red", _('wroom_over')))
8263 - block.append("")
8264 - block.append(_('wroom_score', arg1=(int(state["distance"]))))
8265 - block.append(_('wroom_best', arg1=(state["best"])))
8266 - block.append("")
8267 - block.append(_('wroom_restart'))
8268 - else:
8269 - block.append(_('wroom_controls'))
8270 - block.append("")
8271 - block.append(_c("yellow", _('wroom_press')) if blink else "")
8272 -
8273 - top = max(0, (H - len(block)) // 2)
8274 - rows = [""] * H
8275 - for i, line in enumerate(block):
8276 - if top + i < H:
8277 - rows[top + i] = _center(line, W)
8278 - return rows
8279 -
8280 - # --- fizyka i kolizje -----------------------------------------------------
8281 - def _spawn():
8282 - free = [lane for lane in range(N_LANES)
8283 - if not any(o["lane"] == lane and o["y"] < 4
8284 - for o in state["opponents"])]
8285 - if not free:
8286 - return
8287 - state["opponents"].append({
8288 - "lane": random.choice(free),
8289 - "y": -2.0,
8290 - "speed": state["speed"] * random.uniform(0.45, 0.78),
8291 - "color": random.choice(("red", "yellow", "green")),
8292 - })
8293 -
8294 - def _update(dt):
8295 - state["time"] += dt
8296 - if state["phase"] != "play" or state["paused"]:
8297 - return
8298 -
8299 - state["boost"] *= max(0.0, 1.0 - dt * 3.0)
8300 - base = 90.0 + min(120.0, state["distance"] * 0.02)
8301 - target = max(45.0, base + state["boost"])
8302 - state["speed"] += (target - state["speed"]) * min(1.0, dt * 2.0)
8303 - state["distance"] += state["speed"] * dt * 0.45
8304 - state["scroll"] += state["speed"] * dt * 0.09
8305 - state["x"] += (state["lane"] - state["x"]) * min(1.0, dt * 9.0)
8306 - if state["invuln"] > 0:
8307 - state["invuln"] = max(0.0, state["invuln"] - dt)
8308 - if state["flash"] > 0:
8309 - state["flash"] = max(0.0, state["flash"] - dt)
8310 -
8311 - state["spawn"] -= dt
8312 - if state["spawn"] <= 0:
8313 - _spawn()
8314 - state["spawn"] = max(0.45, 1.35 - state["speed"] / 320.0)
8315 -
8316 - for o in list(state["opponents"]):
8317 - o["y"] += (state["speed"] - o["speed"]) * dt * 0.06
8318 - if o["y"] > state["road_h"] + 2 or o["y"] < -4:
8319 - state["opponents"].remove(o)
8320 -
8321 - if state["invuln"] > 0:
8322 - return
8323 - player_cy = state["road_h"] - 1.0
8324 - for o in list(state["opponents"]):
8325 - if (abs((o["y"] + 1.0) - player_cy) < 1.25
8326 - and abs(o["lane"] - state["x"]) < 0.55):
8327 - state["lives"] -= 1
8328 - state["flash"] = 0.6
8329 - state["invuln"] = 1.8
8330 - state["speed"] = max(45.0, state["speed"] * 0.5)
8331 - state["boost"] = 0.0
8332 - state["opponents"].remove(o)
8333 - state["opponents"] = [x for x in state["opponents"]
8334 - if x["y"] < state["road_h"] - 5]
8335 - try:
8336 - out.write("\a")
8337 - out.flush()
8338 - except OSError:
8339 - pass
8340 - if state["lives"] <= 0:
8341 - state["phase"] = "over"
8342 - state["best"] = max(state["best"],
8343 - int(state["distance"]))
8344 - break
8345 -
8346 - # --- pętla gry ------------------------------------------------------------
8347 - old_attrs = termios.tcgetattr(fd)
8348 - out = sys.stdout
8349 - try:
8350 - tty.setcbreak(fd)
8351 - out.write("\x1b[?1049h\x1b[?25l\x1b[2J")
8352 - out.flush()
8353 - running = True
8354 - last = time.monotonic()
8355 - last_size = None
8356 - while running:
8357 - for key in _keys():
8358 - if key == "QUIT":
8359 - running = False
8360 - break
8361 - if state["phase"] in ("title", "over"):
8362 - if key == "START":
8363 - _new_game()
8364 - elif key == "PAUSE":
8365 - state["paused"] = not state["paused"]
8366 - elif state["paused"]:
8367 - continue
8368 - elif key == "LEFT":
8369 - state["lane"] = max(0, state["lane"] - 1)
8370 - elif key == "RIGHT":
8371 - state["lane"] = min(N_LANES - 1, state["lane"] + 1)
8372 - elif key == "UP":
8373 - state["boost"] = min(55.0, state["boost"] + 14.0)
8374 - elif key == "DOWN":
8375 - state["boost"] = max(-45.0, state["boost"] - 14.0)
8376 - if not running:
8377 - break
8378 -
8379 - size = shutil.get_terminal_size((80, 24))
8380 - W, H = size.columns, size.lines
8381 - if last_size != (W, H):
8382 - last_size = (W, H)
8383 - out.write("\x1b[2J")
8384 - state["road_h"] = max(6, H - 4)
8385 -
8386 - now = time.monotonic()
8387 - dt = min(0.1, max(0.0, now - last))
8388 - last = now
8389 - if W >= MIN_W and H >= MIN_H:
8390 - _update(dt)
8391 -
8392 - if W < MIN_W or H < MIN_H:
8393 - lines = [""] * H
8394 - msg = _('wroom_too_small', arg1=(MIN_W), arg2=(MIN_H))
8395 - lines[H // 2] = _center(_c("yellow", msg), W)
8396 - elif state["phase"] == "play":
8397 - lines = _play_lines(W, H)
8398 - else:
8399 - blink = int(time.monotonic() * 2) % 2 == 0
8400 - lines = _menu_lines(W, H, blink)
8401 -
8402 - buf = ["\x1b[H"]
8403 - for i, line in enumerate(lines):
8404 - buf.append(_vcut(line, W))
8405 - buf.append("\x1b[K")
8406 - if i != len(lines) - 1:
8407 - buf.append("\n")
8408 - out.write("".join(buf))
8409 - out.flush()
8410 -
8411 - spent = time.monotonic() - now
8412 - if spent < 1.0 / 20.0:
8413 - time.sleep(1.0 / 20.0 - spent)
8414 - finally:
8415 - try:
8416 - out.write("\x1b[0m\x1b[?25h\x1b[?1049l")
8417 - out.flush()
8418 - except OSError:
8419 - pass
8420 - termios.tcsetattr(fd, termios.TCSADRAIN, old_attrs)
8421 - return 0
8422 -
8423 -
8424 -def _extract_lang(outdir: str) -> int:
8425 - """Eksport wbudowanych tłumaczeń do outdir/{pl,en}.json (+ klucz "usage").
8426 -
8427 - Używane przez recepturę pakietu (pag.pag), żeby tłumaczenia jechały RAZEM
8428 - z wersją paga – po `pag install/upgrade pag` i self-update są zawsze zgodne.
8429 - """
8430 - os.makedirs(outdir, exist_ok=True)
8431 - for _code in ("pl", "en"):
8432 - _d = dict(T.get(_code, {}))
8433 - _u = globals().get(f"USAGE_{_code.upper()}", "")
8434 - if _u:
8435 - _d["usage"] = _u
8436 - _p = os.path.join(outdir, f"{_code}.json")
8437 - with open(_p, "w", encoding="utf-8") as _fh:
8438 - json.dump(_d, _fh, ensure_ascii=False, indent=2, sort_keys=True)
8439 - print(_(' ✓ {arg1} ({arg2} keys)', arg1=(_p), arg2=(len(_d))))
8440 - return 0
8441 -
8442 -
8443 -def main():
8444 - # Ukryte (używane przy budowie pakietu): eksport tłumaczeń do plików
8445 - if len(sys.argv) >= 3 and sys.argv[1] == "--lang-extract":
8446 - sys.exit(_extract_lang(sys.argv[2]))
8447 - if len(sys.argv) >= 2 and sys.argv[1] in ("--version", "-V", "version"):
8448 - print(f"pag {PAG_VERSION}")
8449 - sys.exit(0)
8450 - if len(sys.argv) == 2 and sys.argv[1] in ("--help", "-h", "help"):
8451 - print(_get_usage()); sys.exit(0)
8452 - if len(sys.argv) < 2:
8453 - print(_get_usage()); sys.exit(0)
8454 -
8455 - cmd = sys.argv[1]
8456 - args = sys.argv[2:]
8457 -
8458 - # Python bez modułu ssl = brak HTTPS w urllib. Powiedz to wprost, zamiast
8459 - # pokazywać mylące „unknown url type: https” przy każdej operacji sieciowej.
8460 - if not _ssl_ok():
8461 - print(f" ⚠ {_('ssl_broken')}", file=sys.stderr)
8462 -
8463 - # `pag repair --dry-run`: diagnostyka bez roota (nic nie zmienia).
8464 - if cmd == "repair" and "--dry-run" in args and os.geteuid() != 0:
8465 - sys.exit(cmd_repair(dry_run=True) or 0)
8466 -
8467 - # --- Komendy TYLKO DO ODCZYTU (nie wymagają roota) ---
8468 - READ_ONLY = {
8469 - "list": lambda: cmd_list("--installed" in args),
8470 - "search": lambda: cmd_search(args[0]) if args else print(_('Usage: pag search <query>')),
8471 - "info": lambda: cmd_info(args[0]) if args else print(_('Usage: pag info <pkg>')),
8472 - "files": lambda: cmd_files(args[0]) if args else print(_('Usage: pag files <pkg>')),
8473 - "verify": lambda: cmd_verify("--deep" in args),
8474 - "why": lambda: cmd_why(args[0]) if args else print(_('Usage: pag why <pkg>')),
8475 - "rdepends": lambda: cmd_rdepends(args[0]) if args else print(_('Usage: pag rdepends <pkg>')),
8476 - "stats": cmd_stats,
8477 - "pinned": cmd_pinned,
8478 - "history": cmd_history,
8479 - "repo-list": cmd_repo_list,
8480 - "key-list": cmd_key_list,
8481 - "key-trusted": cmd_key_trusted,
8482 - "flatpak": lambda: cmd_flatpak(args),
8483 - "flatpak-search": lambda: cmd_flatpak_search(args[0]) if args else print(_('Usage: pag flatpak-search <query>')),
8484 - "flatpak-list": cmd_flatpak_list,
8485 - "flatpak-info": lambda: cmd_flatpak_info(args[0]) if args else print(_('Usage: pag flatpak-info <id>')),
8486 - "deploy-list": cmd_deploy_list,
8487 - "deploy": cmd_deploy_list,
8488 - "snapshot-list": cmd_snapshot_list,
8489 - "snapshots": cmd_snapshot_list,
8490 - "snapshot-grub": cmd_snapshot_grub,
8491 - "sbom": lambda: cmd_sbom(args),
8492 - "wroom": cmd_wroom, # easter egg – działa bez roota
8493 - }
8494 -
8495 - if cmd in READ_ONLY:
8496 - sys.exit(READ_ONLY[cmd]() or 0)
8497 -
8498 - # --- `pag base` / `pag base status`: tylko odczyt (bez roota i bez locka) ---
8499 - # `pag base adopt` NIE wpada tutaj – idzie ścieżką komend zapisu (roota + lock
8500 - # pilnuje wspólna obsługa niżej), żeby transakcja była bezpieczna.
8501 - if cmd in ("base", "base-status") and not (args and args[0] in ("adopt", "register")):
8502 - sys.exit(cmd_base_status() or 0)
8503 -
8504 - # --- Smart search: `pag <nazwa-pakietu>` → repo + Flathub + sugestie ---
8505 - WRITE_CMDS = {
8506 - "install", "remove", "update", "sync", "upgrade", "clean", "download",
8507 - "autoremove", "remove-orphans", "pin", "unpin", "rollback",
8508 - "repo-add", "key-add", "key-remove", "key-trust", "key-untrust",
8509 - "self-update",
8510 - "flatpak", "flatpak-install", "flatpak-remove", "flatpak-update",
8511 - "deploy-rollback", "deploy-cleanup", "initramfs-update", "grub-update",
8512 - "snapshot-create", "snapshot-delete", "snapshot-rollback",
8513 - "base", "base-adopt", "base-register",
8514 - "repair",
8515 - }
8516 - if cmd not in WRITE_CMDS:
8517 - # Literówka komendy? (np. `pag instal steam` zamiast `pag install`) –
8518 - # zasugeruj poprawną komendę ZAMIAST wpadać w smart search (który
8519 - # potrafi wisieć na `flatpak search` aż do Ctrl-C).
8520 - _known = set(READ_ONLY) | set(WRITE_CMDS)
8521 - _known.discard("wroom") # easter egg – nie podpowiadaj go w literówkach
8522 - _close = difflib.get_close_matches(cmd, _known, n=1, cutoff=0.75)
8523 - if _close:
8524 - print(_("❌ Unknown command: '{arg1}'. Did you mean '{arg2}'?", arg1=(cmd), arg2=(_close[0])))
8525 - print(_(" Run 'pag' without arguments to see the command list."))
8526 - sys.exit(1)
8527 - sys.exit(_smart_search(" ".join([cmd] + args)) or 0)
8528 -
8529 - # Obsługa flag globalnych (-y/--yes oraz transakcji/snapshotów)
8530 - global_args = []
8531 - for a in args:
8532 - if a in ("-y", "--yes"):
8533 - os.environ["PAG_YES"] = "1"
8534 - elif a == "--dry-run":
8535 - os.environ["PAG_DRY_RUN"] = "1"
8536 - global_args.append(a) # `repair`/`base adopt` czytają flagę
8537 - elif a == "--snapshot":
8538 - os.environ["PAG_SNAPSHOT"] = "always"
8539 - elif a == "--no-snapshot":
8540 - os.environ["PAG_SNAPSHOT"] = "never"
8541 - elif a == "--atomic":
8542 - os.environ["PAG_ATOMIC"] = "1"
8543 - elif a == "--no-atomic":
8544 - os.environ["PAG_ATOMIC"] = "0"
8545 - else:
8546 - global_args.append(a)
8547 - args = global_args
8548 -
8549 - # --- Komendy ZAPISU (wymagają roota) ---
8550 - if os.geteuid() != 0:
8551 - print(f"❌ {_('root_required')}", file=sys.stderr); sys.exit(1)
8552 -
8553 - ensure_dirs()
8554 -
8555 - with DatabaseLock():
8556 - # Auto-naprawa: backup z przerwanej transakcji (bez wpisu „success")
8557 - # -> przywróć brakujące pliki, zanim cokolwiek innego zrobimy.
8558 - _recover_interrupted_transactions()
8559 - WRITE_COMMANDS = {
8560 - "install": lambda: cmd_install(
8561 - [a for a in args if a not in (
8562 - "-f", "--force", "--dry-run", "--snapshot", "--no-snapshot",
8563 - "--atomic", "--no-atomic", "--")],
8564 - upgrade=("-f" in args or "--force" in args)),
8565 - "remove": lambda: cmd_remove(args),
8566 - "update": lambda: cmd_update(do_upgrade=True),
8567 - "sync": lambda: cmd_update(do_upgrade=False),
8568 - "upgrade": cmd_upgrade,
8569 - "clean": cmd_clean,
8570 - "download": lambda: cmd_download(args),
8571 - "autoremove": cmd_autoremove,
8572 - "remove-orphans": cmd_remove_orphans,
8573 - "pin": lambda: cmd_pin(args[0], args[1] if len(args)>1 else ""),
8574 - "unpin": lambda: cmd_unpin(args[0]) if args else print(_('Usage: pag unpin <pkg>')),
8575 - "rollback": cmd_rollback,
8576 - "repair": lambda: cmd_repair(dry_run="--dry-run" in args),
8577 - "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]')),
8578 - "key-add": lambda: cmd_key_add(args[0]) if args else print(_('Usage: pag key-add <url|file>')),
8579 - "key-remove": lambda: cmd_key_remove(args[0]) if args else print(_('Usage: pag key-remove <id>')),
8580 - "key-trust": lambda: cmd_key_trust(args[0]) if args else print(_('Usage: pag key-trust <repo_url>')),
8581 - "key-untrust": lambda: cmd_key_untrust(args[0]) if args else print(_('Usage: pag key-untrust <repo_url>')),
8582 - "self-update": cmd_self_update,
8583 - "flatpak": lambda: cmd_flatpak(args),
8584 - "flatpak-install": lambda: _flatpak_smart_install(args) if args else print(_('Usage: pag flatpak-install <app>')),
8585 - "flatpak-remove": lambda: _flatpak_smart_remove(args) if args else print(_('Usage: pag flatpak-remove <app>')),
8586 - "flatpak-update": cmd_flatpak_update,
8587 - "deploy-rollback": cmd_deploy_rollback,
8588 - "deploy-cleanup": lambda: cmd_deploy_cleanup(int(args[0]) if args else 3),
8589 - "snapshot-create": lambda: cmd_snapshot_create(" ".join(
8590 - a for a in args if not a.startswith("-"))),
8591 - "snapshot-delete": lambda: cmd_snapshot_delete(args[0]) if args else print(
8592 - _('Usage: pag snapshot-delete <id>')),
8593 - "snapshot-rollback": lambda: cmd_snapshot_rollback(
8594 - args[0] if args else ""),
8595 - "initramfs-update": cmd_initramfs_update,
8596 - "grub-update": cmd_grub_update,
8597 - "base": lambda: cmd_base_register(args) if (args and args[0] == "register") else cmd_base_adopt(args),
8598 - "base-adopt": lambda: cmd_base_adopt(args),
8599 - "base-register": lambda: cmd_base_register(args),
8600 - }
8601 -
8602 - fn = WRITE_COMMANDS.get(cmd)
8603 - if fn:
8604 - sys.exit(fn() or 0)
8605 - # Should never reach here – _smart_search handles unknowns
8606 - sys.exit(_smart_search(" ".join([cmd] + args)) or 0)
8607 -
8608 -if __name__ == "__main__":
8609 - try:
8610 - main()
8611 - except KeyboardInterrupt:
8612 - # Ctrl-C (np. podczas flatpak search / pobierania) – bez tracebacka
8613 - print(_('\n ⚠ Interrupted (Ctrl-C).'))
1 +#!/usr/bin/env python3
2 +"""
3 +╔══════════════════════════════════════════════════════════════════════════════╗
4 +║ PAG - Pagan Linux Package Manager v4.2.1 ║
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.1"
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 _fmt_size(n: float) -> str:
148 + """Rozmiar w czytelnych jednostkach (1.2 MB, 345.6 KB)."""
149 + for unit in ("B", "KB", "MB", "GB"):
150 + if n < 1024:
151 + return f"{n:.1f} {unit}"
152 + n /= 1024
153 + return f"{n:.1f} TB"
154 +
155 +
156 +def _fmt_eta(seconds: float) -> str:
157 + """Czas pozostały w zwięzłej formie: 8s, 1.4m, 2.1h."""
158 + if seconds < 60:
159 + return f"{seconds:.0f}s"
160 + if seconds < 3600:
161 + return f"{seconds / 60:.1f}m"
162 + return f"{seconds / 3600:.1f}h"
163 +
164 +
165 +def _shrink_text(text: str, room: int) -> str:
166 + """Skróć `text` do `room` kolumn (wielokropek na końcu)."""
167 + if room <= 0:
168 + return ""
169 + if len(text) <= room:
170 + return text
171 + return "…" if room == 1 else text[:room - 1] + "…"
172 +
173 +
174 +def _fit_widget_line(line: str, stream) -> str:
175 + """Przytnij linię panelu do szerokości terminala (bez zawijania).
176 +
177 + Zawinięta linia rozjeżdża wielolinijkowy panel: kolejne odświeżenia
178 + trafiają do nowych wierszy zamiast nadpisywać poprzednie.
179 + """
180 + cap = _term_width(stream) - _BAR_MARGIN
181 + if cap <= 0 or len(line) <= cap:
182 + return line
183 + keep = cap - 1
184 + head = (keep + 1) // 2
185 + tail = keep - head
186 + return line[:head] + "…" + (line[-tail:] if tail > 0 else "")
187 +
188 +
189 +def _drakkar_bar(pct: float, width: int, t: float, filled: int) -> str:
190 + """Drakkar (łódź wikingów) płynący po falującym morzu.
191 +
192 + - przed łodzią: falujące morze (~ _ przesuwane w czasie),
193 + - dziób łodzi: » (kolumna = bieżący postęp),
194 + - za łodzią: smuga z wędrującym refleksem światła.
195 + """
196 + done = pct >= 100.0
197 + wave = _WAVE_PHASES[int(t * 6) % len(_WAVE_PHASES)]
198 + ship = min(filled, width - 1)
199 + glow = int(t * 10) % ship if ship > 0 else -1
200 + out = []
201 + for i in range(width):
202 + if done:
203 + out.append("»" if i == width - 1 else "█") # łódź zacumowana
204 + elif i < ship:
205 + out.append("█" if i == glow else "▓")
206 + elif i == ship:
207 + out.append("»")
208 + else:
209 + out.append(wave[i & 1])
210 + return "".join(out)
211 +
212 +
213 +def _snake_bar(pct: float, width: int, t: float, filled: int) -> str:
214 + """Jörmungandr – wąż sunący przez pasek (głowa @, łuski o/~, ogon ·)."""
215 + done = pct >= 100.0
216 + head = min(filled, width - 1)
217 + out = []
218 + for i in range(width):
219 + if done:
220 + out.append("@" if i == width - 1 else "o")
221 + elif i < head:
222 + out.append("o" if (i + int(t * 6)) & 1 else "~")
223 + elif i == head:
224 + out.append("@")
225 + else:
226 + out.append("·")
227 + return "".join(out)
228 +
229 +
230 +def _pagan_bar(pct: float, width: int = 30, t: float = 0.0,
231 + style: Optional[str] = None, animated: bool = True) -> str:
232 + """Zwraca jednoliniowy pasek postępu o STAŁEJ szerokości `width`.
233 +
234 + `pct` – postęp 0..100
235 + `t` – czas (s); różne `t` → inna klatka animacji
236 + `animated` – False wymusza klasyczny statyczny pasek (np. brak TTY)
237 + """
238 + width = max(6, int(width))
239 + pct = max(0.0, min(100.0, float(pct)))
240 + style = style or _PAGAN_STYLE
241 + if not animated or not _PAGAN_ANIM or style == "classic":
242 + return _classic_bar(pct, width)
243 + filled = int(round(width * pct / 100.0))
244 + if style == "snake":
245 + return _snake_bar(pct, width, t, filled)
246 + return _drakkar_bar(pct, width, t, filled)
247 +
248 +
249 +class _Bar:
250 + """Baza animowanych pasków: rysują JEDNĄ nadpisywaną linię na `stream`.
251 +
252 + Gdy mamy TTY, wątek w tle odświeża pasek ~10×/s, dzięki czemu morze faluje
253 + także wtedy, gdy postęp chwilowo się nie zmienia.
254 + """
255 + def __init__(self, width: int, stream=None):
256 + self.width = width
257 + self.stream = stream if stream is not None else sys.stderr
258 + self.tty = self.stream.isatty()
259 + self._lock = threading.RLock()
260 + self._last_len = 0
261 + self._stop = threading.Event()
262 + self._thread = None
263 +
264 + # -- wątek animacji -------------------------------------------------------
265 + def _start_anim(self):
266 + if _PAGAN_ANIM and self.tty and self._thread is None:
267 + self._thread = threading.Thread(target=self._anim_loop, daemon=True)
268 + self._thread.start()
269 +
270 + def _anim_loop(self):
271 + while not self._stop.wait(0.1):
272 + with self._lock:
273 + if self._stop.is_set():
274 + break
275 + self._write(self._line())
276 +
277 + def _stop_anim(self):
278 + self._stop.set()
279 + if self._thread is not None:
280 + self._thread.join(timeout=0.3)
281 + self._thread = None
282 +
283 + # -- rysowanie ------------------------------------------------------------
284 + def _cap(self) -> int:
285 + """Maksymalna liczba kolumn jednej linii paska (z zapasem na wrap)."""
286 + return _term_width(self.stream) - _BAR_MARGIN
287 +
288 + def _shrink(self, text: str, fixed: int) -> str:
289 + """Skróć `text` tak, by `text` + `fixed` kolumn zmieściło się w linii."""
290 + room = self._cap() - fixed
291 + if room >= 1 and len(text) > room:
292 + return "…" if room == 1 else text[:room - 1] + "…"
293 + return text
294 +
295 + def _fit(self, line: str) -> str:
296 + """Ostatnia linia obrony: przytnij linię do szerokości terminala.
297 +
298 + Wycinamy ŚRODEK (wielokropek), więc widoczne zostają początek (nazwa)
299 + i koniec (%, prędkość, ETA). Bez tego zawinięta linia = nowa linia przy
300 + każdym odświeżeniu zamiast nadpisywania poprzedniej.
301 + """
302 + cap = self._cap()
303 + if cap <= 0 or len(line) <= cap:
304 + return line
305 + keep = cap - 1 # miejsce na wielokropek „…”
306 + head = (keep + 1) // 2
307 + tail = keep - head
308 + return line[:head] + "…" + (line[-tail:] if tail > 0 else "")
309 +
310 + def _write(self, line: str):
311 + line = self._fit(line)
312 + clear = " " * max(0, self._last_len - len(line))
313 + with _DRAW_LOCK:
314 + self.stream.write(f"\r{line}{clear}")
315 + self.stream.flush()
316 + self._last_len = len(line)
317 +
318 + def _line(self) -> str:
319 + raise NotImplementedError
320 +
321 + def _clear_line(self):
322 + if self.tty and self._last_len:
323 + with _DRAW_LOCK:
324 + self.stream.write("\r" + " " * self._last_len + "\r")
325 + self.stream.flush()
326 + self._last_len = 0
327 +
328 + def _newline(self):
329 + if self.tty and self._last_len:
330 + self.stream.write("\n")
331 + self.stream.flush()
332 + self._last_len = 0
333 +
334 +
335 +class ProgressBar(_Bar):
336 + """Pasek postępu dla N elementów — animowany („drakkar”) na TTY."""
337 + def __init__(self, total: int, desc: str = "", unit: str = "", width: int = 30):
338 + super().__init__(width)
339 + self.total = max(total, 1)
340 + self.desc = desc
341 + self.unit = unit
342 + self.n = 0
343 + self.suffix = ""
344 + self.start = time.time()
345 + self._start_anim()
346 +
347 + def _line(self) -> str:
348 + pct = self.n / self.total * 100
349 + elapsed = time.time() - self.start
350 + speed = self.n / elapsed if elapsed > 0 else 0
351 + if self.n >= self.total:
352 + eta_str = _("done")
353 + elif speed > 0:
354 + eta_str = _fmt_eta((self.total - self.n) / speed)
355 + else:
356 + eta_str = "?..."
357 + bar = _pagan_bar(pct, self.width, time.time(), animated=self.tty)
358 + tail = f" [{bar}] {self.n}/{self.total} ({pct:.0f}%) ETA {eta_str}{self.suffix}"
359 + desc = self._shrink(self.desc, 2 + len(tail))
360 + return f" {desc}{tail}"
361 +
362 + def update(self, n: Optional[int] = None, suffix: str = ""):
363 + with self._lock:
364 + if n is not None:
365 + self.n = n
366 + else:
367 + self.n += 1
368 + self.suffix = suffix
369 + if self.tty:
370 + self._write(self._line())
371 + elif (self.n == 1 or self.n >= self.total
372 + or self.n % max(1, self.total // 10) == 0):
373 + # Bez TTY – tylko kamienie milowe (czysty log)
374 + print(self._line(), file=self.stream)
375 +
376 + def close(self):
377 + self._stop_anim()
378 + with self._lock:
379 + self._newline()
380 +
381 + def __enter__(self):
382 + return self
383 +
384 + def __exit__(self, *args):
385 + self.close()
386 +
387 +
388 +class DownloadBar(_Bar):
389 + """Animowany pasek pobierania (na podstawie Content-Length)."""
390 + def __init__(self, filename: str, total_bytes: int):
391 + super().__init__(25)
392 + self.filename = filename
393 + self.total = total_bytes
394 + self.downloaded = 0
395 + self.start = time.time()
396 + self._start_anim()
397 +
398 + def _line(self) -> str:
399 + pct = self.downloaded / self.total * 100 if self.total > 0 else 0.0
400 + elapsed = time.time() - self.start
401 + speed = self.downloaded / elapsed if elapsed > 0 else 0
402 + if self.total > 0 and speed > 0:
403 + eta_str = _fmt_eta((self.total - self.downloaded) / speed)
404 + else:
405 + eta_str = "?..."
406 + bar = _pagan_bar(pct, self.width, time.time(), animated=self.tty)
407 + sz = _fmt_size(self.total)
408 + spd = _fmt_size(int(speed))
409 + tail = f" [{bar}] {pct:.0f}% {sz} {spd}/s ETA {eta_str}"
410 + # Nazwa pliku bywa długa (np. linux-firmware-…-1.pag) i wtedy CAŁA linia
411 + # nie mieści się w terminalu (zawijanie → nowa linia przy każdym %).
412 + # Skracamy WYŁĄCZNIE nazwę – pełny pasek, prędkość i ETA zostają.
413 + name = self._shrink(self.filename, 4 + len(tail)) # prefiks „ ↓ ” = 4 kolumny
414 + return f" ↓ {name}{tail}"
415 +
416 + def update(self, chunk_size: int):
417 + with self._lock:
418 + self.downloaded += chunk_size
419 + if self.tty and self.total > 0:
420 + self._write(self._line())
421 +
422 + def close(self):
423 + self._stop_anim()
424 + with self._lock:
425 + if self.total > 0:
426 + self._newline()
427 +
428 +
429 +class _ParallelDownloadDisplay:
430 + """Panel pobierania równoległego: pasek zbiorczy + linia na każde pobranie.
431 +
432 + Linia pobrania pokazuje procent, a w nawiasie nazwę pakietu, liczbę
433 + pobranych bajtów i ETA – czyli dokładnie to, czego brakowało przy
434 + równoległym pobieraniu:
435 +
436 + ⏬ [████»~~~~] 4/12 (33%)
437 + ↓ [███»~~~~~~] 38% (mesa: 12.3/29.1 MB, ETA 8s)
438 + ↓ [█████»~~~~] 67% (glibc: 8.8/10.0 MB, ETA 3s)
439 +
440 + Na TTY panel jest rysowany „w miejscu” (ANSI): pasek zbiorczy i aktywne
441 + pobrania są nadpisywane, a ukończone pobrania zostają wypisane na stałe
442 + nad panelem. Poza TTY nie ruszamy kursora – log dostaje linię startu,
443 + kamienie milowe (25/50/75%) i wynik, więc pozostaje czytelny.
444 + """
445 + BAR_W = 20
446 + _POLL = 0.1
447 +
448 + def __init__(self, total: int, stream=None):
449 + self.stream = stream if stream is not None else sys.stderr
450 + self.tty = self.stream.isatty()
451 + self.total = max(1, int(total))
452 + self.completed = 0
453 + self._lock = threading.RLock()
454 + self._slots: Dict[int, dict] = {}
455 + self._next_id = 0
456 + self._drawn = 0
457 + self._stop = threading.Event()
458 + self._thread = None
459 + self._cursor_hidden = False
460 + if self.tty:
461 + self._emit("\x1b[?25l") # ukryj kursor na czas panelu
462 + self._cursor_hidden = True
463 + self._thread = threading.Thread(target=self._anim_loop, daemon=True)
464 + self._thread.start()
465 +
466 + # -- rysowanie -----------------------------------------------------------
467 + def _emit(self, text: str):
468 + with _DRAW_LOCK:
469 + self.stream.write(text)
470 + self.stream.flush()
471 +
472 + def _cap(self) -> int:
473 + return _term_width(self.stream) - _BAR_MARGIN
474 +
475 + def _clear_panel(self):
476 + """Wyczyść panel i ustaw kursor na początku jego pierwszej linii."""
477 + if not self.tty or self._drawn <= 0:
478 + return
479 + out = ["\r\x1b[2K"]
480 + out.extend("\x1b[1A\r\x1b[2K" for _ in range(self._drawn - 1))
481 + self._emit("".join(out))
482 + self._drawn = 0
483 +
484 + def _render_locked(self):
485 + if not self.tty:
486 + return
487 + self._clear_panel()
488 + lines = [self._overall_line()]
489 + lines.extend(self._slot_line(s) for s in self._slots.values())
490 + self._emit("\n".join(lines))
491 + self._drawn = len(lines)
492 +
493 + def _render(self):
494 + with self._lock:
495 + self._render_locked()
496 +
497 + def _anim_loop(self):
498 + while not self._stop.wait(self._POLL):
499 + self._render()
500 +
501 + def _overall_line(self) -> str:
502 + pct = self.completed / self.total * 100.0
503 + bar = _pagan_bar(pct, self.BAR_W, time.time(), animated=self.tty)
504 + line = f" ⏬ [{bar}] {self.completed}/{self.total} ({pct:.0f}%)"
505 + return _fit_widget_line(line, self.stream)
506 +
507 + def _slot_line(self, s: dict) -> str:
508 + total = int(s.get("total") or 0)
509 + done = int(s.get("downloaded") or 0)
510 + pct = (done / total * 100.0) if total > 0 else 0.0
511 + elapsed = time.time() - s["start"]
512 + speed = done / elapsed if elapsed > 0 else 0.0
513 + finished = total > 0 and done >= total
514 + if finished:
515 + eta = _("done")
516 + elif total > 0 and speed > 0:
517 + eta = _fmt_eta((total - done) / speed)
518 + else:
519 + eta = "?…"
520 + bar = _pagan_bar(pct, self.BAR_W, time.time(), animated=self.tty)
521 + prefix = f" ↓ [{bar}] {pct:3.0f}% "
522 + size = (f"{_fmt_size(done)}/{_fmt_size(total)}" if total > 0
523 + else _fmt_size(done))
524 + suffix = (f": {size}, {eta})" if finished
525 + else f": {size}, ETA {eta})")
526 + # Nazwa bywa długa – skracamy TYLKO ją, zostawiając %, rozmiar i ETA.
527 + room = self._cap() - len(prefix) - 1 - len(suffix)
528 + name = _shrink_text(s["name"], room)
529 + return _fit_widget_line(f"{prefix}({name}{suffix}", self.stream)
530 +
531 + # -- API wątków pobierających --------------------------------------------
532 + def start(self, name: str, expected_size: int = 0) -> int:
533 + with self._lock:
534 + sid = self._next_id
535 + self._next_id += 1
536 + self._slots[sid] = {
537 + "name": name,
538 + "downloaded": 0,
539 + "total": int(expected_size or 0),
540 + "start": time.time(),
541 + "milestone": -1,
542 + }
543 + if self.tty:
544 + self._render_locked()
545 + else:
546 + self._emit(f" ↓ {name}\n")
547 + return sid
548 +
549 + def progress(self, sid: int, downloaded: int, total: int = 0):
550 + with self._lock:
551 + s = self._slots.get(sid)
552 + if s is None:
553 + return
554 + s["downloaded"] = int(downloaded)
555 + if total and total > 0:
556 + s["total"] = int(total)
557 + if self.tty:
558 + return # odświeży wątek animacji
559 + total = s["total"]
560 + pct = downloaded / total * 100.0 if total > 0 else 0.0
561 + step = int(pct // 25) * 25
562 + if step > s["milestone"]:
563 + s["milestone"] = step
564 + if total > 0:
565 + detail = f"{_fmt_size(downloaded)}/{_fmt_size(total)}"
566 + else:
567 + detail = _fmt_size(downloaded)
568 + self._emit(f" ↓ {s['name']}: {pct:.0f}% ({detail})\n")
569 +
570 + def finish(self, sid: int, ok: bool = True):
571 + with self._lock:
572 + s = self._slots.pop(sid, None)
573 + if s is None:
574 + return
575 + self.completed += 1
576 + line = self._done_line(s, ok)
577 + if self.tty:
578 + self._clear_panel()
579 + self._emit(line + "\n")
580 + self._render_locked()
581 + else:
582 + self._emit(line + "\n")
583 +
584 + def log(self, text: str):
585 + """Wypisz komunikat (np. ponowienie pobierania) bez psucia panelu."""
586 + with self._lock:
587 + if self.tty:
588 + self._clear_panel()
589 + self._emit(text + "\n")
590 + self._render_locked()
591 + else:
592 + self._emit(text + "\n")
593 +
594 + def _done_line(self, s: dict, ok: bool) -> str:
595 + if not ok:
596 + return f" ❌ {s['name']}: {_('download_fail')}"
597 + total = int(s.get("total") or 0)
598 + size = _fmt_size(total if total > 0 else s.get("downloaded", 0))
599 + elapsed = _fmt_eta(time.time() - s["start"])
600 + return _fit_widget_line(f" ✅ {s['name']} ({size}, {elapsed})",
601 + self.stream)
602 +
603 + def close(self):
604 + self._stop.set()
605 + if self._thread is not None:
606 + self._thread.join(timeout=0.3)
607 + self._thread = None
608 + with self._lock:
609 + if self.tty:
610 + self._clear_panel()
611 + if self._cursor_hidden:
612 + self._emit("\x1b[?25h") # przywróć kursor
613 + self._cursor_hidden = False
614 +
615 +
616 +class _StepBar(_Bar):
617 + """Animowany pasek dla pętli „krok po kroku” (instalacja/aktualizacja).
618 +
619 + Pasek nie skacze skokowo co pakiet – między krokami łagodnie „dopełza”
620 + w stronę kolejnego progu (jak w instalatorach), więc rośnie w sposób
621 + ciągły. Wątek animacji odświeża go ~10×/s.
622 + """
623 + def __init__(self, total: int, icon: str = "", width: int = 25,
624 + creep_tau: float = 3.0):
625 + super().__init__(width)
626 + self.total = max(total, 1)
627 + self.icon = icon
628 + self.creep_tau = creep_tau # „stała czasu” dopełzania (s)
629 + self.idx = 0
630 + self.label = ""
631 + self.t0 = time.time()
632 + self._step_t = time.time() # start bieżącego pakietu
633 + self._start_anim()
634 +
635 + def _frac(self) -> float:
636 + """Ukończona część [0..1]: kroki + wygładzone dopełzanie w bieżącym."""
637 + done = max(0, self.idx - 1)
638 + if done >= self.total:
639 + return 1.0
640 + # 0.5 ** (dt/tau): 0 → ~1 asymptotycznie; cap 0.9, by krok był widoczny
641 + creep = 1.0 - 0.5 ** ((time.time() - self._step_t) / self.creep_tau)
642 + return (done + min(creep, 0.9)) / self.total
643 +
644 + def _line(self) -> str:
645 + pct = self._frac() * 100.0
646 + eta_s = ""
647 + if self.idx > 1:
648 + avg = (time.time() - self.t0) / (self.idx - 1)
649 + rem = avg * (self.total - self.idx + 1)
650 + eta_s = f" ~{rem:.0f}s" if rem < 60 else f" ~{rem/60:.1f}m"
651 + bar = _pagan_bar(pct, self.width, time.time(), animated=self.tty)
652 + tail = f"[{bar}] {self.idx}/{self.total} ({pct:.0f}%) "
653 + label = self._shrink(self.label, 2 + len(self.icon) + len(tail) + len(eta_s))
654 + return f" {self.icon}{tail}{label}{eta_s}"
655 +
656 + def step(self, idx: int, label: str):
657 + with self._lock:
658 + self.idx = idx
659 + self.label = label
660 + self._step_t = time.time()
661 + if self.tty:
662 + self._write(self._line())
663 + else:
664 + print(self._line(), file=self.stream)
665 +
666 + def end(self):
667 + self._stop_anim()
668 + with self._lock:
669 + self._clear_line()
670 +
671 +# =============================================================================
672 +# GPG – BEZPIECZNE WYWOŁYWANIE (odporne na brak binarki gpg)
673 +# =============================================================================
674 +
675 +GPG_BINARY = shutil.which("gpg2") or shutil.which("gpg") or "gpg"
676 +GPG_HOME = "/etc/pag/gpg" # izolowany keyring (działa z keyboxd GPG 2.4+)
677 +
678 +def _ssl_ok() -> bool:
679 + """Czy Python ma działający moduł ssl (HTTPS w urllib).
680 +
681 + Bez niego urllib nie zna schematu https i każda operacja sieciowa kończy
682 + się „unknown url type: https” – myląco, bo wygląda jak błąd adresu.
683 + """
684 + try:
685 + import ssl # noqa: F401
686 + return True
687 + except Exception:
688 + return False
689 +
690 +
691 +def _gpg_run(*args, timeout: int = 30, **kwargs) -> subprocess.CompletedProcess:
692 + """
693 + Bezpieczne wywołanie GPG – przechwytuje FileNotFoundError,
694 + gdyby gpg/gpg2 nie było zainstalowane w minimalnym środowisku.
695 + Wymusza LC_ALL=C aby komunikaty GPG były zawsze po angielsku
696 + (niezależnie od locale systemu) – kluczowe dla parsowania stderr.
697 + """
698 + env = kwargs.pop("env", None) or os.environ.copy()
699 + env["LC_ALL"] = "C"
700 + env["GNUPGHOME"] = GPG_HOME
701 + _text = bool(kwargs.get("text") or kwargs.get("universal_newlines"))
702 + try:
703 + return subprocess.run([GPG_BINARY, *args], timeout=timeout, env=env, **kwargs)
704 + except FileNotFoundError:
705 + # GPG nie jest dostępne – zwróć błąd z komunikatem
706 + # (szanuj text=True – inaczej caller dostaje bytes i może wybuchnąć TypeError)
707 + _text = bool(kwargs.get("text") or kwargs.get("universal_newlines"))
708 + _msg = _("gpg_binary_not_found", GPG_BINARY)
709 + return subprocess.CompletedProcess(
710 + [GPG_BINARY, *args], 127,
711 + stdout=("" if _text else b""),
712 + stderr=(_msg if _text else _msg.encode()),
713 + )
714 + except subprocess.TimeoutExpired:
715 + _msg = _("gpg_timeout")
716 + return subprocess.CompletedProcess(
717 + [GPG_BINARY, *args], 124,
718 + stdout=("" if _text else b""),
719 + stderr=(_msg if _text else _msg.encode())
720 + )
721 +
722 +def _load_trust_db() -> dict:
723 + """Mapa repo_url → fingerprint klucza podpisującego (baza zaufania)."""
724 + try:
725 + with open(TRUST_DB) as f:
726 + return json.load(f)
727 + except (FileNotFoundError, json.JSONDecodeError):
728 + return {}
729 +
730 +
731 +def _save_trust_db(db: dict):
732 + os.makedirs(os.path.dirname(TRUST_DB), exist_ok=True)
733 + with open(TRUST_DB, "w") as f:
734 + json.dump(db, f, indent=2)
735 +
736 +
737 +def _gpg_verify_fp(sig_path: str, data_path: str, timeout: int = 30):
738 + """Weryfikuje podpis i odczytuje fingerprint podpisującego.
739 +
740 + Używa --status-fd=1 i linii VALIDSIG <fingerprint>. Zwraca (ok, fingerprint).
741 +
742 + FAIL-CLOSED: OK tylko gdy GPG zwrócił 0 ORAZ w statusie maszynowym jest
743 + linia VALIDSIG. Nie zakładamy sukcesu na podstawie samego kodu wyjścia –
744 + gdyby format --status-fd się zmienił, wolimy odrzucić podpis niż przyjąć
745 + niezaufany pakiet (wywołujący traktuje fp=None jako brak potwierdzenia).
746 + """
747 + env = os.environ.copy()
748 + res = _gpg_run("--verify", "--status-fd", "1", sig_path, data_path,
749 + capture_output=True, text=True, timeout=timeout, env=env)
750 + out = res.stdout or ""
751 + m = re.search(r"\[GNUPG:\]\s+VALIDSIG\s+([0-9A-Fa-f]{16,})", out)
752 + if not m:
753 + m = re.search(r"\bVALIDSIG\s+([0-9A-Fa-f]{16,})", out)
754 + if res.returncode != 0 or not m:
755 + return False, None
756 + return True, m.group(1).upper()
757 +
758 +
759 +def _verify_local_pkg_signature(pkg_path: str) -> bool:
760 + """Weryfikuje lokalny .pag tym samym kluczem co zaufane repo."""
761 + # PAG_INSECURE=1 – spójnie z _verify_repo_sig() i _verify_pkg_signature().
762 + # Potrzebne w środowisku BUILDA: instalator buduje własne .pag (np. `kernel`)
763 + # lokalnie, nie ma dla nich pliku .asc, a klucza prywatnego repo celowo NIE ma
764 + # na maszynie budującej. Wcześniej ta funkcja jako jedyna ignorowała
765 + # PAG_INSECURE, więc obejście używane przez resztę builda tu nie działało.
766 + if os.environ.get("PAG_INSECURE", "") == "1":
767 + print(_(' ⚠ PAG_INSECURE=1 – skipping local package signature verification'))
768 + return True
769 + sig_path = next((pkg_path + ext for ext in (".asc", ".sig")
770 + if os.path.isfile(pkg_path + ext)), "")
771 + if not sig_path:
772 + print(_(' ❌ No signature for package: {arg1}', arg1=(pkg_path)))
773 + print(_(' A .pag.asc/.pag.sig file from the same source is required.'))
774 + return False
775 + ok, fingerprint = _gpg_verify_fp(sig_path, pkg_path)
776 + if not ok or not fingerprint:
777 + print(_(' ❌ Invalid package signature: {arg1}', arg1=(pkg_path)))
778 + return False
779 + expected = _repo_pinned_fp(DEFAULT_REPOS[0])
780 + if not expected:
781 + print(_(' ❌ No pinned repo key for the local package.'))
782 + print(_(' Run first: sudo pag sync'))
783 + return False
784 + if fingerprint != expected.upper():
785 + print(_(' ❌ [SECURITY ERROR] Package was signed with a different repo key.'))
786 + print(_(' Expected: {arg1}', arg1=(expected)))
787 + print(_(' Received: {arg1}', arg1=(fingerprint)))
788 + return False
789 + print(_(' 🔐 Package signature OK ({arg1})', arg1=(fingerprint)))
790 + return True
791 +
792 +
793 +# =============================================================================
794 +# i18n – WIELOJĘZYCZNOŚĆ
795 +# =============================================================================
796 +
797 +LANG = os.environ.get("LANG", "en_US.UTF-8")[:2] # pl, en, de...
798 +COLOR = os.environ.get("NO_COLOR", "") == "" and sys.stdout.isatty()
799 +
800 +def _c(code: str, text: str) -> str:
801 + """Dodaje kody ANSI jeśli kolor jest włączony."""
802 + if not COLOR:
803 + return text
804 + colors = {
805 + "green": "\033[32m", "red": "\033[31m", "yellow": "\033[33m",
806 + "cyan": "\033[36m", "bold": "\033[1m", "dim": "\033[2m",
807 + "reset": "\033[0m",
808 + }
809 + return f"{colors.get(code,'')}{text}{colors['reset']}"
810 +
811 +T = {
812 + "en": {
813 + "root_required": "pag requires root privileges (sudo).",
814 + "db_locked": "Another pag instance is running.",
815 + "db_lock_hint": "If no other pag process is running, wait a moment and retry.",
816 + "no_index": "Cannot fetch repository indexes. Run 'pag update'.",
817 + "cache_ro": "Repo cache is read-only ({cache}) – using local index (may be outdated).\n Refresh as root: sudo pag sync",
818 + "all_installed": "All packages are already installed.",
819 + "to_install": "To install: {} packages ({:.2f} MB)",
820 + "new": "NEW",
821 + "continue_q": "Continue? [Y/n] ",
822 + "no_tty": "No TTY / stdin closed (EOF) – cancelling.",
823 + "cancelled": "Cancelled.",
824 + "not_found": "not found in repos",
825 + "pkg_not_found": "Package not found: {} (not in any repo)",
826 + "not_found_hint": "Check the spelling or run 'pag search <query>'.",
827 + "downloading": "Downloading",
828 + "done": "done",
829 + "wroom_terminal": "PAG WROOM needs an interactive terminal – run: pag wroom",
830 + "wroom_too_small": "Enlarge the terminal (min. {arg1}x{arg2})",
831 + "wroom_tagline": "PAGAN RACING 4.2.1 · 38911 BYTES FREE",
832 + "wroom_controls": "←/→ lane ↑/↓ gas/brake P pause Q quit",
833 + "wroom_press": "PRESS SPACE TO RACE",
834 + "wroom_over": "RACE OVER",
835 + "wroom_score": "Score: {arg1}",
836 + "wroom_best": "Best: {arg1}",
837 + "wroom_restart": "R / SPACE – race again Q – quit",
838 + "wroom_paused": "PAUSED",
839 + "wroom_hud": "SCORE {arg1:06d} SPEED {arg2:3d} km/h LIVES {arg3}",
840 + "download_fail": "download failed",
841 + "gpg_fail": "GPG verification failed",
842 + "sha256_mismatch": "SHA256 mismatch",
843 + "install_failed": "installation failed",
844 + "installed": "Installed {} packages.",
845 + "rollback_restored": "Restored previous state from snapshot.",
846 + "rollback_files": "Rolled back {} files.",
847 + "no_history": "No transaction history.",
848 + "pinned_list": "Pinned packages ({}):",
849 + "no_pinned": "No pinned packages.",
850 + "pinned_to": "pinned to",
851 + "unpinned": "unpinned.",
852 + "not_pinned": "was not pinned.",
853 + "repo_added": "Added repository: {}",
854 + "repo_exists": "Repository already exists: {}",
855 + "updated_done": "Index refresh complete. {} packages cached.",
856 + "indexes_refreshed": "Indexes refreshed.",
857 + "updates_available": "⚠ {} packages have updates – run: pag update",
858 + "upgrading": "Upgrading: {} packages",
859 + "all_up_to_date": "All packages are up to date.",
860 + "removing": "Removing",
861 + "orphans_found": "Orphaned dependencies ({}): {}",
862 + "flatpak_missing": "Flatpak is not installed.",
863 + "flatpak_adding": "Adding Flathub remote...",
864 + "flatpak_searching": "Searching Flathub for '{}'...",
865 + "flatpak_found": "Found {} results:",
866 + "flatpak_not_found": "not found on Flathub",
867 + "flatpak_install_prompt": "Install {}? [Y/n] ",
868 + "flatpak_installing": "Installing {}...",
869 + "flatpak_installed": "Flatpak {} installed.",
870 + "flatpak_removed": "Flatpak {} removed.",
871 + "flatpak_not_installed": "Flatpak {} is not installed.",
872 + "flatpak_info_id": "ID",
873 + "flatpak_info_version": "Version",
874 + "flatpak_info_branch": "Branch",
875 + "flatpak_info_origin": "Origin",
876 + "flatpak_info_size": "Installed size",
877 + "flatpak_info_desc": "Description",
878 + "flatpak_updated": "Flatpaks updated.",
879 + "flatpak_usage": "Usage: pag flatpak <search|install|remove|list|update|info> [args]",
880 + "flatpak_scope": "Installation",
881 + "flatpak_menu_hint": "Installed and verified, but this session may not show it in the menu: Flatpak exports are missing from XDG_DATA_DIRS.",
882 + "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.",
883 + "key_imported": "Key imported successfully.",
884 + "key_removed": "Key removed: {}",
885 + "no_keys": "No trusted GPG keys.",
886 + "gpg_missing": "GNUPG MISSING – install gnupg and retry",
887 + "ssl_broken": "Python has no working ssl module (HTTPS impossible) – fix the python/openssl packages (e.g. sudo pag install -f python).",
888 + "key_add_failed": "Key import failed (gpg error) – key was NOT added.",
889 + "verify_ok": "All {} files intact.",
890 + "verify_errors": "{} problems found:",
891 + "cache_cleared": "{} files ({:.2f} MB) cleared from cache.",
892 + "deployments_list": "Deployments ({}):",
893 + "no_deployments": "No deployments.",
894 + "active_deployment": "ACTIVE",
895 + "deploy_rollback_ok": "Switched to deployment: {}",
896 + "deploy_rollback_fail": "No previous deployment.",
897 + "deploy_cleanup_ok": "Removed {} old deployments.",
898 + "deploy_cleanup_none": "No deployments to clean (minimum {}).",
899 + "snapshot_none": "No system snapshots.",
900 + "snapshot_list": "System snapshots ({}):",
901 + "snapshot_created": "Snapshot created: {}.",
902 + "snapshot_deleted": "Snapshot removed: {}.",
903 + "snapshot_not_found": "Snapshot not found: {}",
904 + "snapshot_unsupported": "Snapshots unavailable: {}",
905 + "snapshot_rollback_next": "Next boot set to snapshot: {}",
906 + "snapshot_rollback_hint": "Select this entry in the GRUB menu: {}",
907 + "staging_prepare": "Preparing {} packages in staging (system unchanged)...",
908 + "staging_failed": "Staging failed – the system was NOT modified.",
909 + "staging_commit": "All packages prepared – applying changes...",
910 + "grub_refreshed": "GRUB menu refreshed.",
911 + "grub_failed": "GRUB: {}",
912 + "grub_no_initrd": "GRUB: boot entry has no initramfs – check /boot/initramfs-*.img",
913 + "crlf_fixed": "{}: CRLF removed (it broke grub-mkconfig).",
914 + "initramfs_links_fixed": "initramfs symlinks repaired.",
915 + "no_user_sessions": "no active user sessions – user units load at next login.",
916 + "dry_run_done": "Dry run – nothing was changed.",
917 + "dry_run_plan": "Dry run – transaction plan (no changes):",
918 + "why_explicit": "explicitly installed",
919 + "why_dependency": "dependency of",
920 + "why_not_installed": "not installed",
921 + "rdepends_title": "Reverse dependencies of {} ({}):",
922 + "rdepends_none": "nothing depends on it.",
923 + "optional_deps": "Optional dependencies (not installed automatically):",
924 + "autoremove_ok": "Removed {} orphaned packages.",
925 + "autoremove_none": "No orphaned packages.",
926 + "downloaded": "Downloaded {} to cache ({:.2f} MB).",
927 + "provides_mapped": "{} → {} (provides)",
928 + "stats_title": "PAG Statistics",
929 + "stats_packages": "Installed packages",
930 + "stats_files": "Tracked files",
931 + "stats_size": "Total size",
932 + "stats_cache": "Cache size",
933 + "stats_history": "Transactions",
934 + "stats_last_update": "Last update",
935 + # Komunikaty bezpieczeństwa (baza EN; PL w tabeli "pl" jako sec_*_pl)
936 + "sec_downgrade": "Downgrade blocked: {pkg} {new} < {old}",
937 + "sec_suid": "SUID stripped from {path}",
938 + "sec_https": "HTTPS required for repos",
939 + "sec_badname": "Invalid package name: {name}",
940 + "sec_toobig": "Package too large: {size_mb}MB > {max_mb}MB",
941 + "sec_conflict": "File conflict: {path} owned by {owner}",
942 + "sec_audit": "{pkg} installed by {user}",
943 + "sec_locked": "Another pag process is running",
944 + # Konfiguracja (/etc) – zachowanie zmian użytkownika
945 + "conf_pacnew": "Modified config kept; new version saved as {path}",
946 + "conf_pacsave": "Modified config kept as {path}",
947 + # Zależności wirtualne (provides)
948 + "provides_conflict": "Multiple providers for '{name}' ({providers}) – using '{chosen}'",
949 +
950 + # Base baked into the ISO image (pag base / base adopt)
951 + "base_title": "Base from the ISO image",
952 + "base_no_manifest": "This system carries no base manifest (/usr/share/pag/base.json) – nothing to adopt.",
953 + "base_iso_version": "Image version",
954 + "base_total": "Base packages (from image)",
955 + "base_tracked": "Managed by pag",
956 + "base_adoptable": "Adoptable from repo",
957 + "base_unmatched": "No counterpart in repo",
958 + "base_adopt_hint": "Adopt them (image files get replaced by repo packages): sudo pag base adopt",
959 + "base_unmatched_hint": "These stay at the image version (no such package in repo):",
960 + "base_more": "more",
961 + "base_nothing_selected": "None of the given names is on the adopt list.",
962 + "base_all_managed": "Every base package is already managed by pag.",
963 + "base_adopt_plan": "Adopting {} base packages from the repo (~{:.0f} MB):",
964 + "base_dry_run": "Dry run – nothing was installed.",
965 + "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).",
966 + "base_overwrite": "{} comes from the ISO image – its files will be replaced (backup kept for 'pag rollback').",
967 + "base_reboot_hint": "Base adopted from the repo – reboot before using the new libraries/toolchain.",
968 + "base_register_ok": "Registered {} base packages in the package DB ({} were already tracked).",
969 + "base_register_plan": "Dry run – would register {} base packages.",
970 + "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).",
971 + "base_register_renamed": "{} names were matched to their repo package names.",
972 + "stats_base": "Base (image) managed",
973 + },
974 + "pl": {
975 + "root_required": "pag wymaga uprawnień root (sudo).",
976 + "db_locked": "Inna instancja pag jest uruchomiona.",
977 + "db_lock_hint": "Jeśli żaden inny proces pag nie działa, poczekaj chwilę i spróbuj ponownie.",
978 + "no_index": "Nie można pobrać indeksów repozytoriów. Uruchom 'pag update'.",
979 + "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",
980 + "all_installed": "Wszystkie pakiety są już zainstalowane.",
981 + "to_install": "Do zainstalowania: {} pakietów ({:.2f} MB)",
982 + "new": "NOWY",
983 + "continue_q": "Kontynuować? [T/n] ",
984 + "no_tty": "Brak terminala (EOF) – anuluję.",
985 + "cancelled": "Anulowano.",
986 + "not_found": "brak w repozytoriach",
987 + "pkg_not_found": "Nie znaleziono pakietu: {} (brak w repozytoriach)",
988 + "not_found_hint": "Sprawdź pisownię lub uruchom 'pag search <fraza>'.",
989 + "downloading": "Pobieranie",
990 + "done": "gotowe",
991 + "wroom_terminal": "PAG WROOM wymaga terminala – uruchom: pag wroom",
992 + "wroom_too_small": "Powiększ terminal (min. {arg1}x{arg2})",
993 + "wroom_tagline": "PAGAN RACING 4.2.1 · 38911 BAJTÓW WOLNE",
994 + "wroom_controls": "←/→ pas ↑/↓ gaz/hamulec P pauza Q wyjście",
995 + "wroom_press": "NACIŚNIJ SPACJĘ, ABY RUSZYĆ",
996 + "wroom_over": "KONIEC WYŚCIGU",
997 + "wroom_score": "Wynik: {arg1}",
998 + "wroom_best": "Rekord: {arg1}",
999 + "wroom_restart": "R / SPACJA – jeszcze raz Q – wyjście",
1000 + "wroom_paused": "PAUZA",
1001 + "wroom_hud": "WYNIK {arg1:06d} PRĘDKOŚĆ {arg2:3d} km/h ŻYCIA {arg3}",
1002 + "download_fail": "błąd pobierania",
1003 + "gpg_fail": "błąd weryfikacji GPG",
1004 + "sha256_mismatch": "niezgodność SHA256",
1005 + "install_failed": "błąd instalacji",
1006 + "installed": "Zainstalowano {} pakietów.",
1007 + "rollback_restored": "Przywrócono poprzedni stan z migawki.",
1008 + "rollback_files": "Wycofano {} plików.",
1009 + "no_history": "Brak historii transakcji.",
1010 + "pinned_list": "Przypięte pakiety ({}):",
1011 + "no_pinned": "Brak przypiętych pakietów.",
1012 + "pinned_to": "przypięty do",
1013 + "unpinned": "odpięty.",
1014 + "not_pinned": "nie był przypięty.",
1015 + "repo_added": "Dodano repozytorium: {}",
1016 + "repo_exists": "Repozytorium już istnieje: {}",
1017 + "updated_done": "Odświeżanie zakończone. {} pakietów w cache.",
1018 + "indexes_refreshed": "Indeksy odświeżone.",
1019 + "updates_available": "⚠ jest {} pakietów do zaktualizowania – wpisz: pag update",
1020 + "upgrading": "Aktualizacje: {} pakietów",
1021 + "all_up_to_date": "Wszystkie pakiety są aktualne.",
1022 + "removing": "Usuwanie",
1023 + "orphans_found": "Osierocone zależności ({}): {}",
1024 + "flatpak_missing": "Flatpak nie jest zainstalowany.",
1025 + "flatpak_adding": "Dodaję zdalne repozytorium Flathub...",
1026 + "flatpak_searching": "Szukam '{}' we Flathub...",
1027 + "flatpak_found": "Znaleziono {} wyników:",
1028 + "flatpak_not_found": "nie znaleziono we Flathub",
1029 + "flatpak_install_prompt": "Zainstalować {}? [T/n] ",
1030 + "flatpak_installing": "Instalowanie {}...",
1031 + "flatpak_installed": "Flatpak {} zainstalowany.",
1032 + "flatpak_removed": "Flatpak {} usunięty.",
1033 + "flatpak_not_installed": "Flatpak {} nie jest zainstalowany.",
1034 + "flatpak_info_id": "ID",
1035 + "flatpak_info_version": "Wersja",
1036 + "flatpak_info_branch": "Gałąź",
1037 + "flatpak_info_origin": "Źródło",
1038 + "flatpak_info_size": "Rozmiar",
1039 + "flatpak_info_desc": "Opis",
1040 + "flatpak_updated": "Flapaki zaktualizowane.",
1041 + "flatpak_usage": "Użycie: pag flatpak <search|install|remove|list|update|info> [args]",
1042 + "flatpak_scope": "Instalacja",
1043 + "flatpak_menu_hint": "Zainstalowano i zweryfikowano, ale sesja może jej nie pokazać w menu: brak eksportów Flatpaka w XDG_DATA_DIRS.",
1044 + "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.",
1045 + "key_imported": "Klucz zaimportowany pomyślnie.",
1046 + "key_removed": "Klucz usunięty: {}",
1047 + "no_keys": "Brak zaufanych kluczy GPG.",
1048 + "gpg_missing": "BRAK GNUPG – zainstaluj gnupg i spróbuj ponownie",
1049 + "ssl_broken": "Python bez działającego modułu ssl (HTTPS niemożliwe) – napraw pakiety python/openssl (np. sudo pag install -f python).",
1050 + "key_add_failed": "Import klucza nie powiódł się (błąd gpg) – klucz NIE został dodany.",
1051 + "verify_ok": "Wszystkie {} plików sprawne.",
1052 + "verify_errors": "Znaleziono {} problemów:",
1053 + "cache_cleared": "{} plików ({:.2f} MB) usuniętych z cache.",
1054 + "deployments_list": "Deploymenty ({}):",
1055 + "no_deployments": "Brak deploymentów.",
1056 + "active_deployment": "AKTYWNY",
1057 + "deploy_rollback_ok": "Przełączono na deployment: {}",
1058 + "deploy_rollback_fail": "Brak poprzedniego deploymentu.",
1059 + "deploy_cleanup_ok": "Usunięto {} starych deploymentów.",
1060 + "deploy_cleanup_none": "Nie ma deploymentów do wyczyszczenia (minimum {}).",
1061 + "snapshot_none": "Brak snapshotów systemu.",
1062 + "snapshot_list": "Snapshoty systemu ({}):",
1063 + "snapshot_created": "Utworzono snapshot: {}.",
1064 + "snapshot_deleted": "Usunięto snapshot: {}.",
1065 + "snapshot_not_found": "Nie znaleziono snapshotu: {}",
1066 + "snapshot_unsupported": "Snapshoty niedostępne: {}",
1067 + "snapshot_rollback_next": "Następny start ustawiono na snapshot: {}",
1068 + "snapshot_rollback_hint": "Wybierz ten wpis w menu GRUB: {}",
1069 + "staging_prepare": "Przygotowuję {} pakietów w stagingu (system bez zmian)...",
1070 + "staging_failed": "Etap przygotowania nieudany – system NIE został zmieniony.",
1071 + "staging_commit": "Wszystkie pakiety przygotowane – nakładam zmiany...",
1072 + "grub_refreshed": "Menu GRUB odświeżone.",
1073 + "grub_failed": "GRUB: {}",
1074 + "grub_no_initrd": "GRUB: wpis startowy bez initramfs – sprawdź /boot/initramfs-*.img",
1075 + "crlf_fixed": "{}: usunięto CRLF (psuło grub-mkconfig).",
1076 + "initramfs_links_fixed": "Naprawiono dowiązania initramfs.",
1077 + "no_user_sessions": "brak aktywnych sesji użytkownika – jednostki wczytają się przy logowaniu.",
1078 + "dry_run_done": "Dry-run – nic nie zmieniono.",
1079 + "dry_run_plan": "Dry-run – plan transakcji (bez zmian):",
1080 + "why_explicit": "zainstalowany jawnie",
1081 + "why_dependency": "zależność od",
1082 + "why_not_installed": "niezainstalowany",
1083 + "rdepends_title": "Odwrotne zależności {} ({}):",
1084 + "rdepends_none": "nic od niego nie zależy.",
1085 + "optional_deps": "Opcjonalne zależności (nie są instalowane automatycznie):",
1086 + "autoremove_ok": "Usunięto {} osieroconych pakietów.",
1087 + "autoremove_none": "Brak osieroconych pakietów.",
1088 + "downloaded": "Pobrano {} do cache ({:.2f} MB).",
1089 + "sec_downgrade": "Downgrade blocked: {pkg} {new} < {old}",
1090 + "sec_suid": "SUID stripped from {path}",
1091 + "sec_https": "HTTPS required for repos",
1092 + "sec_badname": "Invalid package name: {name}",
1093 + "sec_toobig": "Package too large: {size_mb}MB > {max_mb}MB",
1094 + "sec_conflict": "File conflict: {path} owned by {owner}",
1095 + "sec_audit": "{pkg} installed by {user}",
1096 + "sec_locked": "Another pag process is running",
1097 + "sec_downgrade_pl": "Blokada downgrade: {pkg} {new} < {old}",
1098 + "sec_suid_pl": "SUID usuniety z {path}",
1099 + "sec_https_pl": "Repozytorium wymaga HTTPS",
1100 + "sec_badname_pl": "Nieprawidlowa nazwa pakietu: {name}",
1101 + "sec_toobig_pl": "Paczka za duza: {size_mb}MB > {max_mb}MB",
1102 + "sec_conflict_pl": "Konflikt plikow: {path} nalezy do {owner}",
1103 + "sec_audit_pl": "{pkg} zainstalowany przez {user}",
1104 + "sec_locked_pl": "Inny proces pag juz dziala",
1105 +
1106 + "provides_mapped": "{} → {} (provides)",
1107 + "stats_title": "Statystyki PAG",
1108 + "stats_packages": "Zainstalowane pakiety",
1109 + "stats_files": "Śledzone pliki",
1110 + "stats_size": "Całkowity rozmiar",
1111 + "stats_cache": "Rozmiar cache",
1112 + "stats_history": "Transakcje",
1113 + "stats_last_update": "Ostatnia aktualizacja",
1114 + "conf_pacnew": "Zmieniony plik konfiguracyjny zachowany; nowa wersja: {path}",
1115 + "conf_pacsave": "Zmieniony plik konfiguracyjny zachowany jako {path}",
1116 + "provides_conflict": "Wielu dostawców dla '{name}' ({providers}) – używam '{chosen}'",
1117 +
1118 + # Baza wypalona w obrazie ISO (pag base / base adopt)
1119 + "base_title": "Baza z obrazu ISO",
1120 + "base_no_manifest": "Ten system nie ma manifestu bazy (/usr/share/pag/base.json) – nie ma czego adoptować.",
1121 + "base_iso_version": "Wersja obrazu",
1122 + "base_total": "Pakiety bazy (z obrazu)",
1123 + "base_tracked": "Zarządzane przez pag",
1124 + "base_adoptable": "Do adoptowania z repo",
1125 + "base_unmatched": "Bez odpowiednika w repo",
1126 + "base_adopt_hint": "Adoptuj (pliki z obrazu zostaną zastąpione pakietami z repo): sudo pag base adopt",
1127 + "base_unmatched_hint": "Te zostaną w wersji z obrazu (brak takiego pakietu w repo):",
1128 + "base_more": "więcej",
1129 + "base_nothing_selected": "Żadna z podanych nazw nie jest na liście do adoptowania.",
1130 + "base_all_managed": "Wszystkie pakiety bazy są już zarządzane przez pag.",
1131 + "base_adopt_plan": "Adoptowanie {} pakietów bazy z repo (~{:.0f} MB):",
1132 + "base_dry_run": "Próba na sucho – nic nie zainstalowano.",
1133 + "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).",
1134 + "base_overwrite": "{} pochodzi z obrazu ISO – pliki zostaną zastąpione (kopia zapasowa dla 'pag rollback').",
1135 + "base_reboot_hint": "Baza zaadoptowana z repo – zrestartuj system, zanim zaczniesz używać nowych bibliotek/narzędzi.",
1136 + "base_register_ok": "Zarejestrowano {} pakietów bazy w bazie pakietów ({} już było).",
1137 + "base_register_plan": "Dry-run – zarejestrowałbym {} pakietów bazy.",
1138 + "base_register_nocache": "Brak cache indeksu repo – zostawiono nazwy z buildera (uruchom 'sudo pag sync' i ponownie 'pag base register', aby je zmapować).",
1139 + "base_register_renamed": "{} nazw dopasowano do nazw pakietów w repo.",
1140 + "stats_base": "Baza (obraz) zarządzana",
1141 + },
1142 +}
1143 +
1144 +# ── i18n: komunikaty CLI (msgid = tekst EN) ─────────────────────────────
1145 +_EXTRA_I18N = {
1146 + ' ⚠ PAG_INSECURE=1 – skipping local package signature verification': ' ⚠ PAG_INSECURE=1 – pomijam weryfikację podpisu pakietu lokalnego',
1147 + ' ❌ No signature for package: {arg1}': ' ❌ Brak podpisu dla pakietu: {arg1}',
1148 + ' 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.',
1149 + ' ❌ Invalid package signature: {arg1}': ' ❌ Nieprawidłowy podpis pakietu: {arg1}',
1150 + ' ❌ No pinned repo key for the local package.': ' ❌ Brak przypiętego klucza repo dla lokalnego pakietu.',
1151 + ' Run first: sudo pag sync': ' Uruchom najpierw: sudo pag sync',
1152 + ' ❌ [SECURITY ERROR] Package was signed with a different repo key.': ' ❌ [SECURITY ERROR] Pakiet podpisano innym kluczem repo.',
1153 + ' Expected: {arg1}': ' Oczekiwany: {arg1}',
1154 + ' Received: {arg1}': ' Otrzymany: {arg1}',
1155 + ' 🔐 Package signature OK ({arg1})': ' 🔐 Podpis pakietu OK ({arg1})',
1156 + ' ⚡ Copying the active deployment...': ' ⚡ Kopiowanie aktywnego deploymentu...',
1157 + ' ✅ Deployment: {arg1} ({arg2})': ' ✅ Deployment: {arg1} ({arg2})',
1158 + ' ✅ First deployment: {arg1}': ' ✅ Pierwszy deployment: {arg1}',
1159 + ' ⚠ Cannot create {arg1}: {arg2}': ' ⚠ Nie mogę utworzyć {arg1}: {arg2}',
1160 + ' ⚠ Failed to create snapshot: {arg1}': ' ⚠ Nie udało się utworzyć snapshotu: {arg1}',
1161 + ' ⚠ btrfs snapshot failed: {arg1}': ' ⚠ btrfs snapshot nie udał się: {arg1}',
1162 + ' 📸 System snapshot: {arg1} (subvol={arg2})': ' 📸 Snapshot systemu: {arg1} (subvol={arg2})',
1163 + ' ❌ Invalid snapshot path – refusing to delete.': ' ❌ Nieprawidłowa ścieżka snapshotu – odmawiam usunięcia.',
1164 + ' ⏪ Snapshot: {arg1}': ' ⏪ Snapshot: {arg1}',
1165 + ' 💡 Reboot the system – GRUB will boot the selected snapshot.': ' 💡 Zrestartuj system – GRUB uruchomi wybrany snapshot.',
1166 + ' 💡 At boot, choose an entry in the GRUB menu (snapshots section).': ' 💡 Przy starcie wybierz wpis w menu GRUB (sekcja snapshotów).',
1167 + '❌ Another pag update is in progress – try again later.': '❌ Inna aktualizacja pag jest w toku – spróbuj ponownie później.',
1168 + ' ⚠ Failed to extract {arg1}: {arg2}': ' ⚠ Nie rozpakowano {arg1}: {arg2}',
1169 + ' ⚠ Corrupted index cache {arg1}: {arg2}': ' ⚠ Uszkodzony cache indeksu {arg1}: {arg2}',
1170 + ' ❌ {arg1}: cannot refresh index – {arg2} is read-only': ' ❌ {arg1}: nie można odświeżyć indeksu – {arg2} jest tylko-do-odczytu',
1171 + ' ⚠ HTTP {arg1} for {arg2}': ' ⚠ HTTP {arg1} dla {arg2}',
1172 + ' ⚠ Failed to download index {arg1}: {arg2}': ' ⚠ Błąd pobierania indeksu {arg1}: {arg2}',
1173 + ' ⚠ Index downloaded, but failed to save cache ({arg1}): {arg2}': ' ⚠ Indeks pobrany, ale nie udało się zapisać cache ({arg1}): {arg2}',
1174 + ' ❌ {arg1}: no GPG keys – verification impossible!': ' ❌ {arg1}: brak kluczy GPG – weryfikacja niemożliwa!',
1175 + ' Set PAG_INSECURE=1 to skip (not recommended)': ' Ustaw PAG_INSECURE=1 aby pominąć (niezalecane)',
1176 + ' ❌ {arg1}: CANNOT DOWNLOAD SIGNATURE repo.json.asc/.sig!': ' ❌ {arg1}: NIE MOŻNA POBRAĆ PODPISU repo.json.asc/.sig!',
1177 + ' 🔑 Imported repo key from {arg1}/paganos.asc': ' 🔑 Importowano klucz repo z {arg1}/paganos.asc',
1178 + ' ⚠ {arg1}: invalid GPG signature (PAG_INSECURE – ignoring)': ' ⚠ {arg1}: nieprawidłowy podpis GPG (PAG_INSECURE – ignoruję)',
1179 + ' ❌ {arg1}: GPG is not installed – cannot verify the signature!': ' ❌ {arg1}: GPG nie jest zainstalowane – nie można zweryfikować podpisu!',
1180 + ' Install gnupg or set PAG_INSECURE=1 (not recommended)': ' Zainstaluj gnupg lub ustaw PAG_INSECURE=1 (niezalecane)',
1181 + ' ❌ {arg1}: INVALID GPG SIGNATURE of the repository index!': ' ❌ {arg1}: NIEPRAWIDŁOWY PODPIS GPG indeksu repozytorium!',
1182 + ' ⚠ {arg1}: cannot read signature fingerprint (PAG_INSECURE – ignoring)': ' ⚠ {arg1}: nie można odczytać fingerprintu (PAG_INSECURE – ignoruję)',
1183 + ' ❌ [SECURITY ERROR] {arg1}: cannot read signature fingerprint!': ' ❌ [SECURITY ERROR] {arg1}: nie można odczytać fingerprintu podpisu!',
1184 + ' Pinned key: {arg1} – rejecting the index.': ' Przypięty klucz: {arg1} – odrzucam indeks.',
1185 + ' ⚠ {arg1}: SIGNING KEY CHANGED (PAG_INSECURE – ignoring)': ' ⚠ {arg1}: ZMIENIONY KLUCZ PODPISU (PAG_INSECURE – ignoruję)',
1186 + ' ❌ [SECURITY ERROR] {arg1}: Repository signing key has changed!': ' ❌ [SECURITY ERROR] {arg1}: Klucz podpisujący repo uległ zmianie!',
1187 + ' If this is an intentional key rotation: pag key-trust {arg1}': ' Jeśli to celowa rotacja klucza: pag key-trust {arg1}',
1188 + ' 🔐 Pinned repo fingerprint {arg1}: {arg2}': ' 🔐 Przypięto fingerprint repo {arg1}: {arg2}',
1189 + ' (TOFU – first trust. If the key changes, pag will refuse updates.)': ' (TOFU – pierwsze zaufanie. Gdy klucz się zmieni, pag odmówi aktualizacji.)',
1190 + ' To avoid TOFU, add the fingerprint to /etc/pag/repos.conf.': ' Aby uniknąć TOFU, dopisz fingerprint w /etc/pag/repos.conf.',
1191 + '❌ Download error: {arg1}': '❌ Błąd pobierania: {arg1}',
1192 + '🔐 Pinning repo key {arg1}...': '🔐 Przypinam klucz repo {arg1}...',
1193 + ' ❌ Cannot read signature fingerprint (missing/failed).': ' ❌ Nie można odczytać fingerprintu podpisu (brak/nieudany).',
1194 + ' 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>).',
1195 + ' ✅ Pinned {arg1} for {arg2}': ' ✅ Przypięto {arg1} dla {arg2}',
1196 + ' From now on, a key change will be reported as SECURITY ERROR.': ' Od teraz zmiana klucza zostanie zgłoszona jako SECURITY ERROR.',
1197 + ' ℹ {arg1} has no pinned fingerprint.': ' ℹ {arg1} nie ma przypiętego fingerprintu.',
1198 + ' ✅ Removed pin for {arg1}.': ' ✅ Usunięto przypięcie dla {arg1}.',
1199 + ' ❌ {arg1}: preparation stage failed ({arg2})': ' ❌ {arg1}: etap przygotowania nieudany ({arg2})',
1200 + ' ❌ {arg1}: commit error – {arg2}': ' ❌ {arg1}: błąd commit – {arg2}',
1201 + ' ⚠ ldconfig not found — linker cache was not refreshed.': ' ⚠ Nie znaleziono ldconfig — cache linkera nie został odświeżony.',
1202 + ' ⚠ Failed to refresh ld.so cache: {arg1}': " ⚠ Nie udało się odświeżyć cache'a ld.so: {arg1}",
1203 + ' ⚠ {arg1} shared files preserved': ' ⚠ {arg1} plików współdzielonych zachowanych',
1204 + ' ⚠ {arg1} sensitive system files preserved': ' ⚠ {arg1} wrażliwych plików systemowych zachowanych',
1205 + ' 🧹 Removed {arg1} obsolete files ({arg2})': ' 🧹 Usunięto {arg1} nieaktualnych plików ({arg2})',
1206 + ' 🛠 Interrupted transaction detected – restored {arg1} missing files.': ' 🛠 Wykryto przerwana transakcje – przywrocono {arg1} brakujacych plikow.',
1207 + ' ⚠ Hook skipped (PAG_NO_HOOKS=1): {arg1} for {arg2}': ' ⚠ Hook pominięty (PAG_NO_HOOKS=1): {arg1} dla {arg2}',
1208 + ' ⚠ Hook {arg1} for {arg2} exited with code {arg3}': ' ⚠ Hook {arg1} dla {arg2} zakończony z kodem {arg3}',
1209 + ' ⚠ Hook {arg1} for {arg2} timed out ({arg3}s)': ' ⚠ Hook {arg1} dla {arg2} przekroczył timeout ({arg3}s)',
1210 + ' Increase PAG_HOOK_TIMEOUT (e.g. PAG_HOOK_TIMEOUT=1800) and retry.': ' Zwiększ PAG_HOOK_TIMEOUT (np. PAG_HOOK_TIMEOUT=1800) i spróbuj ponownie.',
1211 + ' ⚠ Hook {arg1} for {arg2}: {arg3}': ' ⚠ Hook {arg1} dla {arg2}: {arg3}',
1212 + 'Recent transactions ({arg1}):': 'Ostatnie transakcje ({arg1}):',
1213 + '❌ No snapshot to restore.': '❌ Brak snapshotu do przywrócenia.',
1214 + '⏪ Rolling back: {arg1} ({arg2})': '⏪ Wycofywanie: {arg1} ({arg2})',
1215 + ' Packages: {arg1}': ' Pakiety: {arg1}',
1216 + ' ❌ Package not found: {arg1}': ' ❌ Nie znaleziono pakietu: {arg1}',
1217 + ' ❌ {arg1}: missing metadata.json': ' ❌ {arg1}: brak metadata.json',
1218 + ' ❌ {arg1}: failed to read package ({arg2})': ' ❌ {arg1}: nie udało się odczytać pakietu ({arg2})',
1219 + ' ↩ Preparation stage failed – the system was NOT changed.': ' ↩ Etap przygotowania nieudany – system NIE został zmieniony.',
1220 + ' ↓ {arg1}-{arg2} (local) ... ': ' ↓ {arg1}-{arg2} (lokalny) ... ',
1221 + ' ❌ Not enough disk space: need ~{arg1} MB, free {arg2} MB ({arg3})': ' ❌ Za mało miejsca na dysku: potrzeba ~{arg1} MB, wolne {arg2} MB ({arg3})',
1222 + ' ⚠ 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)',
1223 + ' ❌ {arg1} is mounted read-only – cannot install.': ' ❌ {arg1} jest zamontowane tylko-do-odczytu – nie można instalować.',
1224 + '❌ Cannot continue – {arg1} missing dependencies.': '❌ Nie można kontynuować – {arg1} brakujących zależności.',
1225 + ' Install the missing packages or add repositories.': ' Zainstaluj brakujące pakiety lub dodaj repozytoria.',
1226 + ' Install the library provider or update the repository.': ' Zainstaluj dostawcę biblioteki lub zaktualizuj repozytorium.',
1227 + '\n 🏗️ Creating a new deployment...': '\n 🏗️ Tworzenie nowego deploymentu...',
1228 + '\n ⏬ Downloading {arg1} packages in parallel...': '\n ⏬ Pobieranie {arg1} pakietów równolegle...',
1229 + '\n 🐧 Finalizing kernel/driver update (DKMS → initramfs → GRUB)...': '\n 🐧 Finalizuję aktualizację jądra/sterowników (DKMS → initramfs → GRUB)...',
1230 + '\n 🐧 Finalizing kernel/driver update in deployment (initramfs)...': '\n 🐧 Finalizuję aktualizację jądra/sterowników w deploymencie (initramfs)...',
1231 + ' ↩ Aborted BEFORE installation – no package was changed.': ' ↩ Przerwano PRZED instalacją – żadna paczka nie została zmieniona.',
1232 + ' ❌ Failed to create snapshot (--snapshot mode) – aborting.': ' ❌ Nie udało się utworzyć snapshotu (tryb --snapshot) – przerywam.',
1233 + '\n ↩ Rolling back transaction ({arg1} errors)...': '\n ↩ Cofanie transakcji ({arg1} błędów)...',
1234 + '\n 🔄 Switching to deployment {arg1}...': '\n 🔄 Przełączanie na deployment {arg1}...',
1235 + ' ✅ Active deployment: {arg1}': ' ✅ Aktywny deployment: {arg1}',
1236 + ' 💡 Restart required to reload the system.': ' 💡 Restart wymagany do przeładowania systemu.',
1237 + ' ⚠ {arg1}: not installed': ' ⚠ {arg1}: nie zainstalowano',
1238 + '✅ ({arg1} files)': '✅ ({arg1} plików)',
1239 + '\n✅ Removed {arg1}.': '\n✅ Usunięto {arg1}.',
1240 + " 'pag remove-orphans' to clean up.": " Uruchom 'pag remove-orphans', aby posprzątać.",
1241 + ' ⚡ Trigger: {arg1} ({arg2})': ' ⚡ Wyzwalacz: {arg1} ({arg2})',
1242 + ' ⚠ trigger {arg1} timed out (120 s)': ' ⚠ trigger {arg1} przekroczył limit czasu (120 s)',
1243 + ' ⚠ trigger {arg1}: {arg2}': ' ⚠ wyzwalacz {arg1}: {arg2}',
1244 + '❌ No repositories configured.': '❌ Brak repozytoriów w konfiguracji.',
1245 + '🔄 Checking for pag update from {arg1}...': '🔄 Sprawdzam aktualizację pag z {arg1}...',
1246 + ' ❌ Cannot download pag: {arg1}': ' ❌ Nie można pobrać pag: {arg1}',
1247 + ' ⚠ Invalid update signature (PAG_INSECURE – ignoring)': ' ⚠ Nieprawidłowy podpis aktualizacji (PAG_INSECURE – ignoruję)',
1248 + ' ❌ Invalid update signature – not updating.': ' ❌ Nieprawidłowy podpis aktualizacji – nie aktualizuję.',
1249 + ' ❌ Cannot confirm the update signature fingerprint.': ' ❌ Nie można potwierdzić fingerprintu podpisu aktualizacji.',
1250 + ' ⚠ Update signed with a different key (PAG_INSECURE – ignoring)': ' ⚠ Podpis aktualizacji innym kluczem (PAG_INSECURE – ignoruję)',
1251 + ' ❌ [SECURITY ERROR] Update signed with a different key than the repo!': ' ❌ [SECURITY ERROR] Podpis aktualizacji innym kluczem niż repo!',
1252 + ' Expected: {arg1}, received: {arg2}': ' Oczekiwany: {arg1}, Otrzymany: {arg2}',
1253 + ' ❌ SHA256 mismatch! Expected {arg1}, got {arg2}': ' ❌ SHA256 niezgodny! Oczekiwano {arg1}, jest {arg2}',
1254 + ' ✅ SHA256 matches': ' ✅ SHA256 zgodny',
1255 + ' ❌ Syntax error in new pag: {arg1}': ' ❌ Błąd składni w nowym pag: {arg1}',
1256 + ' ✅ Downloaded pag {arg1} (current {arg2}), signature verified': ' ✅ Pobrano pag {arg1} (obecny {arg2}), podpis zweryfikowany',
1257 + ' ✅ Installed new pag. Old version kept as {arg1}': ' ✅ Zainstalowano nowy pag. Stary zachowany jako {arg1}',
1258 + ' ⚠ A different pag is first in PATH: {arg1} (updated {arg2})': ' ⚠ W PATH pierwszy jest inny pag: {arg1} (zaktualizowano {arg2})',
1259 + ' Remove the old copy: sudo rm {arg1}': ' Usuń starą kopię: sudo rm {arg1}',
1260 + ' Restart pag to use the new version.': ' Uruchom ponownie pag, aby użyć nowej wersji.',
1261 + '🔄 Refreshing indexes...': '🔄 Odświeżanie indeksów...',
1262 + ' {arg1} {arg2}: {arg3} packages {arg4}': ' {arg1} {arg2}: {arg3} pakietów {arg4}',
1263 + ' ⚠ New pag version {arg1} available – run: pag self-update': ' ⚠ Nowa wersja pag {arg1} dostępna – uruchom: pag self-update',
1264 + ' 🐧 Rebuilding initramfs (newer kernel)...': ' 🐧 Przebudowa initramfs (nowsze jądro)...',
1265 + 'No packages installed.': 'Brak zainstalowanych pakietów.',
1266 + 'Installed ({arg1}):': 'Zainstalowane ({arg1}):',
1267 + 'Available ({arg1}):': 'Dostępne ({arg1}):',
1268 + '❌ No results for: {arg1}': '❌ Brak wyników dla: {arg1}',
1269 + "Results for '{arg1}' ({arg2}):": "Wyniki dla '{arg1}' ({arg2}):",
1270 + "\n ❌ '{arg1}' — not found.": "\n ❌ '{arg1}' — nie znaleziono.",
1271 + ' PaganOS repo: pag search {arg1}': ' Repo PaganOS: pag search {arg1}',
1272 + ' Flathub: pag flatpak search {arg1}': ' Flathub: pag flatpak search {arg1}',
1273 + ' Add repo: pag repo-add <url>': ' Dodaj repo: pag repo-add <url>',
1274 + ' ... and {arg1} more (pag search {arg2})': ' ... i {arg1} więcej (pag search {arg2})',
1275 + ' ... and {arg1} more (pag flatpak search {arg2})': ' ... i {arg1} więcej (pag flatpak search {arg2})',
1276 + ' ✓ {arg1} is already installed ({arg2})': ' ✓ {arg1} jest już zainstalowany ({arg2})',
1277 + "❌ '{arg1}' not found.": "❌ Nie znaleziono '{arg1}'.",
1278 + ' Version (repo): {arg1}': ' Wersja (repo): {arg1}',
1279 + ' Description: {arg1}': ' Opis: {arg1}',
1280 + ' Size: {arg1:.1f} MB': ' Rozmiar: {arg1:.1f} MB',
1281 + ' SHA256: {arg1}...': ' SHA256: {arg1}...',
1282 + ' GPG: {arg1}': ' GPG: {arg1}',
1283 + ' Dependencies: {arg1}': ' Zależności: {arg1}',
1284 + ' Installed: {arg1} ({arg2})': ' Zainstalowany: {arg1} ({arg2})',
1285 + "❌ '{arg1}' not installed.": "❌ '{arg1}' nie jest zainstalowany.",
1286 + 'Files in {arg1} ({arg2}):': 'Pliki w {arg1} ({arg2}):',
1287 + 'Nothing to repair (no packages installed).': 'Nic do naprawy (brak zainstalowanych pakietow).',
1288 + '✅ All files are in place – nothing to repair.': '✅ Wszystkie pliki na miejscu – nic do naprawy.',
1289 + '🔧 Packages with missing files: {arg1} (total {arg2} files)': '🔧 Pakiety z brakujacymi plikami: {arg1} (lacznie {arg2} plikow)',
1290 + '\n(--dry-run: nothing is changed)': '\n(--dry-run: nic nie zmieniam)',
1291 + '\n🔧 repair: {arg1}': '\n🔧 naprawa: {arg1}',
1292 + '⚠ Repaired {arg1}/{arg2}. Failed: {arg3}': '⚠ Naprawiono {arg1}/{arg2}. Nie udalo sie: {arg3}',
1293 + '✅ Repaired {arg1} packages.': '✅ Naprawiono {arg1} pakietow.',
1294 + 'Nothing to verify.': 'Nie ma czego weryfikować.',
1295 + '✅ No orphans.': 'Brak osieroconych pakietów.',
1296 + 'Orphans ({arg1}):': 'Osierocone ({arg1}):',
1297 + ' ⚠ Search error: {arg1}': ' ⚠ Błąd wyszukiwania: {arg1}',
1298 + '\n Choose a number (1-{arg1}) or press Enter to cancel:': '\n Wybierz numer (1-{arg1}) lub Enter aby anulować: ',
1299 + " 📦 {arg1} – already installed (use 'pag flatpak info {arg2}' for details)": " 📦 {arg1} – już zainstalowany (szczegóły: 'pag flatpak info {arg2}')",
1300 + "\n Multiple matches for '{arg1}':": "\n Wiele dopasowań dla '{arg1}':",
1301 + '\n Choose a number (1-{arg1}) or press Enter:': '\n Wybierz numer (1-{arg1}) lub Enter: ',
1302 + ' ... and {arg1} more. Refine your query.': ' ... i {arg1} więcej. Doprecyzuj zapytanie.',
1303 + '\n Choose a number to install (1-{arg1}) or press Enter to cancel:': '\n Wybierz numer do zainstalowania (1-{arg1}) lub Enter aby anulować: ',
1304 + ' (no installed flatpaks)': ' (brak zainstalowanych flatpaków)',
1305 + 'Installed flatpaks ({arg1}):': ' Zainstalowane flatpaki ({arg1}):',
1306 + ' 🔄 Updating flatpaks...': ' 🔄 Aktualizacja flatpaków...',
1307 + '\n 💡 To install: pag flatpak install {arg1}': '\n 💡 Aby zainstalować: pag flatpak install {arg1}',
1308 + ' 🔧 DKMS: rebuilding out-of-tree modules (nvidia/vbox)...': ' 🔧 DKMS: przebudowa modułów out-of-tree (nvidia/vbox)...',
1309 + ' 🔧 Rebuilding initramfs (pagan-initramfs)...': ' 🔧 Przebudowa initramfs (pagan-initramfs)...',
1310 + ' 🔧 Rebuilding initramfs (dracut)...': ' 🔧 Przebudowa initramfs (dracut)...',
1311 + ' 🔧 Rebuilding initramfs (mkinitcpio)...': ' 🔧 Przebudowa initramfs (mkinitcpio)...',
1312 + ' ⚠ No dracut/mkinitcpio – initramfs was not rebuilt': ' ⚠ Brak dracut/mkinitcpio – initramfs nie został przebudowany',
1313 + ' 🔧 Building initramfs for the deployment...': ' 🔧 Budowanie initramfs dla deploymentu...',
1314 + ' ⚠ pag-initramfs-init not found – skipping initramfs build': ' ⚠ Nie znaleziono pag-initramfs-init – pomijam budowę initramfs',
1315 + " ⚠ No vmlinuz-* found in the deployment's /boot": ' ⚠ Nie znaleziono vmlinuz-* w /boot deploymentu',
1316 + ' 🐧 Kernel: {arg1}': ' 🐧 Jądro: {arg1}',
1317 + ' ⚠ Skipping unavailable files: {arg1}': ' ⚠ Pomijam niedostępne pliki: {arg1}',
1318 + ' ⚠ Skipping unavailable file: {arg1}': ' ⚠ Pomijam niedostępny plik: {arg1}',
1319 + ' ✅ initramfs.img ({arg1:.1f} MB) → {arg2}': ' ✅ initramfs.img ({arg1:.1f} MB) → {arg2}',
1320 + ' ❌ initramfs build error: {arg1}': ' ❌ Błąd budowy initramfs: {arg1}',
1321 + '🏗️ Deployment: {arg1}': '🏗️ Deployment: {arg1}',
1322 + '✅ Initramfs updated.': '✅ Initramfs zaktualizowany.',
1323 + '❌ Initramfs update failed.': '❌ Błąd aktualizacji initramfs.',
1324 + ' 📋 Regenerating GRUB (grub-mkconfig)...': ' 📋 Regeneracja GRUB (grub-mkconfig)...',
1325 + ' ⚠ Could not detect the root partition – GRUB entries will have no root=.': ' ⚠ Nie udało się wykryć partycji root – wpisy GRUB nie dostaną root=.',
1326 + ' Set PAG_ROOT_DEVICE=/dev/... (or PAG_GRUB_ROOT) and retry.': ' Ustaw PAG_ROOT_DEVICE=/dev/... (lub PAG_GRUB_ROOT) i powtórz.',
1327 + ' 📋 GRUB config updated – entries for each deployment': ' 📋 GRUB config zaktualizowany – wpisy dla każdego deploymentu',
1328 + '📋 Updating GRUB configuration...': '📋 Aktualizacja konfiguracji GRUB...',
1329 + '✅ GRUB updated.': '✅ GRUB zaktualizowany.',
1330 + ' +{arg1} more...': ' +{arg1} więcej...',
1331 + '❌ Deployment {arg1} does not exist on disk': '❌ Deployment {arg1} nie istnieje na dysku',
1332 + '⏪ Restoring deployment: {arg1}': '⏪ Przywracanie deploymentu: {arg1}',
1333 + '\n❌ {arg1} – cannot install:': '\n❌ {arg1} – nie można zainstalować:',
1334 + ' {arg1} → needs {arg2} (missing from repositories)': ' {arg1} → potrzebuje {arg2} (brak w repozytoriach)',
1335 + '\n⚠ {arg1} – will be installed as dependencies:': '\n⚠ {arg1} – zostaną doinstalowane:',
1336 + ' {arg1} → {arg2} ({arg3} – will be downloaded)': ' {arg1} → {arg2} ({arg3} – będzie pobrane)',
1337 + ' {arg1} → requires {arg2} – no package provides this version': ' {arg1} → wymaga {arg2} – żaden pakiet nie dostarcza tej wersji',
1338 + ' ↻ Retrying download of {arg1} ({arg2}/{arg3})...': ' ↻ Ponawiam pobieranie {arg1} ({arg2}/{arg3})...',
1339 + ' ⚠ Download error {arg1}: {arg2}': ' ⚠ Błąd pobierania {arg1}: {arg2}',
1340 + '❌ Format: spdx | cyclonedx': '❌ Format: spdx | cyclonedx',
1341 + ' ✓ {arg1} ({arg2} keys)': ' ✓ {arg1} ({arg2} kluczy)',
1342 + 'Usage: pag search <query>': 'Użycie: pag search <query>',
1343 + 'Usage: pag info <pkg>': 'Użycie: pag info <pkg>',
1344 + 'Usage: pag files <pkg>': 'Użycie: pag files <pkg>',
1345 + 'Usage: pag why <pkg>': 'Użycie: pag why <pkg>',
1346 + 'Usage: pag rdepends <pkg>': 'Użycie: pag rdepends <pkg>',
1347 + 'Usage: pag flatpak-search <query>': 'Użycie: pag flatpak-search <query>',
1348 + 'Usage: pag flatpak-info <id>': 'Użycie: pag flatpak-info <id>',
1349 + "❌ Unknown command: '{arg1}'. Did you mean '{arg2}'?": "❌ Nieznana komenda: '{arg1}'. Czy chodziło o '{arg2}'?",
1350 + " Run 'pag' without arguments to see the command list.": " Uruchom 'pag' bez argumentów, aby zobaczyć listę komend.",
1351 + 'Usage: pag unpin <pkg>': 'Użycie: pag unpin <pkg>',
1352 + 'Usage: pag repo-add <url> [name]': 'Użycie: pag repo-add <url> [name]',
1353 + 'Usage: pag key-add <url|file>': 'Użycie: pag key-add <url|file>',
1354 + 'Usage: pag key-remove <id>': 'Użycie: pag key-remove <id>',
1355 + 'Usage: pag key-trust <repo_url>': 'Użycie: pag key-trust <repo_url>',
1356 + 'Usage: pag key-untrust <repo_url>': 'Użycie: pag key-untrust <repo_url>',
1357 + 'Usage: pag flatpak-install <app>': 'Użycie: pag flatpak-install <app>',
1358 + 'Usage: pag flatpak-remove <app>': 'Użycie: pag flatpak-remove <app>',
1359 + 'Usage: pag snapshot-delete <id>': 'Użycie: pag snapshot-delete <id>',
1360 + '\n ⚠ Interrupted (Ctrl-C).': '\n ⚠ Przerwano (Ctrl-C).',
1361 +}
1362 +for _msgid, _pl in _EXTRA_I18N.items():
1363 + T["en"].setdefault(_msgid, _msgid)
1364 + T["pl"].setdefault(_msgid, _pl)
1365 +
1366 +_AUX_I18N = {
1367 + 'installed_marker': ('installed', 'zainstalowany'),
1368 + 'none_value': ('none', 'brak'),
1369 + 'none_parenthesized': ('(none)', '(brak)'),
1370 + 'stats_top': ('Top 5:', 'Największe 5:'),
1371 + 'never': ('never', 'nigdy'),
1372 + 'action_install': ('install', 'instalacja'),
1373 + 'action_upgrade': ('upgrade', 'aktualizacja'),
1374 + 'action_remove': ('remove', 'usunięcie'),
1375 + 'action_rollback': ('rollback', 'wycofanie'),
1376 + 'action_manual': ('manual', 'ręczny'),
1377 + 'action_repair': ('repair', 'naprawa'),
1378 + 'flatpak_searching_any': ('Searching Flathub...', 'Szukam we Flathub...'),
1379 + 'upgrade_marker': ('[upgrade]', '[aktualizacja]'),
1380 + 'hardlink_method': ('hardlinks', 'hardlinki'),
1381 + 'copy_method': ('full copy', 'pełna kopia'),
1382 + 'reflink_method': ('CoW (reflink)', 'CoW (reflink)'),
1383 + 'verify_missing_file': (' ❌ {}: missing {}', ' ❌ {}: brakuje {}'),
1384 + 'verify_sha_mismatch': (' ❌ {}: SHA256 mismatch {}', ' ❌ {}: niezgodność SHA256 {}'),
1385 + 'gpg_binary_not_found': ('GPG binary not found ({})', 'Nie znaleziono binarki GPG ({})'),
1386 + 'gpg_timeout': ('GPG operation timed out', 'Operacja GPG przekroczyła limit czasu'),
1387 + 'audio_services_reloaded': (' ⚡ audio services reloaded for sessions: {}', ' ⚡ przeładowano usługi audio dla sesji: {}'),
1388 + 'grub_fallback_label': ('Pagan Linux – fallback (plain root)', 'Pagan Linux – fallback (zwykły root)'),
1389 + 'done': ('done', 'gotowe'),
1390 + 'deploy_copy_failed': ('Failed to copy the deployment by any method', 'Nie udało się skopiować deploymentu żadną metodą'),
1391 + 'pkg_missing_data_tar': ('missing data.tar.xz in package', 'brak data.tar.xz w pakiecie'),
1392 + 'pkg_sha_mismatch': ('SHA256 mismatch: {}', 'niezgodność SHA256: {}'),
1393 + 'repo_index_invalid': ("missing 'packages' list", "brak listy 'packages'"),
1394 +}
1395 +for _k, (_en, _pl) in _AUX_I18N.items():
1396 + T["en"].setdefault(_k, _en)
1397 + T["pl"].setdefault(_k, _pl)
1398 +
1399 +# ── Tłumaczenia z PLIKÓW (nadpisują/rozszerzają wbudowane PL/EN) ─────────────
1400 +# Kolejność: PAG_LANG_DIR (env) → /etc/pag/lang → /usr/share/pag/lang →
1401 +# ./pag-lang obok binarki (dev). Brak plików NIE jest błędem – zostaje
1402 +# wbudowany słownik T (fallback), więc pag zawsze działa.
1403 +# Przykład pliku (pag-lang/pl.json): {"app_title": "...", "usage": "..."}.
1404 +def _load_lang_files() -> None:
1405 + # PAG_LANG_NO_FILES=1 → pomiń pliki (używane przy eksporcie --lang-extract,
1406 + # żeby wyeksportować CZYSTE wbudowane słowniki, bez starych nadpisań).
1407 + if os.environ.get("PAG_LANG_NO_FILES") == "1":
1408 + return
1409 + dirs = []
1410 + _env = os.environ.get("PAG_LANG_DIR")
1411 + if _env:
1412 + dirs.append(_env)
1413 + # __file__ bywa niedostępne, gdy moduł jest exec/frozen (np. harness
1414 + # instalacyjny) – liczymy wtedy od ścieżki programu, zamiast wywalać
1415 + # NameError przy samym imporcie.
1416 + _self = globals().get("__file__") or sys.argv[0] or "pag"
1417 + dirs += ["/etc/pag/lang", "/usr/share/pag/lang",
1418 + os.path.join(os.path.dirname(os.path.abspath(_self)), "pag-lang")]
1419 + for _d in dirs:
1420 + for _code in list(T.keys()) + ["pl", "en", "de"]:
1421 + _p = os.path.join(_d, f"{_code}.json")
1422 + try:
1423 + with open(_p, "r", encoding="utf-8") as _fh:
1424 + _data = json.load(_fh)
1425 + if isinstance(_data, dict):
1426 + # Merge (nie replace): klucze nieobecne w pliku zachowują
1427 + # wbudowane tłumaczenie. Puste wartości pomijamy, żeby
1428 + # niekompletny/uszkodzony plik nie wyczyścił komunikatu.
1429 + _clean = {str(k): str(v) for k, v in _data.items()
1430 + if str(v).strip()}
1431 + T.setdefault(_code, {}).update(_clean)
1432 + except (OSError, ValueError):
1433 + continue
1434 +
1435 +
1436 +_load_lang_files()
1437 +
1438 +def _(key: str, *args, **kwargs) -> str:
1439 + """Tłumaczy klucz i formatuje argumenty.
1440 +
1441 + Dla LANG=pl preferuje wariant „<key>_pl” (np. komunikaty bezpieczeństwa
1442 + mają krótkie wersje PL obok bazy EN), potem zwykły klucz, potem EN/klicz.
1443 + """
1444 + if LANG == "pl":
1445 + _pl = T.get("pl", {})
1446 + msg = _pl.get(key + "_pl") or _pl.get(key) or T["en"].get(key, key)
1447 + else:
1448 + msg = T.get(LANG, T["en"]).get(key, T["en"].get(key, key))
1449 + if args or kwargs:
1450 + return msg.format(*args, **kwargs)
1451 + return msg
1452 +
1453 +
1454 +def _ask_confirm() -> bool:
1455 + """Pytanie potwierdzające (T/n). PAG_YES=1 → zawsze tak.
1456 +
1457 + EOF/brak terminala (stdin zamknięty, np. ssh bez TTY, cron, subprocess
1458 + panelu webowego) → NIE – anuluj, nie wykonuj operacji bez potwierdzenia
1459 + (inaczej input() rzuca EOFError i pag pada tracebackiem).
1460 + Enter → tak (domyślne Y/n).
1461 + """
1462 + if os.environ.get("PAG_YES", "") == "1":
1463 + print(_("continue_q") + " t (--yes)")
1464 + return True
1465 + try:
1466 + ans = input(_("continue_q")).strip().lower()
1467 + except (EOFError, KeyboardInterrupt):
1468 + print(f"\n ⚠ {_('no_tty')}")
1469 + return False
1470 + return not ans or ans in ("t", "y")
1471 +
1472 +
1473 +# =============================================================================
1474 +# ŚCIEŻKI
1475 +# =============================================================================
1476 +PAG_ROOT = os.environ.get("PAG_ROOT", "/")
1477 +PAG_DB = "/var/lib/pag"
1478 +PAG_CACHE = "/var/cache/pag"
1479 +PAG_CONF = "/etc/pag"
1480 +REPO_CACHE = "/var/cache/pag/repos"
1481 +REPOS_CONF = "/etc/pag/repos.conf"
1482 +REPOS_DIR = PAG_CONF + "/repos" # drop-in: /etc/pag/repos/<nazwa>.conf
1483 +INSTALLED_DB = "/var/lib/pag/installed.json"
1484 +FILES_DB_SQL = "/var/lib/pag/files.db" # SQLite!
1485 +WORLD_FILE = "/var/lib/pag/world"
1486 +PINNED_FILE = "/var/lib/pag/pinned.json"
1487 +HISTORY_FILE = "/var/lib/pag/history.json"
1488 +LOCK_FILE = "/var/lib/pag/pag.lock"
1489 +STAGING_DIR = "/.pag_staging" # na tej samej partycji co / (unikamy EXDEV)
1490 +PKG_EXT = ".pag"
1491 +REPO_CACHE_TTL = 3600
1492 +MAX_PKG_SIZE = 2 * 1024 * 1024 * 1024 # 2 GB – maksymalny rozmiar paczki
1493 +BASE_MANIFEST = "/usr/share/pag/base.json" # baza z obrazu ISO (pag base/adopt)
1494 +
1495 +# ── UPRZYWILEJOWANE PLIKI ────────────────────────────────────────────────────
1496 +# Domyślnie pag zdejmuje bit SUID i wymusza właściciela root:root. Niektóre
1497 +# programy MUSZĄ jednak zachować setuid/setgid albo grupę inną niż root
1498 +# (/usr/bin/sudo, /usr/bin/passwd, /usr/bin/unix_chkpwd,
1499 +# /usr/lib/dbus-daemon-launch-helper). Bez tego tracą możliwość działania
1500 +# po aktualizacji przez pag (np. użytkownik nie zmieni hasła).
1501 +#
1502 +# Bezpieczeństwo: zawartość pakietu jest uwierzytelniona (podpis GPG repo +
1503 +# przypięty fingerprint + SHA256 całego pakietu), więc metadane w nim są
1504 +# zaufane tak samo jak same pliki. Zachowujemy uprawnienia WYŁĄCZNIE dla
1505 +# ścieżek z tej listy (albo z pola `privileged:` receptury, które pagbuild
1506 +# zapisuje w metadata.json).
1507 +PRIVILEGED_PATHS = frozenset({
1508 + "/usr/bin/cdda2wav", "/usr/bin/cdrecord",
1509 + "/usr/bin/chage", "/usr/bin/expiry",
1510 + "/usr/bin/fcrondyn", "/usr/bin/fcronsighup", "/usr/bin/fcrontab",
1511 + "/usr/bin/firejail", "/usr/bin/fping",
1512 + "/usr/bin/fusermount", "/usr/bin/fusermount3",
1513 + "/usr/bin/gpasswd", "/usr/bin/ksu", "/usr/bin/lockfile",
1514 + "/usr/bin/mount", "/usr/bin/mount.nfs",
1515 + "/usr/bin/newgidmap", "/usr/bin/newuidmap",
1516 + "/usr/bin/passwd", "/usr/bin/ping", "/usr/bin/ping6",
1517 + "/usr/bin/procmail", "/usr/bin/readcd", "/usr/bin/rscsi",
1518 + "/usr/bin/screen", "/usr/bin/screen-5.0.2",
1519 + "/usr/bin/sg", "/usr/bin/su", "/usr/bin/sudo", "/usr/bin/traceroute",
1520 + "/usr/bin/umount", "/usr/bin/unix_chkpwd", "/usr/bin/wall",
1521 + "/usr/lib/dbus-daemon-launch-helper",
1522 + "/usr/lib/httpd/suexec",
1523 + "/usr/lib/utempter/utempter",
1524 + "/usr/lib/xscreensaver/xscreensaver-auth",
1525 + "/usr/libexec/libgtop_server2",
1526 + "/usr/libexec/qemu-bridge-helper",
1527 + "/usr/libexec/ssh-keysign",
1528 + "/usr/libexec/xf86-video-intel-backlight-helper",
1529 + "/opt/google/chrome/chrome-sandbox",
1530 + "/opt/gitkraken/chrome-sandbox",
1531 + "/opt/VirtualBox/VBoxHeadless", "/opt/VirtualBox/VBoxNetAdpCtl",
1532 + "/opt/VirtualBox/VBoxNetDHCP", "/opt/VirtualBox/VBoxVolInfo",
1533 + "/opt/VirtualBox/VirtualBoxVM",
1534 +})
1535 +ALLOWED_PKG_RE = re.compile(r'^[a-zA-Z0-9][a-zA-Z0-9._+@-]*$')
1536 +
1537 +# Bezpieczeństwo / audyt
1538 +AUDIT_LOG = "/var/log/pag/audit.log" # dziennik operacji krytycznych (hooki, self-update)
1539 +TRUST_DB = "/etc/pag/trusted.json" # mapa repo_url → fingerprint klucza podpisującego
1540 +HOOK_API_VERSION = "1" # wersjonowane API hooków (env PKG_HOOK_API)
1541 +
1542 +# =============================================================================
1543 +# IMMUTABLE OS – DEPLOYMENTY
1544 +# =============================================================================
1545 +# Model: zamiast mutować /, każda operacja tworzy NOWY deployment.
1546 +# /var, /etc, /home są współdzielone między deploymentami.
1547 +#
1548 +# STRUKTURA:
1549 +# /.deployments/
1550 +# active → 20260723T120000 (symlink do aktywnego)
1551 +# 20260723T120000/
1552 +# usr/ bin/ lib/ lib64/ ... (pełny system)
1553 +# var → /var (symlink do współdzielonego)
1554 +# etc → /etc
1555 +# home → /home
1556 +# ...
1557 +#
1558 +# Jak to działa:
1559 +# 1. pag install → kopiuje active → nowy deployment + nakłada zmiany → switch symlinka
1560 +# 2. pag remove → kopiuje active → nowy deployment - usuwa pliki → switch symlinka
1561 +# 3. pag deploy-rollback → przełącza active symlink na poprzedni deployment
1562 +# 4. Przy starcie systemu: initrd montuje /.deployments/active jako /
1563 +# =============================================================================
1564 +
1565 +DEPLOYMENTS_DIR = "/.deployments"
1566 +ACTIVE_LINK = "/.deployments/active"
1567 +DEPLOYMENTS_DB = "/var/lib/pag/deployments.json"
1568 +
1569 +# Snapshoty systemu (CoW). Na btrfs każdy snapshot jest osobnym subwolumenem,
1570 +# więc zajmuje tylko zmienione bloki, a GRUB potrafi uruchomić system z wybranej
1571 +# migawki (rootflags=subvol=...). Na ext4/xfs nie ma snapshotów CoW – zostaje
1572 +# atomowy staging + backup nadpisywanych plików.
1573 +SNAPSHOTS_DIR = "/.pag_snapshots"
1574 +SNAPSHOTS_DB = "/var/lib/pag/snapshots.json"
1575 +GRUB_SNAPSHOT_SCRIPT = "/etc/grub.d/40_pagan_snapshots"
1576 +
1577 +# Ścieżki współdzielone – NIE wchodzą do deploymentu (są symlinkami do /...)
1578 +SHARED_PATHS = {
1579 + "/var", "/etc", "/home", "/root", "/tmp", "/run",
1580 + "/dev", "/proc", "/sys", "/mnt", "/media", "/srv",
1581 + # /boot współdzielone: jądro + initramfs są wspólne dla wszystkich
1582 + # deploymentów (inaczej każdy trzyma własną ~50-100 MB kopię). GRUB
1583 + # wskazuje na /.deployments/<id>/boot → symlink do /boot.
1584 + "/boot",
1585 + "/.deployments", "/.pag_staging",
1586 +}
1587 +
1588 +def _is_shared_path(rel: str) -> bool:
1589 + """Sprawdza czy ścieżka należy do katalogów współdzielonych (poza deploymentem)."""
1590 + for sp in SHARED_PATHS:
1591 + if rel == sp or rel.startswith(sp + "/"):
1592 + return True
1593 + return False
1594 +
1595 +def _is_config_path(rel: str) -> bool:
1596 + """Czy ścieżka to plik konfiguracyjny (/etc/...)?
1597 +
1598 + Dla takich plików stosujemy .pacnew/.pacsave (zachowanie zmian użytkownika)
1599 + zamiast bezwarunkowego nadpisania/usunięcia."""
1600 + p = rel.lstrip("/")
1601 + return p == "etc" or p.startswith("etc/")
1602 +
1603 +# Wrażliwa konfiguracja auth/systemowa – NIGDY nie nadpisujemy jej po cichu.
1604 +# Nadpisanie /etc/pam.d/system-* przez pakiet (np. shadow) potrafi zablokować
1605 +# logowanie/sudo („account validation failure”); dla tych ścieżek zawsze robimy
1606 +# .pacnew, gdy treść na dysku różni się od tej z pakietu.
1607 +_SENSITIVE_CONFIG_RE = re.compile(
1608 + r'^(pam\.d/|security/|sudoers$|sudoers\.d/|shadow$|gshadow$|passwd$|group$|'
1609 + r'login\.defs$|nsswitch\.conf$|default/useradd$)')
1610 +
1611 +def _is_sensitive_config(rel: str) -> bool:
1612 + """Czy rel to wrażliwy plik /etc (PAM, sudoers, shadow, login.defs…)?"""
1613 + p = rel.lstrip("/")
1614 + if not p.startswith("etc/"):
1615 + return False
1616 + return bool(_SENSITIVE_CONFIG_RE.match(p[4:]))
1617 +
1618 +def _get_deployment_root() -> str:
1619 + """Zwraca ścieżkę do aktywnego deploymentu, lub PAG_ROOT jeśli tryb niemutowalny wyłączony."""
1620 + if os.environ.get("PAG_IMMUTABLE", "") in ("0", "no", "false", ""):
1621 + return PAG_ROOT
1622 + if os.path.islink(ACTIVE_LINK):
1623 + return os.readlink(ACTIVE_LINK)
1624 + if os.path.isdir(ACTIVE_LINK):
1625 + return ACTIVE_LINK
1626 + # Brak deploymentów – użyj /
1627 + return PAG_ROOT
1628 +
1629 +def _load_deployments() -> List[dict]:
1630 + """Wczytuje historię deploymentów."""
1631 + if not os.path.exists(DEPLOYMENTS_DB):
1632 + return []
1633 + try:
1634 + return json.load(open(DEPLOYMENTS_DB))
1635 + except Exception:
1636 + return []
1637 +
1638 +def _save_deployments(deployments: List[dict]):
1639 + os.makedirs(os.path.dirname(DEPLOYMENTS_DB), exist_ok=True)
1640 + json.dump(deployments, open(DEPLOYMENTS_DB, "w"), indent=2)
1641 +
1642 +def _create_deployment(pkg_names: List[str], action: str) -> Tuple[str, str]:
1643 + """
1644 + Tworzy nowy deployment przez skopiowanie aktywnego (CoW) i zwraca jego ścieżkę.
1645 + Zwraca (deployment_dir, deployment_id).
1646 + """
1647 + deploy_id = datetime.now().strftime("%Y%m%dT%H%M%S")
1648 + deploy_dir = os.path.join(DEPLOYMENTS_DIR, deploy_id)
1649 + os.makedirs(DEPLOYMENTS_DIR, exist_ok=True)
1650 +
1651 + active = _get_deployment_root()
1652 +
1653 + if os.path.isdir(active) and active != PAG_ROOT:
1654 + # Trójstopniowa strategia kopiowania deploymentu:
1655 + # 1. reflink (CoW – btrfs, xfs) → 0 MB kopiowane
1656 + # 2. hardlink (linki twarde) → 0 MB kopiowane, tylko inody
1657 + # 3. zwykłe cp (ostateczność) → pełna kopia
1658 + print(_(' ⚡ Copying the active deployment...'))
1659 + copied = False
1660 + for method, cmd, label in [
1661 + ("reflink", ["cp", "--reflink=auto", "-a", active + "/.", deploy_dir + "/"], _("reflink_method")),
1662 + ("hardlink", ["cp", "-al", active + "/.", deploy_dir + "/"], _("hardlink_method")),
1663 + ("copy", ["cp", "-a", active + "/.", deploy_dir + "/"], _("copy_method")),
1664 + ]:
1665 + try:
1666 + subprocess.run(cmd, check=True, timeout=600, capture_output=True)
1667 + print(_(' ✅ Deployment: {arg1} ({arg2})', arg1=(deploy_id), arg2=(label)))
1668 + copied = True
1669 + break
1670 + except subprocess.CalledProcessError:
1671 + if method == "copy":
1672 + raise # ostatnia deska – niech leci wyjątek
1673 + continue
1674 + if not copied:
1675 + raise RuntimeError(_("deploy_copy_failed"))
1676 + else:
1677 + # Pierwszy deployment – tylko katalogi szkieletowe
1678 + # /boot celowo POMINIĘTE – jest współdzielone (SHARED_PATHS); poniższa
1679 + # pętla utworzy w deploymencie symlink boot → /boot.
1680 + for d in ["/usr", "/lib", "/lib64", "/bin", "/sbin", "/opt"]:
1681 + if os.path.isdir(d):
1682 + dest = os.path.join(deploy_dir, d.lstrip("/"))
1683 + os.makedirs(dest, exist_ok=True)
1684 + print(_(' ✅ First deployment: {arg1}', arg1=(deploy_id)))
1685 +
1686 + # Utwórz symlinki do współdzielonych katalogów
1687 + for sp in SHARED_PATHS:
1688 + link_dst = os.path.join(deploy_dir, sp.lstrip("/"))
1689 + if not os.path.lexists(link_dst) and os.path.isdir(sp):
1690 + os.symlink(sp, link_dst)
1691 +
1692 + # Zapisz w bazie deploymentów
1693 + deployments = _load_deployments()
1694 + deployments.append({
1695 + "id": deploy_id,
1696 + "action": action,
1697 + "packages": pkg_names,
1698 + "timestamp": datetime.now().isoformat(),
1699 + "active": True,
1700 + })
1701 + # Oznacz poprzednie jako nieaktywne
1702 + for d in deployments[:-1]:
1703 + d["active"] = False
1704 + _save_deployments(deployments)
1705 +
1706 + return deploy_dir, deploy_id
1707 +
1708 +def _switch_deployment(deploy_dir: str) -> bool:
1709 + """Atomowo przełącza aktywny deployment przez podmianę symlinka."""
1710 + tmp_link = ACTIVE_LINK + ".new"
1711 + if os.path.lexists(tmp_link):
1712 + os.remove(tmp_link)
1713 + os.symlink(deploy_dir, tmp_link)
1714 + os.rename(tmp_link, ACTIVE_LINK) # atomowe na tym samym FS
1715 + return True
1716 +
1717 +# =============================================================================
1718 +# SNAPSHOTY SYSTEMU (CoW – btrfs)
1719 +# =============================================================================
1720 +# Snapshot powstaje PRZED transakcją. Na btrfs to subwolumen (kilka KB
1721 +# metadanych, reszta to współdzielone bloki), więc nie kopiujemy całego
1722 +# systemu. Wpis GRUB pozwala uruchomić system z wybranej migawki.
1723 +# Na ext4/xfs nie ma CoW – instalacja nadal jest atomowa dzięki stagingowi,
1724 +# a rollback opiera się na backupie nadpisywanych plików.
1725 +
1726 +def _btrfs_bin() -> str:
1727 + """Ścieżka do btrfs (PATH bywa okrojony w chroocie/instalatorze)."""
1728 + found = shutil.which("btrfs")
1729 + if found:
1730 + return found
1731 + for cand in ("/usr/bin/btrfs", "/usr/sbin/btrfs", "/sbin/btrfs", "/bin/btrfs"):
1732 + if os.path.exists(cand):
1733 + return cand
1734 + return ""
1735 +
1736 +
1737 +def _root_fstype() -> str:
1738 + try:
1739 + r = subprocess.run(["findmnt", "-n", "-o", "FSTYPE", "/"],
1740 + capture_output=True, text=True, timeout=5)
1741 + fs = r.stdout.strip().splitlines()[0].strip() if r.stdout.strip() else ""
1742 + if fs:
1743 + return fs
1744 + except Exception:
1745 + pass
1746 + try:
1747 + r = subprocess.run(["stat", "-f", "-c", "%T", "/"],
1748 + capture_output=True, text=True, timeout=5)
1749 + return r.stdout.strip()
1750 + except Exception:
1751 + return ""
1752 +
1753 +
1754 +def _btrfs_root_path() -> str:
1755 + """Ścieżka aktywnego subwolumenu root względem top-level btrfs."""
1756 + btrfs = _btrfs_bin()
1757 + if btrfs:
1758 + try:
1759 + r = subprocess.run([btrfs, "subvolume", "show", "/"],
1760 + capture_output=True, text=True, timeout=5)
1761 + if r.returncode == 0:
1762 + for line in r.stdout.splitlines():
1763 + line = line.strip()
1764 + if line.lower().startswith("path:"):
1765 + p = line.split(":", 1)[1].strip()
1766 + if p in ("", "/"):
1767 + return "/"
1768 + return p.strip("/")
1769 + except Exception:
1770 + pass
1771 + try:
1772 + r = subprocess.run(["findmnt", "-n", "-o", "FSROOT", "/"],
1773 + capture_output=True, text=True, timeout=5)
1774 + p = r.stdout.strip()
1775 + if p and p != "/":
1776 + return p.strip("/")
1777 + except Exception:
1778 + pass
1779 + return "/"
1780 +
1781 +
1782 +def _snapshot_support() -> Tuple[bool, str]:
1783 + fs = _root_fstype()
1784 + if fs != "btrfs":
1785 + return False, (f"root jest na {fs or 'nieznanym systemie plików'} – "
1786 + f"snapshoty CoW wymagają btrfs")
1787 + if not _btrfs_bin():
1788 + return False, "brak narzędzia btrfs (zainstaluj pakiet btrfs-progs)"
1789 + return True, ""
1790 +
1791 +
1792 +def _load_snapshots() -> List[dict]:
1793 + if not os.path.exists(SNAPSHOTS_DB):
1794 + return []
1795 + try:
1796 + data = load_json(SNAPSHOTS_DB)
1797 + return data if isinstance(data, list) else []
1798 + except Exception:
1799 + return []
1800 +
1801 +
1802 +def _save_snapshots(items: List[dict]):
1803 + os.makedirs(os.path.dirname(SNAPSHOTS_DB), exist_ok=True)
1804 + save_json(SNAPSHOTS_DB, items)
1805 +
1806 +
1807 +def _snapshot_label(snap: dict) -> str:
1808 + """Czytelna etykieta GRUB (bez znaków, które psują menu)."""
1809 + pkgs = list(snap.get("packages") or [])
1810 + p = ", ".join(pkgs[:3])
1811 + if len(pkgs) > 3:
1812 + p += f" +{len(pkgs) - 3}"
1813 + base = f"Pagan Linux snapshot {snap.get('id', '?')}"
1814 + if snap.get("label"):
1815 + base += f" - {snap['label']}"
1816 + if p:
1817 + base += f" - {p}"
1818 + # GRUB: usuń apostrofy i znaki kontrolne.
1819 + return re.sub(r"[\x00-\x1f']", "", base)[:120]
1820 +
1821 +
1822 +def _root_boot_arg() -> str:
1823 + """`root=UUID=...` dla wpisu GRUB (stabilne po zmianie nazw urządzeń)."""
1824 + dev = _detect_root_device()
1825 + if not dev:
1826 + return ""
1827 + if dev.startswith(("UUID=", "PARTUUID=", "LABEL=", "PARTLABEL=")):
1828 + return f" root={dev}"
1829 + uuid = ""
1830 + try:
1831 + r = subprocess.run(["blkid", "-s", "UUID", "-o", "value", dev],
1832 + capture_output=True, text=True, timeout=5)
1833 + uuid = r.stdout.strip().splitlines()[0].strip() if r.stdout.strip() else ""
1834 + except Exception:
1835 + uuid = ""
1836 + return f" root=UUID={uuid}" if uuid else f" root={dev}"
1837 +
1838 +
1839 +def _initrd_for_kernel(boot_dir: str, kernel: str) -> str:
1840 + """Nazwa initramfs pasująca do jądra (initramfs.img / initramfs-<ver>.img…)."""
1841 + if not kernel or not os.path.isdir(boot_dir):
1842 + return ""
1843 + ver = kernel[len("vmlinuz-"):] if kernel.startswith("vmlinuz-") else ""
1844 + candidates = []
1845 + if ver:
1846 + candidates += [f"initramfs-{ver}.img", f"initrd.img-{ver}"]
1847 + candidates += ["initramfs.img", "initrd.img"]
1848 + for c in candidates:
1849 + if os.path.isfile(os.path.join(boot_dir, c)):
1850 + return c
1851 + for f in sorted(os.listdir(boot_dir)):
1852 + if f.startswith(("initramfs", "initrd")):
1853 + return f
1854 + return ""
1855 +
1856 +
1857 +def _pick_kernel_initrd(boot_dir: str) -> Tuple[str, str]:
1858 + kernels = sorted(
1859 + [f for f in os.listdir(boot_dir) if f.startswith("vmlinuz-")],
1860 + reverse=True,
1861 + ) if os.path.isdir(boot_dir) else []
1862 + if not kernels:
1863 + return "", ""
1864 + k = kernels[0]
1865 + return k, _initrd_for_kernel(boot_dir, k)
1866 +
1867 +
1868 +def _grub_snapshot_entries() -> List[str]:
1869 + """Wpisy menu GRUB dla snapshotów (dla `_update_grub_config` i grub.d)."""
1870 + snaps = _load_snapshots()
1871 + if not snaps:
1872 + return []
1873 +
1874 + root_arg = _root_boot_arg()
1875 + try:
1876 + separate_boot = os.path.isdir("/boot") and os.path.ismount("/boot")
1877 + except OSError:
1878 + separate_boot = False
1879 + bp = _boot_prefix()
1880 +
1881 + lines: List[str] = []
1882 + for snap in reversed(snaps):
1883 + path = snap.get("path") or ""
1884 + if not path or not os.path.isdir(path):
1885 + continue
1886 +
1887 + if separate_boot:
1888 + # Osobne /boot jest współdzielone: użyj jądra ZAPISANEGO przy
1889 + # tworzeniu snapshotu (o ile nadal leży w /boot), a nie zawsze
1890 + # najnowszego – nowe jądro mogło być właśnie przyczyną problemu.
1891 + kname = snap.get("kernel") or ""
1892 + if not kname or not os.path.isfile(os.path.join("/boot", kname)):
1893 + kname, _ = _pick_kernel_initrd("/boot")
1894 + iname = _initrd_for_kernel("/boot", kname) if kname else ""
1895 + kernel = f"{bp}/{kname}" if kname else ""
1896 + initrd = f"{bp}/{iname}" if iname else ""
1897 + else:
1898 + snap_boot = os.path.join(path, "boot")
1899 + kname, iname = _pick_kernel_initrd(snap_boot)
1900 + # Kopia zapasowa: jądro z bieżącego /boot (np. gdy /boot nie
1901 + # było częścią snapshotu lub jest to bardzo stara migawka).
1902 + if not kname:
1903 + kname, iname = _pick_kernel_initrd("/boot")
1904 + kernel = f"{bp}/{kname}" if kname else ""
1905 + initrd = f"{bp}/{iname}" if iname else ""
1906 + else:
1907 + kernel = f"{path}/boot/{kname}"
1908 + initrd = f"{path}/boot/{iname}" if iname else ""
1909 +
1910 + if not kernel:
1911 + continue
1912 +
1913 + subvol = snap.get("subvol") or ""
1914 + flags = f" rootflags=subvol={subvol} rootfstype=btrfs" if subvol else ""
1915 + label = _snapshot_label(snap)
1916 +
1917 + lines.append(f"menuentry '{label}' --class pagan --class gnu-linux --class os {{")
1918 + lines.append(f" linux {kernel}{root_arg}{flags} rw quiet")
1919 + if initrd:
1920 + lines.append(f" initrd {initrd}")
1921 + lines.append("}")
1922 + lines.append("")
1923 + return lines
1924 +
1925 +
1926 +def _ensure_snapshot_grub_script() -> bool:
1927 + """Instaluje /etc/grub.d/40_pagan_snapshots (integracja z grub-mkconfig)."""
1928 + if not os.path.isdir("/etc/grub.d"):
1929 + return False
1930 + # Preferuj BIEŻĄCĄ binarkę (np. testy z repo), a nie starszy /usr/bin/pag:
1931 + # stary pag nie zna `snapshot-grub` i uruchomiłby smart-search.
1932 + _self = os.path.abspath(sys.argv[0]) if sys.argv[0] else ""
1933 + exe = _self if _self and os.path.isfile(_self) else (shutil.which("pag") or "/usr/bin/pag")
1934 + if not exe or not os.path.exists(exe):
1935 + exe = "/usr/bin/pag"
1936 + quoted = exe.replace("'", "'\\''")
1937 + script = (
1938 + "#!/bin/sh\n"
1939 + "# Pagan Linux – wpisy GRUB dla snapshotów systemu (wygenerowane przez pag)\n"
1940 + "# Usuń ten plik, aby ukryć snapshoty w menu GRUB.\n"
1941 + f"PAG_BIN='{quoted}'\n"
1942 + 'if [ ! -x "$PAG_BIN" ]; then\n'
1943 + ' PAG_BIN="$(command -v pag 2>/dev/null || true)"\n'
1944 + "fi\n"
1945 + '[ -x "$PAG_BIN" ] || exit 0\n'
1946 + '# Tylko pag >= 4.1 zna komendę snapshot-grub (starszy zrobiłby\n'
1947 + '# smart-search i mógłby zawiesić grub-mkconfig na sieci).\n'
1948 + 'case "$("$PAG_BIN" --version 2>/dev/null)" in\n'
1949 + ' "pag 4."[1-9]*|"pag "[5-9]*|"pag "[1-9][0-9]*) ;;\n'
1950 + ' *) exit 0 ;;\n'
1951 + 'esac\n'
1952 + 'exec "$PAG_BIN" snapshot-grub\n'
1953 + )
1954 + try:
1955 + with open(GRUB_SNAPSHOT_SCRIPT, "w", encoding="utf-8") as fh:
1956 + fh.write(script)
1957 + os.chmod(GRUB_SNAPSHOT_SCRIPT, 0o755)
1958 + return True
1959 + except OSError:
1960 + return False
1961 +
1962 +
1963 +def _create_system_snapshot(packages: List[str], action: str,
1964 + label: str = "") -> Optional[dict]:
1965 + """Tworzy snapshot root (btrfs) i zapisuje go w bazie.
1966 +
1967 + Zwraca dict snapshotu albo None. Nie przerywa instalacji – o tym decyduje
1968 + wywołujący (tryb --snapshot wymaga sukcesu, tryb auto tylko ostrzega).
1969 + """
1970 + ok, why = _snapshot_support()
1971 + if not ok:
1972 + return None
1973 + btrfs = _btrfs_bin()
1974 + try:
1975 + os.makedirs(SNAPSHOTS_DIR, exist_ok=True)
1976 + except OSError as e:
1977 + print(_(' ⚠ Cannot create {arg1}: {arg2}', arg1=(SNAPSHOTS_DIR), arg2=(e)), file=sys.stderr)
1978 + return None
1979 +
1980 + base_id = datetime.now().strftime("%Y%m%dT%H%M%S")
1981 + snap_id = base_id
1982 + n = 1
1983 + while os.path.lexists(os.path.join(SNAPSHOTS_DIR, snap_id)):
1984 + snap_id = f"{base_id}-{n}"
1985 + n += 1
1986 + snap_path = os.path.join(SNAPSHOTS_DIR, snap_id)
1987 +
1988 + try:
1989 + r = subprocess.run([btrfs, "subvolume", "snapshot", "/", snap_path],
1990 + capture_output=True, text=True, timeout=600)
1991 + except Exception as e:
1992 + print(_(' ⚠ Failed to create snapshot: {arg1}', arg1=(e)), file=sys.stderr)
1993 + return None
1994 + if r.returncode != 0:
1995 + msg = (r.stderr or r.stdout or "").strip().splitlines()
1996 + print(_(' ⚠ btrfs snapshot failed: {arg1}', arg1=(msg[-1] if msg else r.returncode)),
1997 + file=sys.stderr)
1998 + return None
1999 +
2000 + rootp = _btrfs_root_path()
2001 + if rootp in ("", "/"):
2002 + subvol = f"/.pag_snapshots/{snap_id}"
2003 + else:
2004 + subvol = f"{rootp}/.pag_snapshots/{snap_id}"
2005 +
2006 + # Zapamiętaj jądro/initramfs z chwili snapshotu – przy osobnym /boot
2007 + # dzięki temu uruchomimy migawkę ze STARYM (działającym) jądrem.
2008 + _kn, _ir = _pick_kernel_initrd("/boot")
2009 + snap = {
2010 + "id": snap_id,
2011 + "path": snap_path,
2012 + "subvol": subvol,
2013 + "created": datetime.now().isoformat(),
2014 + "action": action,
2015 + "label": label,
2016 + "packages": list(packages)[:100],
2017 + "kernel": _kn,
2018 + "initrd": _ir,
2019 + }
2020 + items = _load_snapshots()
2021 + items.append(snap)
2022 + _save_snapshots(items)
2023 + _ensure_snapshot_grub_script()
2024 + print(_(' 📸 System snapshot: {arg1} (subvol={arg2})', arg1=(snap_id), arg2=(subvol)))
2025 + return snap
2026 +
2027 +
2028 +def _find_snapshot(snap_id: str) -> Optional[dict]:
2029 + items = _load_snapshots()
2030 + if not snap_id:
2031 + return items[-1] if items else None
2032 + for s in items:
2033 + if s.get("id") == snap_id:
2034 + return s
2035 + for s in items:
2036 + if str(s.get("id", "")).startswith(snap_id):
2037 + return s
2038 + return None
2039 +
2040 +
2041 +def cmd_snapshot_list():
2042 + items = _load_snapshots()
2043 + if not items:
2044 + print(_("snapshot_none"))
2045 + return 0
2046 + print(_("snapshot_list", len(items)))
2047 + for s in reversed(items):
2048 + pkgs = list(s.get("packages") or [])
2049 + listed = ", ".join(pkgs[:4])
2050 + if len(pkgs) > 4:
2051 + listed += f" +{len(pkgs) - 4}"
2052 + print(f" {s.get('id', '?')} [{_action_label(s.get('action', ''))}]")
2053 + if listed:
2054 + print(f" {listed}")
2055 + print(f" {s.get('created', '')}")
2056 + print(f" {s.get('path', '')}")
2057 + return 0
2058 +
2059 +
2060 +def cmd_snapshot_grub():
2061 + """Wypisuje menuentry dla grub-mkconfig (wywoływane z 40_pagan_snapshots)."""
2062 + for line in _grub_snapshot_entries():
2063 + print(line)
2064 + return 0
2065 +
2066 +
2067 +def cmd_snapshot_create(label: str = ""):
2068 + ok, why = _snapshot_support()
2069 + if not ok:
2070 + print(f" ❌ {_('snapshot_unsupported', why)}")
2071 + return 1
2072 + snap = _create_system_snapshot([], "manual", label=label)
2073 + if not snap:
2074 + return 1
2075 + _ensure_snapshot_grub_script()
2076 + _refresh_bootloader()
2077 + print(f" ✅ {_('snapshot_created', snap['id'])}")
2078 + return 0
2079 +
2080 +
2081 +def cmd_snapshot_delete(snap_id: str):
2082 + snap = _find_snapshot(snap_id)
2083 + if not snap:
2084 + print(f" ❌ {_('snapshot_not_found', snap_id)}")
2085 + return 1
2086 + path = snap.get("path") or ""
2087 + if not path.startswith(SNAPSHOTS_DIR + "/"):
2088 + print(_(' ❌ Invalid snapshot path – refusing to delete.'))
2089 + return 1
2090 + if os.path.isdir(path):
2091 + btrfs = _btrfs_bin()
2092 + if not btrfs:
2093 + print(f" ❌ {_('snapshot_unsupported', 'brak btrfs')}")
2094 + return 1
2095 + r = subprocess.run([btrfs, "subvolume", "delete", path],
2096 + capture_output=True, text=True, timeout=120)
2097 + if r.returncode != 0:
2098 + print(f" ❌ btrfs: {(r.stderr or '').strip()[:200]}")
2099 + return 1
2100 + _save_snapshots([s for s in _load_snapshots() if s.get("id") != snap.get("id")])
2101 + _refresh_bootloader()
2102 + print(f" ✅ {_('snapshot_deleted', snap.get('id', ''))}")
2103 + return 0
2104 +
2105 +
2106 +def cmd_snapshot_rollback(snap_id: str = ""):
2107 + """Ustawia snapshot jako następny start (albo pokazuje wybór w GRUB)."""
2108 + snap = _find_snapshot(snap_id)
2109 + if not snap:
2110 + print(f" ❌ {_('snapshot_not_found', snap_id or '(brak)' )}")
2111 + return 1
2112 + if not os.path.isdir(snap.get("path") or ""):
2113 + print(f" ❌ {_('snapshot_not_found', snap.get('id', ''))}")
2114 + return 1
2115 +
2116 + label = _snapshot_label(snap)
2117 + print(_(' ⏪ Snapshot: {arg1}', arg1=(snap.get('id', ''))))
2118 + print(f" {snap.get('created', '')}")
2119 + pkgs = list(snap.get("packages") or [])
2120 + if pkgs:
2121 + print(f" {', '.join(pkgs[:8])}{' …' if len(pkgs) > 8 else ''}")
2122 + if not _ask_confirm():
2123 + return 0
2124 +
2125 + _ensure_snapshot_grub_script()
2126 + _refresh_bootloader()
2127 +
2128 + grub_reboot = shutil.which("grub-reboot") or shutil.which("grub2-reboot")
2129 + if grub_reboot:
2130 + r = subprocess.run([grub_reboot, label], capture_output=True, text=True)
2131 + if r.returncode == 0:
2132 + print(f" ✅ {_('snapshot_rollback_next', label)}")
2133 + print(_(' 💡 Reboot the system – GRUB will boot the selected snapshot.'))
2134 + return 0
2135 + print(f" ℹ {_('snapshot_rollback_hint', label)}")
2136 + print(_(' 💡 At boot, choose an entry in the GRUB menu (snapshots section).'))
2137 + return 0
2138 +
2139 +
2140 +DEFAULT_REPOS = [
2141 + "https://repo.paganlinux.eu/stable/",
2142 +]
2143 +
2144 +# =============================================================================
2145 +# INICJALIZACJA
2146 +# =============================================================================
2147 +
2148 +def _require_dir(d: str) -> None:
2149 + """Utwórz katalog, a przy istniejącej NIE-katalogowej ścieżce podaj powód.
2150 +
2151 + `os.makedirs(..., exist_ok=True)` nie wystarcza: gdy `mkdir` zwróci EEXIST,
2152 + Python sprawdza `os.path.isdir(path)`, a dla MARTWEGO dowiązania to False –
2153 + wyjątek leci dalej. Objaw: `pag update` kończył się tracebackiem
2154 + `FileExistsError: /var/cache/pag -> /home/pagan-build/cache-pag` (cel
2155 + dowiązania został skasowany).
2156 + """
2157 + try:
2158 + os.makedirs(d, exist_ok=True)
2159 + return
2160 + except FileExistsError:
2161 + pass
2162 + except OSError as e:
2163 + print(f"❌ Nie mogę utworzyć {d}: {e}")
2164 + sys.exit(1)
2165 + if os.path.islink(d) and not os.path.exists(d):
2166 + print(f"❌ {d} jest martwym dowiązaniem → {os.readlink(d)}")
2167 + print(f" Usuń dowiązanie (rm {d}) albo utwórz katalog docelowy.")
2168 + else:
2169 + print(f"❌ {d} istnieje, ale nie jest katalogiem.")
2170 + sys.exit(1)
2171 +
2172 +
2173 +def ensure_dirs():
2174 + for d in [PAG_DB, PAG_CACHE, PAG_CONF, REPO_CACHE, REPOS_DIR, STAGING_DIR, DEPLOYMENTS_DIR]:
2175 + _require_dir(d)
2176 + for f, default in [
2177 + (REPOS_CONF, "\n".join(DEFAULT_REPOS) + "\n"),
2178 + (INSTALLED_DB, "{}"),
2179 + (PINNED_FILE, "{}"),
2180 + (HISTORY_FILE, "[]"),
2181 + ]:
2182 + if not os.path.exists(f):
2183 + with open(f, "w") as fh: fh.write(default)
2184 + if not os.path.exists(WORLD_FILE):
2185 + Path(WORLD_FILE).touch()
2186 + if not os.path.exists(GPG_HOME):
2187 + os.makedirs(GPG_HOME, exist_ok=True)
2188 + os.chmod(GPG_HOME, 0o700)
2189 + _gpg_run("--list-keys", capture_output=True)
2190 + # Inicjalizuj SQLite
2191 + _db_init()
2192 + # Wyczyść staging po poprzednim przerwanym buildzie/instalacji
2193 + if os.path.isdir(STAGING_DIR):
2194 + for entry in os.listdir(STAGING_DIR):
2195 + if entry == "backups":
2196 + continue # backupy starych wersji – potrzebne do `pag rollback`
2197 + path = os.path.join(STAGING_DIR, entry)
2198 + try:
2199 + if os.path.isfile(path) or os.path.islink(path):
2200 + os.unlink(path)
2201 + elif os.path.isdir(path):
2202 + shutil.rmtree(path, ignore_errors=True)
2203 + except OSError:
2204 + pass
2205 +
2206 +# =============================================================================
2207 +# SQLITE – BAZA PLIKÓW (poprawne zarządzanie połączeniami)
2208 +# =============================================================================
2209 +
2210 +from contextlib import contextmanager
2211 +
2212 +@contextmanager
2213 +def _db_session(readonly: Optional[bool] = None):
2214 + """Context manager – gwarantuje zamknięcie połączenia.
2215 +
2216 + Gdy katalog bazy nie jest zapisywalny (np. komenda read-only uruchomiona
2217 + jako zwykły user), otwieramy połączenie w trybie read-only. Inaczej
2218 + `PRAGMA journal_mode=WAL` próbuje pisać i kończy się błędem
2219 + „attempt to write a readonly database” zamiast zwrócić wynik.
2220 + """
2221 + if readonly is None:
2222 + readonly = not os.access(os.path.dirname(FILES_DB_SQL) or ".", os.W_OK)
2223 + if readonly:
2224 + # Katalog bazy nie jest zapisywalny (np. komenda read-only uruchomiona
2225 + # jako zwykły user). Baza jest w trybie WAL, więc SQLite przy `mode=ro`
2226 + # próbuje utworzyć plik `-shm` w katalogu – bez prawa zapisu kończy się
2227 + # to błędem „attempt to write a readonly database” nawet przy SELECT.
2228 + # Dlatego próbujemy zwykłego `mode=ro`, a gdy zawiedzie, otwieramy z
2229 + # `immutable=1` (SQLite pomija wtedy WAL/SHM i czyta ostatni
2230 + # checkpoint). Przy równoległym zapisie roota odczyt może być chwilowo
2231 + # nieaktualny – dla komend diagnostycznych (files/list/verify) to OK.
2232 + conn = sqlite3.connect(f"file:{FILES_DB_SQL}?mode=ro", uri=True, timeout=15)
2233 + try:
2234 + conn.execute("SELECT 1 FROM sqlite_master LIMIT 1")
2235 + except sqlite3.OperationalError:
2236 + conn.close()
2237 + conn = sqlite3.connect(
2238 + f"file:{FILES_DB_SQL}?mode=ro&immutable=1", uri=True, timeout=15)
2239 + else:
2240 + conn = sqlite3.connect(FILES_DB_SQL, timeout=15)
2241 + conn.execute("PRAGMA journal_mode=WAL")
2242 + conn.execute("PRAGMA synchronous=NORMAL")
2243 + conn.execute("PRAGMA foreign_keys=ON")
2244 + conn.execute("PRAGMA busy_timeout=15000")
2245 + conn.row_factory = sqlite3.Row
2246 + try:
2247 + yield conn
2248 + if not readonly:
2249 + conn.commit()
2250 + except Exception:
2251 + if not readonly:
2252 + conn.rollback()
2253 + raise
2254 + finally:
2255 + conn.close()
2256 +
2257 +
2258 +def _db_init():
2259 + """Tworzy tabele SQLite jeśli nie istnieją."""
2260 + with _db_session() as db:
2261 + db.execute("""
2262 + CREATE TABLE IF NOT EXISTS files (
2263 + id INTEGER PRIMARY KEY AUTOINCREMENT,
2264 + path TEXT NOT NULL,
2265 + package TEXT NOT NULL,
2266 + sha256 TEXT,
2267 + size INTEGER,
2268 + is_symlink INTEGER DEFAULT 0,
2269 + symlink_target TEXT,
2270 + UNIQUE(path, package)
2271 + )
2272 + """)
2273 + db.execute("CREATE INDEX IF NOT EXISTS idx_files_path ON files(path)")
2274 + db.execute("CREATE INDEX IF NOT EXISTS idx_files_pkg ON files(package)")
2275 + db.execute("""
2276 + CREATE TABLE IF NOT EXISTS file_checksums (
2277 + path TEXT PRIMARY KEY,
2278 + sha256 TEXT NOT NULL,
2279 + installed_at TEXT
2280 + )
2281 + """)
2282 + db.commit()
2283 +
2284 +def _db_record_files(pkg_name: str, files: List[dict]):
2285 + """Zapisuje pliki do SQLite (obsługuje symlinki)."""
2286 + with _db_session() as db:
2287 + # Jawna transakcja – atomowość obu zapisów i szybsze wykrycie blokady
2288 + try:
2289 + db.execute("BEGIN IMMEDIATE")
2290 + except sqlite3.OperationalError:
2291 + pass # transakcja już otwarta (implicit)
2292 + db.executemany(
2293 + "INSERT OR REPLACE INTO files (path, package, sha256, size, is_symlink, symlink_target) "
2294 + "VALUES (?,?,?,?,?,?)",
2295 + [(f["path"], pkg_name, f.get("sha256",""), f.get("size",0),
2296 + f.get("is_symlink", 0), f.get("symlink_target", ""))
2297 + for f in files]
2298 + )
2299 + db.executemany(
2300 + "INSERT OR REPLACE INTO file_checksums (path, sha256, installed_at) VALUES (?,?,?)",
2301 + [(f["path"], f.get("sha256",""), datetime.now().isoformat())
2302 + for f in files if f.get("sha256")]
2303 + )
2304 +
2305 +def _db_get_package_files(pkg_name: str) -> List[str]:
2306 + with _db_session() as db:
2307 + return [r["path"] for r in db.execute(
2308 + "SELECT DISTINCT path FROM files WHERE package=?", (pkg_name,)
2309 + )]
2310 +
2311 +def _db_get_file_owners(filepath: str) -> List[str]:
2312 + """Zwraca listę pakietów będących właścicielami pliku."""
2313 + with _db_session() as db:
2314 + return [r["package"] for r in db.execute(
2315 + "SELECT package FROM files WHERE path=?", (filepath,)
2316 + )]
2317 +
2318 +def _db_remove_package_files(pkg_name: str):
2319 + with _db_session() as db:
2320 + db.execute("DELETE FROM files WHERE package=?", (pkg_name,))
2321 + db.commit()
2322 +
2323 +def _db_get_all_file_checksums() -> Dict[str, str]:
2324 + with _db_session() as db:
2325 + return {r["path"]: r["sha256"] for r in db.execute("SELECT path, sha256 FROM file_checksums")}
2326 +
2327 +def _db_get_package_checksums(pkg_name: str) -> Dict[str, str]:
2328 + """Sumy SHA256 zapisane dla plików należących do pakietu.
2329 +
2330 + Używane do wykrycia, czy użytkownik zmodyfikował plik konfiguracyjny
2331 + (porównanie z sumą z chwili instalacji) – serce mechanizmu .pacnew/.pacsave.
2332 + """
2333 + with _db_session() as db:
2334 + return {r["path"]: r["sha256"] for r in db.execute(
2335 + "SELECT fc.path AS path, fc.sha256 AS sha256 FROM file_checksums fc "
2336 + "JOIN files f ON f.path = fc.path WHERE f.package=?", (pkg_name,))}
2337 +
2338 +
2339 +def _db_count_files() -> int:
2340 + with _db_session() as db:
2341 + return db.execute("SELECT COUNT(*) FROM files").fetchone()[0]
2342 +
2343 +# =============================================================================
2344 +# BLOKADA
2345 +# =============================================================================
2346 +
2347 +class DatabaseLock:
2348 + """Blokada plikowa (flock) – jądro zwalnia ją AUTOMATYCZNIE, gdy proces
2349 + ginie (kill -9, twardy reset). Stary PID-file miał race condition: po
2350 + śmierci pag PID mógł zostać przydzielony obcemu procesowi (PID reuse)
2351 + i pag odmawiał działania na zawsze („baza zablokowana”).
2352 + """
2353 + def __init__(self):
2354 + self._f = None
2355 + def __enter__(self):
2356 + os.makedirs(os.path.dirname(LOCK_FILE), exist_ok=True)
2357 + self._f = open(LOCK_FILE, "w")
2358 + try:
2359 + # LOCK_NB: rzuca wyjątek zamiast czekać w nieskończoność
2360 + fcntl.flock(self._f, fcntl.LOCK_EX | fcntl.LOCK_NB)
2361 + except BlockingIOError:
2362 + print(f"❌ {_('db_locked')}", file=sys.stderr)
2363 + print(f" {_('db_lock_hint', LOCK_FILE)}", file=sys.stderr)
2364 + sys.exit(1)
2365 + self._f.write(str(os.getpid()))
2366 + self._f.flush()
2367 + return self
2368 + def __exit__(self, *args):
2369 + if self._f:
2370 + try:
2371 + fcntl.flock(self._f, fcntl.LOCK_UN)
2372 + except OSError:
2373 + pass
2374 + self._f.close()
2375 + self._f = None
2376 + # Uwaga: NIE usuwamy pliku blokady. Stały plik + flock na inode to jedyny
2377 + # bezpieczny wzorzec – os.remove(), gdy inny proces trzyma blokadę na starym
2378 + # inode, otwiera wyścig (nowy proces blokowałby nowo utworzony inode).
2379 +
2380 +
2381 +class SelfUpdateLock:
2382 + """Blokada podmiany binarki pag podczas self-update.
2383 +
2384 + Niezależna od DatabaseLock (inny plik) – cmd_self_update może zostać
2385 + wywołane poza globalną blokadą (np. z zewnętrznego skryptu), a dwie
2386 + równoległe aktualizacje pisałyby do tego samego `dst.new`; `os.replace`
2387 + mógłby wtedy podmienić plik w trakcie wykonywania (uszkodzony pag).
2388 + """
2389 + def __init__(self):
2390 + self._f = None
2391 +
2392 + def __enter__(self):
2393 + lock_path = LOCK_FILE + ".self-update"
2394 + os.makedirs(os.path.dirname(lock_path), exist_ok=True)
2395 + self._f = open(lock_path, "w")
2396 + try:
2397 + fcntl.flock(self._f, fcntl.LOCK_EX | fcntl.LOCK_NB)
2398 + except BlockingIOError:
2399 + self._f.close()
2400 + self._f = None
2401 + print(_('❌ Another pag update is in progress – try again later.'),
2402 + file=sys.stderr)
2403 + sys.exit(1)
2404 + self._f.write(str(os.getpid()))
2405 + self._f.flush()
2406 + return self
2407 +
2408 + def __exit__(self, *args):
2409 + if self._f:
2410 + try:
2411 + fcntl.flock(self._f, fcntl.LOCK_UN)
2412 + except OSError:
2413 + pass
2414 + self._f.close()
2415 + self._f = None
2416 +
2417 +# =============================================================================
2418 +# POMOCNICZE
2419 +# =============================================================================
2420 +
2421 +
2422 +# Katalogi systemowe. /bin, /sbin i /lib64 to na usrmerge symlinki do
2423 +# /usr/bin, /usr/bin i /usr/lib64 – bez nich pag pomijał CAŁĄ zawartość
2424 +# pakietów, które pakują pliki „starymi” ścieżkami (np. busybox: 386 plików
2425 +# w ./bin/, w tym sam ./bin/busybox → "BLOCKED: ./bin/ls" i spółka).
2426 +_ALLOWED_PREFIXES = ("/usr/", "/etc/", "/var/", "/opt/",
2427 + "/boot/", "/lib/", "/lib64/", "/run/",
2428 + "/bin/", "/sbin/", # usrmerge: bin→usr/bin, sbin→usr/bin
2429 + # Pliki wewnętrzne paczki .pkg.tar.xz
2430 + "metadata.json", "data.tar.xz", "hooks/",
2431 + "sums.json")
2432 +
2433 +def _check_path_safety(name: str) -> bool:
2434 + # Normalizuj – usuń leading ./
2435 + if name.startswith("./"):
2436 + name = name[2:]
2437 + if name in (".", ""):
2438 + return True
2439 + # Porównuj z prefiksami BEZ wiodącego '/', by zarówno "/usr/bin/ls", jak i
2440 + # wewnętrzne pliki pakietu ("hooks/pre-install", "data.tar.xz") przechodziły.
2441 + norm = name.lstrip("/")
2442 + for prefix in _ALLOWED_PREFIXES:
2443 + p = prefix.lstrip("/").rstrip("/")
2444 + if norm == p or norm.startswith(p + "/"):
2445 + return True
2446 + return False
2447 +
2448 +
2449 +def _validate_pkg_name(name):
2450 + return bool(ALLOWED_PKG_RE.match(name))
2451 +
2452 +
2453 +
2454 +def _audit(msg):
2455 + from datetime import datetime, timezone
2456 + os.makedirs(os.path.dirname(AUDIT_LOG), exist_ok=True)
2457 + with open(AUDIT_LOG, "a") as f:
2458 + f.write(datetime.now(timezone.utc).isoformat() + " " + msg + "\n")
2459 +
2460 +def _strip_suid(path):
2461 + try:
2462 + st = os.stat(path)
2463 + if st.st_mode & 0o4000:
2464 + os.chmod(path, st.st_mode & ~0o4000)
2465 + print(f" {_("sec_suid", path=path)}")
2466 + except OSError:
2467 + pass
2468 +
2469 +def _check_downgrade(pkg_name, new_ver, installed_db):
2470 + if pkg_name in installed_db:
2471 + old = installed_db[pkg_name].get("version", "0")
2472 + if new_ver < old:
2473 + print(f" {_("sec_downgrade", pkg=pkg_name, new=new_ver, old=old)}")
2474 + return False
2475 + return True
2476 +
2477 +def _safe_extractall(tar: tarfile.TarFile, dest: str, *, preserve_perms: bool = True,
2478 + privileged=frozenset()):
2479 + """
2480 + Bezpieczne rozpakowanie archiwum tar z ochroną przed Directory Traversal.
2481 +
2482 + Działa na Python < 3.12 (gdzie parametr 'filter' w extractall nie istnieje)
2483 + oraz na Python 3.12+. W przeciwieństwie do filtra 'data' z Pythona 3.12,
2484 + zachowuje bity uprawnień POSIX (SUID, SGID, sticky) – preserve_perms=True.
2485 +
2486 + Ochrona oparta jest na FINALNEJ ścieżce (os.path.realpath), nie tylko na
2487 + prostym sprawdzaniu stringa:
2488 + - Blokuje ścieżki absolutne i z '..' (path traversal)
2489 + - Blokuje symlinki/hardlinki, których cel wychodzi poza dest
2490 + - Blokuje zapis "przez" złośliwy symlink, który został wcześniej
2491 + rozpakowany (np. katalog → /etc, potem zapis katalog/plik)
2492 + - Zachowuje oryginalne uprawnienia plików
2493 + """
2494 + dest_real = os.path.realpath(dest)
2495 + os.makedirs(dest_real, exist_ok=True)
2496 +
2497 + def _target_within(path: str) -> bool:
2498 + try:
2499 + return os.path.commonpath([dest_real, os.path.realpath(path)]) == dest_real
2500 + except ValueError:
2501 + # różne napędy / ścieżki nie da się wspólnie porównać → odrzuć
2502 + return False
2503 +
2504 + for member in tar.getmembers():
2505 + name = member.name
2506 +
2507 + # --- Ochrona przed Directory Traversal (szybkie string-checki) ---
2508 + if name.startswith('/'):
2509 + continue
2510 + if '..' in name.split('/'):
2511 + continue
2512 + # Zablokuj bajt NUL i backslash (bugi/obejścia tarfile na niektórych platformach)
2513 + if '\x00' in name or '\\' in name:
2514 + continue
2515 + if not _check_path_safety(name):
2516 + print(f" BLOCKED: {name}")
2517 + continue
2518 +
2519 + target = os.path.join(dest, name)
2520 +
2521 + # --- Ochrona na podstawie finalnej ścieżki ---
2522 + # Jeśli którykolwiek komponent nadrzędny jest (złośliwym) symlinkiem
2523 + # wskazującym poza dest, realpath to wykryje – zablokuj zapis.
2524 + if not _target_within(target):
2525 + print(f" BLOCKED (escape): {name}")
2526 + continue
2527 +
2528 + # --- Ochrona dla symlinków i hardlinków ---
2529 + if member.issym() or member.islnk():
2530 + link = member.linkname
2531 + if '\x00' in link:
2532 + continue
2533 + # Link absolutny jest POPRAWNY, gdy cel jest ścieżką systemową
2534 + # (np. usr/bin/librewolf -> /usr/lib/librewolf/librewolf). Wcześniej
2535 + # odrzucaliśmy wszystkie takie linki po cichu, przez co w systemie
2536 + # brakowalo np. /usr/bin/librewolf — a wpis .desktop z TryExec nie
2537 + # pojawiał się w menu. Odrzucamy tylko cele spoza dozwolonych prefiksów.
2538 + if link.startswith('/'):
2539 + if not _check_path_safety(link):
2540 + print(f" BLOCKED (link target): {name} -> {link}")
2541 + continue
2542 + # Cel absolutny zostaje bez zmian – po instalacji wskazuje
2543 + # właściwą ścieżkę w systemie (sprawdzenie _target_within
2544 + # dotyczy ścieżki RELATYWNEJ i tutaj nie ma zastosowania).
2545 + else:
2546 + # UWAGA: '..' w relatywnym celu linku jest POPRAWNE i częste
2547 + # (np. busybox: bin/ls -> ../usr/bin/busybox). Wcześniej taki
2548 + # link byl po cichu pomijany, przez co busybox instalowal
2549 + # 3 pliki zamiast 388. Decyduje realny cel — _target_within().
2550 + link_target = os.path.join(os.path.dirname(target), link)
2551 + if not _target_within(link_target):
2552 + print(f" BLOCKED (link escape): {name} -> {link}")
2553 + continue
2554 +
2555 + # Rozpakuj z zachowaniem metadanych. Python 3.12+ wymaga jawnego
2556 + # `filter=` (inaczej DeprecationWarning, a w 3.14+ błąd).
2557 + # UWAGA: 'fully_trusted' CELOWO pomija wbudowane filtry bezpieczeństwa
2558 + # Pythona – to nie przeoczenie. Nasza walidacja powyżej (path traversal,
2559 + # NUL/backslash, escape przez symlink, linki wychodzące poza dest) jest
2560 + # równoważna lub ostrzejsza, a 'fully_trusted' pozwala zachować bity
2561 + # SUID/SGID/sticky, które filtr 'data' by usunął (np. /usr/bin/sudo).
2562 + # SUID jest i tak zdejmowany przez _strip_suid() tuż po rozpakowaniu.
2563 + try:
2564 + if hasattr(tarfile, 'data_filter'):
2565 + # Python 3.12+
2566 + tar.extract(member, dest, set_attrs=preserve_perms, numeric_owner=False,
2567 + filter='fully_trusted')
2568 + else:
2569 + tar.extract(member, dest, set_attrs=preserve_perms, numeric_owner=False)
2570 + except Exception as e:
2571 + print(_(' ⚠ Failed to extract {arg1}: {arg2}', arg1=(name), arg2=(e)))
2572 + continue
2573 + # Pliki z listy uprzywilejowanej zachowują SUID/SGID; reszta jest
2574 + # czyszczona (ochrona przed SUID niespodziewanym w pakiecie).
2575 + if "/" + os.path.relpath(target, dest_real) not in privileged:
2576 + _strip_suid(target)
2577 +
2578 +
2579 +def _sha256_file(path: str) -> str:
2580 + """SHA256 pliku. Na Python ≥3.11 używa hashlib.file_digest (pętla w C);
2581 + starsze wersje mają fallback z pętlą chunków."""
2582 + with open(path, "rb") as f:
2583 + if hasattr(hashlib, "file_digest"):
2584 + return hashlib.file_digest(f, "sha256").hexdigest()
2585 + h = hashlib.sha256()
2586 + for chunk in iter(lambda: f.read(65536), b""):
2587 + h.update(chunk)
2588 + return h.hexdigest()
2589 +
2590 +def _split_version(v: str):
2591 + """Rozdziela wersję na (release_parts, prerelease_parts).
2592 +
2593 + Przykład: '1.2.0-rc1' → ([1,2,0], ['rc','1']).
2594 + """
2595 + v = v.strip().lower().lstrip("v")
2596 + # build metadata po '+' jest ignorowane przy porównywaniu (semver)
2597 + v = v.split("+", 1)[0]
2598 + # prerelease po '-' lub '_' (np. 1.2.0-rc1, 1.2.0_rc1)
2599 + if "-" in v:
2600 + rel, pre = v.split("-", 1)
2601 + elif "_" in v:
2602 + rel, pre = v.split("_", 1)
2603 + else:
2604 + rel, pre = v, ""
2605 + nums = []
2606 + for part in rel.split("."):
2607 + m = re.match(r"(\d+)", part)
2608 + nums.append(int(m.group(1)) if m else 0)
2609 + pre_parts = [p for p in pre.split(".") if p]
2610 + return nums, pre_parts
2611 +
2612 +
2613 +def _cmp_pre(a, b):
2614 + """Porównuje ciągi identyfikatorów prerelease (reguły semver)."""
2615 + for i in range(max(len(a), len(b))):
2616 + if i >= len(a):
2617 + return -1 # krótszy prerelease jest niższy
2618 + if i >= len(b):
2619 + return 1
2620 + ia, ib = a[i], b[i]
2621 + if ia == ib:
2622 + continue
2623 + na, nb = ia.isdigit(), ib.isdigit()
2624 + if na and nb:
2625 + return 1 if int(ia) > int(ib) else -1
2626 + if na != nb:
2627 + return -1 if na else 1 # identyfikator liczbowy < alfanumeryczny
2628 + return 1 if ia > ib else -1
2629 + return 0
2630 +
2631 +
2632 +def _cmp_version(a: str, b: str) -> int:
2633 + """Porównuje dwie wersje; zwraca -1/0/1. Obsługuje prerelease (rc1, beta...)."""
2634 + a_rel, a_pre = _split_version(a)
2635 + b_rel, b_pre = _split_version(b)
2636 + # Porównaj część release (brakujące komponenty traktuj jako 0)
2637 + for i in range(max(len(a_rel), len(b_rel))):
2638 + xa = a_rel[i] if i < len(a_rel) else 0
2639 + xb = b_rel[i] if i < len(b_rel) else 0
2640 + if xa != xb:
2641 + return 1 if xa > xb else -1
2642 + # Część release równa → decyduje prerelease.
2643 + # Wersja finalna (bez prerelease) jest ZAWSZE nowsza od prerelease.
2644 + if not a_pre and not b_pre:
2645 + return 0
2646 + if not a_pre:
2647 + return 1
2648 + if not b_pre:
2649 + return -1
2650 + return _cmp_pre(a_pre, b_pre)
2651 +
2652 +
2653 +def _version_newer(a: str, b: str) -> bool:
2654 + """True gdy wersja a jest nowsza od b (z poprawną obsługą prerelease)."""
2655 + try:
2656 + return _cmp_version(a, b) > 0
2657 + except Exception:
2658 + return a != b
2659 +
2660 +def load_json(path):
2661 + try:
2662 + with open(path) as f:
2663 + return json.load(f)
2664 + except (FileNotFoundError, json.JSONDecodeError):
2665 + return {}
2666 +
2667 +def save_json(path, data):
2668 + with open(path, "w") as f:
2669 + json.dump(data, f, indent=2)
2670 +
2671 +class PackageInfo:
2672 + __slots__ = ("name","version","release","description","dependencies",
2673 + "optdepends","size_bytes","sha256","gpg_fp","repo_url","filename",
2674 + "provides","license","provides_so","requires_so","privileged")
2675 + def __init__(self, d, repo=""):
2676 + self.name = d.get("name","?")
2677 + self.version = d.get("version","0")
2678 + self.release = d.get("release", 1)
2679 + self.description = d.get("description","")
2680 + self.dependencies = d.get("dependencies", d.get("depends", []))
2681 + # Opcjonalne zależności (flatpak, btrfs-progs, grub, ...) – tylko
2682 + # informacyjne; `pag install` NIE instaluje ich automatycznie.
2683 + self.optdepends = d.get("optdepends", []) or []
2684 + self.size_bytes = d.get("size",0)
2685 + self.sha256 = d.get("sha256","")
2686 + self.gpg_fp = d.get("gpg_fingerprint","")
2687 + self.repo_url = repo
2688 + self.filename = d.get("filename", f"{self.name}-{self.version}{PKG_EXT}")
2689 + self.provides = d.get("provides", []) or []
2690 + self.license = d.get("license", []) or []
2691 + self.provides_so = d.get("provides_so", []) or []
2692 + self.requires_so = d.get("requires_so", []) or []
2693 + # Ścieżki, którym wolno zachować setuid/setgid i grupę (z receptury).
2694 + self.privileged = d.get("privileged", []) or []
2695 +
2696 +# =============================================================================
2697 +# REPOZYTORIA (cache, ETag, GPG)
2698 +# =============================================================================
2699 +
2700 +def _parse_repos_config():
2701 + """Parsuje repozytoria z /etc/pag/repos.conf oraz /etc/pag/repos/*.conf.
2702 +
2703 + Format linii: <url> [fingerprint]
2704 + Opcjonalny `fingerprint` (40 znaków hex) pozwala przypiąć klucz
2705 + podpisujący repo do konkretnego adresu – wtedy TOFU (auto-zaufanie przy
2706 + pierwszym użyciu) nie jest potrzebne, a zmiana klucza = błąd bezpieczeństwa.
2707 +
2708 + Drop-iny (np. stable.conf) są czytane alfabetycznie – pozwalają na
2709 + wygodne dodawanie repo bez dotykania głównego repos.conf
2710 + (np. `echo 'https://repo.paganlinux.eu/stable' > /etc/pag/repos/stable.conf`).
2711 + """
2712 + entries = []
2713 +
2714 + def _read_lines(path):
2715 + if not os.path.exists(path):
2716 + return
2717 + for line in open(path):
2718 + line = line.strip()
2719 + if not line or line.startswith("#"):
2720 + continue
2721 + parts = line.split()
2722 + url = parts[0].rstrip("/")
2723 + fp = parts[1].lower() if len(parts) > 1 else ""
2724 + entries.append({"url": url, "fingerprint": fp or None})
2725 +
2726 + # 1) Legacy: pojedynczy plik /etc/pag/repos.conf
2727 + _read_lines(REPOS_CONF)
2728 + # 2) Drop-in: /etc/pag/repos/<nazwa>.conf (sortowane, stabilna kolejność)
2729 + if os.path.isdir(REPOS_DIR):
2730 + for drop in sorted(os.listdir(REPOS_DIR)):
2731 + if drop.endswith(".conf"):
2732 + _read_lines(os.path.join(REPOS_DIR, drop))
2733 +
2734 + # Dedupe po URL (zachowaj pierwszy wpis – może mieć fingerprint)
2735 + seen, unique = set(), []
2736 + for e in entries:
2737 + if e["url"] not in seen:
2738 + seen.add(e["url"])
2739 + unique.append(e)
2740 +
2741 + if not unique:
2742 + for url in DEFAULT_REPOS:
2743 + # rstrip: get_repos()/_repo_pinned_fp() kluczują URL-e bez ukośnika
2744 + unique.append({"url": url.rstrip("/"), "fingerprint": None})
2745 + return unique
2746 +
2747 +
2748 +def get_repos():
2749 + return [e["url"] for e in _parse_repos_config()]
2750 +
2751 +
2752 +def _repo_pinned_fp(repo_url):
2753 + """Zwraca przypięty fingerprint klucza dla repo (z konfiguracji lub trust DB)."""
2754 + # Normalizacja ukośnika: _parse_repos_config() i trust DB kluczują URL-e BEZ
2755 + # końcowego „/”, a wywołujący podają często DEFAULT_REPOS[0] Z ukośnikiem.
2756 + # Bez tego przypięty klucz nie był znajdowany i lokalny .pag dostawał
2757 + # fałszywe „Brak przypiętego klucza repo” mimo poprawnego wpisu w trusted.json.
2758 + repo_url = repo_url.rstrip("/")
2759 + by_url = {e["url"]: e["fingerprint"] for e in _parse_repos_config()}
2760 + if by_url.get(repo_url):
2761 + return by_url[repo_url]
2762 + db = _load_trust_db()
2763 + fp = db.get(repo_url)
2764 + return fp.lower() if fp else None
2765 +
2766 +def _repo_cache_path(url):
2767 + return os.path.join(REPO_CACHE, url.replace("://","_").replace("/","_").replace(".","_") + ".json")
2768 +
2769 +def _repo_etag_path(url): return _repo_cache_path(url) + ".etag"
2770 +def _repo_ts_path(url): return _repo_cache_path(url) + ".ts"
2771 +
2772 +# Informacja (raz na uruchomienie), gdy cache repozytoriów jest tylko-do-odczytu –
2773 +# np. komendy read-only (`pag info`, `pag search`…) jako zwykły user: nie ma sensu
2774 +# ani prawa odświeżać /var/cache/pag/repos, więc używamy lokalnej kopii indeksu.
2775 +_cache_ro_notice_done = False
2776 +
2777 +def _cache_ro_notice():
2778 + global _cache_ro_notice_done
2779 + if _cache_ro_notice_done:
2780 + return
2781 + _cache_ro_notice_done = True
2782 + print(f" ⚠ {_('cache_ro', cache=REPO_CACHE)}", file=sys.stderr)
2783 +
2784 +def _load_repo_cache(cp: str) -> Optional[list]:
2785 + """Wczytuje cache indeksu repo; zwraca None gdy brak albo uszkodzony.
2786 +
2787 + Partial write (crash w trakcie zapisu) mógł zostawić obcięty JSON. Zamiast
2788 + zwracać pustą listę pakietów (użytkownik myśli, że repo jest puste)
2789 + sygnalizujemy None – wywołujący ponowi pobranie albo pokaże ostrzeżenie."""
2790 + if not os.path.exists(cp):
2791 + return None
2792 + try:
2793 + with open(cp, "r", encoding="utf-8") as fh:
2794 + data = json.load(fh)
2795 + pkgs = data.get("packages")
2796 + if not isinstance(pkgs, list):
2797 + raise ValueError(_("repo_index_invalid"))
2798 + return pkgs
2799 + except (OSError, ValueError) as e:
2800 + print(_(' ⚠ Corrupted index cache {arg1}: {arg2}', arg1=(cp), arg2=(e)), file=sys.stderr)
2801 + return None
2802 +
2803 +
2804 +def fetch_repo_index(repo_url, force=False):
2805 + cp = _repo_cache_path(repo_url)
2806 + ep = _repo_etag_path(repo_url)
2807 + tp = _repo_ts_path(repo_url)
2808 +
2809 + if not force and os.path.exists(cp) and os.path.exists(tp):
2810 + try:
2811 + if time.time() - float(open(tp).read().strip()) < REPO_CACHE_TTL:
2812 + cached = _load_repo_cache(cp)
2813 + if cached is not None:
2814 + return cached
2815 + # uszkodzony cache – spróbuj odświeżyć z sieci
2816 + except (OSError, ValueError):
2817 + pass
2818 +
2819 + # --- Cache tylko-do-odczytu (np. `pag info` jako zwykły user) ---
2820 + # /var/cache/pag/repos należy do roota. Nie próbuj odświeżać ani pisać –
2821 + # zwykły user i tak nie zapisze indeksu; użyj lokalnej kopii (może być
2822 + # nieaktualna). Pełne odświeżenie indeksu: sudo pag sync
2823 + if not (os.path.isdir(REPO_CACHE) and os.access(REPO_CACHE, os.W_OK)):
2824 + if force:
2825 + print(_(' ❌ {arg1}: cannot refresh index – {arg2} is read-only', arg1=(repo_url), arg2=(REPO_CACHE)),
2826 + file=sys.stderr)
2827 + return None
2828 + _cache_ro_notice()
2829 + cached = _load_repo_cache(cp)
2830 + if cached is not None:
2831 + return cached
2832 + return None
2833 +
2834 + headers = {"User-Agent": "pag/3.0"}
2835 + if os.path.exists(tp) and not force:
2836 + try:
2837 + lm = datetime.fromtimestamp(float(open(tp).read().strip()), tz=timezone.utc)
2838 + # Wymuś lokalizację C/POSIX dla nagłówków HTTP, aby unikać problemów z nazwami dni/miesięcy
2839 + try:
2840 + old_locale = locale.setlocale(locale.LC_TIME)
2841 + locale.setlocale(locale.LC_TIME, 'C')
2842 + headers["If-Modified-Since"] = lm.strftime("%a, %d %b %Y %H:%M:%S GMT")
2843 + locale.setlocale(locale.LC_TIME, old_locale)
2844 + except (locale.Error, ValueError):
2845 + # Jeśli ustawienie lokalizacji się nie powiedzie, użyj domyślnej
2846 + headers["If-Modified-Since"] = lm.strftime("%a, %d %b %Y %H:%M:%S GMT")
2847 + except: pass
2848 + if os.path.exists(ep) and not force:
2849 + try: headers["If-None-Match"] = open(ep).read().strip()
2850 + except: pass
2851 +
2852 + # --- Pobranie indeksu (błędy SIECI nie są błędami zapisu cache) ---
2853 + try:
2854 + req = Request(f"{repo_url}/repo.json", headers=headers)
2855 + with urlopen(req, timeout=30) as resp:
2856 + etag = resp.headers.get("ETag","")
2857 + raw = resp.read()
2858 + data = json.loads(raw.decode())
2859 + except HTTPError as e:
2860 + if e.code == 304:
2861 + # Serwer: indeks bez zmian – odśwież tylko znacznik czasu (best-effort)
2862 + try:
2863 + open(tp,"w").write(str(time.time()))
2864 + except OSError:
2865 + pass
2866 + cached = _load_repo_cache(cp)
2867 + if cached is not None:
2868 + return cached
2869 + # uszkodzona kopia – potraktuj jak brak (ostrzeżenie niżej)
2870 + print(_(' ⚠ HTTP {arg1} for {arg2}', arg1=(e.code), arg2=(repo_url)), file=sys.stderr)
2871 + return None
2872 + except Exception as e:
2873 + print(_(' ⚠ Failed to download index {arg1}: {arg2}', arg1=(repo_url), arg2=(e)), file=sys.stderr)
2874 + return _load_repo_cache(cp)
2875 +
2876 + # Indeks pobrany – zapisz SUROWE bajty (nie re-serializuj! podpis GPG jest
2877 + # nad oryginalnymi bajtami repo.json z serwera) i zweryfikuj podpis.
2878 + # Najpierw zapis tymczasowy + weryfikacja GPG, dopiero potem podmiana cp:
2879 + # błąd zapisu (np. pełny dysk) nie niszczy starej, zweryfikowanej kopii
2880 + # i NIGDY nie zwracamy danych, które nie przeszły weryfikacji.
2881 + tmp_path = cp + ".tmp"
2882 + try:
2883 + with open(tmp_path, "wb") as f:
2884 + f.write(raw)
2885 + if not _verify_repo_sig(repo_url, tmp_path):
2886 + return None # weryfikacja nie powiodła się – stary cache zostaje
2887 + os.replace(tmp_path, cp)
2888 + # przenieś podpis obok docelowego pliku (marker „repo ma podpis")
2889 + for _ext in (".asc", ".sig"):
2890 + if os.path.exists(tmp_path + _ext):
2891 + try:
2892 + os.replace(tmp_path + _ext, cp + _ext)
2893 + except OSError:
2894 + pass
2895 + break
2896 + if etag:
2897 + try:
2898 + open(ep,"w").write(etag)
2899 + except OSError:
2900 + pass
2901 + try:
2902 + open(tp,"w").write(str(time.time()))
2903 + except OSError:
2904 + pass
2905 + return data.get("packages",[])
2906 + except OSError as e:
2907 + print(_(' ⚠ Index downloaded, but failed to save cache ({arg1}): {arg2}', arg1=(REPO_CACHE), arg2=(e)),
2908 + file=sys.stderr)
2909 + # cp nie został podmieniony (podmiana jest po weryfikacji) – lokalna kopia
2910 + # to wciąż stare, zweryfikowane dane
2911 + return _load_repo_cache(cp)
2912 + finally:
2913 + for _p in (tmp_path, tmp_path + ".asc", tmp_path + ".sig"):
2914 + try:
2915 + os.unlink(_p)
2916 + except OSError:
2917 + pass
2918 +
2919 +def _verify_repo_sig(repo_url, cache_path) -> bool:
2920 + """Weryfikuje podpis GPG indeksu repozytorium i przypina fingerprint.
2921 +
2922 + FAIL-CLOSED: brak/nieprawidłowy podpis = False (chyba że PAG_INSECURE=1).
2923 + Zwraca True jeśli indeks jest zaufany, False jeśli należy go odrzucić.
2924 +
2925 + Model zaufania (TOFU + pinning):
2926 + - Pierwszy raz (brak przypiętego fingerprintu) → klucz jest importowany,
2927 + a fingerprint zapisywany w /etc/pag/trusted.json z JAWNYM ostrzeżeniem.
2928 + To świadomy kompromis wygody i bezpieczeństwa.
2929 + - Kolejne uruchomienia: fingerprint jest porównywany z przypiętym.
2930 + Zmiana klucza = ❌ SECURITY ERROR (fail-closed), wymagane ręczne:
2931 + pag key-trust <repo_url> (po weryfikacji nowego klucza)
2932 + """
2933 + insecure = os.environ.get("PAG_INSECURE", "") == "1"
2934 +
2935 + if not os.path.exists(GPG_HOME):
2936 + if insecure:
2937 + return True # brak GPG home – tryb insecure, akceptuj
2938 + print(_(' ❌ {arg1}: no GPG keys – verification impossible!', arg1=(repo_url)))
2939 + print(_(' Set PAG_INSECURE=1 to skip (not recommended)'))
2940 + os.remove(cache_path)
2941 + return False
2942 +
2943 + sig_path = cache_path + ".sig"
2944 + # Podpisy generowane jako .asc (armored) – próbuj .asc, potem .sig
2945 + sig_data = None
2946 + sig_ext = ""
2947 + for ext in (".asc", ".sig"):
2948 + try:
2949 + req = Request(f"{repo_url}/repo.json{ext}", headers={"User-Agent":"pag/3.0"})
2950 + with urlopen(req, timeout=15) as resp:
2951 + sig_data = resp.read()
2952 + sig_ext = ext
2953 + break
2954 + except Exception:
2955 + continue
2956 + if not sig_data:
2957 + if insecure:
2958 + return True # tryb insecure – akceptuj bez podpisu
2959 + print(_(' ❌ {arg1}: CANNOT DOWNLOAD SIGNATURE repo.json.asc/.sig!', arg1=(repo_url)))
2960 + print(_(' Set PAG_INSECURE=1 to skip (not recommended)'))
2961 + os.remove(cache_path)
2962 + return False
2963 + sig_path = cache_path + sig_ext
2964 + with open(sig_path, "wb") as f:
2965 + f.write(sig_data)
2966 +
2967 + ok, fingerprint = _gpg_verify_fp(sig_path, cache_path)
2968 + if not ok:
2969 + # Automatyczny import klucza repo przy pierwszym uruchomieniu (TOFU,
2970 + # jak apt) – gdy w keyringu brakuje klucza (No public key).
2971 + res = _gpg_run("--verify", sig_path, cache_path,
2972 + capture_output=True, text=True, timeout=30)
2973 + _stderr = res.stderr.decode(errors="replace") if isinstance(res.stderr, bytes) else (res.stderr or "")
2974 + if "public key" in _stderr.lower() and "no public key" in _stderr.lower():
2975 + try:
2976 + with urlopen(Request(f"{repo_url}/paganos.asc", headers={"User-Agent": "pag/3.0"}), timeout=20) as r:
2977 + keydata = r.read()
2978 + with tempfile.NamedTemporaryFile(delete=False, suffix=".asc") as tmp:
2979 + tmp.write(keydata)
2980 + tmp.flush()
2981 + _gpg_run("--import", tmp.name, capture_output=True, timeout=30)
2982 + os.unlink(tmp.name)
2983 + print(_(' 🔑 Imported repo key from {arg1}/paganos.asc', arg1=(repo_url)))
2984 + ok, fingerprint = _gpg_verify_fp(sig_path, cache_path)
2985 + except Exception:
2986 + pass
2987 + if not ok:
2988 + if insecure:
2989 + print(_(' ⚠ {arg1}: invalid GPG signature (PAG_INSECURE – ignoring)', arg1=(repo_url)))
2990 + return True
2991 + os.remove(cache_path)
2992 + if not shutil.which(GPG_BINARY):
2993 + print(_(' ❌ {arg1}: GPG is not installed – cannot verify the signature!', arg1=(repo_url)))
2994 + print(_(' Install gnupg or set PAG_INSECURE=1 (not recommended)'))
2995 + else:
2996 + print(_(' ❌ {arg1}: INVALID GPG SIGNATURE of the repository index!', arg1=(repo_url)))
2997 + return False
2998 +
2999 + # --- Wymuś przypięty fingerprint (TOFU + pinning) ---
3000 + pinned = _repo_pinned_fp(repo_url)
3001 + if pinned:
3002 + if not fingerprint:
3003 + if insecure:
3004 + print(_(' ⚠ {arg1}: cannot read signature fingerprint (PAG_INSECURE – ignoring)', arg1=(repo_url)))
3005 + return True
3006 + os.remove(cache_path)
3007 + print(_(' ❌ [SECURITY ERROR] {arg1}: cannot read signature fingerprint!', arg1=(repo_url)))
3008 + print(_(' Pinned key: {arg1} – rejecting the index.', arg1=(pinned)))
3009 + return False
3010 + if fingerprint != pinned.upper():
3011 + if insecure:
3012 + print(_(' ⚠ {arg1}: SIGNING KEY CHANGED (PAG_INSECURE – ignoring)', arg1=(repo_url)))
3013 + return True
3014 + os.remove(cache_path)
3015 + print(_(' ❌ [SECURITY ERROR] {arg1}: Repository signing key has changed!', arg1=(repo_url)))
3016 + print(_(' Expected: {arg1}', arg1=(pinned)))
3017 + print(_(' Received: {arg1}', arg1=(fingerprint)))
3018 + print(_(' If this is an intentional key rotation: pag key-trust {arg1}', arg1=(repo_url)))
3019 + return False
3020 + return True
3021 +
3022 + if fingerprint:
3023 + # Brak przypiętego fingerprintu → TOFU: zapisz go w bazie zaufania.
3024 + db = _load_trust_db()
3025 + if db.get(repo_url) != fingerprint:
3026 + _save_trust_db({**db, repo_url: fingerprint})
3027 + print(_(' 🔐 Pinned repo fingerprint {arg1}: {arg2}', arg1=(repo_url), arg2=(fingerprint)))
3028 + print(_(' (TOFU – first trust. If the key changes, pag will refuse updates.)'))
3029 + print(_(' To avoid TOFU, add the fingerprint to /etc/pag/repos.conf.'))
3030 + return True
3031 +
3032 +def fetch_all_packages(force=False):
3033 + all_pkgs = {}
3034 + for repo_url in get_repos():
3035 + pkgs = fetch_repo_index(repo_url, force)
3036 + if pkgs:
3037 + for pdata in pkgs:
3038 + name = pdata.get("name", pdata.get("filename","?").split("-")[0])
3039 + pkg = PackageInfo(pdata, repo_url)
3040 + if name not in all_pkgs or _version_newer(pkg.version, all_pkgs[name].version):
3041 + all_pkgs[name] = pkg
3042 + return all_pkgs
3043 +
3044 +# =============================================================================
3045 +# GPG
3046 +# =============================================================================
3047 +
3048 +def _verify_pkg_gpg(pkg_path, repo_url=None):
3049 + """Weryfikuje podpis GPG pakietu i (jeśli znamy repo) przypięty fingerprint.
3050 +
3051 + FAIL-CLOSED: brak podpisu = odrzucenie (chyba że PAG_INSECURE=1).
3052 + Zwraca (passed: bool, message: str).
3053 + """
3054 + insecure = os.environ.get("PAG_INSECURE", "") == "1"
3055 + # Brak gnupg = weryfikacja niemożliwa. Bez tej gałęzi użytkownik dostawał
3056 + # mylące „NIEPRAWIDŁOWY PODPIS GPG”, mimo że paczka i podpis są w porządku.
3057 + if not shutil.which(GPG_BINARY):
3058 + if insecure:
3059 + return True, "(gpg missing – PAG_INSECURE)"
3060 + return False, _("gpg_missing")
3061 + sig_path = pkg_path + ".sig"
3062 + if not os.path.exists(sig_path) and os.path.exists(pkg_path + ".asc"):
3063 + sig_path = pkg_path + ".asc"
3064 +
3065 + if not os.path.exists(sig_path):
3066 + if insecure:
3067 + return True, "(no signature – PAG_INSECURE)"
3068 + return False, "BRAK PODPISU – pakiet odrzucony (ustaw PAG_INSECURE=1 aby pominąć)"
3069 +
3070 + ok, fp = _gpg_verify_fp(sig_path, pkg_path)
3071 + if not ok:
3072 + if insecure:
3073 + return True, "(invalid signature – PAG_INSECURE)"
3074 + return False, "NIEPRAWIDŁOWY PODPIS GPG"
3075 +
3076 + # Opcjonalnie: sprawdź, czy podpis pochodzi od klucza przypiętego dla repo.
3077 + if repo_url:
3078 + pinned = _repo_pinned_fp(repo_url)
3079 + if pinned and fp and fp != pinned.upper():
3080 + if insecure:
3081 + return True, "(pkg signer mismatch – PAG_INSECURE)"
3082 + return False, f"PAKIET PODPISANY INNYM KLUCZEM niż repo (oczekiwano {pinned})"
3083 +
3084 + return True, "GPG verified"
3085 +
3086 +def cmd_key_add(source):
3087 + ensure_dirs()
3088 + if not shutil.which(GPG_BINARY):
3089 + print(f"❌ {_('gpg_missing')}"); return 1
3090 + if source.startswith("http"):
3091 + try:
3092 + with urlopen(Request(source, headers={"User-Agent":"pag/3.0"}), timeout=30) as resp:
3093 + keydata = resp.read()
3094 + with tempfile.NamedTemporaryFile(delete=False, suffix=".gpg") as tmp:
3095 + tmp.write(keydata); tmp.flush()
3096 + res = _gpg_run("--import", tmp.name, capture_output=True, timeout=30)
3097 + os.unlink(tmp.name)
3098 + if res.returncode != 0:
3099 + print(f"❌ {_('key_add_failed')}"); return 1
3100 + except Exception as e:
3101 + print(_('❌ Download error: {arg1}', arg1=(e))); return 1
3102 + else:
3103 + res = _gpg_run("--import", source, capture_output=True, timeout=30)
3104 + if res.returncode != 0:
3105 + print(f"❌ {_('key_add_failed')}"); return 1
3106 + print(f"✅ {_('key_imported')}")
3107 +
3108 +def cmd_key_list():
3109 + if not shutil.which(GPG_BINARY):
3110 + print(f"❌ {_('gpg_missing')}"); return
3111 + if not os.path.exists(GPG_HOME):
3112 + print(_("no_keys")); return
3113 + result = _gpg_run("--list-keys", "--keyid-format", "LONG",
3114 + capture_output=True, text=True, timeout=30)
3115 + if result.returncode != 0:
3116 + print(f"❌ {_('gpg_missing')}"); return
3117 + print(result.stdout or _("no_keys"))
3118 +
3119 +def cmd_key_remove(key_id):
3120 + _gpg_run("--batch", "--yes", "--delete-key", key_id,
3121 + capture_output=True, timeout=30)
3122 + print(f"✅ {_('key_removed', key_id)}")
3123 +
3124 +def _repo_signer_fp(repo_url):
3125 + """Pobiera repo.json + podpis i zwraca fingerprint podpisującego (bez pinningu)."""
3126 + repo_url = repo_url.rstrip("/")
3127 + try:
3128 + with urlopen(Request(f"{repo_url}/repo.json", headers={"User-Agent":"pag/3.0"}), timeout=30) as r:
3129 + data = r.read()
3130 + except Exception:
3131 + return None
3132 + sig = None
3133 + sig_ext = ".asc"
3134 + for ext in (".asc", ".sig"):
3135 + try:
3136 + with urlopen(Request(f"{repo_url}/repo.json{ext}", headers={"User-Agent":"pag/3.0"}), timeout=20) as r:
3137 + sig = r.read()
3138 + sig_ext = ext
3139 + break
3140 + except Exception:
3141 + continue
3142 + if not sig:
3143 + return None
3144 + with tempfile.NamedTemporaryFile(delete=False, suffix=".json") as tf:
3145 + tf.write(data); tf.flush()
3146 + data_path = tf.name
3147 + sig_path = data_path + sig_ext
3148 + try:
3149 + with open(sig_path, "wb") as f:
3150 + f.write(sig)
3151 + ok, fp = _gpg_verify_fp(sig_path, data_path)
3152 + finally:
3153 + for p in (data_path, sig_path):
3154 + try: os.unlink(p)
3155 + except OSError: pass
3156 + return fp if ok else None
3157 +
3158 +
3159 +def cmd_key_trust(repo_url):
3160 + """Przypina fingerprint klucza podpisującego repo (koniec z TOFU dla tego repo)."""
3161 + repo_url = repo_url.rstrip("/")
3162 + print(_('🔐 Pinning repo key {arg1}...', arg1=(repo_url)))
3163 + fp = _repo_signer_fp(repo_url)
3164 + if not fp:
3165 + print(_(' ❌ Cannot read signature fingerprint (missing/failed).'))
3166 + print(_(' Make sure the repo key is in the keyring (pag key-add <url|file>).'))
3167 + return 1
3168 + db = _load_trust_db()
3169 + _save_trust_db({**db, repo_url: fp})
3170 + print(_(' ✅ Pinned {arg1} for {arg2}', arg1=(fp), arg2=(repo_url)))
3171 + print(_(' From now on, a key change will be reported as SECURITY ERROR.'))
3172 + return 0
3173 +
3174 +
3175 +def cmd_key_untrust(repo_url):
3176 + """Usuwa przypięcie fingerprintu dla repo (wraca do TOFU)."""
3177 + repo_url = repo_url.rstrip("/")
3178 + db = _load_trust_db()
3179 + if repo_url not in db:
3180 + print(_(' ℹ {arg1} has no pinned fingerprint.', arg1=(repo_url)))
3181 + return 0
3182 + del db[repo_url]
3183 + _save_trust_db(db)
3184 + print(_(' ✅ Removed pin for {arg1}.', arg1=(repo_url)))
3185 + return 0
3186 +
3187 +
3188 +def cmd_key_trusted():
3189 + """Listuje przypięte fingerprinty repozytoriów."""
3190 + db = _load_trust_db()
3191 + if not db:
3192 + print(_("no_keys"))
3193 + return
3194 + for url, fp in sorted(db.items()):
3195 + print(f" {url}\n {fp}")
3196 +
3197 +# =============================================================================
3198 +# ATOMOWA INSTALACJA (STAGING)
3199 +# =============================================================================
3200 +
3201 +def _safe_rename(src: str, dst: str) -> bool:
3202 + """
3203 + Atomowe przeniesienie pliku. Jeśli src i dst są na różnych
3204 + systemach plików (EXDEV), kopiuje + usuwa źródło.
3205 + """
3206 + try:
3207 + os.rename(src, dst)
3208 + return True
3209 + except OSError as e:
3210 + if e.errno == 18: # EXDEV – cross-device link
3211 + shutil.copy2(src, dst)
3212 + os.remove(src)
3213 + return True
3214 + raise
3215 +
3216 +
3217 +def _install_file(src: str, rel: str, data_staging: str, sums: dict,
3218 + staging: str, journal: list, installed_files: list,
3219 + deploy_dir: str = "", backup_dir: str = "",
3220 + backup_journal: Optional[list] = None,
3221 + old_checksums: Optional[dict] = None,
3222 + privileged=frozenset()) -> bool:
3223 + """
3224 + Instaluje pojedynczy plik (zwykły lub symlink).
3225 + Obsługuje: cross-device rename, symlinki, weryfikację SHA256.
3226 +
3227 + Jeśli deploy_dir jest podany (tryb immutable), pliki systemowe trafiają
3228 + do deploymentu, a współdzielone (/var, /etc, ...) bezpośrednio do /.
3229 +
3230 + Jeśli backup_dir jest podany, a pod dst istnieje już plik (upgrade/reinstall),
3231 + stara wersja jest przenoszona do backup_dir, by rollback mógł ją przywrócić.
3232 +
3233 + old_checksums: {ścieżka: sha256 z chwili instalacji}. Gdy podane i plik /etc
3234 + został zmodyfikowany przez użytkownika, nowa wersja ląduje jako .pacnew
3235 + (stary plik NIE jest ruszany) – wzorzec jak w pacmanie.
3236 + """
3237 + # W trybie immutable: pliki współdzielone idą do /, reszta do deploymentu
3238 + if deploy_dir and _is_shared_path("/" + rel):
3239 + dst_root = PAG_ROOT
3240 + elif deploy_dir:
3241 + dst_root = deploy_dir
3242 + else:
3243 + dst_root = PAG_ROOT
3244 +
3245 + dst = os.path.join(dst_root, rel)
3246 +
3247 + # --- SYMLINK ---
3248 + if os.path.islink(src):
3249 + link_target = os.readlink(src)
3250 + # Weryfikuj sums.json dla symlinka (hash ścieżki docelowej)
3251 + expected = sums.get("/" + rel, "")
3252 + if expected:
3253 + link_hash = hashlib.sha256(link_target.encode()).hexdigest()
3254 + if expected and link_hash != expected:
3255 + return False
3256 +
3257 + os.makedirs(os.path.dirname(dst), exist_ok=True)
3258 + # Backup istniejącego symlinka (upgrade) – dla poprawnego rollbacku
3259 + if backup_dir and backup_journal is not None and os.path.lexists(dst):
3260 + try:
3261 + backup_path = os.path.join(backup_dir, rel)
3262 + os.makedirs(os.path.dirname(backup_path), exist_ok=True)
3263 + os.replace(dst, backup_path)
3264 + backup_journal.append((backup_path, "/" + rel))
3265 + journal.append(("backup", backup_path, dst))
3266 + except OSError:
3267 + pass
3268 + # Jeśli docelowy symlink już istnieje, usuń go
3269 + if os.path.islink(dst) or os.path.exists(dst):
3270 + os.remove(dst)
3271 + os.symlink(link_target, dst)
3272 + journal.append(("symlink", "", dst))
3273 + installed_files.append({
3274 + "path": "/" + rel,
3275 + "sha256": hashlib.sha256(link_target.encode()).hexdigest(),
3276 + "size": len(link_target),
3277 + "is_symlink": True,
3278 + "symlink_target": link_target,
3279 + })
3280 + return True
3281 +
3282 + # --- ZWYKŁY PLIK ---
3283 + # Oblicz SHA256
3284 + try:
3285 + file_sha = _sha256_file(src)
3286 + except Exception:
3287 + file_sha = ""
3288 +
3289 + # Weryfikuj sums.json
3290 + expected = sums.get("/" + rel, "")
3291 + if expected and file_sha and file_sha != expected:
3292 + return False
3293 +
3294 + # --- .pacnew: NIE nadpisuj pliku konfiguracyjnego, którego nie wolno zgubić ---
3295 + # Robimy `<plik>.pacnew`, gdy:
3296 + # a) plik jest śledzony i użytkownik go zmodyfikował (hash != zapisanej sumy),
3297 + # b) to wrażliwa konfiguracja (/etc/pam.d, /etc/security, sudoers, shadow…),
3298 + # a treść na dysku różni się od tej z pakietu – chroni auth przed
3299 + # cichym nadpisaniem przez `install`/`upgrade` (np. przez shadow).
3300 + # NIE robimy .pacnew, jeśli plik na dysku jest identyczny z nowym albo był
3301 + # niezmieniony od instalacji (wtedy nadpisanie jest bezpieczne).
3302 + old_sha = (old_checksums or {}).get("/" + rel, "")
3303 + if file_sha and _is_config_path(rel) and os.path.isfile(dst) and not os.path.islink(dst):
3304 + tracked_modified = bool(old_sha) and file_sha != old_sha
3305 + if tracked_modified or _is_sensitive_config(rel):
3306 + try:
3307 + cur_sha = _sha256_file(dst)
3308 + except OSError:
3309 + cur_sha = ""
3310 + if cur_sha and cur_sha != file_sha and not (old_sha and cur_sha == old_sha):
3311 + pacnew = dst + ".pacnew"
3312 + try:
3313 + _safe_rename(src, pacnew)
3314 + try:
3315 + os.chown(pacnew, 0, 0)
3316 + except (OSError, PermissionError):
3317 + pass
3318 + # Journal (do cofnięcia przy nieudanej transakcji) – ale NIE
3319 + # zapisujemy .pacnew w bazie plików: to artefakt użytkownika.
3320 + journal.append(("file", src, pacnew))
3321 + print(f" ⚠ {_('conf_pacnew', path=pacnew)}")
3322 + return True
3323 + except OSError:
3324 + pass # nie udało się – kontynuuj normalną instalację
3325 +
3326 + # Utwórz katalog docelowy
3327 + os.makedirs(os.path.dirname(dst), exist_ok=True)
3328 +
3329 + # Backup istniejącego pliku (upgrade) – dla poprawnego rollbacku
3330 + if backup_dir and backup_journal is not None and os.path.lexists(dst):
3331 + try:
3332 + backup_path = os.path.join(backup_dir, rel)
3333 + os.makedirs(os.path.dirname(backup_path), exist_ok=True)
3334 + os.replace(dst, backup_path)
3335 + backup_journal.append((backup_path, "/" + rel))
3336 + journal.append(("backup", backup_path, dst))
3337 + except OSError:
3338 + pass
3339 +
3340 + # Atomowe przeniesienie (z fallbackiem dla cross-device).
3341 + # Zachowuje bity uprawnień (SUID/SGID/sticky) – NIE używamy filter='data'.
3342 + _safe_rename(src, dst)
3343 +
3344 + if "/" + rel in privileged:
3345 + # Plik uprzywilejowany: zostaw właściciela, grupę i bity z pakietu
3346 + # (np. sudo 4755 root:root, qemu-bridge-helper 4750 root:kvm).
3347 + try:
3348 + st = os.stat(dst)
3349 + if st.st_mode & 0o6000:
3350 + _audit(f"privileged {dst} mode={oct(st.st_mode & 0o7777)} "
3351 + f"uid={st.st_uid} gid={st.st_gid}")
3352 + except OSError:
3353 + pass
3354 + else:
3355 + # Wymuś właściciela root:root. UWAGA: os.chown() NIE czyści bitów SUID/SGID.
3356 + try:
3357 + os.chown(dst, 0, 0)
3358 + except (OSError, PermissionError):
3359 + # Na niektórych systemach plików (tmpfs, fat) chown może się nie powieść
3360 + pass
3361 +
3362 + journal.append(("file", src, dst))
3363 + installed_files.append({
3364 + "path": "/" + rel,
3365 + "sha256": file_sha,
3366 + "size": os.path.getsize(dst),
3367 + "is_symlink": False,
3368 + })
3369 + return True
3370 +
3371 +
3372 +
3373 +def _stage_package(pkg_path: str, pkg: PackageInfo) -> Optional[dict]:
3374 + """Rozpakowuje pakiet do stagingu, NIE dotykając systemu.
3375 +
3376 + Zwraca dict: staging, data, sums, hooks. None przy błędzie.
3377 +
3378 + To pierwsza faza transakcji grupowej: najpierw przygotowujemy WSZYSTKIE
3379 + pakiety (np. całe GNOME – 50 paczek). Dopiero gdy każda się rozpakuje i
3380 + przejdzie weryfikację SHA256, przechodzimy do fazy commit. Błąd jednej
3381 + paczki nie zostawia więc systemu w połowie instalacji.
3382 + """
3383 + staging = tempfile.mkdtemp(dir=STAGING_DIR, prefix=f".stage-{pkg.name}-")
3384 + try:
3385 + with tarfile.open(pkg_path, "r:xz") as tf:
3386 + _safe_extractall(tf, staging)
3387 +
3388 + data_tar = os.path.join(staging, "data.tar.xz")
3389 + if not os.path.exists(data_tar):
3390 + raise RuntimeError(_("pkg_missing_data_tar"))
3391 +
3392 + data_staging = os.path.join(staging, "data")
3393 + os.makedirs(data_staging, exist_ok=True)
3394 + priv = PRIVILEGED_PATHS | frozenset(pkg.privileged or ())
3395 + with tarfile.open(data_tar, "r:xz") as tf:
3396 + _safe_extractall(tf, data_staging, privileged=priv)
3397 +
3398 + sums_path = os.path.join(data_staging, "sums.json")
3399 + sums = json.load(open(sums_path)) if os.path.exists(sums_path) else {}
3400 +
3401 + # Weryfikacja SHA256 JUŻ w stagingu – uszkodzona paczka nie dojdzie
3402 + # do fazy commit, więc nie zdąży nadpisać żadnego pliku w systemie.
3403 + _bad: List[str] = []
3404 + for _root, _dirs, _files in os.walk(data_staging):
3405 + for _name in list(_dirs) + _files:
3406 + if _name == "sums.json":
3407 + continue
3408 + _fp = os.path.join(_root, _name)
3409 + _rel = "/" + os.path.relpath(_fp, data_staging)
3410 + _expected = sums.get(_rel, "")
3411 + if not _expected:
3412 + continue
3413 + try:
3414 + if os.path.islink(_fp):
3415 + _actual = hashlib.sha256(
3416 + os.readlink(_fp).encode()).hexdigest()
3417 + elif os.path.isfile(_fp):
3418 + _actual = _sha256_file(_fp)
3419 + else:
3420 + continue
3421 + except OSError:
3422 + _actual = ""
3423 + if _actual != _expected:
3424 + _bad.append(_rel)
3425 + if len(_bad) >= 5:
3426 + break
3427 + if len(_bad) >= 5:
3428 + break
3429 + if _bad:
3430 + raise RuntimeError(_("pkg_sha_mismatch", ", ".join(_bad[:5])))
3431 +
3432 + return {
3433 + "staging": staging,
3434 + "data": data_staging,
3435 + "sums": sums,
3436 + "hooks": os.path.join(staging, "hooks"),
3437 + }
3438 + except Exception as e:
3439 + shutil.rmtree(staging, ignore_errors=True)
3440 + print(_(' ❌ {arg1}: preparation stage failed ({arg2})', arg1=(pkg.name), arg2=(e)))
3441 + return None
3442 +
3443 +
3444 +def _discard_staged(staged: Optional[dict]):
3445 + """Usuwa katalog stagingu przygotowanego pakietu (bez zmian w systemie)."""
3446 + if staged and staged.get("staging"):
3447 + shutil.rmtree(staged["staging"], ignore_errors=True)
3448 +
3449 +
3450 +def _apply_staged_package(staged: dict, pkg: PackageInfo, deploy_dir: str = "",
3451 + backup_dir: str = "",
3452 + old_checksums: Optional[dict] = None
3453 + ) -> Tuple[bool, List[dict], List[Tuple[str, str]]]:
3454 + """Faza commit: przenosi przygotowany pakiet do systemu.
3455 +
3456 + Hooki pre/post-install uruchamiane są tutaj – dopiero po tym, jak cała
3457 + grupa pakietów została poprawnie rozpakowana w stagingu.
3458 + """
3459 + staging = staged["staging"]
3460 + data_staging = staged["data"]
3461 + sums = staged["sums"]
3462 + hooks_dir = staged["hooks"]
3463 + priv = PRIVILEGED_PATHS | frozenset(pkg.privileged or ())
3464 + journal: List[tuple] = []
3465 + installed_files: List[dict] = []
3466 + backup_journal: List[Tuple[str, str]] = []
3467 +
3468 + try:
3469 + # Hook pre-install (przed przeniesieniem plików do systemu)
3470 + _run_hook(hooks_dir, "pre-install", pkg)
3471 +
3472 + # Przenieś pliki: staging/data/* → /
3473 + for root, dirs, files in os.walk(data_staging):
3474 + # Symlink do katalogu (np. /lib → usr/lib) os.walk zwraca w `dirs`.
3475 + # Nie wolno tworzyć z niego prawdziwego katalogu – przekieruj do
3476 + # pętli plików, gdzie _install_file odtworzy symlink.
3477 + for _d in list(dirs):
3478 + if os.path.islink(os.path.join(root, _d)):
3479 + dirs.remove(_d)
3480 + files.append(_d)
3481 +
3482 + # Odtwórz katalogi z pakietu – w tym PUSTE (np. /etc/pulse/default.pa.d).
3483 + for d in dirs:
3484 + src_dir = os.path.join(root, d)
3485 + rel_dir = os.path.relpath(src_dir, data_staging)
3486 + if deploy_dir and _is_shared_path("/" + rel_dir):
3487 + dst_root = PAG_ROOT
3488 + elif deploy_dir:
3489 + dst_root = deploy_dir
3490 + else:
3491 + dst_root = PAG_ROOT
3492 + dst_dir = os.path.join(dst_root, rel_dir)
3493 + if not os.path.isdir(dst_dir):
3494 + try:
3495 + os.makedirs(dst_dir, exist_ok=True)
3496 + except OSError:
3497 + pass
3498 + for fname in files:
3499 + if fname == "sums.json":
3500 + continue
3501 + src = os.path.join(root, fname)
3502 + rel = os.path.relpath(src, data_staging)
3503 +
3504 + ok = _install_file(src, rel, data_staging, sums,
3505 + staging, journal, installed_files, deploy_dir,
3506 + backup_dir, backup_journal,
3507 + old_checksums=old_checksums,
3508 + privileged=priv)
3509 + if not ok:
3510 + # Cofnij wszystkie operacje
3511 + _rollback_journal(journal, staging)
3512 + return False, [], backup_journal
3513 +
3514 + # Odbuduj cache ikon GTK dla motywów dotkniętych instalacją.
3515 + _icon_dirs = set()
3516 + for f in installed_files:
3517 + fp = f.get("path", "") or ""
3518 + if fp.startswith("/usr/share/icons/"):
3519 + _rest = fp[len("/usr/share/icons/"):]
3520 + _theme = _rest.split("/", 1)[0]
3521 + if _theme:
3522 + _icon_dirs.add(os.path.join(PAG_ROOT, "usr/share/icons", _theme))
3523 + if _icon_dirs:
3524 + try:
3525 + subprocess.run(["gtk-update-icon-cache", "--version"],
3526 + capture_output=True, timeout=10)
3527 + for _d in sorted(_icon_dirs):
3528 + if os.path.isdir(_d):
3529 + subprocess.run(["gtk-update-icon-cache", "-f", "-q", _d],
3530 + capture_output=True, timeout=300)
3531 + except Exception:
3532 + pass
3533 +
3534 + # Uruchom hooki post-install
3535 + _run_hook(hooks_dir, "post-install", pkg)
3536 +
3537 + # Zachowaj hooki na wypadek usunięcia pakietu (pre/post-remove)
3538 + try:
3539 + if os.path.isdir(hooks_dir):
3540 + persisted = os.path.join(PAG_DB, "hooks", pkg.name)
3541 + shutil.rmtree(persisted, ignore_errors=True)
3542 + shutil.copytree(hooks_dir, persisted)
3543 + except Exception:
3544 + pass
3545 +
3546 + # Zapisz do SQLite
3547 + _db_record_files(pkg.name, installed_files)
3548 +
3549 + shutil.rmtree(staging, ignore_errors=True)
3550 + return True, installed_files, backup_journal
3551 +
3552 + except Exception as e:
3553 + _rollback_journal(journal, staging)
3554 + print(_(' ❌ {arg1}: commit error – {arg2}', arg1=(pkg.name), arg2=(e)))
3555 + return False, [], backup_journal
3556 +
3557 +
3558 +def _atomic_install(pkg_path: str, pkg: PackageInfo, deploy_dir: str = "",
3559 + backup_dir: str = "",
3560 + old_checksums: Optional[dict] = None
3561 + ) -> Tuple[bool, List[dict], List[Tuple[str, str]]]:
3562 + """Instaluje pojedynczy pakiet dwufazowo: staging → commit.
3563 +
3564 + Zachowane jako publiczny wrapper dla instalacji pojedynczych plików
3565 + lokalnych; transakcja grupowa w cmd_install przygotowuje staging dla
3566 + całej grupy i wywołuje _apply_staged_package bezpośrednio.
3567 + """
3568 + staged = _stage_package(pkg_path, pkg)
3569 + if not staged:
3570 + return False, [], []
3571 + return _apply_staged_package(staged, pkg, deploy_dir, backup_dir, old_checksums)
3572 +
3573 +def _refresh_dynamic_linker_cache(deploy_dir: str = "") -> bool:
3574 + """Odświeża cache ld.so po udanej instalacji pakietów."""
3575 + ldconfig = shutil.which("ldconfig")
3576 + if not ldconfig:
3577 + print(_(' ⚠ ldconfig not found — linker cache was not refreshed.'),
3578 + file=sys.stderr)
3579 + return False
3580 +
3581 + target_root = deploy_dir or PAG_ROOT
3582 + command = [ldconfig]
3583 + if target_root != "/":
3584 + command.extend(["-r", target_root])
3585 +
3586 + try:
3587 + subprocess.run(command, check=True, timeout=60,
3588 + stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
3589 + text=True)
3590 + return True
3591 + except (OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc:
3592 + detail = getattr(exc, "stderr", None) or str(exc)
3593 + print(_(' ⚠ Failed to refresh ld.so cache: {arg1}', arg1=(detail.strip())),
3594 + file=sys.stderr)
3595 + return False
3596 +
3597 +
3598 +def _rollback_journal(journal: list, staging_path: str):
3599 + """Cofa wszystkie operacje z journala (odwrotna kolejność)."""
3600 + for entry in reversed(journal):
3601 + op = entry[0]
3602 + if op == "file":
3603 + _, src, dst = entry
3604 + try:
3605 + if os.path.exists(dst) or os.path.islink(dst):
3606 + _safe_rename(dst, src)
3607 + except Exception:
3608 + pass
3609 + elif op == "symlink":
3610 + _, _, dst = entry
3611 + try:
3612 + if os.path.islink(dst) or os.path.exists(dst):
3613 + os.remove(dst)
3614 + except Exception:
3615 + pass
3616 + elif op == "backup":
3617 + # Przywróć starą wersję pliku z backupu (upgrade)
3618 + _, bpath, dst = entry
3619 + try:
3620 + if os.path.lexists(bpath):
3621 + os.replace(bpath, dst)
3622 + except Exception:
3623 + pass
3624 + shutil.rmtree(staging_path, ignore_errors=True)
3625 +
3626 +# =============================================================================
3627 +# BEZPIECZNE USUWANIE
3628 +# =============================================================================
3629 +
3630 +def _safe_remove_files(pkg_name: str, installed_db: dict) -> Tuple[int, List[str]]:
3631 + """
3632 + Usuwa pliki pakietu, ale tylko jeśli NIE są współdzielone z innym pakietem.
3633 + Zwraca (liczba usuniętych, [lista usuniętych ścieżek]).
3634 + """
3635 + pkg_files = _db_get_package_files(pkg_name)
3636 + recorded = _db_get_package_checksums(pkg_name)
3637 + removed = []
3638 + skipped_shared = []
3639 + skipped_sensitive = []
3640 +
3641 + for fpath in pkg_files:
3642 + owners = _db_get_file_owners(fpath)
3643 + # Sprawdź czy inny ZAINSTALOWANY pakiet też jest właścicielem
3644 + other_owners = [o for o in owners if o != pkg_name and o in installed_db]
3645 +
3646 + if other_owners:
3647 + # Plik współdzielony – tylko usuń wpis w DB, nie kasuj pliku
3648 + skipped_shared.append(fpath)
3649 + continue
3650 +
3651 + full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
3652 + if os.path.isfile(full) or os.path.islink(full):
3653 + # Wrażliwej konfiguracji systemowej (/etc/pam.d, sudoers, shadow…)
3654 + # NIE kasujemy przy `remove` – jej brak potrafi zablokować logowanie
3655 + # i sudo (np. usunięcie system-auth/system-account). Zostaje wpis w bazie.
3656 + if _is_sensitive_config(fpath):
3657 + skipped_sensitive.append(fpath)
3658 + continue
3659 + # .pacsave: zachowaj ZMIENIONY plik konfiguracyjny zamiast kasować
3660 + # (porównanie z sumą z chwili instalacji), wzorzec jak w pacmanie.
3661 + if not os.path.islink(full) and _is_config_path(fpath):
3662 + old_sha = recorded.get(fpath, "")
3663 + if old_sha:
3664 + try:
3665 + cur_sha = _sha256_file(full)
3666 + except OSError:
3667 + cur_sha = ""
3668 + if cur_sha and cur_sha != old_sha:
3669 + pacsave = full + ".pacsave"
3670 + try:
3671 + os.replace(full, pacsave)
3672 + print(f" ⚠ {_('conf_pacsave', path=pacsave)}")
3673 + removed.append(fpath)
3674 + continue
3675 + except OSError:
3676 + pass
3677 + os.remove(full)
3678 + removed.append(fpath)
3679 +
3680 + # Usuń puste katalogi (od najgłębszych)
3681 + dirs = set()
3682 + for fpath in removed + skipped_shared:
3683 + parent = os.path.dirname(fpath)
3684 + while parent and parent != "/":
3685 + dirs.add(parent)
3686 + parent = os.path.dirname(parent)
3687 +
3688 + for d in sorted(dirs, key=len, reverse=True):
3689 + full_d = os.path.join(PAG_ROOT, d.lstrip("/"))
3690 + if os.path.isdir(full_d):
3691 + try:
3692 + os.rmdir(full_d)
3693 + except OSError:
3694 + pass # nie jest pusty – OK
3695 +
3696 + # Usuń z SQLite
3697 + _db_remove_package_files(pkg_name)
3698 +
3699 + if skipped_shared:
3700 + print(_(' ⚠ {arg1} shared files preserved', arg1=(len(skipped_shared))))
3701 + if skipped_sensitive:
3702 + print(_(' ⚠ {arg1} sensitive system files preserved', arg1=(len(skipped_sensitive))))
3703 +
3704 + return len(removed) + len(skipped_shared) + len(skipped_sensitive), removed
3705 +
3706 +
3707 +def _remove_stale_files(pkg_name: str, old_files: List[str], new_paths: List[str],
3708 + installed_db: dict, deploy_dir: str = "",
3709 + backup_dir: str = "", backup_journal: Optional[list] = None) -> Tuple[int, List[str]]:
3710 + """
3711 + Po upgrade usuwa pliki starej wersji, których nie ma w nowej.
3712 +
3713 + - Pliki współdzielone z innym zainstalowanym pakietem są ZACHOWYWANE
3714 + (usuwany jest tylko wpis z bazy `files` dla tego pakietu).
3715 + - Sprząta puste katalogi i wpisy SQLite starej wersji.
3716 + Zwraca (liczba usuniętych, [usunięte ścieżki]).
3717 + """
3718 + new_set = set(new_paths)
3719 + # Warianty /usr/lib <-> /usr/lib64: plik obecny w nowej wersji pod równoważną
3720 + # ścieżką NIE jest przestarzały. Bez tego upgrade kasował właśnie
3721 + # zainstalowany plik, gdy stara i nowa wersja używały różnych libdir
3722 + # (kolizja lib/lib64).
3723 + new_effective = set()
3724 + for _p in new_set:
3725 + new_effective.add(_p)
3726 + if _p.startswith("/usr/lib64/"):
3727 + new_effective.add("/usr/lib/" + _p[len("/usr/lib64/"):])
3728 + elif _p.startswith("/usr/lib/"):
3729 + new_effective.add("/usr/lib64/" + _p[len("/usr/lib/"):])
3730 + stale = [f for f in old_files if f not in new_effective]
3731 + if not stale:
3732 + return 0, []
3733 +
3734 + root = deploy_dir or PAG_ROOT
3735 + removed = []
3736 + skipped = 0
3737 + for fpath in stale:
3738 + owners = _db_get_file_owners(fpath)
3739 + other_owners = [o for o in owners if o != pkg_name and o in installed_db]
3740 + if other_owners:
3741 + # Współdzielony z innym pakietem – tylko usuń wpis z DB dla tego pakietu
3742 + skipped += 1
3743 + else:
3744 + # Wrażliwych plików systemowych NIE kasujemy, gdy nowy pakiet ich już
3745 + # nie dostarcza (np. shadow przestaje pakować system-*). Ich brak
3746 + # blokuje login/sudo; usuwamy więc tylko wpis w bazie.
3747 + if _is_sensitive_config(fpath):
3748 + skipped += 1
3749 + else:
3750 + # Gdy nowa wersja pliku /etc trafiła do .pacnew, plik użytkownika
3751 + # MUSI zostać – nie jest „przestarzały”. Zachowujemy też wpis w bazie
3752 + # (stara suma), by kolejny upgrade dalej wykrywał zmiany użytkownika.
3753 + if _is_config_path(fpath):
3754 + _cfg_full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
3755 + if os.path.lexists(_cfg_full + ".pacnew"):
3756 + skipped += 1
3757 + continue
3758 + full = os.path.join(root, fpath.lstrip("/"))
3759 + if os.path.isfile(full) or os.path.islink(full):
3760 + try:
3761 + if backup_dir and backup_journal is not None:
3762 + backup_path = os.path.join(backup_dir, fpath.lstrip("/"))
3763 + os.makedirs(os.path.dirname(backup_path), exist_ok=True)
3764 + os.replace(full, backup_path) # przenieś do backupu (rollback)
3765 + backup_journal.append((backup_path, fpath))
3766 + else:
3767 + os.remove(full)
3768 + removed.append(fpath)
3769 + except OSError:
3770 + pass
3771 + # Usuń wpis `files` dla tego pakietu (stara wersja już go nie zawiera)
3772 + with _db_session() as db:
3773 + db.execute("DELETE FROM files WHERE package=? AND path=?", (pkg_name, fpath))
3774 +
3775 + # Usuń puste katalogi (od najgłębszych)
3776 + dirs = set()
3777 + for fpath in removed:
3778 + parent = os.path.dirname(fpath)
3779 + while parent and parent != "/":
3780 + dirs.add(parent)
3781 + parent = os.path.dirname(parent)
3782 + for d in sorted(dirs, key=len, reverse=True):
3783 + full_d = os.path.join(root, d.lstrip("/"))
3784 + if os.path.isdir(full_d):
3785 + try:
3786 + os.rmdir(full_d)
3787 + except OSError:
3788 + pass # nie jest pusty – OK
3789 +
3790 + if removed:
3791 + print(_(' 🧹 Removed {arg1} obsolete files ({arg2})', arg1=(len(removed)), arg2=(pkg_name)))
3792 + if skipped:
3793 + print(_(' ⚠ {arg1} shared files preserved', arg1=(skipped)))
3794 +
3795 + return len(removed), removed
3796 +
3797 +
3798 +def _new_transaction_backup_root() -> str:
3799 + """Katalog na backupy NADPISYWANYCH plików dla bieżącej transakcji.
3800 +
3801 + Tworzony dla KAŻDEJ transakcji, nie tylko upgrade: „świeża” instalacja
3802 + pakietu też potrafi nadpisać pliki spoza bazy pag (baza rootfs/ISO).
3803 + Gdy transakcja padnie, rollback MUSI mieć co przywrócić – inaczej kasuje
3804 + te pliki (tak zniknął m.in. libpam.so.0 i przestał działać sudo)."""
3805 + txn = datetime.now().strftime("%Y%m%dT%H%M%S") + "-" + str(os.getpid())
3806 + root = os.path.join(STAGING_DIR, "backups", txn)
3807 + os.makedirs(root, exist_ok=True)
3808 + return root
3809 +
3810 +
3811 +def _purge_old_backups(keep_root: str = ""):
3812 + """Usuwa backupy starszych transakcji (zostawia bieżący – dla `pag rollback`)."""
3813 + base = os.path.join(STAGING_DIR, "backups")
3814 + if not os.path.isdir(base):
3815 + return
3816 + for entry in os.listdir(base):
3817 + p = os.path.join(base, entry)
3818 + if p != keep_root and os.path.isdir(p):
3819 + shutil.rmtree(p, ignore_errors=True)
3820 +
3821 +
3822 +def _recover_interrupted_transactions(verbose=True) -> int:
3823 + """Przywraca pliki po transakcji PRZERWANEJ w polowie (crash / kill -9).
3824 +
3825 + Backup transakcji (/.pag_staging/backups/<txn>) powstaje, ZANIM pliki zostana
3826 + podmienione. Jesli pag zginie w trakcie, czesc plikow jest juz przeniesiona do
3827 + backupu, a nowych jeszcze nie ma -> system zostaje bez pliku.
3828 +
3829 + Dla kazdego katalogu backupu, ktory NIE jest zapisany w historii jako UDANA
3830 + transakcja (`upgrade_backup_root` przy `success=true`; takie zostawiamy dla
3831 + `pag rollback`), przywracamy pliki nieobecne w systemie. Potem odswiezamy
3832 + cache linkera.
3833 + """
3834 + base = os.path.join(STAGING_DIR, "backups")
3835 + if not os.path.isdir(base):
3836 + return 0
3837 + try:
3838 + history = load_json(HISTORY_FILE) or []
3839 + except Exception:
3840 + history = []
3841 + done_roots = {
3842 + e.get("upgrade_backup_root") for e in history
3843 + if isinstance(e, dict) and e.get("success") and e.get("upgrade_backup_root")
3844 + }
3845 + restored = 0
3846 + for txn in sorted(os.listdir(base)):
3847 + root = os.path.join(base, txn)
3848 + if not os.path.isdir(root) or root in done_roots:
3849 + continue
3850 + for dirpath, _dirs, files in os.walk(root):
3851 + for fn in files:
3852 + src = os.path.join(dirpath, fn)
3853 + rel = os.path.relpath(src, root)
3854 + dst = os.path.join(PAG_ROOT, rel)
3855 + if os.path.lexists(dst):
3856 + continue
3857 + try:
3858 + os.makedirs(os.path.dirname(dst), exist_ok=True)
3859 + if os.path.islink(src):
3860 + os.symlink(os.readlink(src), dst)
3861 + else:
3862 + shutil.copy2(src, dst)
3863 + restored += 1
3864 + except OSError:
3865 + pass
3866 + if restored:
3867 + try:
3868 + subprocess.run(["ldconfig"], capture_output=True, timeout=120)
3869 + except Exception:
3870 + pass
3871 + if verbose:
3872 + print(_(' 🛠 Interrupted transaction detected – restored {arg1} missing files.', arg1=(restored)))
3873 + return restored
3874 +
3875 +
3876 +# =============================================================================
3877 +# HOOKI
3878 +# =============================================================================
3879 +# Hooki uruchamiają dowolny plik z pakietu jako root — to naturalna cecha
3880 +# menedżera pakietów (apt/pacman też tak mają), dlatego MUSISZ ufać repozytorium.
3881 +# Aby ograniczyć ryzyko:
3882 +# - hook dostaje minimalne, "czyste" środowisko (bez LD_PRELOAD, BASH_ENV itp.)
3883 +# - hooki można wyłączyć (PAG_NO_HOOKS=1) i ustawić timeout (PAG_HOOK_TIMEOUT)
3884 +# - każde uruchomienie jest logowane do /var/log/pag/audit.log
3885 +# - hook ma wersjonowane API (PKG_HOOK_API)
3886 +# =============================================================================
3887 +
3888 +# Lista wykonanych hooków — trafia do wpisu transakcji (informacja w rejestrze).
3889 +_HOOKS_RUN: List[str] = []
3890 +
3891 +
3892 +def _hook_env(pkg: PackageInfo, hook_name: str) -> dict:
3893 + """Buduje minimalne środowisko dla hooka (bez niebezpiecznych zmiennych)."""
3894 + return {
3895 + "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
3896 + "HOME": "/root",
3897 + "LANG": "C.UTF-8",
3898 + "LC_ALL": "C.UTF-8",
3899 + "PKG_NAME": pkg.name,
3900 + "PKG_VERSION": pkg.version,
3901 + "PKG_ACTION": hook_name,
3902 + "PKG_HOOK_API": HOOK_API_VERSION,
3903 + }
3904 +
3905 +
3906 +def _hook_timeout() -> int:
3907 + """Timeout hooka w sekundach.
3908 +
3909 + Domyślnie 900 s, bo hooki jądra/NVIDIA budują moduły DKMS i initramfs –
3910 + na wolniejszych maszynach to kilka minut. Krótszy limit (dawniej 60 s)
3911 + zabijał hook w połowie i zostawiał /boot bez aktualnego initramfs.
3912 + Nadpisz przez `PAG_HOOK_TIMEOUT`.
3913 + """
3914 + try:
3915 + return max(1, int(os.environ.get("PAG_HOOK_TIMEOUT", "900")))
3916 + except Exception:
3917 + return 900
3918 +
3919 +
3920 +def _run_hook(hooks_dir: str, hook_name: str, pkg: PackageInfo) -> bool:
3921 + """Uruchamia skrypt hooka jeśli istnieje.
3922 +
3923 + Zwraca True jeśli hook został WYKONANY (istniał i uruchomiono go), False w
3924 + pozostałych przypadkach (brak pliku, wyłączone hooki, błąd). Obsługuje
3925 + ograniczone środowisko, timeout, logowanie do audytu i rejestr w transakcji.
3926 + """
3927 + hook_path = os.path.join(hooks_dir, hook_name)
3928 + if not os.path.exists(hook_path):
3929 + return False
3930 +
3931 + if os.environ.get("PAG_NO_HOOKS", "") == "1":
3932 + print(_(' ⚠ Hook skipped (PAG_NO_HOOKS=1): {arg1} for {arg2}', arg1=(hook_name), arg2=(pkg.name)))
3933 + _audit(f"hook SKIP {hook_name} {pkg.name}-{pkg.version} (PAG_NO_HOOKS=1)")
3934 + return False
3935 +
3936 + os.chmod(hook_path, 0o755)
3937 + env = _hook_env(pkg, hook_name)
3938 + tag = f"{hook_name} {pkg.name}-{pkg.version}"
3939 + try:
3940 + result = subprocess.run([hook_path], env=env, timeout=_hook_timeout(),
3941 + check=False, capture_output=True, text=True,
3942 + cwd="/")
3943 + _HOOKS_RUN.append(tag)
3944 + if result.returncode != 0:
3945 + print(_(' ⚠ Hook {arg1} for {arg2} exited with code {arg3}', arg1=(hook_name), arg2=(pkg.name), arg3=(result.returncode)))
3946 + if result.stderr:
3947 + print(f" {result.stderr.strip()[-200:]}")
3948 + _audit(f"hook FAIL {tag} rc={result.returncode}")
3949 + else:
3950 + _audit(f"hook OK {tag}")
3951 + return True
3952 + except subprocess.TimeoutExpired:
3953 + print(_(' ⚠ Hook {arg1} for {arg2} timed out ({arg3}s)', arg1=(hook_name), arg2=(pkg.name), arg3=(_hook_timeout())))
3954 + print(_(' Increase PAG_HOOK_TIMEOUT (e.g. PAG_HOOK_TIMEOUT=1800) and retry.'))
3955 + _audit(f"hook TIMEOUT {tag}")
3956 + return False
3957 + except Exception as e:
3958 + print(_(' ⚠ Hook {arg1} for {arg2}: {arg3}', arg1=(hook_name), arg2=(pkg.name), arg3=(e)))
3959 + _audit(f"hook ERROR {tag}: {e}")
3960 + return False
3961 +
3962 +# =============================================================================
3963 +# TRANSAKCJE I ROLLBACK
3964 +# =============================================================================
3965 +
3966 +def _record_transaction(action, packages, success, snapshot, file_journal=None, hooks=None,
3967 + upgrade_backups=None, upgrade_backup_root="", snapshot_id=""):
3968 + history = load_json(HISTORY_FILE) if os.path.exists(HISTORY_FILE) else []
3969 + # Rejestr wykonanych hooków – informacja o tym, że uruchomiono kod pakietu
3970 + # jako root. Trafia do historii, by dało się później sprawdzić, co się działo.
3971 + executed_hooks = list(_HOOKS_RUN) if hooks is None else hooks
3972 + _HOOKS_RUN.clear()
3973 + entry = {
3974 + "action": action, "packages": packages, "success": success,
3975 + "timestamp": datetime.now().isoformat(),
3976 + "snapshot": snapshot,
3977 + "file_journal": file_journal, # lista plików do wycofania
3978 + "hooks": executed_hooks, # wykonane hooki (pre/post-install/remove)
3979 + }
3980 + if snapshot_id:
3981 + # Snapshot systemu (btrfs) z chwili PRZED transakcją – można z niego
3982 + # uruchomić system z menu GRUB albo podejrzeć `pag snapshot-list`.
3983 + entry["snapshot_id"] = snapshot_id
3984 + if upgrade_backups:
3985 + entry["upgrade_backups"] = upgrade_backups # {dst: backup_path}
3986 + entry["upgrade_backup_root"] = upgrade_backup_root
3987 + history.append(entry)
3988 + if len(history) > 50:
3989 + history = history[-50:]
3990 + save_json(HISTORY_FILE, history)
3991 +
3992 +def _action_label(action):
3993 + key = "action_" + str(action)
3994 + return _(key) if key in T.get("en", {}) else str(action)
3995 +
3996 +def cmd_history():
3997 + if not os.path.exists(HISTORY_FILE):
3998 + print(_("no_history")); return
3999 + history = load_json(HISTORY_FILE)
4000 + if not history:
4001 + print(_("no_history")); return
4002 + print(_('Recent transactions ({arg1}):', arg1=(len(history))))
4003 + for i, e in enumerate(reversed(history), 1):
4004 + icon = "✅" if e["success"] else "❌"
4005 + pkgs = ", ".join(e["packages"][:5])
4006 + if len(e["packages"]) > 5: pkgs += f" (+{len(e['packages'])-5})"
4007 + print(f" {i}. {icon} {_action_label(e['action'])}: {pkgs}")
4008 + print(f" {e['timestamp']}")
4009 +
4010 +def cmd_rollback():
4011 + if not os.path.exists(HISTORY_FILE):
4012 + print(_("no_history")); return 1
4013 + history = load_json(HISTORY_FILE)
4014 + if not history:
4015 + print(_("no_history")); return 1
4016 +
4017 + last = None
4018 + for e in reversed(history):
4019 + if e["success"] and e.get("snapshot"):
4020 + last = e; break
4021 +
4022 + if not last:
4023 + print(_('❌ No snapshot to restore.')); return 1
4024 +
4025 + print(_('⏪ Rolling back: {arg1} ({arg2})', arg1=(_action_label(last['action'])), arg2=(last['timestamp'])))
4026 + print(_(' Packages: {arg1}', arg1=(', '.join(last['packages'][:10]))))
4027 +
4028 + if not _ask_confirm():
4029 + return 0
4030 +
4031 + # Przywróć installed.json
4032 + save_json(INSTALLED_DB, last["snapshot"])
4033 +
4034 + # Wycofaj fizyczne pliki (jeśli zapisano journal)
4035 + # Deduplikacja: pakiet może zgłosić ten sam plik więcej niż raz (np. przez
4036 + # `provides` lub wspólną ścieżkę), a journal z historii mógł zostać zapisany
4037 + # przed dodaniem deduplikacji.
4038 + file_journal = list(dict.fromkeys(last.get("file_journal", [])))
4039 + upgrade_backups = last.get("upgrade_backups", {}) or {}
4040 + backup_root = last.get("upgrade_backup_root", "")
4041 +
4042 + # Przywróć stare wersje z backupów (upgrade) – nadpisane i usunięte stale pliki
4043 + for dst, bpath in upgrade_backups.items():
4044 + full = os.path.join(PAG_ROOT, dst.lstrip("/"))
4045 + if bpath and os.path.lexists(bpath):
4046 + try:
4047 + os.makedirs(os.path.dirname(full), exist_ok=True)
4048 + os.replace(bpath, full)
4049 + except OSError:
4050 + pass
4051 +
4052 + # Usuń nowe pliki (które nie miały poprzedniej wersji)
4053 + backed = set(upgrade_backups)
4054 + if file_journal:
4055 + for fpath in reversed(file_journal):
4056 + if fpath in backed:
4057 + continue
4058 + full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
4059 + if os.path.exists(full) or os.path.islink(full):
4060 + os.remove(full)
4061 + print(f" {_('rollback_files', len(file_journal))}")
4062 +
4063 + # Sprzątanie pustych katalogów + katalogu backupów
4064 + dirs = set()
4065 + for fpath in file_journal:
4066 + parent = os.path.dirname(fpath)
4067 + while parent and parent != "/":
4068 + dirs.add(parent)
4069 + parent = os.path.dirname(parent)
4070 + for d in sorted(dirs, key=len, reverse=True):
4071 + full_d = os.path.join(PAG_ROOT, d.lstrip("/"))
4072 + if os.path.isdir(full_d):
4073 + try:
4074 + os.rmdir(full_d)
4075 + except OSError:
4076 + pass
4077 + if backup_root:
4078 + shutil.rmtree(backup_root, ignore_errors=True)
4079 +
4080 + print(f"✅ {_('rollback_restored')}")
4081 + _record_transaction("rollback", last["packages"], True, None)
4082 + return 0
4083 +
4084 +# =============================================================================
4085 +# INSTALACJA
4086 +# =============================================================================
4087 +
4088 +def _install_local_pkg_files(paths, install_succeeded):
4089 + """Instaluje lokalne pliki .pag (bez repozytorium).
4090 +
4091 + Najpierw przygotowuje WSZYSTKIE paczki w stagingu, potem je nakłada.
4092 + Dzięki temu uszkodzony plik w środku grupy nie zostawia systemu
4093 + w połowie instalacji. Zwraca (failed_count, installed_files).
4094 + """
4095 + failed = 0
4096 + prepared = []
4097 + for p in paths:
4098 + p = os.path.abspath(p)
4099 + if not os.path.isfile(p):
4100 + print(_(' ❌ Package not found: {arg1}', arg1=(p)))
4101 + failed += 1
4102 + break
4103 + if not _verify_local_pkg_signature(p):
4104 + failed += 1
4105 + break
4106 + try:
4107 + with tarfile.open(p, "r:xz") as tf:
4108 + meta = tf.extractfile("metadata.json")
4109 + if meta is None:
4110 + print(_(' ❌ {arg1}: missing metadata.json', arg1=(p)))
4111 + failed += 1
4112 + break
4113 + data = json.loads(meta.read())
4114 + except Exception as e:
4115 + print(_(' ❌ {arg1}: failed to read package ({arg2})', arg1=(p), arg2=(e)))
4116 + failed += 1
4117 + break
4118 + pkg = PackageInfo(data, repo="local")
4119 + staged = _stage_package(p, pkg)
4120 + if not staged:
4121 + failed += 1
4122 + break
4123 + prepared.append((pkg, staged))
4124 +
4125 + if failed:
4126 + for _pkg, _st in prepared:
4127 + _discard_staged(_st)
4128 + print(_(' ↩ Preparation stage failed – the system was NOT changed.'))
4129 + return failed, []
4130 +
4131 + all_files = []
4132 + for pkg, staged in prepared:
4133 + print(_(' ↓ {arg1}-{arg2} (local) ... ', arg1=(pkg.name), arg2=(pkg.version)), end="", flush=True)
4134 + ok, files, _ = _apply_staged_package(staged, pkg)
4135 + if ok:
4136 + install_succeeded(pkg, files)
4137 + all_files.extend(f["path"] for f in files)
4138 + print("✅")
4139 + else:
4140 + print("❌")
4141 + failed += 1
4142 + return failed, all_files
4143 +
4144 +
4145 +def _preflight_disk(total_bytes: int) -> bool:
4146 + """Pre-flight przed transakcją: wolne miejsce + mount read-only.
4147 +
4148 + Zwraca False (przerywa instalację) gdy na partycji docelowej brakuje
4149 + miejsca na pakiety albo katalog stagingu jest zamontowany read-only
4150 + (inaczej instalacja rwałaby się w połowie, zostawiając uszkodzony system).
4151 + """
4152 + target = PAG_ROOT or "/"
4153 + try:
4154 + st = os.statvfs(target)
4155 + free = st.f_bavail * st.f_frsize
4156 + except OSError:
4157 + return True # nie da się sprawdzić – nie blokuj
4158 + need_mb = total_bytes // 1048576
4159 + free_mb = free // 1048576
4160 + if free < total_bytes:
4161 + print(_(' ❌ Not enough disk space: need ~{arg1} MB, free {arg2} MB ({arg3})', arg1=(need_mb), arg2=(free_mb), arg3=(target)))
4162 + return False
4163 + if free < total_bytes * 3:
4164 + print(_(' ⚠ Low disk space: {arg1} MB free, packages ~{arg2} MB (extracted will take more)', arg1=(free_mb), arg2=(need_mb)))
4165 + # Wykryj mount read-only (test zapisu w stagingu)
4166 + try:
4167 + probe = os.path.join(STAGING_DIR, ".pag-probe")
4168 + with open(probe, "w") as f:
4169 + f.write("x")
4170 + os.remove(probe)
4171 + except OSError:
4172 + print(_(' ❌ {arg1} is mounted read-only – cannot install.', arg1=(target)))
4173 + return False
4174 + return True
4175 +
4176 +
4177 +def cmd_install(package_names, as_dep=False, upgrade=False):
4178 + ensure_dirs()
4179 + installed_db = load_json(INSTALLED_DB)
4180 + world = load_world()
4181 + pinned = load_json(PINNED_FILE)
4182 +
4183 + # Obsługa lokalnych plików .pkg.tar.xz (zbudowanych przez pagbuild) –
4184 + # nie wymaga repozytorium ani GPG.
4185 + local_files = [p for p in package_names if p.endswith(PKG_EXT) or
4186 + (os.sep in p and os.path.isfile(os.path.abspath(p)))]
4187 + if local_files:
4188 + _local_need = sum(
4189 + os.path.getsize(os.path.abspath(p))
4190 + for p in local_files if os.path.isfile(os.path.abspath(p))
4191 + )
4192 + if not _preflight_disk(_local_need):
4193 + return 1
4194 +
4195 + def _ok(pkg, files):
4196 + installed_db[pkg.name] = {
4197 + "version": pkg.version, "release": pkg.release, "description": pkg.description,
4198 + "dependencies": pkg.dependencies, "size_bytes": pkg.size_bytes,
4199 + "sha256": pkg.sha256, "installed_at": datetime.now().isoformat(),
4200 + "repo": "local",
4201 + "provides": getattr(pkg, "provides", None) or [],
4202 + "provides_so": getattr(pkg, "provides_so", None) or [],
4203 + "requires_so": getattr(pkg, "requires_so", None) or [],
4204 + }
4205 + world.add(pkg.name)
4206 + failed_local, _fl = _install_local_pkg_files(local_files, _ok)
4207 + save_json(INSTALLED_DB, installed_db)
4208 + save_world(world)
4209 + if failed_local:
4210 + return 1
4211 + _refresh_dynamic_linker_cache()
4212 + package_names = [n for n in package_names if n not in
4213 + [os.path.abspath(x) for x in local_files] and
4214 + n not in local_files]
4215 + to_install = []
4216 + if not package_names:
4217 + return 0
4218 + # pozostałe argumenty to nazwy pakietów z repo – kontynuuj
4219 +
4220 + repo_pkgs = fetch_all_packages()
4221 +
4222 + if not repo_pkgs:
4223 + print(f"❌ {_('no_index')}"); return 1
4224 +
4225 + for name in list(package_names):
4226 + if name in pinned:
4227 + print(f"⚠ {name} {_('pinned_to')} {pinned[name]} – skipping")
4228 + package_names.remove(name)
4229 +
4230 + to_install, missing_deps = _resolve_deps(package_names, repo_pkgs, installed_db)
4231 +
4232 + # ── Pakiety, których NIE MA w repo ani nie są zainstalowane ──
4233 + # Zgłoś od razu zamiast mylącego „Do zainstalowania: N (0.00 MB)”
4234 + # i prośby o potwierdzenie (np. `pag install steam` gdy steam nie istnieje).
4235 + not_found = []
4236 + for n in package_names:
4237 + real = _resolve_provides(n, repo_pkgs, installed_db)
4238 + if real not in repo_pkgs and real not in installed_db \
4239 + and not os.path.exists(os.path.abspath(n)):
4240 + not_found.append(n)
4241 + if not_found:
4242 + print(f"\n ❌ {_('pkg_not_found', ', '.join(not_found))}")
4243 + print(f" {_('not_found_hint')}")
4244 + return 1
4245 +
4246 + # --- Tryb upgrade: pakiety już zainstalowane MUSZĄ zostać ponownie
4247 + # zainstalowane z nowszej wersji (zastąpienie w tej samej transakcji).
4248 + if upgrade:
4249 + # `pag update` przekazuje tu tylko pakiety z NOWSZĄ wersją (już
4250 + # przefiltrowane w _pending_updates), a `pag install -f` wymusza
4251 + # reinstalację nawet tej SAMEJ wersji – dlatego nie filtrujemy po
4252 + # _version_newer.
4253 + upgrade_targets = [
4254 + name for name in package_names
4255 + if name in repo_pkgs
4256 + and name in installed_db
4257 + and name not in pinned
4258 + ]
4259 + for name in upgrade_targets:
4260 + if name not in to_install:
4261 + to_install.append(name)
4262 +
4263 + if not to_install and not missing_deps:
4264 + print(f"✅ {_('all_installed')}"); return 0
4265 +
4266 + # ── WERYFIKACJA ZALEŻNOŚCI ──────────────────────────────────────────
4267 + fatal_missing = _verify_dependencies(to_install, repo_pkgs, installed_db)
4268 +
4269 + if fatal_missing > 0:
4270 + print(_('❌ Cannot continue – {arg1} missing dependencies.', arg1=(fatal_missing)))
4271 + print(_(' Install the missing packages or add repositories.'))
4272 + return 1
4273 +
4274 + so_missing = _verify_so_deps(to_install, repo_pkgs, installed_db)
4275 + if so_missing > 0:
4276 + print(_(' Install the library provider or update the repository.'))
4277 + return 1
4278 +
4279 + if not to_install:
4280 + print(f"✅ {_('all_installed')}"); return 0
4281 +
4282 + MAX_MB = MAX_PKG_SIZE // 1048576
4283 + for n in to_install:
4284 + if not _validate_pkg_name(n):
4285 + print(f" {_("sec_badname", name=n)}")
4286 + return 1
4287 + sz = repo_pkgs[n].size_bytes if n in repo_pkgs else 0
4288 + if sz > MAX_PKG_SIZE:
4289 + mb = sz // 1048576
4290 + print(f" {_("sec_toobig", size_mb=mb, max_mb=MAX_MB)}")
4291 + return 1
4292 + total_size = sum(repo_pkgs[n].size_bytes for n in to_install if n in repo_pkgs)
4293 + if not _preflight_disk(total_size):
4294 + return 1
4295 + print(f"\n📦 {_('to_install', len(to_install), total_size/1048576)}")
4296 + for name in to_install:
4297 + p = repo_pkgs.get(name)
4298 + if p:
4299 + if name in installed_db:
4300 + marker = f" {_('upgrade_marker')}" if upgrade else ""
4301 + else:
4302 + marker = f" [{_('new')}]"
4303 + print(f" {name}-{p.version}{marker}")
4304 +
4305 + # Pakiet z bazy obrazu ISO (nie w installed.json) → ostrzeż, że pliki z ISO
4306 + # zostaną zastąpione pakietem z repo (kopia do `pag rollback`).
4307 + _base_warn_overwrite(to_install)
4308 +
4309 + if not as_dep and not upgrade:
4310 + if not _ask_confirm():
4311 + print(_("cancelled")); return 0
4312 +
4313 + # `--dry-run`: pokaż plan i wyjdź. Nic nie jest pobierane, rozpakowywane
4314 + # ani zmieniane – bezpieczne sprawdzenie, co zrobiłaby transakcja.
4315 + if os.environ.get("PAG_DRY_RUN", "") == "1":
4316 + print(f"\n 🧪 {_('dry_run_plan')}")
4317 + for _n in to_install:
4318 + _p = repo_pkgs.get(_n)
4319 + if _p:
4320 + _mark = f" {_('upgrade_marker')}" if _n in installed_db else f" [{_('new')}]"
4321 + print(f" {_n}-{_p.version}{_mark}")
4322 + print(f" {_('dry_run_done')}")
4323 + return 0
4324 +
4325 + snapshot = copy.deepcopy(installed_db)
4326 + all_installed_files = []
4327 + failed = []
4328 + # Pary (pkg, stare_pliki, nowe_pliki) do usunięcia martwych plików po upgrade
4329 + stale_candidates = []
4330 + # Katalog backupów nadpisywanych plików – dla poprawnego rollbacku.
4331 + # Dla KAŻDEJ transakcji: instalacja „nowego” pakietu także nadpisuje pliki
4332 + # spoza bazy pag (baza rootfs/ISO), a rollback bez backupu by je skasował.
4333 + backup_root = ""
4334 + all_backups: List[Tuple[str, str]] = [] # (backup_path, dst)
4335 + if to_install:
4336 + backup_root = _new_transaction_backup_root()
4337 +
4338 + # --- Dziennik transakcji (dla pełnej atomowości) ---
4339 + # Jeśli którykolwiek pakiet zawiedzie, cofamy WSZYSTKIE zainstalowane
4340 + # w tej transakcji przez _rollback_transaction().
4341 + transaction_journal: List[Tuple[str, str, str]] = [] # (op, src, dst)
4342 +
4343 + # --- Tryb immutable: utwórz nowy deployment ---
4344 + immutable = os.environ.get("PAG_IMMUTABLE", "") == "1"
4345 + deploy_dir = ""
4346 + deploy_id = ""
4347 + if immutable:
4348 + print(_('\n 🏗️ Creating a new deployment...'))
4349 + deploy_dir, deploy_id = _create_deployment(to_install, "upgrade" if upgrade else "install")
4350 + target_root = deploy_dir
4351 + else:
4352 + target_root = ""
4353 +
4354 + # --- Faza 1: Równoległe pobieranie wszystkich pakietów ---
4355 + to_download = [repo_pkgs[name] for name in to_install if name in repo_pkgs]
4356 + if len(to_download) > 1:
4357 + print(_('\n ⏬ Downloading {arg1} packages in parallel...', arg1=(len(to_download))))
4358 + downloaded = _download_packages_parallel(to_download)
4359 + else:
4360 + downloaded = {}
4361 +
4362 + # --- Faza 1b: WERYFIKACJA WSZYSTKICH paczek PRZED instalacją ---
4363 + # KLUCZOWE: GPG i SHA256 sprawdzamy dla WSZYSTKICH paczek, ZANIM
4364 + # zainstalujemy choćby jedną. Inaczej instalowany pakiet może podmienić
4365 + # bibliotekę używaną przez sam gpg (np. libassuan 3.0.1 zmienił namespace
4366 + # symboli LIBASSUAN_1.0 -> LIBASSUAN_2.0) i wtedy weryfikacja kolejnych
4367 + # paczek w tej samej transakcji pada, dając fałszywe
4368 + # „NIEPRAWIDŁOWY PODPIS GPG".
4369 + verified = {}
4370 + _vfail = []
4371 + for _name in to_install:
4372 + _pkg = repo_pkgs.get(_name)
4373 + if not _pkg:
4374 + _vfail.append((_name, _('not_found')))
4375 + continue
4376 + _pp = downloaded.get(_name)
4377 + if not _pp:
4378 + _pp = _download_pkg(_pkg)
4379 + if not _pp:
4380 + _vfail.append((_name, _('download_fail')))
4381 + continue
4382 + _gok, _gmsg = _verify_pkg_gpg(_pp, repo_url=_pkg.repo_url)
4383 + if not _gok:
4384 + _vfail.append((_name, f"{_('gpg_fail')}: {_gmsg[:60]}"))
4385 + continue
4386 + if _pkg.sha256 and _sha256_file(_pp) != _pkg.sha256:
4387 + _vfail.append((_name, _('sha256_mismatch')))
4388 + continue
4389 + verified[_name] = _pp
4390 + if _vfail:
4391 + for _n, _m in _vfail:
4392 + print(f" ❌ {_n}: {_m}")
4393 + print(_(' ↩ Aborted BEFORE installation – no package was changed.'))
4394 + return 1
4395 +
4396 + # --- Snapshot systemu PRZED transakcją (btrfs CoW) ---
4397 + # Tworzymy go PO pobraniu i weryfikacji paczek, ale PRZED rozpakowaniem
4398 + # czegokolwiek do systemu. Domyślnie `auto`: tylko na btrfs. `--snapshot`
4399 + # wymusza migawkę (i przerywa, gdy się nie uda), `--no-snapshot` wyłącza.
4400 + snapshot_mode = (os.environ.get("PAG_SNAPSHOT") or "auto").strip().lower()
4401 + sys_snap: Optional[dict] = None
4402 + if to_install and snapshot_mode not in ("never", "no", "0", "off"):
4403 + _snap_ok, _snap_why = _snapshot_support()
4404 + if _snap_ok:
4405 + sys_snap = _create_system_snapshot(
4406 + to_install, "upgrade" if upgrade else "install")
4407 + if sys_snap:
4408 + _refresh_bootloader()
4409 + elif snapshot_mode in ("always", "require", "1", "yes"):
4410 + print(_(' ❌ Failed to create snapshot (--snapshot mode) – aborting.'))
4411 + return 1
4412 + elif snapshot_mode in ("always", "require", "1", "yes"):
4413 + print(f" ❌ {_('snapshot_unsupported', _snap_why)}")
4414 + return 1
4415 + else:
4416 + print(f" ℹ {_('snapshot_unsupported', _snap_why)}")
4417 +
4418 + # --- Faza 1c: PRZYGOTOWANIE CAŁEJ GRUPY W STAGINGU ---
4419 + # Rozpakowujemy WSZYSTKIE pakiety do `/.pag_staging/.stage-*`, zanim
4420 + # dotkniemy systemu. Jeśli jedna z 50 paczek (np. GNOME) jest uszkodzona,
4421 + # transakcja kończy się tutaj – na dysku nie ma żadnych zmian.
4422 + atomic = os.environ.get("PAG_ATOMIC", "1") != "0"
4423 + staged_pkgs: List[Tuple[str, PackageInfo, Optional[dict]]] = []
4424 + if atomic and to_install:
4425 + print(f"\n 🧰 {_('staging_prepare', len(to_install))}")
4426 + _sbar = _StepBar(len(to_install), icon="🧰 ", width=25)
4427 + _stage_failed: List[str] = []
4428 + for _si, _name in enumerate(to_install, 1):
4429 + _pkg = repo_pkgs.get(_name)
4430 + _pp = verified.get(_name)
4431 + if not _pkg or not _pp:
4432 + _stage_failed.append(_name)
4433 + break
4434 + _sbar.step(_si, f"{_name}-{_pkg.version}")
4435 + _st = _stage_package(_pp, _pkg)
4436 + if not _st:
4437 + _stage_failed.append(_name)
4438 + break
4439 + staged_pkgs.append((_name, _pkg, _st))
4440 + _sbar.end()
4441 + if _stage_failed:
4442 + for _n, _p, _st in staged_pkgs:
4443 + _discard_staged(_st)
4444 + print(f" ↩ {_('staging_failed')}")
4445 + if backup_root:
4446 + shutil.rmtree(backup_root, ignore_errors=True)
4447 + _record_transaction("upgrade" if upgrade else "install", to_install, False,
4448 + snapshot,
4449 + snapshot_id=sys_snap["id"] if sys_snap else "")
4450 + return 1
4451 + print(f" ✅ {_('staging_commit')}")
4452 + elif to_install:
4453 + staged_pkgs = [(n, repo_pkgs[n], None) for n in to_install]
4454 +
4455 + # --- Faza 2: Instalacja – JEDNA nadpisywana linia postępu (jak przy
4456 + # pobieraniu), bez ściany tekstu na każdy pakiet. W trybie
4457 + # nieinteraktywnym (logi, netinstall instalatora) wypisujemy linię na
4458 + # pakiet – tam to pożądane do logu.
4459 + t0 = time.time()
4460 + stdout_tty = sys.stdout.isatty()
4461 +
4462 + # Animowany pasek postępu („drakkar”) – jedna nadpisywana linia; morze
4463 + # faluje nawet wtedy, gdy pojedynczy pakiet instaluje się długo.
4464 + _pbar = _StepBar(len(to_install), icon="📦 ", width=25)
4465 +
4466 + def _bar_draw(idx: int, name: str) -> None:
4467 + _pbar.step(idx, name)
4468 +
4469 + def _bar_end() -> None:
4470 + _pbar.end()
4471 +
4472 + for _pkg_i, (name, pkg, _staged) in enumerate(staged_pkgs, 1):
4473 + if not pkg:
4474 + _bar_end()
4475 + print(f" ❌ {name}: {_('not_found')}")
4476 + failed.append(name)
4477 + break
4478 +
4479 + _bar_draw(_pkg_i, f"{name}-{pkg.version}")
4480 +
4481 + # Przed instalacją zapamiętaj pliki starej wersji (potrzebne w upgrade)
4482 + old_files = _db_get_package_files(name) if name in installed_db else []
4483 + # Stare sumy SHA256 – do wykrycia zmian użytkownika w plikach /etc (.pacnew)
4484 + old_checksums = _db_get_package_checksums(name) if name in installed_db else None
4485 +
4486 + # Commit przygotowanego pakietu (w upgrade backupuje nadpisywane pliki).
4487 + # Tryb `PAG_ATOMIC=0` zachowuje starą ścieżkę pojedynczą (staging per pakiet).
4488 + if _staged is not None:
4489 + ok, files, backup_j = _apply_staged_package(
4490 + _staged, pkg, deploy_dir,
4491 + backup_dir=backup_root,
4492 + old_checksums=old_checksums)
4493 + else:
4494 + # Ścieżka pobrana i ZWERYFIKOWANA w fazie 1b.
4495 + pkg_path = verified.get(name)
4496 + if not pkg_path:
4497 + _bar_end()
4498 + print(f" ❌ {name}: {_('download_fail')}")
4499 + failed.append(name)
4500 + break # przerwij transakcję
4501 + ok, files, backup_j = _atomic_install(
4502 + pkg_path, pkg, deploy_dir,
4503 + backup_dir=backup_root,
4504 + old_checksums=old_checksums)
4505 + if ok:
4506 + installed_db[name] = {
4507 + "version": pkg.version, "release": pkg.release, "description": pkg.description,
4508 + "dependencies": pkg.dependencies, "size_bytes": pkg.size_bytes,
4509 + "sha256": pkg.sha256, "installed_at": datetime.now().isoformat(),
4510 + "repo": pkg.repo_url,
4511 + "provides": getattr(pkg, "provides", None) or [],
4512 + "provides_so": getattr(pkg, "provides_so", None) or [],
4513 + "requires_so": getattr(pkg, "requires_so", None) or [],
4514 + }
4515 + if not as_dep and name in package_names:
4516 + world.add(name)
4517 + if not stdout_tty:
4518 + print(f" ✓ {name}-{pkg.version}", flush=True)
4519 + all_installed_files.extend(f["path"] for f in files)
4520 + all_backups.extend(backup_j)
4521 +
4522 + # Upgrade: zapamiętaj stare pliki, by po sukcesie usunąć te,
4523 + # których nie ma już w nowej wersji.
4524 + if upgrade and old_files:
4525 + stale_candidates.append((name, old_files, [f["path"] for f in files]))
4526 + else:
4527 + _bar_end()
4528 + print(f" ❌ {name}: {_('install_failed')}")
4529 + failed.append(name)
4530 + break # PRZERWIJ – błąd instalacji
4531 +
4532 + # Deduplikacja journalu – ten sam plik może trafić tu dwukrotnie (np. przez
4533 + # `provides`); rollback i historia nie potrzebują duplikatów.
4534 + all_installed_files = list(dict.fromkeys(all_installed_files))
4535 +
4536 + # --- Rollback całej transakcji jeśli cokolwiek zawiodło ---
4537 + if failed:
4538 + _bar_end()
4539 + print(_('\n ↩ Rolling back transaction ({arg1} errors)...', arg1=(len(failed))))
4540 + for _n, _p, _st in staged_pkgs:
4541 + _discard_staged(_st)
4542 + _rollback_transaction(installed_db, snapshot, all_installed_files,
4543 + deploy_dir, immutable, backups=all_backups)
4544 + if backup_root:
4545 + shutil.rmtree(backup_root, ignore_errors=True)
4546 + _record_transaction("upgrade" if upgrade else "install", to_install, False,
4547 + snapshot,
4548 + snapshot_id=sys_snap["id"] if sys_snap else "")
4549 + return 1
4550 +
4551 + save_json(INSTALLED_DB, installed_db)
4552 + save_world(world)
4553 +
4554 + # --- Po ZAPISANIU bazy: usuń nieaktualne pliki starych wersji (upgrade).
4555 + # Kolejność ma znaczenie: najpierw utrwalamy stan nowej wersji w bazie, a
4556 + # dopiero potem kasujemy pliki, których nowa wersja nie zawiera. Odwrotna
4557 + # kolejność (kasowanie przed zapisem) przy przerwaniu zostawiała system bez
4558 + # plików. Usunięte pliki trafiają do backupu, aby `pag rollback` mógł je
4559 + # przywrócić.
4560 + for pkg_name, old_files, new_paths in stale_candidates:
4561 + _remove_stale_files(pkg_name, old_files, new_paths, installed_db, deploy_dir,
4562 + backup_root, all_backups)
4563 + _record_transaction("upgrade" if upgrade else "install", to_install, True, snapshot,
4564 + file_journal=all_installed_files,
4565 + upgrade_backups={dst: bp for bp, dst in all_backups} if all_backups else None,
4566 + upgrade_backup_root=backup_root,
4567 + snapshot_id=sys_snap["id"] if sys_snap else "")
4568 +
4569 + # Zachowaj backupy bieżącej transakcji (dla `pag rollback`), usuń starsze.
4570 + if backup_root:
4571 + _purge_old_backups(keep_root=backup_root)
4572 +
4573 + _bar_end()
4574 +
4575 + # --- Tryb immutable: przełącz na nowy deployment ---
4576 + if immutable and not failed:
4577 + _refresh_dynamic_linker_cache(deploy_dir)
4578 + # Initramfs dla deploymentu budujemy RAZ – po wszystkich pakietach,
4579 + # żeby zawierał też moduły nvidia/vbox dołożone w tej transakcji.
4580 + if any(_needs_initramfs_refresh(_n) for _n in to_install):
4581 + print(_('\n 🐧 Finalizing kernel/driver update in deployment (initramfs)...'))
4582 + _rebuild_initramfs(deploy_dir)
4583 + print(_('\n 🔄 Switching to deployment {arg1}...', arg1=(deploy_id)))
4584 + _switch_deployment(deploy_dir)
4585 + print(_(' ✅ Active deployment: {arg1}', arg1=(deploy_id)))
4586 + _update_grub_config()
4587 + cmd_deploy_cleanup(keep=5) # Zostawia 5 najnowszych deploymentów
4588 + print(_(' 💡 Restart required to reload the system.'))
4589 + else:
4590 + _refresh_dynamic_linker_cache()
4591 + # Hooki zbiorcze – raz na transakcję (fc-cache itp.), tylko gdy pliki
4592 + # trafiły do realnego systemu (nie do deploymentu).
4593 + _process_triggers(all_installed_files)
4594 + # Jądro/sterowniki zmienione na ZWYKŁEJ instalacji → DKMS + initramfs +
4595 + # GRUB, dokładnie RAZ i po wszystkich pakietach. Hook pakietu nie może
4596 + # odświeżyć GRUB-a (trzymany lock PAG-a), a wcześniejsza przebudowa
4597 + # initramfs w pętli dawała fałszywe ETA i dublowała pracę.
4598 + if any(_needs_initramfs_refresh(_n) for _n in to_install):
4599 + print(_('\n 🐧 Finalizing kernel/driver update (DKMS → initramfs → GRUB)...'))
4600 + _post_kernel_hooks()
4601 + elif sys_snap:
4602 + # Snapshot istnieje, ale nie było zmiany jądra – odśwież menu GRUB,
4603 + # żeby wpis migawki był widoczny przy najbliższym starcie.
4604 + _ensure_snapshot_grub_script()
4605 + _refresh_bootloader()
4606 +
4607 + print(f"\n✅ {_('installed', len(to_install))} ({(time.time()-t0):.0f}s)")
4608 + return 0
4609 +
4610 +
4611 +def _rollback_transaction(installed_db: dict, snapshot: dict,
4612 + installed_files: List[str],
4613 + deploy_dir: str, is_immutable: bool,
4614 + backups: Optional[List[Tuple[str, str]]] = None):
4615 + """
4616 + Cofa WSZYSTKIE pakiety zainstalowane w bieżącej transakcji.
4617 + Przywraca installed_db do stanu sprzed transakcji.
4618 + Usuwa fizyczne pliki z systemu (lub deploymentu w trybie immutable).
4619 + Jeśli podano `backups` (upgrade) – przywraca stare wersje nadpisanych plików.
4620 + """
4621 + # Przywróć installed_db
4622 + installed_db.clear()
4623 + installed_db.update(snapshot)
4624 +
4625 + root = deploy_dir if is_immutable else PAG_ROOT
4626 + backup_map = {dst: src for src, dst in (backups or [])}
4627 +
4628 + # Przywróć stare wersje z backupów (upgrade)
4629 + for dst, bpath in backup_map.items():
4630 + full = os.path.join(root, dst.lstrip("/"))
4631 + if os.path.lexists(bpath):
4632 + try:
4633 + os.makedirs(os.path.dirname(full), exist_ok=True)
4634 + os.replace(bpath, full)
4635 + except OSError:
4636 + pass
4637 +
4638 + # Usuń nowe pliki (które nie miały poprzedniej wersji)
4639 + for fpath in reversed(installed_files):
4640 + if fpath in backup_map:
4641 + continue
4642 + full = os.path.join(root, fpath.lstrip("/"))
4643 + if os.path.isfile(full) or os.path.islink(full):
4644 + try:
4645 + os.remove(full)
4646 + except OSError:
4647 + pass
4648 +
4649 + # Wyczyść puste katalogi
4650 + dirs_to_check = set()
4651 + for fpath in installed_files:
4652 + parent = os.path.dirname(fpath)
4653 + while parent and parent != "/":
4654 + dirs_to_check.add(parent)
4655 + parent = os.path.dirname(parent)
4656 + for d in sorted(dirs_to_check, key=len, reverse=True):
4657 + full_d = os.path.join(root, d.lstrip("/"))
4658 + if os.path.isdir(full_d):
4659 + try:
4660 + os.rmdir(full_d)
4661 + except OSError:
4662 + pass
4663 +
4664 + # W trybie immutable: usuń nieudany deployment
4665 + if is_immutable and deploy_dir:
4666 + shutil.rmtree(deploy_dir, ignore_errors=True)
4667 +
4668 + save_json(INSTALLED_DB, snapshot)
4669 +
4670 +
4671 +# =============================================================================
4672 +# USUWANIE
4673 +# =============================================================================
4674 +
4675 +def cmd_remove(package_names):
4676 + installed_db = load_json(INSTALLED_DB)
4677 + world = load_world()
4678 + snapshot = copy.deepcopy(installed_db)
4679 + removed = []
4680 + removed_files = []
4681 +
4682 + total = len(package_names)
4683 + for i, name in enumerate(package_names, 1):
4684 + if name not in installed_db:
4685 + print(_(' ⚠ {arg1}: not installed', arg1=(name))); continue
4686 +
4687 + # Pasek postępu (animowany „drakkar” na TTY)
4688 + pct = (i - 1) / total * 100
4689 + bar = _pagan_bar(pct, 25, time.time(), animated=sys.stderr.isatty())
4690 + print(f" 🗑 [{bar}] {i}/{total} ({pct:.0f}%) ", end="\r", file=sys.stderr, flush=True)
4691 +
4692 + print(f"🗑 {name}-{installed_db[name]['version']} ...", end=" ", flush=True)
4693 +
4694 + # Pre-remove hook (jeśli dostępny w staging)
4695 + _run_hook_for_installed(name, "pre-remove")
4696 +
4697 + count, rm_files = _safe_remove_files(name, installed_db)
4698 + del installed_db[name]
4699 + world.discard(name)
4700 + removed.append(name)
4701 + removed_files.extend(rm_files)
4702 + print(_('✅ ({arg1} files)', arg1=(count)))
4703 +
4704 + # Post-remove hook + sprzątanie zapisanych hooków
4705 + _run_hook_for_installed(name, "post-remove")
4706 + shutil.rmtree(os.path.join(PAG_DB, "hooks", name), ignore_errors=True)
4707 +
4708 + save_json(INSTALLED_DB, installed_db)
4709 + save_world(world)
4710 + _record_transaction("remove", removed, True, snapshot)
4711 +
4712 + print(file=sys.stderr) # wyczyść linię paska postępu
4713 +
4714 + if not removed: return 0
4715 + print(_('\n✅ Removed {arg1}.', arg1=(len(removed))))
4716 + _process_triggers(removed_files)
4717 +
4718 + orphans = _find_orphans(installed_db, world)
4719 + if orphans:
4720 + print(f"\n💡 {_('orphans_found', len(orphans), ', '.join(sorted(orphans)[:10]))}")
4721 + print(_(" 'pag remove-orphans' to clean up."))
4722 + return 0
4723 +
4724 +def _run_hook_for_installed(pkg_name, hook_name):
4725 + """Próbuje uruchomić hook z katalogu pakietu (jeśli został zapisany)."""
4726 + hook_dir = os.path.join(PAG_DB, "hooks", pkg_name)
4727 + if os.path.isdir(hook_dir):
4728 + ver = load_json(INSTALLED_DB).get(pkg_name, {}).get("version", "")
4729 + _run_hook(hook_dir, hook_name, PackageInfo({"name": pkg_name, "version": ver}))
4730 +
4731 +
4732 +# =============================================================================
4733 +# TRIGGERS – hooki zbiorcze (raz na transakcję, nie per pakiet)
4734 +# =============================================================================
4735 +# Wzorem pacman/dpkg: pakiet/administrator deklaruje zainteresowanie ścieżkami,
4736 +# a pasujący trigger uruchamia się DOKŁADNIE RAZ na końcu transakcji
4737 +# (np. fc-cache, glib-compile-schemas, update-desktop-database) zamiast po
4738 +# każdym pakiecie z osobna.
4739 +
4740 +TRIGGERS_DIR = PAG_CONF + "/triggers"
4741 +
4742 +DEFAULT_TRIGGERS = [
4743 + {"name": "font-cache", "paths": ["/usr/share/fonts/", "/usr/local/share/fonts/"],
4744 + "run": "fc-cache -fs"},
4745 + {"name": "glib-schemas", "paths": ["/usr/share/glib-2.0/schemas/"],
4746 + "run": "glib-compile-schemas /usr/share/glib-2.0/schemas"},
4747 + {"name": "desktop-database", "paths": ["/usr/share/applications/"],
4748 + "run": "update-desktop-database -q /usr/share/applications"},
4749 + {"name": "mime-database", "paths": ["/usr/share/mime/"],
4750 + "run": "update-mime-database /usr/share/mime"},
4751 + {"name": "systemd-daemon-reload", "paths": ["/usr/lib/systemd/system/"],
4752 + "run": "systemctl daemon-reload"},
4753 + # `systemctl --global daemon-reload` NIE istnieje – --global dotyczy tylko
4754 + # enable/disable jednostek. Przeładowanie robi _user_daemon_reload()
4755 + # (per zalogowany użytkownik), a "run" zostaje jako opis/cel audytu.
4756 + {"name": "systemd-user-daemon-reload", "paths": ["/usr/lib/systemd/user/"],
4757 + "internal": "user-daemon-reload",
4758 + "run": "systemctl --user daemon-reload"},
4759 + {"name": "udev-reload", "paths": ["/usr/lib/udev/rules.d/"],
4760 + "run": "udevadm control --reload-rules"},
4761 +]
4762 +
4763 +def _load_triggers() -> List[dict]:
4764 + """Ładuje triggery: domyślne (tylko gdy binarka istnieje) + /etc/pag/triggers/*.json."""
4765 + out = []
4766 + for t in DEFAULT_TRIGGERS:
4767 + bin_name = t["run"].split()[0]
4768 + if shutil.which(bin_name):
4769 + out.append(dict(t))
4770 + if os.path.isdir(TRIGGERS_DIR):
4771 + for fn in sorted(os.listdir(TRIGGERS_DIR)):
4772 + if not fn.endswith(".json"):
4773 + continue
4774 + try:
4775 + with open(os.path.join(TRIGGERS_DIR, fn)) as f:
4776 + data = json.load(f)
4777 + except (OSError, json.JSONDecodeError):
4778 + continue
4779 + if isinstance(data, dict):
4780 + data = [data]
4781 + for t in data:
4782 + if isinstance(t, dict) and t.get("name") and t.get("paths") and t.get("run"):
4783 + out.append(t)
4784 + return out
4785 +
4786 +def _logged_in_users() -> List[tuple]:
4787 + """[(uid, user)] aktywnych logowań wg loginctl. Best-effort."""
4788 + try:
4789 + r = subprocess.run(["loginctl", "list-users", "--no-legend"],
4790 + capture_output=True, text=True, timeout=30)
4791 + except Exception:
4792 + return []
4793 + out = []
4794 + for ln in (r.stdout or "").splitlines():
4795 + parts = ln.split()
4796 + if len(parts) < 2 or not parts[0].isdigit():
4797 + continue
4798 + out.append((parts[0], parts[1]))
4799 + return out
4800 +
4801 +
4802 +def _user_daemon_reload() -> int:
4803 + """Przeładowuje menedżery systemd ZALOGOWANYCH użytkowników.
4804 +
4805 + `systemctl --user` działa tylko w kontekście danego użytkownika (sesyjny
4806 + D-Bus), więc dla roota trzeba wejść w jego sesję. Zwraca liczbę udanych
4807 + przeładowań; brak sesji to nie błąd – jednostki wczytają się przy logowaniu.
4808 + """
4809 + done = 0
4810 + for uid, user in _logged_in_users():
4811 + rt = f"/run/user/{uid}"
4812 + if not os.path.isdir(rt):
4813 + continue
4814 + try:
4815 + if shutil.which("runuser"):
4816 + r = subprocess.run(
4817 + ["runuser", "-u", user, "--", "env", f"XDG_RUNTIME_DIR={rt}",
4818 + "systemctl", "--user", "daemon-reload"],
4819 + capture_output=True, timeout=60)
4820 + else:
4821 + r = subprocess.run(
4822 + ["su", "-", user, "-c",
4823 + f"XDG_RUNTIME_DIR={rt} systemctl --user daemon-reload"],
4824 + capture_output=True, timeout=60)
4825 + if r.returncode == 0:
4826 + done += 1
4827 + except Exception:
4828 + pass
4829 + return done
4830 +
4831 +
4832 +def _reload_user_media_services(touched_paths: List[str]) -> None:
4833 + """Po aktualizacji multimediow przeladuj uslugi UZYTKOWNIKA (pipewire/wireplumber).
4834 +
4835 + Nowe binarki/moduly sa juz na dysku, ale dzialajace sesje maja stare w
4836 + pamieci i probuja ladowac nieistniejace wersje modulow. Best-effort:
4837 + przeladowanie menedzerow systemd uzytkownikow + try-restart w sesjach.
4838 + """
4839 + if os.environ.get("PAG_NO_HOOKS", "") == "1":
4840 + return
4841 + _pfx = ("/usr/lib/systemd/user/pipewire", "/usr/lib/systemd/user/wireplumber",
4842 + "/usr/bin/pipewire", "/usr/bin/wireplumber",
4843 + "/usr/lib/pipewire-0.3/", "/usr/lib64/pipewire-0.3/",
4844 + "/usr/lib/wireplumber-0.5/", "/usr/lib64/wireplumber-0.5/")
4845 + if not any(_p.startswith(_x) for _x in _pfx for _p in touched_paths):
4846 + return
4847 + _user_daemon_reload()
4848 + try:
4849 + _r = subprocess.run(["loginctl", "list-users", "--no-legend"],
4850 + capture_output=True, text=True, timeout=30)
4851 + _users = [ln.split()[1] for ln in (_r.stdout or "").splitlines()
4852 + if len(ln.split()) >= 2]
4853 + except Exception:
4854 + _users = []
4855 + _done = []
4856 + for _u in _users:
4857 + try:
4858 + _rr = subprocess.run(
4859 + ["su", "-", _u, "-c",
4860 + "systemctl --user try-restart pipewire.socket pipewire.service "
4861 + "wireplumber.service"],
4862 + capture_output=True, timeout=60)
4863 + if _rr.returncode == 0:
4864 + _done.append(_u)
4865 + except Exception:
4866 + pass
4867 + if _done:
4868 + print(_("audio_services_reloaded", ", ".join(sorted(set(_done)))))
4869 +
4870 +def _process_triggers(touched_paths: List[str]):
4871 + """Uruchamia pasujące triggery RAZ na końcu transakcji (best-effort)."""
4872 + if not touched_paths:
4873 + return
4874 + if os.environ.get("PAG_NO_HOOKS", "") == "1":
4875 + return
4876 + import shlex as _shlex
4877 + matched = []
4878 + for trig in _load_triggers():
4879 + if any(path.startswith(p) for p in trig["paths"] for path in touched_paths):
4880 + matched.append(trig)
4881 + for trig in matched:
4882 + run = trig["run"]
4883 + print(_(' ⚡ Trigger: {arg1} ({arg2})', arg1=(trig['name']), arg2=(run)))
4884 + if trig.get("internal") == "user-daemon-reload":
4885 + _n = _user_daemon_reload()
4886 + _audit(f"TRIGGER {trig['name']}: user-daemon-reload ok={_n}")
4887 + if not _n:
4888 + print(" ℹ " + _('no_user_sessions'))
4889 + continue
4890 + try:
4891 + r = subprocess.run(_shlex.split(run), capture_output=True, text=True, timeout=120)
4892 + _audit(f"TRIGGER {trig['name']}: {run} rc={r.returncode}")
4893 + if r.returncode != 0:
4894 + print(f" ⚠ rc={r.returncode}: {(r.stderr or r.stdout or '').strip()[:160]}")
4895 + except subprocess.TimeoutExpired:
4896 + print(_(' ⚠ trigger {arg1} timed out (120 s)', arg1=(trig['name'])))
4897 + _audit(f"TRIGGER {trig['name']} TIMEOUT")
4898 + except Exception as e:
4899 + print(_(' ⚠ trigger {arg1}: {arg2}', arg1=(trig['name']), arg2=(e)))
4900 + _reload_user_media_services(touched_paths)
4901 +
4902 +
4903 +# =============================================================================
4904 +# UPDATE / UPGRADE / LIST / SEARCH / INFO / VERIFY
4905 +# =============================================================================
4906 +
4907 +def _cleanup_tmp_files(*paths):
4908 + """Usuwa tymczasowe pliki (np. .pag.new) po nieudanej operacji."""
4909 + for p in paths:
4910 + try:
4911 + if os.path.isfile(p):
4912 + os.remove(p)
4913 + except OSError:
4914 + pass
4915 +
4916 +
4917 +def cmd_self_update():
4918 + """Aktualizuje samego klienta pag z repo (podpisany /stable/pag).
4919 +
4920 + Kolejność: pobierz → weryfikacja GPG (+ fingerprint repo) → SHA256 →
4921 + kontrola składni (compile) → backup → atomowe os.replace.
4922 +
4923 + Podmieniamy plik, z którego pag ZOSTAŁ URUCHOMIONY (a nie hardkodowane
4924 + /usr/local/bin/pag): gdy pakiet instaluje /usr/bin/pag, a self-update
4925 + pisał do /usr/local/bin/pag, powstawały DWIE kopie o różnych wersjach
4926 + i zależnie od PATH `pag --version` pokazywał raz jedną, raz drugą."""
4927 + # Dedykowana blokada – patrz SelfUpdateLock. Chroni zapis dst.new oraz
4928 + # os.replace przed równoległą aktualizacją (np. cron + ręcznie).
4929 + with SelfUpdateLock():
4930 + return _self_update_impl()
4931 +
4932 +
4933 +def _self_update_impl():
4934 + repos = get_repos()
4935 + if not repos:
4936 + print(_('❌ No repositories configured.'))
4937 + return 1
4938 + # Aktualizuj bieżący plik (Python ≥3.9 ustawia __file__ jako ścieżkę
4939 + # bezwzględną). Poza /usr|/usr/local (np. uruchomienie z checkoutu)
4940 + # nie nadpisujemy niczego – wracamy do domyślnej lokalizacji instalacji.
4941 + dst = "/usr/local/bin/pag"
4942 + try:
4943 + cand = os.path.realpath(__file__)
4944 + if cand.startswith(("/usr/", "/usr/local/")):
4945 + dst = cand
4946 + except Exception:
4947 + pass
4948 + base = repos[0]
4949 + dst_new = dst + ".new"
4950 + dst_bak = dst + ".bak"
4951 + print(_('🔄 Checking for pag update from {arg1}...', arg1=(base)))
4952 + try:
4953 + with urlopen(Request(f"{base}/pag", headers={"User-Agent": "pag/3.0"}), timeout=20) as r:
4954 + data = r.read()
4955 + with urlopen(Request(f"{base}/pag.asc", headers={"User-Agent": "pag/3.0"}), timeout=20) as r:
4956 + sig = r.read()
4957 + except Exception as e:
4958 + print(_(' ❌ Cannot download pag: {arg1}', arg1=(e)))
4959 + return 1
4960 +
4961 + # Zapisz nową wersję w katalogu docelowym (ta sama partycja → atomowy rename)
4962 + with open(dst_new, "wb") as f:
4963 + f.write(data)
4964 + with open(dst_new + ".asc", "wb") as f:
4965 + f.write(sig)
4966 +
4967 + # --- 1. Weryfikacja podpisu GPG – bez tego nie instalujemy ---
4968 + insecure = os.environ.get("PAG_INSECURE", "") == "1"
4969 + ok, fp = _gpg_verify_fp(dst_new + ".asc", dst_new)
4970 + if not ok:
4971 + # Automatyczny import klucza (TOFU) – jak w _verify_repo_sig
4972 + res = _gpg_run("--verify", dst_new + ".asc", dst_new,
4973 + capture_output=True, text=True)
4974 + _stderr = res.stderr.decode(errors="replace") if isinstance(res.stderr, bytes) else (res.stderr or "")
4975 + if "public key" in _stderr.lower() and "no public key" in _stderr.lower():
4976 + try:
4977 + with urlopen(Request(f"{base}/paganos.asc", headers={"User-Agent": "pag/3.0"}), timeout=20) as r:
4978 + keydata = r.read()
4979 + with tempfile.NamedTemporaryFile(delete=False, suffix=".asc") as tmp:
4980 + tmp.write(keydata); tmp.flush()
4981 + _gpg_run("--import", tmp.name, capture_output=True, timeout=30)
4982 + os.unlink(tmp.name)
4983 + print(_(' 🔑 Imported repo key from {arg1}/paganos.asc', arg1=(base)))
4984 + ok, fp = _gpg_verify_fp(dst_new + ".asc", dst_new)
4985 + except Exception:
4986 + pass
4987 + if not ok:
4988 + if insecure:
4989 + print(_(' ⚠ Invalid update signature (PAG_INSECURE – ignoring)'))
4990 + else:
4991 + print(_(' ❌ Invalid update signature – not updating.'))
4992 + _cleanup_tmp_files(dst_new, dst_new + ".asc")
4993 + return 1
4994 + # Sprawdź fingerprint względem przypiętego klucza repo
4995 + pinned = _repo_pinned_fp(base)
4996 + if pinned:
4997 + if not fp:
4998 + print(_(' ❌ Cannot confirm the update signature fingerprint.'))
4999 + _cleanup_tmp_files(dst_new, dst_new + ".asc")
5000 + return 1
5001 + if fp != pinned.upper():
5002 + if insecure:
5003 + print(_(' ⚠ Update signed with a different key (PAG_INSECURE – ignoring)'))
5004 + else:
5005 + print(_(' ❌ [SECURITY ERROR] Update signed with a different key than the repo!'))
5006 + print(_(' Expected: {arg1}, received: {arg2}', arg1=(pinned), arg2=(fp)))
5007 + _cleanup_tmp_files(dst_new, dst_new + ".asc")
5008 + return 1
5009 +
5010 + # --- 2. Weryfikacja SHA256 (jeśli repo publikuje pag.sha256) ---
5011 + try:
5012 + with urlopen(Request(f"{base}/pag.sha256", headers={"User-Agent": "pag/3.0"}), timeout=15) as r:
5013 + sha = r.read().decode().strip().split()[0]
5014 + if sha:
5015 + actual = hashlib.sha256(data).hexdigest()
5016 + if actual.lower() != sha.lower():
5017 + print(_(' ❌ SHA256 mismatch! Expected {arg1}, got {arg2}', arg1=(sha), arg2=(actual)))
5018 + _cleanup_tmp_files(dst_new, dst_new + ".asc")
5019 + return 1
5020 + print(_(' ✅ SHA256 matches'))
5021 + except Exception:
5022 + # Brak pag.sha256 w repo – opcjonalne; nie blokuj aktualizacji.
5023 + pass
5024 +
5025 + # --- 3. Kontrola składni (nie uruchamiaj uszkodzonego/poddanego edycji pliku) ---
5026 + try:
5027 + compile(data, "pag", "exec")
5028 + except SyntaxError as e:
5029 + print(_(' ❌ Syntax error in new pag: {arg1}', arg1=(e)))
5030 + _cleanup_tmp_files(dst_new, dst_new + ".asc")
5031 + return 1
5032 +
5033 + m = (re.search(rb'PAG_VERSION\s*=\s*"(\d+\.\d+\.\d+[a-z]?)"', data[:3000])
5034 + or re.search(rb"v(\d+\.\d+\.\d+[a-z]?)", data[:3000]))
5035 + new_ver = m.group(1).decode() if m else "?"
5036 + print(_(' ✅ Downloaded pag {arg1} (current {arg2}), signature verified', arg1=(new_ver), arg2=(PAG_VERSION)))
5037 +
5038 + # --- 4. Backup + atomowa podmiana ---
5039 + if os.path.exists(dst):
5040 + shutil.copy2(dst, dst_bak)
5041 + os.chmod(dst_new, 0o755)
5042 + os.replace(dst_new, dst) # atomowe na tym samym FS
5043 + try:
5044 + if os.path.exists(dst_new + ".asc"):
5045 + os.remove(dst_new + ".asc")
5046 + except OSError:
5047 + pass
5048 + print(_(' ✅ Installed new pag. Old version kept as {arg1}', arg1=(dst_bak)))
5049 + # Ostrzeż, gdy w PATH pierwsza jest INNA kopia `pag` – inaczej
5050 + # `pag --version` dalej pokaże starą wersję i wygląda to jak brak update.
5051 + other = shutil.which("pag")
5052 + if other and os.path.realpath(other) != os.path.realpath(dst):
5053 + print(_(' ⚠ A different pag is first in PATH: {arg1} (updated {arg2})', arg1=(other), arg2=(dst)))
5054 + print(_(' Remove the old copy: sudo rm {arg1}', arg1=(other)))
5055 + print(_(' Restart pag to use the new version.'))
5056 + return 0
5057 +
5058 +
5059 +def _candidate_newer(rp, inst):
5060 + """Czy pakiet z repo jest nowszy od zainstalowanego.
5061 + Porównuje (version, release): sam bump pkgrel (np. auto-rebuild modułów
5062 + po aktualizacji jądra: nvidia-kernel-618 610.57.04-1 -> -2) też musi być
5063 + widziany przez `pag update`. Stare rekordy instalacji (bez pola release)
5064 + traktujemy jak release=1 – nie generują churnu, dopóki nie wrócą do
5065 + reinstalacji/zmiany wersji."""
5066 + rv = getattr(rp, "version", "0")
5067 + iv = inst.get("version", "0")
5068 + if _version_newer(rv, iv):
5069 + return True
5070 + if rv != iv:
5071 + return False
5072 + rr = int(getattr(rp, "release", 1) or 1)
5073 + ir = int(inst.get("release", 1) or 1)
5074 + return rr > ir
5075 +
5076 +
5077 +def _pending_updates() -> List[str]:
5078 + """Zainstalowane pakiety z nowszą wersją/release w repo (bez przypiętych)."""
5079 + installed = load_json(INSTALLED_DB)
5080 + pinned = load_json(PINNED_FILE)
5081 + repo = fetch_all_packages()
5082 + if not repo:
5083 + return []
5084 + return [n for n, i in installed.items()
5085 + if n not in pinned and (rp := repo.get(n)) and _candidate_newer(rp, i)]
5086 +
5087 +# =============================================================================
5088 +# BAZA Z OBRAZU ISO → REPO (`pag base`) – pełny rolling
5089 +# =============================================================================
5090 +# ISO jest zbudowane ZE ŹRÓDEŁ (glibc, gcc, gtk, XFCE, …) – pag tych pakietów
5091 +# nie instalował, więc nie ma ich w installed.json/files.db. Skutki:
5092 +# • `pag upgrade` ich NIE dotyka (nie ma o nich pojęcia),
5093 +# • mimo to `pag install <nazwa>` je NADPISZE – pag robi kopię plików spoza
5094 +# swojej bazy (patrz _new_transaction_backup_root), więc nie są nietykalne.
5095 +#
5096 +# /usr/share/pag/base.json (wypalany przez build-pagan.sh) mówi, co jest w bazie
5097 +# obrazu i w jakiej wersji. `pag base` pokazuje stan, a `pag base adopt` dogrywa
5098 +# te pakiety z repo – po tym zabiegu pag zarządza nimi normalnie, więc
5099 +# `pag upgrade` aktualizuje CAŁY system (rolling), a nie tylko to, co sam
5100 +# wcześniej zainstalował.
5101 +#
5102 +# Nazwy z buildera różnią się od nazw pakietów w repo (builder buduje „libX11”,
5103 +# repo ma pakiet „xorg-libx11”), stąd aliasy poniżej. Nazwy bez odpowiednika
5104 +# w repo zostają w wersji z obrazu – raport mówi o tym wprost, zamiast udawać,
5105 +# że są aktualne.
5106 +BASE_NAME_ALIASES = {
5107 + "atk": "at-spi2-core",
5108 + "dejavu-fonts": "dejavu-ttf",
5109 + "fontconfig": "xorg-fontconfig",
5110 + "gtk": "gtk3",
5111 + "iceauth": "xorg-iceauth",
5112 + "libX11": "xorg-libx11",
5113 + "libXau": "xorg-libxau",
5114 + "libXdmcp": "xorg-libxdmcp",
5115 + "libXext": "xorg-libxext",
5116 + "libXft": "xorg-libxft",
5117 + "libdrm": "xorg-libdrm",
5118 + "libnspr": "nspr",
5119 + "libxkbfile": "xorg-libxkbfile",
5120 + "libxklavier": "xorg-libxklavier",
5121 + "linux-pam": "pam",
5122 + "pixman": "xorg-pixman",
5123 + "sdl2": "sdl",
5124 + "setxkbmap": "xorg-setxkbmap",
5125 + "xauth": "xorg-xauth",
5126 + "xf86-input-libinput": "xorg-xf86-input-libinput",
5127 + "xf86-video-fbdev": "xorg-xf86-video-fbdev",
5128 + "xinit": "xorg-xinit",
5129 + "xkbcomp": "xorg-xkbcomp",
5130 + "xkeyboard-config": "xorg-xkeyboard-config",
5131 + # Builder buduje wpa_supplicant (z podkreślnikiem), a repo ma wpa-supplicant
5132 + # (z myślnikiem) – bez tego aliasu pakiet nie dostawał aktualizacji z repo,
5133 + # mimo że repo.json zna DOKŁADNIE tę samą wersję.
5134 + "wpa_supplicant": "wpa-supplicant",
5135 +}
5136 +
5137 +
5138 +def _base_manifest() -> dict:
5139 + """Manifest bazy z obrazu ({} gdy obraz go nie dostarcza)."""
5140 + _d = load_json(os.path.join(PAG_ROOT, BASE_MANIFEST.lstrip("/")))
5141 + return _d if isinstance(_d, dict) else {}
5142 +
5143 +
5144 +def _base_entries() -> list:
5145 + """[(nazwa_z_buildera, wersja_z_obrazu), ...] z manifestu."""
5146 + _out = []
5147 + for _e in (_base_manifest().get("packages") or []):
5148 + if isinstance(_e, str):
5149 + if _e:
5150 + _out.append((_e, "?"))
5151 + elif isinstance(_e, dict) and _e.get("name"):
5152 + _out.append((str(_e["name"]), str(_e.get("version") or "?")))
5153 + return _out
5154 +
5155 +
5156 +def _base_repo_name(name: str, repo: dict, installed: dict) -> str:
5157 + """Nazwa pakietu w repo dla nazwy z buildera (alias → provides → brak)."""
5158 + if name in repo:
5159 + return name
5160 + _alias = BASE_NAME_ALIASES.get(name)
5161 + if _alias and _alias in repo:
5162 + return _alias
5163 + _real = _resolve_provides(name, repo, installed)
5164 + return _real if _real in repo else ""
5165 +
5166 +
5167 +def _base_summary(repo: Optional[dict] = None) -> dict:
5168 + """Klasyfikacja pakietów bazy z obrazu wobec repo.
5169 +
5170 + repo=None → pobiera indeks repo (potrzebny do listy „do adoptowania”).
5171 + repo={} → bez sieci: rozpoznaje tylko to, czym pag już zarządza.
5172 + """
5173 + _entries = _base_entries()
5174 + if not _entries:
5175 + return {"total": 0, "tracked": 0, "adoptable": [], "unmatched": []}
5176 + if repo is None:
5177 + repo = fetch_all_packages()
5178 + installed = load_json(INSTALLED_DB)
5179 + tracked, adoptable, unmatched = 0, [], []
5180 + for _n, _v in _entries:
5181 + _real = _base_repo_name(_n, repo, installed)
5182 + if _n in installed or (_real and _real in installed):
5183 + tracked += 1
5184 + elif _real:
5185 + adoptable.append((_n, _real, _v))
5186 + else:
5187 + unmatched.append(_n)
5188 + return {"total": len(_entries), "tracked": tracked,
5189 + "adoptable": adoptable, "unmatched": unmatched}
5190 +
5191 +
5192 +def _base_hint_unmanaged() -> None:
5193 + """Jednozdaniowa informacja dla `pag sync/update/upgrade`."""
5194 + try:
5195 + _s = _base_summary()
5196 + except Exception:
5197 + return
5198 + if _s["adoptable"]:
5199 + print(f"\n ℹ {_('base_unmanaged_hint', len(_s['adoptable']))}")
5200 +
5201 +
5202 +def _base_warn_overwrite(names) -> None:
5203 + """Ostrzeżenie w `pag install`, gdy pakiet pochodzi z bazy obrazu ISO."""
5204 + _entries = _base_entries()
5205 + if not _entries:
5206 + return
5207 + _known = set()
5208 + for _n, _v in _entries:
5209 + _known.add(_n)
5210 + _al = BASE_NAME_ALIASES.get(_n)
5211 + if _al:
5212 + _known.add(_al)
5213 + _hit = [n for n in names if n in _known]
5214 + if _hit:
5215 + _listed = ", ".join(_hit[:5]) + (" …" if len(_hit) > 5 else "")
5216 + print(f" ℹ {_('base_overwrite', _listed)}")
5217 +
5218 +
5219 +def cmd_base_status():
5220 + """`pag base` / `pag base status` – co w systemie pochodzi z obrazu,
5221 + czym pag już zarządza i co da się zaadoptować z repo."""
5222 + _man = _base_manifest()
5223 + if not _man:
5224 + print(f" ℹ {_('base_no_manifest')}")
5225 + return 0
5226 + _s = _base_summary()
5227 + print(f"\n {_c('bold', _('base_title'))}")
5228 + print(f" {'─' * 46}")
5229 + _de = _man.get("de") or ""
5230 + print(f" {_('base_iso_version'):<34} {_man.get('iso_version', '?')}" + (f" ({_de})" if _de else ""))
5231 + print(f" {_('base_total'):<34} {_s['total']}")
5232 + print(f" {_('base_tracked'):<34} {_s['tracked']}")
5233 + print(f" {_('base_adoptable'):<34} {len(_s['adoptable'])}")
5234 + print(f" {_('base_unmatched'):<34} {len(_s['unmatched'])}")
5235 + if _s["adoptable"]:
5236 + print(f"\n {_('base_adopt_hint')}")
5237 + for _iso_n, _real, _v in _s["adoptable"][:10]:
5238 + _m = "" if _iso_n == _real else f" ({_iso_n})"
5239 + print(f" {_real}-{_v}{_m}")
5240 + if len(_s["adoptable"]) > 10:
5241 + print(f" … {len(_s['adoptable']) - 10} {_('base_more')}")
5242 + if _s["unmatched"]:
5243 + print(f"\n {_('base_unmatched_hint')}")
5244 + print(" " + ", ".join(_s["unmatched"][:12])
5245 + + (f" … +{len(_s['unmatched']) - 12}" if len(_s["unmatched"]) > 12 else ""))
5246 + return 0
5247 +
5248 +
5249 +def cmd_base_adopt(args):
5250 + """`pag base adopt [pkg...] [--dry-run]` – dograj bazę z obrazu z repo.
5251 +
5252 + Pakiety bazy nie ma w installed.json, więc pag traktuje je jak NOWĄ
5253 + instalację: pliki z obrazu trafiają do kopii transakcji (działa
5254 + `pag rollback`), a po sukcesie pag zarządza nimi jak każdym innym pakietem.
5255 + """
5256 + if not _base_manifest():
5257 + print(f" ℹ {_('base_no_manifest')}")
5258 + return 1
5259 + repo = fetch_all_packages()
5260 + if not repo:
5261 + print(f"❌ {_('no_index')}")
5262 + return 1
5263 + _want = [a for a in args if not a.startswith("-") and a != "adopt"]
5264 + _s = _base_summary(repo)
5265 + plan = _s["adoptable"]
5266 + if _want:
5267 + _sel = set(_want)
5268 + plan = [p for p in plan if p[0] in _sel or p[1] in _sel]
5269 + if not plan:
5270 + print(f" ℹ {_('base_nothing_selected')}")
5271 + return 0
5272 + if not plan:
5273 + print(f"✅ {_('base_all_managed')}")
5274 + return 0
5275 + _size = sum(repo[r].size_bytes for _i, r, _v in plan if r in repo)
5276 + print(f"\n {_('base_adopt_plan', len(plan), _size / 1048576)}")
5277 + for _iso_n, _real, _v in plan[:20]:
5278 + _p = repo.get(_real)
5279 + _rv = _p.version if _p else "?"
5280 + _rr = (getattr(_p, "release", "") or "") if _p else ""
5281 + _rvr = f"{_rv}-{_rr}" if _rr else _rv
5282 + _m = "" if _iso_n == _real else f" ({_iso_n} → {_real})"
5283 + print(f" {_real}: {_v} → {_rvr}{_m}")
5284 + if len(plan) > 20:
5285 + print(f" … {len(plan) - 20} {_('base_more')}")
5286 + if "-n" in args or "--dry-run" in args:
5287 + print(f" {_('base_dry_run')}")
5288 + return 0
5289 + _rc = cmd_install([r for _i, r, _v in plan])
5290 + if _rc == 0:
5291 + # Wymienione biblioteki/narzędzia (glibc, gcc, GTK…) są już nowe na dysku,
5292 + # ale działające procesy wciąż mają stare w pamięci – restart domyka.
5293 + print(f"\n ℹ {_('base_reboot_hint')}")
5294 + return _rc
5295 +
5296 +
5297 +def _base_cached_index() -> dict:
5298 + """Indeks repo TYLKO z lokalnego cache (zero sieci) – do mapowania nazw.
5299 +
5300 + Potrzebne dla `pag base register`: rejestracja bazy obrazu nie może zależeć
5301 + od sieci (odpala się w buildzie, w chroocie, bez DNS). Cache indeksu powstaje
5302 + przy okazji `pag sync`/`pag install` i po nim wystarcza.
5303 + """
5304 + _out = {}
5305 + try:
5306 + for _r in get_repos():
5307 + _cp = _repo_cache_path(_r)
5308 + if not os.path.exists(_cp):
5309 + continue
5310 + for _pdata in (_load_repo_cache(_cp) or []):
5311 + _n = _pdata.get("name") or _pdata.get("filename", "?").split("-")[0]
5312 + _pkg = PackageInfo(_pdata, _r)
5313 + if _n not in _out or _version_newer(_pkg.version, _out[_n].version):
5314 + _out[_n] = _pkg
5315 + except Exception:
5316 + return _out
5317 + return _out
5318 +
5319 +
5320 +def cmd_base_register(args):
5321 + """`pag base register [--force] [--dry-run]` – wpisz bazę obrazu do installed.json.
5322 +
5323 + PO CO: pakietów zbudowanych przez builder (glibc, gcc, GTK, XFCE…) nie ma
5324 + w installed.json, więc `pag upgrade` ich NIE widzi i system nie da się
5325 + prowadzić w trybie rolling – trzeba by najpierw `pag base adopt`, czyli
5326 + ponownie ŚCIĄGNĄĆ całą bazę z repo. Rejestracja zamiast tego zapisuje je
5327 + jako zainstalowane **z wersją z obrazu** (to ona leży na dysku), więc
5328 + `pag upgrade` porówna ją z repo i podniesie tylko to, co nowsze.
5329 +
5330 + Offline: nic nie pobiera. Cache indeksu repo (jeśli jest) służy WYŁĄCZNIE do
5331 + mapowania nazw builder → repo (BASE_NAME_ALIASES/provides) i metadanych
5332 + (release/opis/zależności). Nazwy bez odpowiednika w repo zostają jak są.
5333 +
5334 + OGRANICZENIE: rejestracja nie zna listy plików pakietu (files.db), więc
5335 + dopóki pakiet nie zostanie zaktualizowany z repo, `pag verify`/`pag remove`
5336 + go nie obejmą (`pag base adopt` nadal jest drogą do pełnego przejęcia).
5337 + """
5338 + _force = "-f" in args or "--force" in args
5339 + _dry = "-n" in args or "--dry-run" in args
5340 +
5341 + _entries = _base_entries()
5342 + if not _entries:
5343 + print(f" ℹ {_('base_no_manifest')}")
5344 + return 1
5345 +
5346 + _repo = _base_cached_index()
5347 + installed = load_json(INSTALLED_DB)
5348 + world = load_world()
5349 + _now = datetime.now().isoformat()
5350 +
5351 + added, skipped, renamed = [], 0, 0
5352 + for _n, _v in _entries:
5353 + _real = _base_repo_name(_n, _repo, installed) if _repo else ""
5354 + _key = _real or _n
5355 + if _real and _real != _n:
5356 + renamed += 1
5357 + if _key in installed and not _force:
5358 + skipped += 1
5359 + continue
5360 + _pkg = _repo.get(_key)
5361 + installed[_key] = {
5362 + "version": _v or (getattr(_pkg, "version", "") or "?"),
5363 + "release": getattr(_pkg, "release", "") or "1",
5364 + "description": (getattr(_pkg, "description", "") or "")
5365 + or "Pagan Linux – pakiet bazy obrazu",
5366 + "dependencies": list(getattr(_pkg, "dependencies", []) or []),
5367 + "size_bytes": getattr(_pkg, "size_bytes", 0) or 0,
5368 + "sha256": "",
5369 + "installed_at": _now,
5370 + "repo": "base",
5371 + "provides": list(getattr(_pkg, "provides", []) or []),
5372 + "provides_so": list(getattr(_pkg, "provides_so", []) or []),
5373 + "requires_so": list(getattr(_pkg, "requires_so", []) or []),
5374 + }
5375 + world.add(_key)
5376 + added.append(_key)
5377 +
5378 + if _dry:
5379 + print(f" ℹ {_('base_register_plan', len(added))}")
5380 + return 0
5381 + if added:
5382 + save_json(INSTALLED_DB, installed)
5383 + save_world(world)
5384 + print(f" ✅ {_('base_register_ok', len(added), skipped)}")
5385 + if renamed:
5386 + print(f" ℹ {_('base_register_renamed', renamed)}")
5387 + if not _repo:
5388 + print(f" ℹ {_('base_register_nocache')}")
5389 + return 0
5390 +
5391 +
5392 +def cmd_update(do_upgrade: bool = False):
5393 + """`pag sync` / `pag update` – odświeżenie indeksów + raport aktualizacji.
5394 +
5395 + sync → tylko odświeżenie indeksów + info: „jest X pakietów do
5396 + zaktualizowania – wpisz: pag update".
5397 + update → odświeżenie indeksów + AKTUALIZACJA PAKIETÓW (pakiety, nie system).
5398 + Pomijamy cache TTL (inaczej nowe pakiety/aktualizacje są niewidoczne nawet
5399 + przez godzinę). Pełne pobranie + weryfikacja GPG przy każdym odświeżeniu.
5400 + """
5401 + force = True
5402 + print(_('🔄 Refreshing indexes...'))
5403 + for repo_url in get_repos():
5404 + pkgs = fetch_repo_index(repo_url, force=force)
5405 + cp = _repo_cache_path(repo_url)
5406 + has_sig = os.path.exists(cp + ".sig")
5407 + 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 '⚠')))
5408 + print(f"✅ {_('indexes_refreshed')}")
5409 +
5410 + # Powiadomienie o nowszej wersji pag (repo.json["pag_version"])
5411 + try:
5412 + for r in get_repos():
5413 + cp = _repo_cache_path(r)
5414 + if os.path.exists(cp):
5415 + d = json.load(open(cp))
5416 + rv = d.get("pag_version", "")
5417 + if rv and rv != PAG_VERSION:
5418 + print(_(' ⚠ New pag version {arg1} available – run: pag self-update', arg1=(rv)))
5419 + except Exception:
5420 + pass
5421 +
5422 + # Raport: pakiety do aktualizacji
5423 + pending = _kernel_group_updates(_pending_updates())
5424 + if not pending:
5425 + print(f"✅ {_('all_up_to_date')}")
5426 + _base_hint_unmanaged()
5427 + return 0
5428 + print(f"{_('updates_available', len(pending))}")
5429 + installed = load_json(INSTALLED_DB)
5430 + repo = fetch_all_packages()
5431 + for n in pending:
5432 + _i = installed.get(n, {})
5433 + _ir = _i.get("release")
5434 + _nr = getattr(repo[n], "release", "") or ""
5435 + _old = f"{_i.get('version', '?')}-{_ir}" if _ir else _i.get("version", "?")
5436 + _new = f"{repo[n].version}-{_nr}" if _nr else repo[n].version
5437 + print(f" {n}: {_old} → {_new}")
5438 + if not do_upgrade:
5439 + _base_hint_unmanaged()
5440 + return 0 # sync: tylko informacja
5441 + if not _ask_confirm():
5442 + return 0
5443 + _rc = cmd_install(pending, upgrade=True)
5444 + _base_hint_unmanaged()
5445 + return _rc
5446 +
5447 +def _versioned_kernels(boot: str = "/boot") -> list:
5448 + """Wersjonowane obrazy jąder z /boot (bez aliasu `vmlinuz-linux`)."""
5449 + try:
5450 + out = []
5451 + for n in os.listdir(boot):
5452 + if not n.startswith("vmlinuz-"):
5453 + continue
5454 + ver = n[len("vmlinuz-"):]
5455 + if not ver or not ver[0].isdigit():
5456 + continue # vmlinuz-linux to alias, nie wersja
5457 + if os.path.islink(os.path.join(boot, n)):
5458 + continue
5459 + out.append(ver)
5460 + return out
5461 + except Exception:
5462 + return []
5463 +
5464 +
5465 +def _initramfs_stale() -> bool:
5466 + """Czy initramfs najnowszego (wersjonowanego) jądra wymaga przebudowy.
5467 +
5468 + Uwaga: aliasy `initramfs.img` / `initramfs-linux.img` bywają martwymi
5469 + symlinkami — `os.path.exists()` zwraca wtedy False, co wcześniej kończyło
5470 + się wiecznym „stale” i przebudową w pętli. Patrzymy na KONKRETNY plik
5471 + `initramfs-<wersja>.img`.
5472 + """
5473 + try:
5474 + if not os.path.isdir("/boot"):
5475 + return False
5476 + vers = _versioned_kernels()
5477 + if not vers:
5478 + return False
5479 + newest = max(vers, key=lambda v: os.path.getmtime(f"/boot/vmlinuz-{v}"))
5480 + img = f"/boot/initramfs-{newest}.img"
5481 + if not os.path.isfile(img):
5482 + return True
5483 + return os.path.getmtime(img) < os.path.getmtime(f"/boot/vmlinuz-{newest}")
5484 + except Exception:
5485 + return False
5486 +
5487 +def cmd_upgrade():
5488 + """`pag upgrade` – aktualizacja SYSTEMU: pakiety + kernel/initramfs/GRUB."""
5489 + rc = cmd_update(do_upgrade=True)
5490 + if rc != 0:
5491 + return rc
5492 + # System: dopilnuj initramfs (gdyby kernel był nowszy) + GRUB.
5493 + if _initramfs_stale():
5494 + print(_(' 🐧 Rebuilding initramfs (newer kernel)...'))
5495 + _rebuild_initramfs()
5496 + _refresh_bootloader()
5497 + return 0
5498 +
5499 +def cmd_list(installed_only=False):
5500 + if installed_only:
5501 + db = load_json(INSTALLED_DB)
5502 + pinned = load_json(PINNED_FILE)
5503 + if not db: print(_('No packages installed.')); return
5504 + print(_('Installed ({arg1}):', arg1=(len(db))))
5505 + for n, i in sorted(db.items()):
5506 + pin = " 📌" if n in pinned else ""
5507 + print(f" {n}-{i['version']}{pin} – {i.get('description','')}")
5508 + else:
5509 + pkgs = fetch_all_packages()
5510 + installed = load_json(INSTALLED_DB)
5511 + pinned = load_json(PINNED_FILE)
5512 + print(_('Available ({arg1}):', arg1=(len(pkgs))))
5513 + for n, p in sorted(pkgs.items()):
5514 + m = "✓" if n in installed else " "
5515 + extra = f" [{_('installed_marker')}: {installed[n]['version']}]" if n in installed else ""
5516 + if n in pinned: extra += " 📌"
5517 + print(f" [{m}] {n}-{p.version} – {p.description}{extra}")
5518 +
5519 +def cmd_search(query):
5520 + pkgs = fetch_all_packages()
5521 + results = [(n,p) for n,p in pkgs.items() if query.lower() in n.lower() or query.lower() in p.description.lower()]
5522 + if not results: print(_('❌ No results for: {arg1}', arg1=(query))); return
5523 + installed = load_json(INSTALLED_DB)
5524 + print(_("Results for '{arg1}' ({arg2}):", arg1=(query), arg2=(len(results))))
5525 + for n,p in sorted(results):
5526 + print(f" [{'✓' if n in installed else ' '}] {n}-{p.version}")
5527 + print(f" {p.description}")
5528 +
5529 +
5530 +def _smart_search(query: str) -> int:
5531 + """
5532 + Inteligentne wyszukiwanie: repo PaganOS + Flathub.
5533 + Uruchamiane gdy użytkownik wpisze `pag <nazwa>` zamiast `pag install <nazwa>`.
5534 + Pokazuje dostępne źródła i sugeruje komendy instalacji.
5535 + """
5536 + # 1. Repo PaganOS
5537 + try:
5538 + pkgs = fetch_all_packages()
5539 + except Exception:
5540 + pkgs = {}
5541 + repo_lower = [(n, p) for n, p in pkgs.items()
5542 + if query.lower() in n.lower() or query.lower() in p.description.lower()]
5543 +
5544 + # 2. Flathub (jeśli dostępny)
5545 + flat = _flatpak_search_raw(query) if _check_flatpak(quiet=True) else []
5546 +
5547 + if not repo_lower and not flat:
5548 + print(_("\n ❌ '{arg1}' — not found.", arg1=(query)))
5549 + print(_(' PaganOS repo: pag search {arg1}', arg1=(query)))
5550 + if _check_flatpak(quiet=True):
5551 + print(_(' Flathub: pag flatpak search {arg1}', arg1=(query)))
5552 + print(_(' Add repo: pag repo-add <url>'))
5553 + return 1
5554 +
5555 + installed = load_json(INSTALLED_DB)
5556 +
5557 + # ── Repo PaganOS ──
5558 + if repo_lower:
5559 + exact = [(n, p) for n, p in repo_lower if n.lower() == query.lower()]
5560 + show = (exact or repo_lower)[:6]
5561 + print(f"\n 📦 PaganOS — '{query}':")
5562 + for n, p in sorted(show):
5563 + mark = "✓" if n in installed else " "
5564 + desc = p.description[:70] if len(p.description) > 75 else p.description
5565 + print(f" [{mark}] {n}-{p.version}")
5566 + if desc:
5567 + print(f" {desc}")
5568 + if len(repo_lower) > 6:
5569 + print(_(' ... and {arg1} more (pag search {arg2})', arg1=(len(repo_lower) - 6), arg2=(query)))
5570 +
5571 + # ── Flathub ──
5572 + if flat:
5573 + print(f"\n 📦 Flathub — '{query}':")
5574 + for r in flat[:5]:
5575 + mark = "✓" if r.get("installed") else " "
5576 + name = r.get("name") or r.get("application", "?")
5577 + desc = (r.get("description") or "")[:65]
5578 + print(f" [{mark}] {name}")
5579 + if desc:
5580 + print(f" {desc}")
5581 + if len(flat) > 5:
5582 + print(_(' ... and {arg1} more (pag flatpak search {arg2})', arg1=(len(flat) - 5), arg2=(query)))
5583 +
5584 + # ── Sugestie instalacji ──
5585 + print()
5586 + if repo_lower:
5587 + 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]
5588 + if best in installed:
5589 + print(_(' ✓ {arg1} is already installed ({arg2})', arg1=(best), arg2=(installed[best]['version'])))
5590 + else:
5591 + print(f" 💡 sudo pag install {best}")
5592 + if flat:
5593 + best_fp = flat[0].get("application") or flat[0].get("name", query)
5594 + print(f" 💡 pag flatpak install {best_fp}")
5595 +
5596 + return 0
5597 +
5598 +def cmd_info(name):
5599 + pkgs = fetch_all_packages()
5600 + p = pkgs.get(name)
5601 + info = load_json(INSTALLED_DB).get(name)
5602 + if not p and not info: print(_("❌ '{arg1}' not found.", arg1=(name))); return 1
5603 + print(f"📦 {name}")
5604 + if p:
5605 + print(_(' Version (repo): {arg1}', arg1=(p.version)))
5606 + print(_(' Description: {arg1}', arg1=(p.description)))
5607 + print(_(' Size: {arg1:.1f} MB', arg1=(p.size_bytes/1048576)))
5608 + print(_(' SHA256: {arg1}...', arg1=(p.sha256[:32])))
5609 + print(_(' GPG: {arg1}', arg1=(p.gpg_fp or _('none_value'))))
5610 + print(_(' Dependencies: {arg1}', arg1=((', '.join(p.dependencies)) if p.dependencies else _('none_parenthesized'))))
5611 + if p.optdepends:
5612 + print(f" {_('optional_deps')}")
5613 + for _od in p.optdepends:
5614 + print(f" - {_od}")
5615 + if info:
5616 + print(_(' Installed: {arg1} ({arg2})', arg1=(info['version']), arg2=(info.get('installed_at','?'))))
5617 +
5618 +def cmd_files(name):
5619 + if name not in load_json(INSTALLED_DB):
5620 + print(_("❌ '{arg1}' not installed.", arg1=(name))); return 1
5621 + files = _db_get_package_files(name)
5622 + print(_('Files in {arg1} ({arg2}):', arg1=(name), arg2=(len(files))))
5623 + for f in sorted(files): print(f" {f}")
5624 +
5625 +def cmd_repair(dry_run=False):
5626 + """Naprawia system: reinstaluje pakiety, ktorych pliki zginely.
5627 +
5628 + Przechodzi po bazie plikow (jak `verify`), zbiera pakiety z brakujacymi
5629 + plikami i dla kazdego robi REINSTALACJE z repozytorium (staging + GPG).
5630 + Reinstalacja nie rusza konfiguracji uzytkownika (.pacnew), a przywraca
5631 + brakujace pliki pakietu (np. qt6-declarative, accountsservice).
5632 + """
5633 + installed = load_json(INSTALLED_DB)
5634 + if not installed:
5635 + print(_('Nothing to repair (no packages installed).'))
5636 + return 0
5637 + missing = {}
5638 + for name in installed:
5639 + cnt = 0
5640 + for fpath in _db_get_package_files(name):
5641 + full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
5642 + if not (os.path.exists(full) or os.path.islink(full)):
5643 + cnt += 1
5644 + if cnt:
5645 + missing[name] = cnt
5646 + if not missing:
5647 + print(_('✅ All files are in place – nothing to repair.'))
5648 + return 0
5649 + total = sum(missing.values())
5650 + print(_('🔧 Packages with missing files: {arg1} (total {arg2} files)', arg1=(len(missing)), arg2=(total)))
5651 + for n, c in sorted(missing.items(), key=lambda kv: (-kv[1], kv[0])):
5652 + print(f" {n}: {c}")
5653 + if dry_run:
5654 + print(_('\n(--dry-run: nothing is changed)'))
5655 + return 0
5656 + if not _ask_confirm():
5657 + print(_("cancelled")); return 0
5658 + # Jedna migawka na całą naprawę – nie tworzymy snapshotu per pakiet.
5659 + _snap_ok, _ = _snapshot_support()
5660 + if _snap_ok:
5661 + _create_system_snapshot(list(missing), "repair")
5662 + _refresh_bootloader()
5663 + _prev_snap = os.environ.get("PAG_SNAPSHOT")
5664 + os.environ["PAG_SNAPSHOT"] = "never"
5665 + failed = []
5666 + try:
5667 + for n in sorted(missing, key=lambda x: (-missing[x], x)):
5668 + print(_('\n🔧 repair: {arg1}', arg1=(n)))
5669 + try:
5670 + rc = cmd_install([n], upgrade=True)
5671 + except SystemExit as e:
5672 + rc = e.code
5673 + except Exception as e:
5674 + print(f" ❌ {n}: {e}")
5675 + rc = 1
5676 + if rc:
5677 + failed.append(n)
5678 + finally:
5679 + if _prev_snap is None:
5680 + os.environ.pop("PAG_SNAPSHOT", None)
5681 + else:
5682 + os.environ["PAG_SNAPSHOT"] = _prev_snap
5683 + print()
5684 + ok = len(missing) - len(failed)
5685 + if failed:
5686 + print(_('⚠ Repaired {arg1}/{arg2}. Failed: {arg3}', arg1=(ok), arg2=(len(missing)), arg3=(', '.join(failed))))
5687 + return 1
5688 + print(_('✅ Repaired {arg1} packages.', arg1=(ok)))
5689 + return 0
5690 +
5691 +
5692 +def cmd_verify(deep=False):
5693 + installed = load_json(INSTALLED_DB)
5694 + if not installed: print(_('Nothing to verify.')); return
5695 + errors = []
5696 +
5697 + # Wczytaj WSZYSTKIE sumy RAZ (nie w pętli!) – przy 50k plików wywołanie
5698 + # _db_get_all_file_checksums() per-plik dawało O(n²) i godziny zamiast sekund.
5699 + all_checksums = _db_get_all_file_checksums() if deep else {}
5700 + for name in installed:
5701 + for fpath in _db_get_package_files(name):
5702 + full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
5703 + if not (os.path.exists(full) or os.path.islink(full)):
5704 + errors.append(_("verify_missing_file", name, fpath))
5705 + elif deep:
5706 + expected = all_checksums.get(fpath, "")
5707 + if expected:
5708 + actual = _sha256_file(full)
5709 + if actual != expected:
5710 + errors.append(_("verify_sha_mismatch", name, fpath))
5711 +
5712 + if errors:
5713 + print(f"❌ {_('verify_errors', len(errors))}")
5714 + for e in errors: print(e)
5715 + return 1
5716 + total = _db_count_files()
5717 + print(f"✅ {_('verify_ok', total)}")
5718 +
5719 +# =============================================================================
5720 +# PINNING / CLEAN / ORPHANS / REPO / FLATPAK
5721 +# =============================================================================
5722 +
5723 +def cmd_pin(name, version=""):
5724 + pinned = load_json(PINNED_FILE)
5725 + if version:
5726 + pinned[name] = version
5727 + else:
5728 + info = load_json(INSTALLED_DB).get(name, {})
5729 + pinned[name] = info.get("version", "?")
5730 + save_json(PINNED_FILE, pinned)
5731 + print(f"📌 {name} {_('pinned_to')} {pinned[name]}")
5732 +
5733 +def cmd_unpin(name):
5734 + pinned = load_json(PINNED_FILE)
5735 + if name in pinned:
5736 + del pinned[name]; save_json(PINNED_FILE, pinned)
5737 + print(f"🔓 {name} {_('unpinned')}")
5738 + else:
5739 + print(f"⚠ {name} {_('not_pinned')}")
5740 +
5741 +def cmd_pinned():
5742 + pinned = load_json(PINNED_FILE)
5743 + if not pinned: print(_("no_pinned")); return
5744 + print(_("pinned_list", len(pinned)))
5745 + for n,v in sorted(pinned.items()): print(f" 📌 {n} = {v}")
5746 +
5747 +def cmd_clean():
5748 + if os.path.isdir(PAG_CACHE):
5749 + count = size = 0
5750 + for f in os.listdir(PAG_CACHE):
5751 + fp = os.path.join(PAG_CACHE, f)
5752 + if os.path.isfile(fp):
5753 + size += os.path.getsize(fp); os.remove(fp); count += 1
5754 + print(f"✅ {_('cache_cleared', count, size/1048576)}")
5755 +
5756 +def cmd_remove_orphans():
5757 + installed = load_json(INSTALLED_DB)
5758 + world = load_world()
5759 + orphans = _find_orphans(installed, world)
5760 + if not orphans: print(_('✅ No orphans.')); return
5761 + print(_('Orphans ({arg1}):', arg1=(len(orphans))))
5762 + for n in sorted(orphans): print(f" {n}-{installed[n]['version']}")
5763 + if not _ask_confirm():
5764 + return
5765 + cmd_remove(list(orphans))
5766 +
5767 +
5768 +# =============================================================================
5769 +# PROVIDES – PAKIETY WIRTUALNE
5770 +# =============================================================================
5771 +
5772 +PROVIDES_MAP = {
5773 + "pkgconfig(glib-2.0)": "glib",
5774 + "pkgconfig(gobject-introspection-1.0)": "gobject-introspection",
5775 + "pkgconfig(gtk+-3.0)": "gtk",
5776 + "pkgconfig(gtk4)": "gtk",
5777 + "pkgconfig(zlib)": "zlib",
5778 + "pkgconfig(libffi)": "libffi",
5779 + "pkgconfig(expat)": "expat",
5780 + "pkgconfig(libsystemd)": "systemd",
5781 + "pkgconfig(dbus-1)": "dbus",
5782 + "pkgconfig(mount)": "util-linux",
5783 + "pkgconfig(blkid)": "util-linux",
5784 + "pkgconfig(libcap)": "libcap",
5785 + "pkgconfig(liblzma)": "xz",
5786 + "pkgconfig(libzstd)": "zstd",
5787 + "pkgconfig(bzip2)": "bzip2",
5788 + "pkgconfig(libcurl)": "curl",
5789 + "pkgconfig(openssl)": "openssl",
5790 + "pkgconfig(libpcre2-8)": "pcre2",
5791 + "pkgconfig(libxml-2.0)": "libxml2",
5792 + "pkgconfig(libxslt)": "libxslt",
5793 + "pkgconfig(freetype2)": "freetype",
5794 + "pkgconfig(fontconfig)": "fontconfig",
5795 + "pkgconfig(harfbuzz)": "harfbuzz",
5796 + "pkgconfig(cairo)": "cairo",
5797 + "pkgconfig(pango)": "pango",
5798 + "pkgconfig(xt)": "xorg-libxt",
5799 + "pkgconfig(xmu)": "xorg-libxmu",
5800 + "pkgconfig(ice)": "xorg-libice",
5801 + "pkgconfig(sm)": "xorg-libsm",
5802 + "pkgconfig(x11)": "xorg-libx11",
5803 + "pkgconfig(xext)": "xorg-libxext",
5804 + "pkgconfig(xrandr)": "xorg-libxrandr",
5805 + "pkgconfig(xfixes)": "xorg-libxfixes",
5806 + "pkgconfig(xcursor)": "xorg-libxcursor",
5807 + "pkgconfig(xinerama)": "xorg-libxinerama",
5808 + "pkgconfig(xrender)": "xorg-libxrender",
5809 + "pkgconfig(xau)": "xorg-libxau",
5810 + "pkgconfig(xcb)": "xorg-libxcb",
5811 + "pkgconfig(xdamage)": "xorg-libxdamage",
5812 + "pkgconfig(xcomposite)": "xorg-libxcomposite",
5813 + "pkgconfig(xft)": "xorg-libxft",
5814 + "pkgconfig(xss)": "xorg-libxss",
5815 + "pkgconfig(libsoup-3.0)": "libsoup3",
5816 + "pkgconfig(libsoup-2.4)": "libsoup2",
5817 + "pkgconfig(gdk-pixbuf-2.0)": "gdk-pixbuf2",
5818 + "pkgconfig(libpng)": "libpng",
5819 + "pkgconfig(libjpeg)": "libjpeg-turbo",
5820 + "pkgconfig(libtiff-4)": "libtiff",
5821 + "pkgconfig(ffi)": "libffi",
5822 + # ── system / baza ──
5823 + "pkgconfig(libcrypto)": "openssl",
5824 + "pkgconfig(libssl)": "openssl",
5825 + "pkgconfig(libudev)": "systemd",
5826 + "pkgconfig(libmount)": "util-linux",
5827 + "pkgconfig(libblkid)": "util-linux",
5828 + "pkgconfig(uuid)": "util-linux",
5829 + "pkgconfig(libexpat)": "expat",
5830 + "pkgconfig(libpcre)": "pcre",
5831 + "pkgconfig(ncursesw)": "ncurses",
5832 + "pkgconfig(tinfo)": "ncurses",
5833 + "pkgconfig(panel)": "ncurses",
5834 + "pkgconfig(readline)": "readline",
5835 + "pkgconfig(libseccomp)": "libseccomp",
5836 + "pkgconfig(pam)": "linux-pam",
5837 + "pkgconfig(libxcrypt)": "libxcrypt",
5838 + "pkgconfig(libcrypt)": "libxcrypt",
5839 + "pkgconfig(libnsl)": "libnsl",
5840 + "pkgconfig(liblz4)": "lz4",
5841 + "pkgconfig(libevent)": "libevent",
5842 + "pkgconfig(libarchive)": "libarchive",
5843 + "pkgconfig(sqlite3)": "sqlite",
5844 + "pkgconfig(libpq)": "postgresql",
5845 + "pkgconfig(mysqlclient)": "mariadb",
5846 + "pkgconfig(json-c)": "json-c",
5847 + "pkgconfig(json-glib-1.0)": "json-glib",
5848 + "pkgconfig(libunistring)": "libunistring",
5849 + "pkgconfig(libidn2)": "libidn2",
5850 + "pkgconfig(libpsl)": "libpsl",
5851 + "pkgconfig(icu-uc)": "icu",
5852 + "pkgconfig(icu-i18n)": "icu",
5853 + "pkgconfig(icu-io)": "icu",
5854 + "pkgconfig(gnutls)": "gnutls",
5855 + "pkgconfig(nettle)": "nettle",
5856 + "pkgconfig(hogweed)": "nettle",
5857 + "pkgconfig(libgcrypt)": "libgcrypt",
5858 + "pkgconfig(libgpg-error)": "libgpg-error",
5859 + "pkgconfig(libassuan)": "libassuan",
5860 + "pkgconfig(libusb-1.0)": "libusb",
5861 + "pkgconfig(libusb)": "libusb",
5862 + "pkgconfig(libgudev-1.0)": "libgudev",
5863 + "pkgconfig(gudev-1.0)": "libgudev",
5864 + "pkgconfig(polkit-gobject-1)": "polkit",
5865 + "pkgconfig(polkit-agent-1)": "polkit",
5866 + "pkgconfig(libpciaccess)": "libpciaccess",
5867 + "pkgconfig(pixman-1)": "pixman",
5868 + "pkgconfig(libdrm)": "libdrm",
5869 + "pkgconfig(libva)": "libva",
5870 + "pkgconfig(libva-drm)": "libva",
5871 + "pkgconfig(libva-x11)": "libva",
5872 + "pkgconfig(libva-wayland)": "libva",
5873 + "pkgconfig(vdpau)": "libvdpau",
5874 + "pkgconfig(libvdpau)": "libvdpau",
5875 + "pkgconfig(libinput)": "libinput",
5876 + "pkgconfig(libevdev)": "libevdev",
5877 + "pkgconfig(mtdev)": "mtdev",
5878 + # ── grafika / GL / multimedia ──
5879 + "pkgconfig(gbm)": "mesa",
5880 + "pkgconfig(gl)": "libglvnd",
5881 + "pkgconfig(egl)": "libglvnd",
5882 + "pkgconfig(glesv2)": "libglvnd",
5883 + "pkgconfig(glx)": "libglvnd",
5884 + "pkgconfig(vulkan)": "vulkan-loader",
5885 + "pkgconfig(libxkbcommon)": "libxkbcommon",
5886 + "pkgconfig(xkbcommon)": "libxkbcommon",
5887 + "pkgconfig(xkbcommon-x11)": "libxkbcommon",
5888 + "pkgconfig(xcb)": "xorg-libxcb",
5889 + "pkgconfig(xcb-util)": "xcb-util",
5890 + "pkgconfig(xcb-keysyms)": "xcb-util-keysyms",
5891 + "pkgconfig(xcb-icccm)": "xcb-util-wm",
5892 + "pkgconfig(xcb-cursor)": "xcb-util-cursor",
5893 + "pkgconfig(xcb-renderutil)": "xcb-util-renderutil",
5894 + "pkgconfig(xcb-image)": "xcb-util-image",
5895 + "pkgconfig(xcb-errors)": "xcb-util-errors",
5896 + "pkgconfig(wayland-client)": "wayland",
5897 + "pkgconfig(wayland-server)": "wayland",
5898 + "pkgconfig(wayland-cursor)": "wayland",
5899 + "pkgconfig(wayland-egl)": "wayland",
5900 + "pkgconfig(wayland-protocols)": "wayland-protocols",
5901 + "pkgconfig(gstreamer-1.0)": "gstreamer",
5902 + "pkgconfig(gstreamer-base-1.0)": "gstreamer",
5903 + "pkgconfig(gstreamer-check-1.0)": "gstreamer",
5904 + "pkgconfig(gstreamer-controller-1.0)": "gstreamer",
5905 + "pkgconfig(gstreamer-app-1.0)": "gst-plugins-base",
5906 + "pkgconfig(gstreamer-video-1.0)": "gst-plugins-base",
5907 + "pkgconfig(gstreamer-audio-1.0)": "gst-plugins-base",
5908 + "pkgconfig(gstreamer-pbutils-1.0)": "gst-plugins-base",
5909 + "pkgconfig(gstreamer-fft-1.0)": "gst-plugins-base",
5910 + "pkgconfig(gstreamer-riff-1.0)": "gst-plugins-base",
5911 + "pkgconfig(gstreamer-rtp-1.0)": "gst-plugins-base",
5912 + "pkgconfig(gstreamer-rtsp-1.0)": "gst-plugins-base",
5913 + "pkgconfig(gstreamer-sdp-1.0)": "gst-plugins-base",
5914 + "pkgconfig(gstreamer-net-1.0)": "gst-plugins-base",
5915 + "pkgconfig(gstreamer-gl-1.0)": "gst-plugins-base",
5916 + "pkgconfig(libpulse)": "libpulse",
5917 + "pkgconfig(libpulse-simple)": "libpulse",
5918 + "pkgconfig(libpulse-mainloop-glib)": "libpulse",
5919 + "pkgconfig(alsa)": "alsa-lib",
5920 + "pkgconfig(jack)": "jack2",
5921 + "pkgconfig(libsamplerate)": "libsamplerate",
5922 + "pkgconfig(sndfile)": "libsndfile",
5923 + "pkgconfig(libavcodec)": "ffmpeg",
5924 + "pkgconfig(libavformat)": "ffmpeg",
5925 + "pkgconfig(libavutil)": "ffmpeg",
5926 + "pkgconfig(libavfilter)": "ffmpeg",
5927 + "pkgconfig(libswscale)": "ffmpeg",
5928 + "pkgconfig(libswresample)": "ffmpeg",
5929 + "pkgconfig(libpostproc)": "ffmpeg",
5930 + "pkgconfig(SDL2)": "sdl2",
5931 + "pkgconfig(SDL)": "sdl",
5932 + "pkgconfig(SDL2_image)": "sdl2-image",
5933 + "pkgconfig(SDL2_ttf)": "sdl2-ttf",
5934 + "pkgconfig(SDL2_mixer)": "sdl2-mixer",
5935 + "pkgconfig(SDL2_net)": "sdl2-net",
5936 + "pkgconfig(libpng16)": "libpng",
5937 + "pkgconfig(libwebp)": "libwebp",
5938 + "pkgconfig(libwebpmux)": "libwebp",
5939 + "pkgconfig(libwebpdemux)": "libwebp",
5940 + "pkgconfig(libopenjp2)": "openjpeg2",
5941 + "pkgconfig(lcms2)": "lcms2",
5942 + "pkgconfig(libheif)": "libheif",
5943 + "pkgconfig(libde265)": "libde265",
5944 + "pkgconfig(x264)": "x264",
5945 + "pkgconfig(x265)": "x265",
5946 + # ── glib / gio ──
5947 + "pkgconfig(gio-unix-2.0)": "glib",
5948 + "pkgconfig(gmodule-2.0)": "glib",
5949 + "pkgconfig(gthread-2.0)": "glib",
5950 + "pkgconfig(girepository-2.0)": "gobject-introspection",
5951 + "pkgconfig(girepository-1.0)": "gobject-introspection",
5952 + "pkgconfig(libglib-2.0)": "glib",
5953 + "pkgconfig(libgobject-2.0)": "glib",
5954 +}
5955 +
5956 +# Ostrzeżenia o wielu dostawcach tej samej wirtualnej nazwy – raz na proces.
5957 +_PROVIDES_WARNED = set()
5958 +# Cache indeksu provides dla danego obiektu repo: (repo_obj, {virtual: [pkg,...]}).
5959 +# Trzymamy referencję do repo, by uniknąć pomyłki przy ponownym użyciu id().
5960 +_provides_cache = (None, {})
5961 +
5962 +def _provides_index(repo: dict) -> dict:
5963 + """Buduje (i cache’uje) mapę wirtualna nazwa → lista dostawców w repo.
5964 +
5965 + Pozwala wybrać dostawcę DETERMINISTYCZNIE (posortowanego) zamiast zależeć
5966 + od kolejności wstawiania w repo.json, oraz ostrzec o konflikcie provides."""
5967 + global _provides_cache
5968 + cached_repo, idx = _provides_cache
5969 + if cached_repo is repo:
5970 + return idx
5971 + idx = {}
5972 + for _pn, _p in repo.items():
5973 + for _prov in (getattr(_p, "provides", None) or []):
5974 + idx.setdefault(_prov, []).append(_pn)
5975 + for _prov, _pns in idx.items():
5976 + if len(_pns) > 1 and _prov not in _PROVIDES_WARNED:
5977 + _PROVIDES_WARNED.add(_prov)
5978 + _sorted = sorted(_pns)
5979 + print(f" ⚠ {_('provides_conflict', name=_prov, providers=', '.join(_sorted), chosen=_sorted[0])}",
5980 + file=sys.stderr)
5981 + _provides_cache = (repo, idx)
5982 + return idx
5983 +
5984 +
5985 +def _resolve_provides(name: str, repo: dict, installed: Optional[dict] = None) -> str:
5986 + """Rozwija wirtualną nazwę pakietu do rzeczywistej nazwy.
5987 +
5988 + Kolejność: repo → PROVIDES_MAP → wzorce → provides z repo.json →
5989 + provides ZAINSTALOWANYCH pakietów (lokalnie zbudowane poza repo też
5990 + dostarczają wirtualne zależności) → fallback pkgconfig (czyszczenie nazwy).
5991 + """
5992 + if name in repo:
5993 + return name
5994 + if name in PROVIDES_MAP:
5995 + real = PROVIDES_MAP[name]
5996 + if real in repo:
5997 + return real
5998 + # Wzorce: moduły Qt (Qt5Core/Qt6Widgets) i GStreamer (gstreamer-video-1.0)
5999 + if name.startswith("pkgconfig(Qt5"):
6000 + real = "qt5"
6001 + if real in repo:
6002 + return real
6003 + if name.startswith("pkgconfig(Qt6"):
6004 + real = "qt6"
6005 + if real in repo:
6006 + return real
6007 + if name.startswith("pkgconfig(gstreamer-") and name.endswith("-1.0)"):
6008 + real = "gstreamer"
6009 + if real in repo:
6010 + return real
6011 + if name.startswith("pkgconfig(gst-"):
6012 + real = "gst-plugins-base"
6013 + if real in repo:
6014 + return real
6015 + # Dynamiczne provides z repo.json (sekcja provides: w PAGBUILD.yaml)
6016 + # Determinizm: przy wielu dostawcach wybieramy posortowanego pierwszego
6017 + # (i ostrzegamy raz), zamiast zależeć od kolejności w repo.json.
6018 + _idx = _provides_index(repo)
6019 + if name in _idx:
6020 + return min(_idx[name])
6021 + # provides ZAINSTALOWANYCH pakietów – lokalnie zbudowane (pagbuild, poza
6022 + # repo) też dostarczają wirtualne zależności i muszą być rozpoznawane.
6023 + if installed:
6024 + _inst_cands = [pn for pn, meta in installed.items()
6025 + if isinstance(meta, dict) and name in (meta.get("provides") or [])]
6026 + if _inst_cands:
6027 + return min(_inst_cands)
6028 + clean = name
6029 + if name.startswith("pkgconfig(") and ")" in name:
6030 + clean = name.split("(", 1)[1].rstrip(")")
6031 + elif name.startswith("pkgconfig32(") and ")" in name:
6032 + clean = name.split("(", 1)[1].rstrip(")")
6033 + if clean != name and clean in repo:
6034 + return clean
6035 + return name
6036 +
6037 +
6038 +def cmd_why(pkg_name: str):
6039 + """Pokazuje dlaczego pakiet jest zainstalowany."""
6040 + installed = load_json(INSTALLED_DB)
6041 + world = load_world()
6042 + if pkg_name not in installed:
6043 + print(f" {pkg_name}: {_('why_not_installed')}"); return 1
6044 + if pkg_name in world:
6045 + print(f" {pkg_name}-{installed[pkg_name]['version']}: {_('why_explicit')}")
6046 + return 0
6047 + parents = set()
6048 + for w in world:
6049 + _find_dep_path(w, pkg_name, installed, set(), [], parents)
6050 + if parents:
6051 + for pp in sorted(parents):
6052 + print(f" {pkg_name}: {_('why_dependency')} {' → '.join(pp)}")
6053 + else:
6054 + print(f" {pkg_name}: {_('why_dependency')} (unknown/orphan)")
6055 + return 0
6056 +
6057 +
6058 +def _find_dep_path(cur, target, installed, visited, path, results):
6059 + if cur in visited: return
6060 + visited.add(cur); path.append(cur)
6061 + if cur == target:
6062 + results.add(tuple(path))
6063 + else:
6064 + for dep in installed.get(cur, {}).get("dependencies", []):
6065 + _find_dep_path(dep, target, installed, visited, path, results)
6066 + path.pop(); visited.discard(cur)
6067 +
6068 +
6069 +def cmd_rdepends(pkg_name: str):
6070 + """Pokazuje które pakiety zależą od danego pakietu (reverse dependencies).
6071 +
6072 + Odwrotność `pag why`: dla każdego zainstalowanego pakietu sprawdza, czy
6073 + któraś z jego zależności (także wirtualna, przez provides) wskazuje na
6074 + pkg_name. Przydatne przed `pag remove` – pokazuje, co przestanie działać.
6075 + """
6076 + installed = load_json(INSTALLED_DB)
6077 + if pkg_name not in installed:
6078 + print(f" {pkg_name}: {_('why_not_installed')}"); return 1
6079 + world = load_world()
6080 + # Nazwy, które zależą od pkg_name – sama nazwa plus jej wirtualne provides.
6081 + provided = {pkg_name} | set(installed[pkg_name].get("provides") or [])
6082 + rev = []
6083 + for name, meta in installed.items():
6084 + if name == pkg_name:
6085 + continue
6086 + for dep in (meta.get("dependencies") or []):
6087 + if dep in provided or _resolve_provides(dep, {}, installed) == pkg_name:
6088 + rev.append(name); break
6089 + if not rev:
6090 + print(f" {pkg_name}: {_('rdepends_none')}")
6091 + return 0
6092 + print(f"🔗 {_('rdepends_title', pkg_name, len(rev))}")
6093 + for n in sorted(rev):
6094 + kind = _("why_explicit") if n in world else _("why_dependency")
6095 + print(f" {n}-{installed[n].get('version', '?')} ({kind})")
6096 + return 0
6097 +
6098 +
6099 +def cmd_autoremove():
6100 + """Automatycznie usuwa osierocone zależności bez pytania."""
6101 + installed = load_json(INSTALLED_DB)
6102 + world = load_world()
6103 + orphans = _find_orphans(installed, world)
6104 + if not orphans: print(f"✅ {_('autoremove_none')}"); return 0
6105 + print(f"🗑 {_('orphans_found', len(orphans), ', '.join(sorted(orphans)[:10]))}")
6106 + return cmd_remove(list(orphans))
6107 +
6108 +
6109 +def cmd_download(package_names):
6110 + """Pobiera pakiety do cache bez instalowania."""
6111 + ensure_dirs()
6112 + repo = fetch_all_packages()
6113 + if not repo: print(f"❌ {_('no_index')}"); return 1
6114 + total_size = 0; downloaded = []
6115 + for name in package_names:
6116 + pkg = repo.get(name)
6117 + if not pkg:
6118 + print(f" ❌ {name}: {_('not_found')}"); continue
6119 + print(f" ↓ {name}-{pkg.version} ...", end=" ", flush=True)
6120 + path = _download_pkg(pkg)
6121 + if path:
6122 + total_size += os.path.getsize(path)
6123 + downloaded.append(name)
6124 + print(_c("green", "✓"))
6125 + else:
6126 + print(_c("red", "✗"))
6127 + if downloaded:
6128 + print(f"\n✅ {_('downloaded', len(downloaded), total_size/1048576)}")
6129 + return 0 if len(downloaded) == len(package_names) else 1
6130 +
6131 +
6132 +def cmd_stats():
6133 + """Wyświetla statystyki PAG."""
6134 + installed = load_json(INSTALLED_DB)
6135 + history = load_json(HISTORY_FILE) if os.path.exists(HISTORY_FILE) else []
6136 + total_size = sum(i.get("size_bytes", 0) for i in installed.values())
6137 + total_files = _db_count_files()
6138 + cache_size = sum(
6139 + os.path.getsize(os.path.join(PAG_CACHE, f))
6140 + for f in os.listdir(PAG_CACHE)
6141 + if os.path.isfile(os.path.join(PAG_CACHE, f))
6142 + ) if os.path.isdir(PAG_CACHE) else 0
6143 + last_update = _("never")
6144 + for e in reversed(history):
6145 + if e.get("action") in ("install", "upgrade") and e.get("success"):
6146 + last_update = e.get("timestamp", "?")[:19]; break
6147 + print(f"\n {_c('bold', _('stats_title'))}")
6148 + print(f" {'─' * 40}")
6149 + print(f" {_('stats_packages'):<30} {len(installed)}")
6150 + print(f" {_('stats_files'):<30} {total_files}")
6151 + print(f" {_('stats_size'):<30} {total_size/1048576:.1f} MB")
6152 + print(f" {_('stats_cache'):<30} {cache_size/1048576:.1f} MB")
6153 + print(f" {_('stats_history'):<30} {len(history)}")
6154 + print(f" {_('stats_last_update'):<30} {last_update}")
6155 + _bs = _base_summary(repo={}) # bez sieci – tylko stan zarządzania bazą
6156 + if _bs["total"]:
6157 + _bt = f"{_bs['tracked']}/{_bs['total']}"
6158 + if _bs["tracked"] < _bs["total"]:
6159 + _bt += " (sudo pag base adopt)"
6160 + print(f" {_('stats_base'):<30} {_bt}")
6161 + by_size = sorted(installed.items(), key=lambda x: x[1].get("size_bytes", 0), reverse=True)[:5]
6162 + if by_size:
6163 + print(f"\n {_c('dim', _('stats_top'))}")
6164 + for n, i in by_size:
6165 + print(f" {n}-{i['version']} {i.get('size_bytes',0)/1048576:.1f} MB")
6166 + return 0
6167 +
6168 +
6169 +def cmd_repo_add(url, name=None):
6170 + if not url.startswith("https://") and not os.environ.get("PAG_INSECURE"):
6171 + print(f" {_('sec_https')}"); return 1
6172 + ensure_dirs()
6173 + url = url.rstrip("/")
6174 + repos = get_repos()
6175 + if url in repos: print(f"⚠ {_('repo_exists', url)}"); return
6176 + if name:
6177 + # Drop-in: /etc/pag/repos/<nazwa>.conf (jak `echo url > .../stable.conf`)
6178 + os.makedirs(REPOS_DIR, exist_ok=True)
6179 + target = os.path.join(REPOS_DIR, name.rstrip("/").replace("/", "_") + ".conf")
6180 + with open(target, "w") as f: f.write(f"{url}\n")
6181 + print(f"✅ {_('repo_added', url)} → {target}")
6182 + return
6183 + with open(REPOS_CONF, "a") as f: f.write(f"{url}\n")
6184 + print(f"✅ {_('repo_added', url)}")
6185 +
6186 +def cmd_repo_list():
6187 + for i, url in enumerate(get_repos(), 1): print(f" {i}. {url}")
6188 +
6189 +FLATPAK_REMOTE_URL = "https://flathub.org/repo/flathub.flatpakrepo"
6190 +
6191 +def _check_flatpak(quiet: bool = False):
6192 + if not shutil.which("flatpak"):
6193 + if not quiet:
6194 + print(f"❌ {_('flatpak_missing')}")
6195 + return False
6196 + r = subprocess.run(["flatpak", "remotes"], capture_output=True, text=True)
6197 + if "flathub" not in r.stdout:
6198 + print(f"⚠ {_('flatpak_adding')}")
6199 + # Jako root dodajemy remote systemowy; bez roota – w instalacji użytkownika,
6200 + # żeby remote i miejsce instalacji były spójne (patrz _flatpak_do_install).
6201 + add = ["flatpak", "remote-add", "--if-not-exists"]
6202 + if os.geteuid() != 0:
6203 + add.append("--user")
6204 + subprocess.run(add + ["flathub", FLATPAK_REMOTE_URL], check=False)
6205 + return True
6206 +
6207 +def _spinner(msg: str):
6208 + """Prosty spinner „myślenia” w osobnym wątku. Zwraca funkcję stop()."""
6209 + stop = threading.Event()
6210 + def _spin():
6211 + for c in itertools.cycle("|/-\\"):
6212 + if stop.is_set():
6213 + break
6214 + sys.stdout.write(f"\r {msg} {c}")
6215 + sys.stdout.flush()
6216 + time.sleep(0.1)
6217 + t = threading.Thread(target=_spin, daemon=True)
6218 + t.start()
6219 + def _stop():
6220 + stop.set()
6221 + t.join(timeout=0.3)
6222 + sys.stdout.write("\r" + " " * (len(msg) + 4) + "\r")
6223 + sys.stdout.flush()
6224 + return _stop
6225 +
6226 +
6227 +def _flatpak_search_raw(query: str) -> List[dict]:
6228 + """Szuka we Flathub i zwraca listę wyników jako słowniki."""
6229 + if not _check_flatpak():
6230 + return []
6231 + stop = _spinner(_("flatpak_searching_any"))
6232 + try:
6233 + try:
6234 + r = subprocess.run(
6235 + ["flatpak", "search", "--columns=name,description,application,version,branch,remotes", query],
6236 + capture_output=True, text=True, timeout=120
6237 + )
6238 + finally:
6239 + stop()
6240 + if r.returncode != 0 and "No matches found" not in r.stdout and not r.stdout.strip():
6241 + print(f" ⚠ flatpak search: {r.stderr.strip()[:150]}")
6242 + results = []
6243 + for line in r.stdout.strip().split("\n"):
6244 + parts = line.split("\t")
6245 + if len(parts) >= 3:
6246 + results.append({
6247 + "name": parts[0].strip(),
6248 + "description": parts[1].strip() if len(parts) > 1 else "",
6249 + "app_id": parts[2].strip() if len(parts) > 2 else "",
6250 + "version": parts[3].strip() if len(parts) > 3 else "",
6251 + "branch": parts[4].strip() if len(parts) > 4 else "stable",
6252 + "origin": parts[5].strip() if len(parts) > 5 else "flathub",
6253 + })
6254 + return results
6255 + except Exception as e:
6256 + print(_(' ⚠ Search error: {arg1}', arg1=(e)), file=sys.stderr)
6257 + return []
6258 +
6259 +def _flatpak_find_best(query: str) -> Optional[dict]:
6260 + """
6261 + Szuka we Flathub i próbuje znaleźć najlepsze dopasowanie.
6262 + - Jeśli query dokładnie pasuje do app_id → zwraca od razu
6263 + - Jeśli query pasuje do nazwy → zwraca pierwsze
6264 + - Jeśli wiele wyników → wyświetla listę i pyta użytkownika
6265 + - Jeśli brak → zwraca None
6266 + """
6267 + results = _flatpak_search_raw(query)
6268 + if not results:
6269 + return None
6270 +
6271 + # Dokładne dopasowanie app_id
6272 + exact = [r for r in results if r["app_id"].lower() == query.lower()]
6273 + if exact:
6274 + return exact[0]
6275 +
6276 + # Dokładne dopasowanie nazwy
6277 + exact_name = [r for r in results if r["name"].lower() == query.lower()]
6278 + if exact_name:
6279 + return exact_name[0]
6280 +
6281 + # Jednoznaczne dopasowanie (tylko 1 wynik)
6282 + if len(results) == 1:
6283 + return results[0]
6284 +
6285 + # Wiele wyników – pokaż użytkownikowi
6286 + print(f"\n {_('flatpak_found', len(results))}")
6287 + for i, r in enumerate(results):
6288 + print(f" {i+1}. {_c('bold', r['name'])} ({r['app_id']})")
6289 + if r["version"]:
6290 + print(f" {_('flatpak_info_version')}: {r['version']}")
6291 + if r["description"]:
6292 + desc = r["description"][:80] + ("..." if len(r["description"]) > 80 else "")
6293 + print(f" {desc}")
6294 +
6295 + try:
6296 + choice = input(_('\n Choose a number (1-{arg1}) or press Enter to cancel:', arg1=(len(results)))).strip()
6297 + if not choice:
6298 + return None
6299 + idx = int(choice) - 1
6300 + if 0 <= idx < len(results):
6301 + return results[idx]
6302 + except (EOFError, ValueError, IndexError):
6303 + pass
6304 + return None
6305 +
6306 +def _flatpak_get_installed_info(app_id: str) -> Optional[dict]:
6307 + """Zwraca info o zainstalowanym flatpaku lub None."""
6308 + try:
6309 + r = subprocess.run(
6310 + ["flatpak", "info", "--columns=name,version,branch,origin,installed-size,description", app_id],
6311 + capture_output=True, text=True, timeout=10
6312 + )
6313 + if r.returncode != 0:
6314 + return None
6315 + parts = r.stdout.strip().split("\t")
6316 + if len(parts) < 3:
6317 + return None
6318 + return {
6319 + "name": parts[0].strip(),
6320 + "version": parts[1].strip() if len(parts) > 1 else "",
6321 + "branch": parts[2].strip() if len(parts) > 2 else "",
6322 + "origin": parts[3].strip() if len(parts) > 3 else "",
6323 + "size": parts[4].strip() if len(parts) > 4 else "",
6324 + "description": parts[5].strip() if len(parts) > 5 else "",
6325 + }
6326 + except Exception:
6327 + return None
6328 +
6329 +def _flatpak_is_installed(app_id: str) -> bool:
6330 + """Sprawdza czy flatpak o danym ID jest zainstalowany."""
6331 + try:
6332 + r = subprocess.run(
6333 + ["flatpak", "info", app_id],
6334 + capture_output=True, text=True, timeout=10
6335 + )
6336 + return r.returncode == 0
6337 + except Exception:
6338 + return False
6339 +
6340 +# =============================================================================
6341 +# FLATPAK – KOMENDY GŁÓWNE (zunifikowany interfejs)
6342 +# =============================================================================
6343 +# pag flatpak <query> → szuka i proponuje instalację (jeśli nie zainstalowany)
6344 +# pag flatpak search <query> → tylko szuka
6345 +# pag flatpak install <query> → instaluje
6346 +# pag flatpak remove <id> → usuwa
6347 +# pag flatpak list → lista zainstalowanych
6348 +# pag flatpak update → aktualizuje wszystkie
6349 +# pag flatpak info <id> → szczegóły flatpaka
6350 +
6351 +def cmd_flatpak(args: list):
6352 + """
6353 + Główna komenda flatpak – inteligentnie rozpoznaje intencję:
6354 + pag flatpak firefox → szuka i instaluje (jeśli nieznaleziony → szuka)
6355 + pag flatpak search firefox → tylko wyszukiwanie
6356 + pag flatpak install ... → bezpośrednia instalacja
6357 + pag flatpak remove ... → odinstalowanie
6358 + pag flatpak list → lista
6359 + pag flatpak update → aktualizacja
6360 + pag flatpak info ... → szczegóły
6361 + """
6362 + if not _check_flatpak():
6363 + return 1
6364 +
6365 + if not args:
6366 + # Bez argumentów – domyślnie lista
6367 + return cmd_flatpak_list()
6368 +
6369 + subcmd = args[0].lower()
6370 + rest = args[1:]
6371 +
6372 + # ── Podkomendy jawne ────────────────────────────────────────────────
6373 + if subcmd == "search":
6374 + if not rest:
6375 + print(_("flatpak_usage")); return 1
6376 + return cmd_flatpak_search(" ".join(rest))
6377 +
6378 + elif subcmd == "install":
6379 + if not rest:
6380 + print(_("flatpak_usage")); return 1
6381 + return _flatpak_smart_install(rest)
6382 +
6383 + elif subcmd == "remove" or subcmd == "uninstall":
6384 + if not rest:
6385 + print(_("flatpak_usage")); return 1
6386 + return _flatpak_smart_remove(rest)
6387 +
6388 + elif subcmd == "list":
6389 + return cmd_flatpak_list()
6390 +
6391 + elif subcmd == "update":
6392 + return cmd_flatpak_update()
6393 +
6394 + elif subcmd == "info":
6395 + if not rest:
6396 + print(_("flatpak_usage")); return 1
6397 + return cmd_flatpak_info(rest[0])
6398 +
6399 + else:
6400 + # ── Inteligentne wykrywanie: pag flatpak <nazwa> ────────────────
6401 + # Sprawdź czy to zainstalowany flatpak → pokaż info
6402 + # Jeśli nie → szukaj i zaproponuj instalację
6403 + query = " ".join(args)
6404 +
6405 + # Najpierw sprawdź czy już zainstalowany
6406 + if _flatpak_is_installed(query):
6407 + print(_(" 📦 {arg1} – already installed (use 'pag flatpak info {arg2}' for details)", arg1=(_c('green', query)), arg2=(query)))
6408 + return cmd_flatpak_info(query)
6409 +
6410 + # Szukaj we Flathub
6411 + print(f" {_('flatpak_searching', query)}")
6412 + best = _flatpak_find_best(query)
6413 + if not best:
6414 + print(f" ❌ '{query}' – {_('flatpak_not_found')}")
6415 + return 1
6416 +
6417 + print(f"\n {_c('cyan', best['name'])} ({best['app_id']})")
6418 + if best["version"]:
6419 + print(f" {_('flatpak_info_version')}: {best['version']}")
6420 + if best["description"]:
6421 + print(f" {best['description']}")
6422 +
6423 + try:
6424 + ans = input(f"\n {_('flatpak_install_prompt', best['name'])}").strip().lower()
6425 + except (EOFError, KeyboardInterrupt):
6426 + print(f"\n ⚠ {_('no_tty')}")
6427 + return 0
6428 + if ans and ans not in ("t", "y"):
6429 + print(_("cancelled"))
6430 + return 0
6431 +
6432 + return _flatpak_do_install(best["app_id"])
6433 +
6434 +def _flatpak_smart_install(names: list) -> int:
6435 + """Instaluje flatpaki – obsługuje nazwy częściowe (wyszukuje przed instalacją)."""
6436 + failed = 0
6437 + for name in names:
6438 + if "." in name and "/" not in name:
6439 + # Wygląda na pełne app_id (np. org.mozilla.firefox)
6440 + app_id = name
6441 + else:
6442 + # Szukaj najlepszego dopasowania
6443 + best = _flatpak_find_best(name)
6444 + if not best:
6445 + print(f" ❌ '{name}' – {_('flatpak_not_found')}")
6446 + failed += 1
6447 + continue
6448 + app_id = best["app_id"]
6449 + print(f" → {best['name']} ({app_id})")
6450 +
6451 + if _flatpak_do_install(app_id) != 0:
6452 + failed += 1
6453 + return 1 if failed else 0
6454 +
6455 +def _flatpak_export_dirs() -> List[str]:
6456 + """Katalogi eksportów Flatpaka (system + użytkownika) obecne na dysku.
6457 +
6458 + Instalacja użytkownika roota (/root/.local/share/flatpak) jest świadomie
6459 + POMIJANA – to wewnętrzny artefakt roota, którego sesja użytkownika nigdy
6460 + nie zobaczy (patrz _flatpak_do_install)."""
6461 + dirs = ["/var/lib/flatpak/exports"]
6462 + home = os.path.expanduser("~")
6463 + if home and home not in ("/root", "/"):
6464 + dirs.append(os.path.join(home, ".local", "share", "flatpak", "exports"))
6465 + return [d for d in dirs if os.path.isdir(d)]
6466 +
6467 +
6468 +def _flatpak_refresh_caches() -> None:
6469 + """Odświeża cache pulpitu i ikon po zmianie w Flatpaku (best-effort).
6470 +
6471 + Flatpak robi to sam, ale tylko gdy `update-desktop-database` jest w PATH.
6472 + Bez tego nowo zainstalowana aplikacja bywa nieobecna w menu."""
6473 + for exports in _flatpak_export_dirs():
6474 + apps = os.path.join(exports, "share", "applications")
6475 + if os.path.isdir(apps) and shutil.which("update-desktop-database"):
6476 + subprocess.run(["update-desktop-database", apps],
6477 + capture_output=True, check=False, timeout=60)
6478 + icons = os.path.join(exports, "share", "icons", "hicolor")
6479 + if os.path.isdir(icons) and shutil.which("gtk-update-icon-cache"):
6480 + subprocess.run(["gtk-update-icon-cache", "-q", "-t", "-f", icons],
6481 + capture_output=True, check=False, timeout=120)
6482 +
6483 +
6484 +def _flatpak_session_sees_exports() -> bool:
6485 + """Czy bieżąca sesja ma eksporty Flatpaka w XDG_DATA_DIRS."""
6486 + raw = os.environ.get("XDG_DATA_DIRS", "")
6487 + dirs = {d for d in raw.split(":") if d} or {"/usr/local/share", "/usr/share"}
6488 + return any(os.path.join(e, "share") in dirs for e in _flatpak_export_dirs())
6489 +
6490 +
6491 +def _flatpak_warn_if_invisible() -> None:
6492 + """Ostrzega, gdy sesja nie widzi eksportów – inaczej wygląda to jak
6493 + „zainstalowało się, ale nie ma go w menu / na PC”."""
6494 + if not _flatpak_session_sees_exports():
6495 + print(f" ⚠ {_('flatpak_menu_hint')}")
6496 + print(f" {_('flatpak_menu_fix')}")
6497 +
6498 +
6499 +def _flatpak_do_install(app_id: str) -> int:
6500 + """Wykonuje właściwą instalację flatpaka.
6501 +
6502 + Jako root wymuszamy instalację SYSTEMOWĄ (--system). Bez tego `flatpak`
6503 + uruchomiony jako root potrafi zainstalować aplikację w instalacji
6504 + użytkownika roota (/root/.local/share/flatpak) – widocznej dla roota, ale
6505 + nie dla zalogowanego użytkownika. To dokładnie efekt „instaluje, ale nie
6506 + mam tego na PC”. Bez roota próbujemy instalacji systemowej (polkit),
6507 + a w razie niepowodzenia cofamy się do instalacji użytkownika (--user).
6508 +
6509 + Zakres (scope) ma znaczenie: instalacja SYSTEMOWA (--system) jest widoczna
6510 + dla wszystkich użytkowników, a --user tylko dla bieżącego (dla roota:
6511 + /root/.local/... → niewidoczna dla sesji). `flatpak list` bez flag pokazuje
6512 + oba zakresy, więc systemowa instalacja roota jest widoczna też dla
6513 + zwykłego użytkownika."""
6514 + print(f" {_('flatpak_installing', app_id)}")
6515 + if os.geteuid() == 0:
6516 + result = subprocess.run(
6517 + ["flatpak", "install", "-y", "--system", "flathub", app_id],
6518 + check=False, timeout=600)
6519 + else:
6520 + result = subprocess.run(
6521 + ["flatpak", "install", "-y", "flathub", app_id],
6522 + check=False, timeout=600)
6523 + if result.returncode != 0:
6524 + # Flathub tylko dla użytkownika / brak agenta polkit – instalacja
6525 + # lokalna użytkownika jest lepsza niż twardy błąd.
6526 + subprocess.run(
6527 + ["flatpak", "remote-add", "--if-not-exists", "--user",
6528 + "flathub", FLATPAK_REMOTE_URL], check=False, timeout=60)
6529 + result = subprocess.run(
6530 + ["flatpak", "install", "-y", "--user", "flathub", app_id],
6531 + check=False, timeout=600)
6532 + if result.returncode != 0:
6533 + print(f" ❌ {_('download_fail')}: {app_id}")
6534 + return 1
6535 + _flatpak_refresh_caches()
6536 + print(f" ✅ {_('flatpak_installed', app_id)}")
6537 + _flatpak_warn_if_invisible()
6538 + return 0
6539 +
6540 +def _flatpak_smart_remove(names: list) -> int:
6541 + """Usuwa flatpaki – obsługuje nazwy częściowe."""
6542 + # Pobierz listę zainstalowanych
6543 + try:
6544 + r = subprocess.run(
6545 + ["flatpak", "list", "--columns=application,name"],
6546 + capture_output=True, text=True, timeout=10
6547 + )
6548 + installed = {}
6549 + for line in r.stdout.strip().split("\n"):
6550 + parts = line.split("\t")
6551 + if len(parts) >= 2:
6552 + installed[parts[0].strip()] = parts[1].strip()
6553 + except Exception:
6554 + installed = {}
6555 +
6556 + failed = 0
6557 + for name in names:
6558 + app_id = name
6559 +
6560 + # Jeśli nie podano pełnego ID – spróbuj dopasować
6561 + if name not in installed:
6562 + matches = {aid: aname for aid, aname in installed.items()
6563 + if name.lower() in aid.lower() or name.lower() in aname.lower()}
6564 + if len(matches) == 0:
6565 + print(f" ❌ '{name}' – {_('flatpak_not_installed', name)}")
6566 + failed += 1
6567 + continue
6568 + elif len(matches) == 1:
6569 + app_id = list(matches.keys())[0]
6570 + print(f" → {matches[app_id]} ({app_id})")
6571 + else:
6572 + print(_("\n Multiple matches for '{arg1}':", arg1=(name)))
6573 + for i, (aid, aname) in enumerate(sorted(matches.items()), 1):
6574 + print(f" {i}. {aname} ({aid})")
6575 + try:
6576 + choice = input(_('\n Choose a number (1-{arg1}) or press Enter:', arg1=(len(matches)))).strip()
6577 + if not choice:
6578 + failed += 1
6579 + continue
6580 + aid_list = sorted(matches.keys())
6581 + app_id = aid_list[int(choice) - 1]
6582 + except (EOFError, ValueError, IndexError):
6583 + failed += 1
6584 + continue
6585 +
6586 + print(f" 🗑 {app_id} ...", end=" ", flush=True)
6587 + result = subprocess.run(
6588 + ["flatpak", "uninstall", "-y", app_id],
6589 + capture_output=True, text=True, timeout=120
6590 + )
6591 + if result.returncode == 0:
6592 + print("✅")
6593 + print(f" {_('flatpak_removed', app_id)}")
6594 + else:
6595 + print("❌")
6596 + failed += 1
6597 + if not failed:
6598 + _flatpak_refresh_caches()
6599 + return 1 if failed else 0
6600 +
6601 +def cmd_flatpak_search(q: str):
6602 + """Wyszukuje we Flathub i wyświetla wyniki (z możliwością wyboru do instalacji)."""
6603 + if not _check_flatpak():
6604 + return 1
6605 + results = _flatpak_search_raw(q)
6606 + if not results:
6607 + print(f" ❌ '{q}' – {_('flatpak_not_found')}")
6608 + return 1
6609 + print(f"\n {_('flatpak_found', len(results))}")
6610 + shown = results[:30] # max 30 wyników
6611 + for i, r in enumerate(shown, 1):
6612 + installed = "📦 " if _flatpak_is_installed(r["app_id"]) else " "
6613 + print(f" {i:>2}. {installed}{_c('bold', r['name'])} ({r['app_id']})")
6614 + if r["version"]:
6615 + print(f" {_('flatpak_info_version')}: {r['version']} | {_('flatpak_info_branch')}: {r['branch']}")
6616 + if r["description"]:
6617 + desc = r["description"][:100] + ("..." if len(r["description"]) > 100 else "")
6618 + print(f" {_c('dim', desc)}")
6619 + if len(results) > 30:
6620 + print(_(' ... and {arg1} more. Refine your query.', arg1=(len(results) - 30)))
6621 +
6622 + # Interaktywny wybór – wpisz numer, aby zainstalować (Enter = anuluj)
6623 + try:
6624 + ans = input(_('\n Choose a number to install (1-{arg1}) or press Enter to cancel:', arg1=(len(shown)))).strip()
6625 + except (EOFError, KeyboardInterrupt):
6626 + return 0
6627 + if ans:
6628 + try:
6629 + idx = int(ans) - 1
6630 + if 0 <= idx < len(shown):
6631 + return _flatpak_do_install(shown[idx]["app_id"])
6632 + print(_("cancelled"))
6633 + except (ValueError, IndexError):
6634 + print(_("cancelled"))
6635 + return 0
6636 +
6637 +def cmd_flatpak_list():
6638 + """Wyświetla zainstalowane flatpaki."""
6639 + if not _check_flatpak():
6640 + return 1
6641 + r = subprocess.run(
6642 + ["flatpak", "list", "--columns=application,name,version,origin,installation,installed-size"],
6643 + capture_output=True, text=True, timeout=10
6644 + )
6645 + lines = [l for l in r.stdout.strip().split("\n") if l.strip()]
6646 + if not lines:
6647 + print(_(' (no installed flatpaks)'))
6648 + return 0
6649 + print(_('Installed flatpaks ({arg1}):', arg1=(len(lines))))
6650 + for line in lines:
6651 + parts = line.split("\t")
6652 + if len(parts) >= 3:
6653 + app_id, name, version = parts[0], parts[1], parts[2]
6654 + scope = parts[4] if len(parts) > 4 else ""
6655 + size = parts[5] if len(parts) > 5 else ""
6656 + size_str = f" ({size})" if size else ""
6657 + scope_str = f" [{scope}]" if scope else ""
6658 + print(f" 📦 {_c('bold', name)} {version}{scope_str}{size_str}")
6659 + print(f" {_c('dim', app_id)}")
6660 + return 0
6661 +
6662 +def cmd_flatpak_update():
6663 + """Aktualizuje wszystkie flatpaki."""
6664 + if not _check_flatpak():
6665 + return 1
6666 + print(_(' 🔄 Updating flatpaks...'))
6667 + result = subprocess.run(["flatpak", "update", "-y"], check=False, timeout=600)
6668 + if result.returncode == 0:
6669 + _flatpak_refresh_caches()
6670 + print(f" ✅ {_('flatpak_updated')}")
6671 + return result.returncode
6672 +
6673 +def cmd_flatpak_info(app_id: str):
6674 + """Wyświetla szczegóły flatpaka (zainstalowanego lub z Flathub)."""
6675 + if not _check_flatpak():
6676 + return 1
6677 +
6678 + # Najpierw sprawdź zainstalowany
6679 + info = _flatpak_get_installed_info(app_id)
6680 + if info:
6681 + print(f"\n 📦 {_c('bold', info['name'])} {_c('green', '[zainstalowany]')}")
6682 + print(f" {'─' * 45}")
6683 + print(f" {_('flatpak_info_id'):<16} {app_id}")
6684 + print(f" {_('flatpak_info_version'):<16} {info['version']}")
6685 + print(f" {_('flatpak_info_branch'):<16} {info['branch']}")
6686 + print(f" {_('flatpak_info_origin'):<16} {info['origin']}")
6687 + if info["size"]:
6688 + print(f" {_('flatpak_info_size'):<16} {info['size']}")
6689 + if info["description"]:
6690 + print(f" {_('flatpak_info_desc'):<16} {info['description']}")
6691 + return 0
6692 +
6693 + # Szukaj we Flathub
6694 + results = _flatpak_search_raw(app_id)
6695 + exact = [r for r in results if r["app_id"].lower() == app_id.lower()]
6696 + if not exact:
6697 + # Spróbuj częściowego dopasowania
6698 + if results:
6699 + exact = [results[0]]
6700 + else:
6701 + print(f" ❌ '{app_id}' – {_('flatpak_not_found')}")
6702 + return 1
6703 +
6704 + r = exact[0]
6705 + print(f"\n 📦 {_c('bold', r['name'])} (Flathub)")
6706 + print(f" {'─' * 45}")
6707 + print(f" {_('flatpak_info_id'):<16} {r['app_id']}")
6708 + print(f" {_('flatpak_info_version'):<16} {r['version']}")
6709 + if r["description"]:
6710 + print(f" {_('flatpak_info_desc'):<16} {r['description']}")
6711 + print(_('\n 💡 To install: pag flatpak install {arg1}', arg1=(r['app_id'])))
6712 + return 0
6713 +
6714 +# =============================================================================
6715 +# IMMUTABLE OS – KOMENDY DEPLOYMENTOWE
6716 +# =============================================================================
6717 +
6718 +# Pakiety jądra – po ich instalacji trzeba przebudować initramfs
6719 +KERNEL_PACKAGE_PATTERNS = ["linux", "kernel", "linux-kernel", "linux-lts"]
6720 +
6721 +# Pakiety, po których initramfs MUSI zostać przebudowany: jądra oraz moduły
6722 +# out-of-tree (NVIDIA/VirtualBox). `pag` robi to raz, po całej transakcji.
6723 +INITRAMFS_PACKAGE_PATTERNS = tuple(KERNEL_PACKAGE_PATTERNS) + (
6724 + "nvidia-dkms", "nvidia-kernel",
6725 + "vboxhost-kernel", "virtualbox-host-modules", "virtualbox-guest-modules",
6726 +)
6727 +
6728 +def _is_kernel_package(name: str) -> bool:
6729 + """Sprawdza czy pakiet to jądro (wymaga przebudowy initramfs)."""
6730 + name_lower = name.lower()
6731 + return any(pattern in name_lower for pattern in KERNEL_PACKAGE_PATTERNS)
6732 +
6733 +
6734 +def _needs_initramfs_refresh(name: str) -> bool:
6735 + """Czy po tym pakiecie trzeba przebudować initramfs (jądro lub moduły)."""
6736 + name_lower = name.lower()
6737 + return any(pattern in name_lower
6738 + for pattern in INITRAMFS_PACKAGE_PATTERNS)
6739 +
6740 +# Towarzysze jądra – aktualizowani RAZEM z jądrem, jeśli są zainstalowani,
6741 +# żeby userspace i moduły jądra nie rozjechały się wersjami.
6742 +KERNEL_SIBLINGS = ("linux-headers", "nvidia-dkms", "nvidia-kernel", "dkms",
6743 + "virtualbox-host-modules", "virtualbox-guest-modules")
6744 +
6745 +
6746 +def _kernel_group_updates(pending):
6747 + """Gdy w transakcji jest jądro, dołóż jego towarzyszy (jeśli zainstalowani)."""
6748 + if not any(_is_kernel_package(n) for n in pending):
6749 + return pending
6750 + try:
6751 + installed = load_json(INSTALLED_DB)
6752 + repo = fetch_all_packages()
6753 + except Exception:
6754 + return pending
6755 + out = list(pending)
6756 + for sib in KERNEL_SIBLINGS:
6757 + if sib in installed and sib in repo and sib not in out:
6758 + out.append(sib)
6759 + return out
6760 +
6761 +
6762 +def _post_kernel_hooks():
6763 + """Po zmianie jądra na ZWYKŁEJ instalacji: DKMS → initramfs → GRUB.
6764 +
6765 + Kolejność ma znaczenie: najpierw moduły out-of-tree (DKMS) pod nowe jądro,
6766 + potem initramfs (żeby zawierał już przebudowane moduły), na końcu wpisy
6767 + GRUB. To JEDYNE miejsce, które buduje initramfs po transakcji – hooki
6768 + pakietów mogą pominąć własną przebudowę, gdy działają pod lockiem `pag`.
6769 + """
6770 + if shutil.which("dkms"):
6771 + try:
6772 + print(_(' 🔧 DKMS: rebuilding out-of-tree modules (nvidia/vbox)...'))
6773 + subprocess.run(["dkms", "autoinstall"],
6774 + capture_output=True, text=True, timeout=1800)
6775 + except Exception:
6776 + pass
6777 + try:
6778 + _rebuild_initramfs()
6779 + except Exception:
6780 + pass
6781 + _refresh_bootloader()
6782 +
6783 +def _rebuild_initramfs(deploy_dir: str = "") -> bool:
6784 + """
6785 + Przebudowuje initramfs dla aktywnego (lub podanego) deploymentu.
6786 + Używa skryptu pag-initramfs lub ręcznego cpio.
6787 + """
6788 + if deploy_dir:
6789 + root = deploy_dir
6790 + else:
6791 + root = _get_deployment_root()
6792 +
6793 + if root == PAG_ROOT:
6794 + # Zwykły system – NAJPIERW natywne narzędzie PaganOS (per-wersja +
6795 + # root=UUID/PARTUUID/LABEL), potem dracut/mkinitcpio.
6796 + if shutil.which("pagan-initramfs"):
6797 + print(_(' 🔧 Rebuilding initramfs (pagan-initramfs)...'))
6798 + try:
6799 + r = subprocess.run(["pagan-initramfs"], capture_output=True,
6800 + text=True, timeout=1800)
6801 + if r.returncode == 0:
6802 + return True
6803 + except Exception:
6804 + pass
6805 + # Zwykły system – użyj dracut jeśli dostępny
6806 + if shutil.which("dracut"):
6807 + print(_(' 🔧 Rebuilding initramfs (dracut)...'))
6808 + result = subprocess.run(
6809 + ["dracut", "--force", "/boot/initramfs.img"],
6810 + capture_output=True, text=True, timeout=600
6811 + )
6812 + return result.returncode == 0
6813 + elif shutil.which("mkinitcpio"):
6814 + print(_(' 🔧 Rebuilding initramfs (mkinitcpio)...'))
6815 + result = subprocess.run(
6816 + ["mkinitcpio", "-g", "/boot/initramfs.img"],
6817 + capture_output=True, text=True, timeout=600
6818 + )
6819 + return result.returncode == 0
6820 + else:
6821 + print(_(' ⚠ No dracut/mkinitcpio – initramfs was not rebuilt'))
6822 + return False
6823 +
6824 + # Tryb immutable – budujemy initramfs dla deploymentu
6825 + print(_(' 🔧 Building initramfs for the deployment...'))
6826 +
6827 + # Sprawdź czy mamy nasz skrypt init
6828 + pag_init_script = "/usr/share/pag/initramfs-init"
6829 + if not os.path.exists(pag_init_script):
6830 + # Szukaj w źródłach (developerski fallback)
6831 + alt_paths = [
6832 + os.path.join(os.path.dirname(os.path.abspath(__file__)), "scripts", "initramfs-init"),
6833 + "/usr/share/pag/init",
6834 + ]
6835 + for p in alt_paths:
6836 + if os.path.exists(p):
6837 + pag_init_script = p
6838 + break
6839 +
6840 + if not os.path.exists(pag_init_script):
6841 + print(_(' ⚠ pag-initramfs-init not found – skipping initramfs build'))
6842 + return False
6843 +
6844 + boot_dir = os.path.join(root, "boot")
6845 + os.makedirs(boot_dir, exist_ok=True)
6846 +
6847 + # Znajdź jądro (vmlinuz-*)
6848 + kernels = sorted(
6849 + [f for f in os.listdir(boot_dir) if f.startswith("vmlinuz-")],
6850 + reverse=True
6851 + ) if os.path.exists(boot_dir) else []
6852 + if not kernels:
6853 + print(_(" ⚠ No vmlinuz-* found in the deployment's /boot"))
6854 + return False
6855 +
6856 + kernel_ver = kernels[0].replace("vmlinuz-", "")
6857 + print(_(' 🐧 Kernel: {arg1}', arg1=(kernel_ver)))
6858 +
6859 + # Buduj initramfs ręcznie (cpio)
6860 + tmpdir = tempfile.mkdtemp(prefix="pag-initramfs-")
6861 + try:
6862 + # Podstawowa struktura
6863 + for d in ["bin", "sbin", "dev", "proc", "sys", "run", "new_root",
6864 + "usr/bin", "usr/sbin", "lib", "lib64", "etc"]:
6865 + os.makedirs(os.path.join(tmpdir, d), exist_ok=True)
6866 +
6867 + # Skopiuj init
6868 + shutil.copy2(pag_init_script, os.path.join(tmpdir, "init"))
6869 + os.chmod(os.path.join(tmpdir, "init"), 0o755)
6870 +
6871 + # Skopiuj niezbędne binaria (busybox lub podstawowe narzędzia)
6872 + busybox_paths = [
6873 + os.path.join(root, "usr/bin/busybox"),
6874 + os.path.join(root, "bin/busybox"),
6875 + "/usr/bin/busybox",
6876 + "/bin/busybox",
6877 + ]
6878 + busybox = None
6879 + for bp in busybox_paths:
6880 + if os.path.exists(bp):
6881 + busybox = bp
6882 + break
6883 +
6884 + if busybox:
6885 + shutil.copy2(busybox, os.path.join(tmpdir, "bin/busybox"))
6886 + # Utwórz symlinki dla podstawowych komend
6887 + for cmd in ["sh", "mount", "umount", "ls", "cat", "echo", "sleep",
6888 + "readlink", "mkdir", "switch_root", "cp", "rm"]:
6889 + link = os.path.join(tmpdir, "bin", cmd)
6890 + if not os.path.exists(link):
6891 + os.symlink("busybox", link)
6892 + # /bin/sh → busybox
6893 + if not os.path.exists(os.path.join(tmpdir, "bin/sh")):
6894 + os.symlink("busybox", os.path.join(tmpdir, "bin/sh"))
6895 + else:
6896 + # Bez busybox – kopiuj podstawowe narzędzia z deploymentu
6897 + for tool in ["bash", "mount", "umount", "readlink", "mkdir", "cat", "sleep", "cp", "rm"]:
6898 + src = os.path.join(root, "usr/bin", tool)
6899 + if not os.path.exists(src):
6900 + src = os.path.join(root, "bin", tool)
6901 + if os.path.exists(src):
6902 + dest = os.path.join(tmpdir, "bin", os.path.basename(tool))
6903 + shutil.copy2(src, dest)
6904 + # Kopiuj zależności .so
6905 + _copy_libs_for_binary(src, tmpdir, root)
6906 +
6907 + # Dodaj moduły jądra (opcjonalnie – dla sterowników dyskowych)
6908 + modules_src = os.path.join(root, "lib/modules", kernel_ver)
6909 + if os.path.isdir(modules_src):
6910 + modules_dst = os.path.join(tmpdir, "lib/modules", kernel_ver)
6911 + # Kopiuj tylko niezbędne (fs, block, drivers/ata, drivers/nvme)
6912 + for sub in ["kernel/fs", "kernel/drivers/ata", "kernel/drivers/nvme",
6913 + "kernel/drivers/scsi", "kernel/drivers/virtio",
6914 + "modules.order", "modules.builtin"]:
6915 + src_sub = os.path.join(modules_src, sub)
6916 + if os.path.exists(src_sub):
6917 + dst_sub = os.path.join(modules_dst, sub)
6918 + os.makedirs(os.path.dirname(dst_sub), exist_ok=True)
6919 + if os.path.isdir(src_sub):
6920 + try:
6921 + shutil.copytree(src_sub, dst_sub, dirs_exist_ok=True, symlinks=True,
6922 + ignore_dangling_symlinks=True)
6923 + except (FileNotFoundError, PermissionError):
6924 + print(_(' ⚠ Skipping unavailable files: {arg1}', arg1=(sub)))
6925 + else:
6926 + try:
6927 + shutil.copy2(src_sub, dst_sub)
6928 + except (FileNotFoundError, PermissionError):
6929 + print(_(' ⚠ Skipping unavailable file: {arg1}', arg1=(sub)))
6930 +
6931 + # Pakuj do initramfs.img
6932 + initramfs_path = os.path.join(boot_dir, "initramfs.img")
6933 + old_cwd = os.getcwd()
6934 + os.chdir(tmpdir)
6935 + try:
6936 + with open(initramfs_path + ".tmp", "wb") as out:
6937 + _run_cpio_pipeline(tmpdir, out)
6938 + os.rename(initramfs_path + ".tmp", initramfs_path)
6939 + finally:
6940 + os.chdir(old_cwd)
6941 +
6942 + size_mb = os.path.getsize(initramfs_path) / 1048576
6943 + print(_(' ✅ initramfs.img ({arg1:.1f} MB) → {arg2}', arg1=(size_mb), arg2=(initramfs_path)))
6944 + return True
6945 +
6946 + except Exception as e:
6947 + print(_(' ❌ initramfs build error: {arg1}', arg1=(e)))
6948 + return False
6949 + finally:
6950 + shutil.rmtree(tmpdir, ignore_errors=True)
6951 +
6952 +
6953 +def _run_cpio_pipeline(tmpdir: str, out):
6954 + """find . -print0 | cpio --null -oH newc | gzip — bez shell=True.
6955 +
6956 + Buduje pipeline przez subprocess.Popen, unikając pośrednika powłoki
6957 + (brak ryzyka injection i niepotrzebnego procesu sh). Wykonuje się w cwd=tmpdir.
6958 + Separatory NUL (\0): plik/katalog ze znakiem nowej linii w nazwie nie
6959 + rozjeżdża cpio (inaczej uszkodzone archiwum → kernel panic przy rozruchu).
6960 + """
6961 + find = subprocess.Popen(["find", ".", "-print0"], cwd=tmpdir, stdout=subprocess.PIPE)
6962 + cpio = subprocess.Popen(["cpio", "--null", "-oH", "newc"], cwd=tmpdir,
6963 + stdin=find.stdout, stdout=subprocess.PIPE)
6964 + find.stdout.close() # zwolnij uchwyt – cpio dostanie SIGPIPE po zakończeniu find
6965 + gzip = subprocess.Popen(["gzip"], stdin=cpio.stdout, stdout=out)
6966 + cpio.stdout.close()
6967 + try:
6968 + gzip.wait(timeout=120)
6969 + if gzip.returncode != 0:
6970 + raise subprocess.CalledProcessError(gzip.returncode, ["gzip"])
6971 + cpio.wait(timeout=30)
6972 + find.wait(timeout=30)
6973 + except subprocess.TimeoutExpired:
6974 + for p in (gzip, cpio, find):
6975 + p.kill()
6976 + raise
6977 + finally:
6978 + for p in (find, cpio, gzip):
6979 + if p.poll() is None:
6980 + p.kill()
6981 + # Skontroluj też kody procesów pośrednich (cpio/find mogą zawieść, a gzip zwrócić 0)
6982 + if cpio.returncode != 0:
6983 + raise subprocess.CalledProcessError(cpio.returncode, ["cpio"])
6984 + if find.returncode != 0:
6985 + raise subprocess.CalledProcessError(find.returncode, ["find"])
6986 +
6987 +
6988 +def _copy_libs_for_binary(binary: str, dest_dir: str, root: str):
6989 + """Kopiuje zależności .so dla binarki do initramfs (uproszczone ldd)."""
6990 + try:
6991 + result = subprocess.run(
6992 + ["ldd", binary], capture_output=True, text=True, timeout=10
6993 + )
6994 + for line in result.stdout.split("\n"):
6995 + m = re.search(r'=>\s+(/\S+)', line)
6996 + if m:
6997 + lib_path = m.group(1)
6998 + lib_rel = lib_path.lstrip("/")
6999 + lib_dest = os.path.join(dest_dir, lib_rel)
7000 + if not os.path.exists(lib_dest):
7001 + os.makedirs(os.path.dirname(lib_dest), exist_ok=True)
7002 + # Szukaj w deployment root lub systemie
7003 + if os.path.exists(lib_path):
7004 + shutil.copy2(lib_path, lib_dest)
7005 + else:
7006 + alt = os.path.join(root, lib_rel)
7007 + if os.path.exists(alt):
7008 + shutil.copy2(alt, lib_dest)
7009 + except Exception:
7010 + pass
7011 +
7012 +
7013 +def cmd_initramfs_update():
7014 + """Ręcznie przebudowuje initramfs dla bieżącego deploymentu."""
7015 + ensure_dirs()
7016 + deploy_dir = _get_deployment_root()
7017 + if deploy_dir != PAG_ROOT:
7018 + print(_('🏗️ Deployment: {arg1}', arg1=(os.path.basename(deploy_dir))))
7019 + ok = _rebuild_initramfs(deploy_dir)
7020 + if ok:
7021 + print(_('✅ Initramfs updated.'))
7022 + # Po initramfs – zaktualizuj też GRUB
7023 + _update_grub_config()
7024 + else:
7025 + print(_('❌ Initramfs update failed.'))
7026 + return 0 if ok else 1
7027 +
7028 +
7029 +def _boot_prefix() -> str:
7030 + """Prefiks ścieżek jądra/initrd w grub.cfg.
7031 +
7032 + Gdy /boot jest OSOBNYM punktem montowania, GRUB ma w `root` partycję
7033 + /boot (tam leży grub.cfg i jądra), więc ścieżki podajemy względem niej:
7034 + "/vmlinuz-…", "/initramfs.img" – BEZ przedrostka /boot. Gdy /boot leży
7035 + na roocie, wymagane jest "/boot/…". Zły przedrostek = "file not found".
7036 + """
7037 + try:
7038 + if os.path.isdir("/boot") and os.path.ismount("/boot"):
7039 + return ""
7040 + except OSError:
7041 + pass
7042 + return "/boot"
7043 +
7044 +
7045 +def _strip_crlf(path: str) -> bool:
7046 + """Usuwa CRLF/CR z pliku. True, jeśli coś zmieniono.
7047 +
7048 + /etc/default/grub z końcówkami Windows wywala `grub-mkconfig`
7049 + (line 2: bad command), a wtedy menu GRUB nie jest odświeżane po
7050 + aktualizacji jądra — zostaje stary wpis startowy.
7051 + """
7052 + try:
7053 + if not os.path.isfile(path):
7054 + return False
7055 + with open(path, "rb") as f:
7056 + data = f.read()
7057 + if b"\r" not in data:
7058 + return False
7059 + with open(path, "wb") as f:
7060 + f.write(data.replace(b"\r\n", b"\n").replace(b"\r", b"\n"))
7061 + return True
7062 + except Exception:
7063 + return False
7064 +
7065 +
7066 +def _repair_initramfs_links(boot: str = "/boot") -> bool:
7067 + """Doprowadza aliasy initramfs do stanu, w którym GRUB ma co podać.
7068 +
7069 + /etc/grub.d/10_linux dodaje linię `initrd` tylko jeśli istnieje
7070 + `initrd.img-<wersja>` lub `initramfs-<wersja>.img`. Dla wpisu z aliasu
7071 + `vmlinuz-linux` szuka `initrd.img-linux` / `initramfs-linux.img`.
7072 + Martwy łańcuch dowiązań = start BEZ initramfs, czyli panika
7073 + (VFS: Cannot open root device), gdy NVMe/LUKS są modułami.
7074 + """
7075 + changed = False
7076 + try:
7077 + if not os.path.isdir(boot):
7078 + return False
7079 + imgs = []
7080 + for n in os.listdir(boot):
7081 + if not (n.startswith("initramfs-") and n.endswith(".img")):
7082 + continue
7083 + ver = n[len("initramfs-"):-len(".img")]
7084 + if not ver or not ver[0].isdigit():
7085 + continue # initramfs-linux.img to alias
7086 + fp = os.path.join(boot, n)
7087 + if os.path.isfile(fp) and not os.path.islink(fp):
7088 + imgs.append((os.path.getmtime(fp), n))
7089 + if not imgs:
7090 + return False
7091 + newest = max(imgs)[1]
7092 +
7093 + def _link(alias: str, target: str, force: bool = False) -> None:
7094 + nonlocal changed
7095 + ap = os.path.join(boot, alias)
7096 + if os.path.islink(ap):
7097 + if os.readlink(ap) == target and os.path.exists(ap):
7098 + return
7099 + if os.path.exists(ap) and not force:
7100 + return # cel istnieje – nie ruszamy
7101 + os.remove(ap)
7102 + elif os.path.exists(ap):
7103 + return # prawdziwy plik – nie ruszamy
7104 + try:
7105 + os.symlink(target, ap)
7106 + changed = True
7107 + except OSError:
7108 + pass
7109 +
7110 + _link("initramfs.img", newest, force=True)
7111 + if os.path.exists(os.path.join(boot, "vmlinuz-linux")):
7112 + _link("initramfs-linux.img", "initramfs.img")
7113 + _link("initrd.img-linux", "initramfs.img")
7114 + return changed
7115 + except Exception:
7116 + return changed
7117 +
7118 +
7119 +def _grub_entry_lacks_initrd(grub_cfg: str = "/boot/grub/grub.cfg") -> bool:
7120 + """Czy pierwszy wpis menu nie ma linii `initrd` (start bez initramfs)."""
7121 + try:
7122 + with open(grub_cfg, encoding="utf-8", errors="replace") as f:
7123 + lines = f.read().splitlines()
7124 + except Exception:
7125 + return False
7126 + inside = False
7127 + for ln in lines:
7128 + st = ln.strip()
7129 + # Uwaga: `menuentry_id_option="..."` z nagłówka grub.cfg też zaczyna się
7130 + # od "menuentry" – wymagamy separatora, inaczej parser zgłasza fałszywy
7131 + # alarm „wpis startowy bez initramfs”.
7132 + if st.startswith("menuentry") and st[9:10] in (" ", "\t", "'", '"'):
7133 + if inside:
7134 + return True
7135 + inside = True
7136 + continue
7137 + if not inside:
7138 + continue
7139 + if st.startswith("initrd"):
7140 + return False
7141 + if st == "}":
7142 + return True
7143 + return False
7144 +
7145 +
7146 +def _refresh_bootloader():
7147 + """Odświeża wpisy bootloadera po zmianie jądra.
7148 +
7149 + Deploymenty (immutable OS): własny generator _update_grub_config().
7150 + Zwykła instalacja: standardowy `grub-mkconfig` – /etc/grub.d/10_linux
7151 + sam wygeneruje wpisy dla KAŻDEGO /boot/vmlinuz-* wraz z jego własnym
7152 + initrd. Bez tego `pag upgrade kernel` zostawiał w menu STARY wpis:
7153 + system startował ze starym jądrem, a nowe moduły leżały bezużyteczne
7154 + ("moduły 7.2.8 na jądrze 7.2.5" → zawieszenie na starcie).
7155 + """
7156 + try:
7157 + if _load_deployments():
7158 + _update_grub_config()
7159 + return
7160 + except Exception:
7161 + pass
7162 + grub_cfg = "/boot/grub/grub.cfg"
7163 + if not os.path.isdir("/boot/grub"):
7164 + return
7165 + # Zanim wygenerujemy menu: napraw dane wejściowe. Inaczej grub-mkconfig
7166 + # albo się wywali, albo wygeneruje wpis bez initramfs.
7167 + for _f in ("/etc/default/grub", "/boot/grub/grub.cfg.exemple"):
7168 + if _strip_crlf(_f):
7169 + print(" 🧹 " + _('crlf_fixed', _f))
7170 + if _repair_initramfs_links():
7171 + print(" 🔗 " + _('initramfs_links_fixed'))
7172 + for tool, cmd in ((
7173 + "grub-mkconfig", ["grub-mkconfig", "-o", grub_cfg]), (
7174 + "grub2-mkconfig", ["grub2-mkconfig", "-o", grub_cfg])):
7175 + if shutil.which(tool):
7176 + try:
7177 + print(_(' 📋 Regenerating GRUB (grub-mkconfig)...'))
7178 + r = subprocess.run(cmd, capture_output=True, text=True,
7179 + errors="replace", timeout=180)
7180 + if r.returncode != 0:
7181 + tail = [x for x in (r.stderr or r.stdout or "").splitlines() if x.strip()]
7182 + print(" ⚠ " + _('grub_failed', tail[-1] if tail else r.returncode))
7183 + elif _grub_entry_lacks_initrd(grub_cfg):
7184 + print(" ⚠ " + _('grub_no_initrd'))
7185 + else:
7186 + print(" ✅ " + _('grub_refreshed'))
7187 + except Exception:
7188 + pass
7189 + return
7190 +
7191 +
7192 +def _update_grub_config():
7193 + """
7194 + Generuje wpisy GRUB dla wszystkich deploymentów.
7195 + Każdy deployment dostaje własny wpis – rollback możliwy z bootloadera.
7196 + """
7197 + grub_cfg = "/boot/grub/grub.cfg"
7198 + if not os.path.exists(os.path.dirname(grub_cfg)):
7199 + return # brak GRUB
7200 +
7201 + deployments = _load_deployments()
7202 + root_dev = _detect_root_device()
7203 + if not root_dev:
7204 + print(_(' ⚠ Could not detect the root partition – GRUB entries will have no root=.'),
7205 + file=sys.stderr)
7206 + print(_(' Set PAG_ROOT_DEVICE=/dev/... (or PAG_GRUB_ROOT) and retry.'),
7207 + file=sys.stderr)
7208 + root_arg = f" root={root_dev}" if root_dev else ""
7209 +
7210 + lines = [
7211 + "# =====================================================================",
7212 + "# Pagan Linux – GRUB config (wygenerowane przez pag grub-update)",
7213 + f"# Data: {datetime.now().isoformat()}",
7214 + "# =====================================================================",
7215 + "",
7216 + ]
7217 +
7218 + # Domyślny – ostatni (najnowszy) deployment
7219 + if deployments:
7220 + latest = deployments[-1]["id"]
7221 + lines.append(f"set default=0")
7222 + lines.append(f"set timeout=5")
7223 + else:
7224 + lines.append("set default=0")
7225 + lines.append("set timeout=5")
7226 + lines.append("")
7227 +
7228 + # Wpisy dla każdego deploymentu (od najnowszego)
7229 + entry_num = 0
7230 + for d in reversed(deployments):
7231 + deploy_dir = os.path.join(DEPLOYMENTS_DIR, d["id"])
7232 + boot_dir = os.path.join(deploy_dir, "boot")
7233 + kernels = sorted(
7234 + [f for f in os.listdir(boot_dir) if f.startswith("vmlinuz-")],
7235 + reverse=True
7236 + ) if os.path.isdir(boot_dir) else []
7237 +
7238 + kernel_path = f"/.deployments/{d['id']}/boot/{kernels[0]}" if kernels else ""
7239 + initrd_path = f"/.deployments/{d['id']}/boot/initramfs.img"
7240 + initrd_line = f"initrd {initrd_path}" if os.path.exists(os.path.join(boot_dir, "initramfs.img")) else ""
7241 +
7242 + active_mark = f" [{_('active_deployment')}]" if d.get("active") else ""
7243 + pkg_list = ", ".join(d.get("packages", [])[:3])
7244 + label = f"Pagan Linux – {d['id']}{active_mark}"
7245 +
7246 + lines.append(f"menuentry '{label}' {{")
7247 + if kernel_path:
7248 + lines.append(f" linux {kernel_path}{root_arg} rw quiet")
7249 + else:
7250 + lines.append(f" # Brak jądra w tym deploymencie")
7251 + if initrd_line:
7252 + lines.append(f" {initrd_line}")
7253 + lines.append("}")
7254 + lines.append("")
7255 + entry_num += 1
7256 +
7257 + # Snapshoty systemu (btrfs) – każdy jako osobny wpis do uruchomienia.
7258 + _snap_lines = _grub_snapshot_entries()
7259 + if _snap_lines:
7260 + lines.append("# --- Snapshoty systemu (CoW) ---")
7261 + lines.extend(_snap_lines)
7262 +
7263 + # Wpis fallback: zwykły root (gdyby wszystko padło).
7264 + # Uwaga: GRUB NIE rozwija globów – trzeba podać KONKRETNY plik jądra
7265 + # (wcześniejsze `linux /boot/vmlinuz-*` było niepoprawne).
7266 + fallback_kernels = sorted(
7267 + [f for f in os.listdir("/boot") if f.startswith("vmlinuz-")],
7268 + reverse=True
7269 + ) if os.path.isdir("/boot") else []
7270 + # Osobna partycja /boot => GRUB ma ją w `root`, ścieżki BEZ /boot.
7271 + _bp = _boot_prefix()
7272 + lines.append(f"menuentry '{_('grub_fallback_label')}' {{")
7273 + if fallback_kernels:
7274 + lines.append(f" linux {_bp}/{fallback_kernels[0]}{root_arg} rw quiet")
7275 + _fi = _initrd_for_kernel("/boot", fallback_kernels[0])
7276 + if _fi:
7277 + lines.append(f" initrd {_bp}/{_fi}")
7278 + else:
7279 + lines.append(" # Brak jądra w /boot")
7280 + lines.append("}")
7281 + lines.append("")
7282 +
7283 + # Zapisz
7284 + os.makedirs(os.path.dirname(grub_cfg), exist_ok=True)
7285 + with open(grub_cfg, "w") as f:
7286 + f.write("\n".join(lines))
7287 +
7288 + print(_(' 📋 GRUB config updated – entries for each deployment'))
7289 +
7290 +
7291 +def _root_device_from_fstab(path: str = "/etc/fstab") -> str:
7292 + """Zwraca DEVICE z wpisu dla '/' w fstab (pomija komentarze)."""
7293 + try:
7294 + with open(path, "r", encoding="utf-8", errors="replace") as fh:
7295 + for line in fh:
7296 + line = line.split("#", 1)[0].strip()
7297 + if not line:
7298 + continue
7299 + parts = line.split()
7300 + if len(parts) >= 2 and parts[1] == "/":
7301 + return parts[0]
7302 + except OSError:
7303 + pass
7304 + return ""
7305 +
7306 +
7307 +def _in_chroot() -> bool:
7308 + """Heurystyka: czy działamy w chrocie (build ISO/IMG)?
7309 +
7310 + W chrocie /proc/1/root to root HOSTA – inny system plików niż nasz '/'.
7311 + Na zwykłym systemie PID 1 ma root równy '/'. PAGAN_ROOT ustawiają skrypty
7312 + budujące i jest dziedziczony przez chroot (dodatkowa wskazówka).
7313 + """
7314 + if os.environ.get("PAG_IN_CHROOT") == "1":
7315 + return True
7316 + if os.environ.get("PAGAN_ROOT"):
7317 + return True
7318 + try:
7319 + return os.stat("/").st_dev != os.stat("/proc/1/root").st_dev
7320 + except OSError:
7321 + return False
7322 +
7323 +
7324 +def _detect_root_device() -> str:
7325 + """Wykrywa urządzenie/identyfikator partycji root dla GRUB (root=...).
7326 +
7327 + Kolejność (od najbardziej wiarygodnego w danym kontekście):
7328 + 1) PAG_ROOT_DEVICE / PAG_GRUB_ROOT – jawny override (build ISO/IMG,
7329 + instalator); najpewniejszy, bo nie zgadujemy.
7330 + 2) /etc/fstab TARGETU – w chrocie findmnt '/' zwraca partycję HOSTA,
7331 + a fstab opisuje target (np. root=/dev/sda2 dla obrazu IMG).
7332 + 3) findmnt '/' – na żywym systemie (obsługuje UUID/LUKS/subvol).
7333 + Zwraca "" gdy nie da się ustalić – wtedy GRUB nie dostaje błędnego root=.
7334 + """
7335 + explicit = (os.environ.get("PAG_ROOT_DEVICE")
7336 + or os.environ.get("PAG_GRUB_ROOT") or "").strip()
7337 + if explicit:
7338 + return explicit
7339 +
7340 + fstab_dev = _root_device_from_fstab()
7341 + if _in_chroot() and fstab_dev:
7342 + return fstab_dev
7343 +
7344 + try:
7345 + result = subprocess.run(
7346 + ["findmnt", "-n", "-o", "SOURCE", "/"],
7347 + capture_output=True, text=True, timeout=5
7348 + )
7349 + if result.returncode == 0 and result.stdout.strip():
7350 + return result.stdout.strip()
7351 + except Exception:
7352 + pass
7353 +
7354 + # Ostatnia deska: fstab targetu (lepsze niż hardkodowane /dev/sda1,
7355 + # które na sprzęcie z NVMe dawało niebootowalny system).
7356 + return fstab_dev
7357 +
7358 +
7359 +def cmd_grub_update():
7360 + """Ręcznie regeneruje konfigurację GRUB (deploymenty + snapshoty)."""
7361 + ensure_dirs()
7362 + print(_('📋 Updating GRUB configuration...'))
7363 + _ensure_snapshot_grub_script()
7364 + # Deploymenty mają własny generator; zwykły system – grub-mkconfig,
7365 + # który uruchomi /etc/grub.d/40_pagan_snapshots i zachowa pozostałe wpisy.
7366 + _refresh_bootloader()
7367 + print(_('✅ GRUB updated.'))
7368 + return 0
7369 +
7370 +def cmd_deploy_list():
7371 + """Wyświetla listę wszystkich deploymentów."""
7372 + deployments = _load_deployments()
7373 + if not deployments:
7374 + print(_("no_deployments")); return
7375 +
7376 + print(_("deployments_list", len(deployments)))
7377 + active = os.readlink(ACTIVE_LINK) if os.path.islink(ACTIVE_LINK) else ""
7378 +
7379 + for d in reversed(deployments):
7380 + marker = f" ◀ {_('active_deployment')}" if d.get("active") or d["id"] == os.path.basename(active) else ""
7381 + print(f" {d['id']}{marker}")
7382 + print(f" {_action_label(d['action'])}: {', '.join(d['packages'][:5])}")
7383 + if len(d.get('packages', [])) > 5:
7384 + print(_(' +{arg1} more...', arg1=(len(d['packages']) - 5)))
7385 + print(f" {d['timestamp']}")
7386 +
7387 +
7388 +def cmd_deploy_rollback():
7389 + """Przełącza na poprzedni deployment."""
7390 + deployments = _load_deployments()
7391 + active_indices = [i for i, d in enumerate(deployments) if d.get("active")]
7392 +
7393 + if len(deployments) < 2:
7394 + print(f"❌ {_('deploy_rollback_fail')}"); return 1
7395 +
7396 + current_idx = active_indices[0] if active_indices else len(deployments) - 1
7397 + prev_idx = current_idx - 1 if current_idx > 0 else -1
7398 +
7399 + if prev_idx < 0:
7400 + print(f"❌ {_('deploy_rollback_fail')}"); return 1
7401 +
7402 + prev = deployments[prev_idx]
7403 + prev_dir = os.path.join(DEPLOYMENTS_DIR, prev["id"])
7404 +
7405 + if not os.path.isdir(prev_dir):
7406 + print(_('❌ Deployment {arg1} does not exist on disk', arg1=(prev['id']))); return 1
7407 +
7408 + print(_('⏪ Restoring deployment: {arg1}', arg1=(prev['id'])))
7409 + print(f" {prev['action']}: {', '.join(prev['packages'][:5])}")
7410 +
7411 + if not _ask_confirm():
7412 + return 0
7413 +
7414 + _switch_deployment(prev_dir)
7415 +
7416 + for d in deployments:
7417 + d["active"] = (d["id"] == prev["id"])
7418 + _save_deployments(deployments)
7419 +
7420 + _update_grub_config()
7421 + print(f"✅ {_('deploy_rollback_ok', prev['id'])}")
7422 + print(_(' 💡 Restart required to reload the system.'))
7423 + return 0
7424 +
7425 +
7426 +def cmd_deploy_cleanup(keep: int = 3):
7427 + """Usuwa stare deploymenty, zachowując ostatnie `keep`."""
7428 + deployments = _load_deployments()
7429 +
7430 + if len(deployments) <= keep:
7431 + print(f"✅ {_('deploy_cleanup_none', keep)}"); return 0
7432 +
7433 + to_remove = deployments[:-keep]
7434 + removed = 0
7435 +
7436 + for d in to_remove:
7437 + deploy_dir = os.path.join(DEPLOYMENTS_DIR, d["id"])
7438 + if os.path.isdir(deploy_dir):
7439 + shutil.rmtree(deploy_dir, ignore_errors=True)
7440 + removed += 1
7441 +
7442 + remaining = deployments[-keep:]
7443 + _save_deployments(remaining)
7444 +
7445 + print(f"✅ {_('deploy_cleanup_ok', removed)}")
7446 + return 0
7447 +
7448 +
7449 +# =============================================================================
7450 +# POMOCNICZE
7451 +# =============================================================================
7452 +
7453 +# Pakiety dostarczane przez bazowy system (zawsze "zainstalowane"). Wchodzą do
7454 +# rootfs z ISO przez data.tar.xz, więc NIE ma ich w repo.json ani w bazie pag –
7455 +# każda zależność od nich (glibc, bash, python3…) wyglądałaby na "brakującą".
7456 +# Współdzielone przez rozwijanie i weryfikację zależności.
7457 +SYSTEM_BASE = {
7458 + "glibc", "libc", "gcc", "g++", "make", "binutils", "coreutils", "bash",
7459 + "linux-api-headers", "kernel-headers", "zlib", "pkg-config", "pkgconf",
7460 + "tar", "gzip", "xz", "bzip2", "findutils", "grep", "sed", "gawk", "awk",
7461 + "diffutils", "patch", "file", "m4", "perl", "python3", "sh",
7462 +}
7463 +
7464 +
7465 +def _resolve_deps(names, repo, installed):
7466 + resolved, visited = [], set()
7467 + missing = [] # zależności których nie ma ani w repo ani zainstalowane
7468 +
7469 + def _is_base(dep):
7470 + """True, gdy zależność dostarcza bazowy system (także przez provides)."""
7471 + return dep in SYSTEM_BASE \
7472 + or _resolve_provides(dep, repo, installed) in SYSTEM_BASE
7473 +
7474 + def visit(name, explicit=False):
7475 + if name in visited: return
7476 +
7477 + # Rozwijanie wirtualnych zależności przez provides
7478 + target = _resolve_provides(name, repo, installed)
7479 +
7480 + # Zależność dostarczana przez bazowy system – nie ma jej w repo ani w
7481 + # bazie pag, więc nie "brakuje" jej i nie próbujemy jej instalować.
7482 + # Wyjątek: nazwa podana wprost przez użytkownika (explicit=True).
7483 + if not explicit and target in SYSTEM_BASE:
7484 + return
7485 +
7486 + if target in visited: return
7487 + visited.add(target)
7488 + if target in repo:
7489 + for dep in repo[target].dependencies:
7490 + real_dep = _resolve_provides(dep, repo, installed)
7491 + real_target = real_dep if real_dep in repo else dep
7492 +
7493 + if _is_base(dep):
7494 + continue
7495 +
7496 + # Sprawdź czy zależność jest dostępna
7497 + if real_target not in installed and real_target not in repo:
7498 + if dep not in missing:
7499 + missing.append(dep)
7500 +
7501 + if dep not in installed:
7502 + visit(real_target)
7503 + elif target not in installed:
7504 + # Pakiet nie istnieje ani w repo ani zainstalowany
7505 + if target not in missing:
7506 + missing.append(target)
7507 +
7508 + if target not in installed and target not in resolved:
7509 + resolved.append(target)
7510 +
7511 + for name in names:
7512 + visit(name, explicit=True)
7513 +
7514 + # Zwróć brakujące (do sprawdzenia przez wywołującego)
7515 + return resolved, missing
7516 +
7517 +def _verify_dependencies(to_install: list, repo: dict, installed: dict) -> int:
7518 + """
7519 + Sprawdza czy wszystkie zależności pakietów do instalacji są spełnione.
7520 + Zwraca liczbę brakujących zależności.
7521 + """
7522 + all_missing = []
7523 + all_warnings = []
7524 +
7525 + for pkg_name in to_install:
7526 + pkg = repo.get(pkg_name)
7527 + if not pkg:
7528 + continue
7529 +
7530 + for dep in pkg.dependencies:
7531 + if dep in SYSTEM_BASE:
7532 + continue # bazowy system dostarcza tę zależność
7533 + real_dep = _resolve_provides(dep, repo, installed)
7534 + # Sprawdź czy zależność jest dostępna (w repo lub już zainstalowana)
7535 + in_repo = real_dep in repo
7536 + in_installed = real_dep in installed
7537 + will_be_installed = real_dep in to_install
7538 +
7539 + if not in_repo and not in_installed and not will_be_installed:
7540 + if dep not in all_missing:
7541 + all_missing.append((pkg_name, dep))
7542 + elif in_repo and not in_installed and not will_be_installed:
7543 + if dep not in [w[1] for w in all_warnings]:
7544 + all_warnings.append((pkg_name, dep, real_dep))
7545 +
7546 + if all_missing:
7547 + print(_('\n❌ {arg1} – cannot install:', arg1=(_c('red', 'BRAKUJĄCE ZALEŻNOŚCI'))))
7548 + for pkg, dep in all_missing:
7549 + print(_(' {arg1} → needs {arg2} (missing from repositories)', arg1=(pkg), arg2=(_c('red', dep))))
7550 + print()
7551 +
7552 + if all_warnings:
7553 + print(_('\n⚠ {arg1} – will be installed as dependencies:', arg1=(_c('yellow', 'NIESPEŁNIONE ZALEŻNOŚCI'))))
7554 + for pkg, dep, real in all_warnings:
7555 + print(_(' {arg1} → {arg2} ({arg3} – will be downloaded)', arg1=(pkg), arg2=(dep), arg3=(_c('green', real))))
7556 + print()
7557 +
7558 + return len(all_missing)
7559 +
7560 +# Biblioteki bazowe (glibc/gcc runtime) – zawsze dostępne, nie wymagają pakietu
7561 +BASE_SO = {
7562 + "libc.so.6", "libm.so.6", "libpthread.so.0", "libdl.so.2", "librt.so.1",
7563 + "libutil.so.1", "libresolv.so.2", "libnsl.so.1", "libcrypt.so.1",
7564 + "ld-linux.so.2", "ld-linux-x86-64.so.2", "ld-linux-aarch64.so.1",
7565 + "libgcc_s.so.1", "linux-vdso.so.1",
7566 +}
7567 +
7568 +def _verify_so_deps(to_install: list, repo: dict, installed: dict) -> int:
7569 + """Sprawdza wymagania ABI (provides_so / requires_so z metadata.json).
7570 +
7571 + Fail-closed TYLKO gdy metadata jawnie deklaruje requires_so, a żaden pakiet
7572 + (bazowy, zainstalowany lub instalowany w tej transakcji) nie dostarcza
7573 + wymaganej wersji biblioteki. Stare pakiety bez tych pól są pomijane.
7574 + """
7575 + provided = set(BASE_SO)
7576 + for n in to_install:
7577 + p = repo.get(n)
7578 + if p:
7579 + provided.update(p.provides_so or [])
7580 + for n, info in installed.items():
7581 + provided.update(info.get("provides_so", []) or [])
7582 +
7583 + # NAPRAWA: soname faktycznie obecne w systemie (ldconfig -p). Metadane
7584 + # starych paczek (zbudowanych przed polem provides_so) ich nie deklaruja,
7585 + # a biblioteki sa na dysku - bez tego fail-closed check blokuje legalne
7586 + # aktualizacje (np. mesa -> libLLVM.so.22.1).
7587 + try:
7588 + import shutil as _sh, subprocess as _sp
7589 + _ld = _sh.which("ldconfig")
7590 + if _ld:
7591 + _o = _sp.run([_ld, "-p"], capture_output=True, text=True).stdout
7592 + for _ln in _o.splitlines():
7593 + _ln = _ln.strip()
7594 + if "=>" in _ln:
7595 + provided.add(_ln.split("=>")[0].strip().split()[0])
7596 + except Exception:
7597 + pass
7598 +
7599 + missing = []
7600 + for n in sorted(to_install):
7601 + p = repo.get(n)
7602 + if not p:
7603 + continue
7604 + for so in (p.requires_so or []):
7605 + if so not in provided:
7606 + missing.append((n, so))
7607 +
7608 + if missing:
7609 + print(f"\n❌ {_c('red', 'BRAK WYMAGANYCH BIBLIOTEK (ABI so-name)')}:")
7610 + for n, so in missing:
7611 + print(_(' {arg1} → requires {arg2} – no package provides this version', arg1=(n), arg2=(_c('red', so))))
7612 + print()
7613 + return len(missing)
7614 +
7615 +def _download_pkg(pkg, attempts: int = 3, progress: bool = True,
7616 + on_progress=None, on_log=None):
7617 + """Pobiera pakiet do cache.
7618 +
7619 + `progress=False` wycisza pojedynczy pasek (np. gdy równoległy pobierający
7620 + pokazuje własny panel zbiorczy). `on_progress(downloaded, total)` pozwala
7621 + takiemu panelowi śledzić postęp bez wypisywania własnych linii, a
7622 + `on_log(text)` przekierowuje komunikaty (ponowienia, błędy) do panelu,
7623 + żeby nie rozbijały jego wielolinijkowego układu.
7624 + """
7625 + def _log(msg: str) -> None:
7626 + if on_log is not None:
7627 + on_log(msg)
7628 + else:
7629 + print(msg, file=sys.stderr)
7630 +
7631 + url = f"{pkg.repo_url}/{pkg.filename}"
7632 + dest = os.path.join(PAG_CACHE, pkg.filename)
7633 + if os.path.exists(dest) and (not pkg.sha256 or _sha256_file(dest) == pkg.sha256):
7634 + _download_pkg_sig(pkg, dest) # upewnij się, że sygnatura jest w cache
7635 + return dest
7636 + last_err = None
7637 + for attempt in range(1, attempts + 1):
7638 + try:
7639 + req = Request(url, headers={"User-Agent":"pag/3.0"})
7640 + with urlopen(req, timeout=600) as resp:
7641 + total = int(resp.headers.get("Content-Length", 0))
7642 + bar = DownloadBar(pkg.filename, total) if progress else None
7643 + done = 0
7644 + try:
7645 + with open(dest, "wb") as f:
7646 + while True:
7647 + chunk = resp.read(65536)
7648 + if not chunk:
7649 + break
7650 + f.write(chunk)
7651 + done += len(chunk)
7652 + if bar is not None:
7653 + bar.update(len(chunk))
7654 + if on_progress is not None:
7655 + on_progress(done, total)
7656 + finally:
7657 + if bar is not None:
7658 + bar.close()
7659 + if pkg.sha256 and _sha256_file(dest) != pkg.sha256:
7660 + last_err = _("sha256_mismatch")
7661 + try:
7662 + os.remove(dest)
7663 + except OSError:
7664 + pass
7665 + if attempt < attempts:
7666 + _log(_(' ↻ Retrying download of {arg1} ({arg2}/{arg3})...', arg1=(pkg.filename), arg2=(attempt), arg3=(attempts - 1)))
7667 + time.sleep(attempt)
7668 + continue
7669 + return None
7670 + _download_pkg_sig(pkg, dest)
7671 + return dest
7672 + except Exception as e:
7673 + last_err = e
7674 + # Usuń częściowy plik – bez tego mógłby zostać użyty jako „cache”
7675 + # (gdy pakiet nie ma sha256) albo mylić kolejną próbę.
7676 + try:
7677 + if os.path.exists(dest):
7678 + os.remove(dest)
7679 + except OSError:
7680 + pass
7681 + if attempt < attempts:
7682 + _log(_(' ↻ Retrying download of {arg1} ({arg2}/{arg3})...', arg1=(pkg.filename), arg2=(attempt), arg3=(attempts - 1)))
7683 + time.sleep(attempt)
7684 + continue
7685 + _log(_(' ⚠ Download error {arg1}: {arg2}', arg1=(pkg.filename), arg2=(last_err)))
7686 + return None
7687 +
7688 +def _download_pkg_sig(pkg, dest):
7689 + """Zapewnia AKTUALNY podpis pakietu (.asc, fallback .sig) w cache.
7690 +
7691 + Istniejący podpis jest używany tylko wtedy, gdy faktycznie weryfikuje TĘ
7692 + paczkę. Inaczej po przebudowie tej samej wersji (ten sam plik, nowy sha256)
7693 + stary podpis zostawał obok nowej paczki i weryfikacja dawała fałszywe
7694 + „NIEPRAWIDŁOWY PODPIS GPG”.
7695 + """
7696 + for ext in (".asc", ".sig"):
7697 + sig_dest = dest + ext
7698 + if os.path.exists(sig_dest):
7699 + ok, _fp = _gpg_verify_fp(sig_dest, dest)
7700 + if ok:
7701 + return
7702 + for ext in (".asc", ".sig"):
7703 + sig_dest = dest + ext
7704 + try:
7705 + req = Request(f"{pkg.repo_url}/{pkg.filename}{ext}", headers={"User-Agent":"pag/3.0"})
7706 + with urlopen(req, timeout=30) as resp:
7707 + data = resp.read()
7708 + except Exception:
7709 + continue
7710 + # nie mieszaj rozszerzeń – zostaje tylko ten wariant podpisu
7711 + for other in (".asc", ".sig"):
7712 + if other != ext:
7713 + try:
7714 + os.remove(dest + other)
7715 + except OSError:
7716 + pass
7717 + with open(sig_dest, "wb") as f:
7718 + f.write(data)
7719 + return
7720 + # Nie udało się pobrać podpisu – usuń nieaktualny z cache, żeby weryfikacja
7721 + # nie porównywała paczki z podpisem od innej wersji (czytelny „BRAK PODPISU”).
7722 + for other in (".asc", ".sig"):
7723 + try:
7724 + os.remove(dest + other)
7725 + except OSError:
7726 + pass
7727 +
7728 +def _download_packages_parallel(pkgs: List[PackageInfo], max_workers: int = 4) -> Dict[str, Optional[str]]:
7729 + """
7730 + Równoległe pobieranie wielu pakietów przez ThreadPoolExecutor.
7731 + Znacząco przyspiesza przy dużych aktualizacjach (50+ pakietów).
7732 +
7733 + Każdy aktywny wątek ma własną linię w panelu: procent, nazwa pakietu,
7734 + pobrane/rozmiar i ETA (patrz `_ParallelDownloadDisplay`).
7735 + Zwraca słownik {nazwa_pakietu: ścieżka_lub_None}.
7736 + """
7737 + results = {}
7738 + display = _ParallelDownloadDisplay(len(pkgs))
7739 +
7740 + def _worker(pkg: PackageInfo):
7741 + sid = display.start(pkg.name, getattr(pkg, "size_bytes", 0) or 0)
7742 + path = None
7743 + try:
7744 + path = _download_pkg(
7745 + pkg, progress=False,
7746 + on_progress=lambda done, total: display.progress(sid, done, total),
7747 + on_log=display.log)
7748 + return path
7749 + finally:
7750 + display.finish(sid, ok=bool(path))
7751 +
7752 + try:
7753 + with ThreadPoolExecutor(max_workers=max_workers) as executor:
7754 + future_to_pkg = {executor.submit(_worker, pkg): pkg for pkg in pkgs}
7755 + for future in as_completed(future_to_pkg):
7756 + pkg = future_to_pkg[future]
7757 + try:
7758 + results[pkg.name] = future.result()
7759 + except Exception:
7760 + results[pkg.name] = None
7761 + finally:
7762 + display.close()
7763 + return results
7764 +
7765 +def load_world():
7766 + if not os.path.exists(WORLD_FILE): return set()
7767 + return {l.strip() for l in open(WORLD_FILE) if l.strip()}
7768 +
7769 +def save_world(w):
7770 + with open(WORLD_FILE,"w") as f:
7771 + for n in sorted(w): f.write(f"{n}\n")
7772 +
7773 +def _find_orphans(installed, world):
7774 + needed = set(world)
7775 + changed = True
7776 + while changed:
7777 + changed = False
7778 + for n in list(needed):
7779 + for dep in installed.get(n,{}).get("dependencies",[]):
7780 + if dep not in needed and dep in installed:
7781 + needed.add(dep); changed = True
7782 + return {n for n in installed if n not in needed}
7783 +
7784 +# =============================================================================
7785 +# MAIN
7786 +# =============================================================================
7787 +
7788 +def cmd_sbom(argv):
7789 + """pag sbom export [spdx|cyclonedx] – manifest SBOM zainstalowanych pakietów.
7790 +
7791 + Wypisuje na stdout JSON (SPDX 2.3 lub CycloneDX 1.5) z listą
7792 + zainstalowanych pakietów, wersji, licencji i sum SHA256.
7793 + """
7794 + fmt = (argv[0] if argv else "spdx").lower()
7795 + if fmt not in ("spdx", "cyclonedx"):
7796 + print(_('❌ Format: spdx | cyclonedx'))
7797 + return 1
7798 + installed = load_json(INSTALLED_DB)
7799 + if not installed:
7800 + print("{}") if fmt == "cyclonedx" else print("{\"packages\": []}")
7801 + return 0
7802 + # metadata repo (licencje) – best-effort
7803 + try:
7804 + repo = fetch_all_packages()
7805 + except Exception:
7806 + repo = {}
7807 + names = sorted(installed)
7808 + created = datetime.now().astimezone().isoformat(timespec="seconds")
7809 +
7810 + def _license_of(name):
7811 + p = repo.get(name)
7812 + lic = getattr(p, "license", None) or []
7813 + if isinstance(lic, list):
7814 + lic = ", ".join(x for x in lic if x)
7815 + return lic or "NOASSERTION"
7816 +
7817 + if fmt == "spdx":
7818 + doc = {
7819 + "spdxVersion": "SPDX-2.3",
7820 + "dataLicense": "CC0-1.0",
7821 + "SPDXID": "SPDXRef-DOCUMENT",
7822 + "name": "PaganOS-installed",
7823 + "documentNamespace": f"https://repo.paganlinux.eu/sbom/installed-{int(time.time())}",
7824 + "creationInfo": {
7825 + "created": created,
7826 + "creators": [f"Tool: pag-{PAG_VERSION}"],
7827 + },
7828 + "packages": [],
7829 + }
7830 + for i, n in enumerate(names):
7831 + info = installed[n]
7832 + doc["packages"].append({
7833 + "SPDXID": f"SPDXRef-Package-{i+1}",
7834 + "name": n,
7835 + "versionInfo": info.get("version", ""),
7836 + "downloadLocation": info.get("repo", "NOASSERTION"),
7837 + "filesAnalyzed": False,
7838 + "licenseConcluded": _license_of(n),
7839 + "checksums": [{"algorithm": "SHA256", "checksumValue": info.get("sha256", "")}],
7840 + })
7841 + else: # cyclonedx
7842 + doc = {
7843 + "bomFormat": "CycloneDX",
7844 + "specVersion": "1.5",
7845 + "serialNumber": f"urn:uuid:{str(uuid.uuid4())}",
7846 + "version": 1,
7847 + "metadata": {
7848 + "timestamp": created,
7849 + "tools": [{"vendor": "PaganOS", "name": "pag", "version": PAG_VERSION}],
7850 + },
7851 + "components": [],
7852 + }
7853 + for n in names:
7854 + info = installed[n]
7855 + lic = _license_of(n)
7856 + comp = {
7857 + "type": "library",
7858 + "name": n,
7859 + "version": info.get("version", ""),
7860 + "hashes": [{"alg": "SHA-256", "content": info.get("sha256", "")}],
7861 + }
7862 + if lic != "NOASSERTION":
7863 + comp["licenses"] = [{"license": {"id": lic}}]
7864 + doc["components"].append(comp)
7865 + print(json.dumps(doc, indent=2, ensure_ascii=False))
7866 + return 0
7867 +
7868 +
7869 +USAGE_EN = """pag v3 – Pagan Linux Package Manager
7870 +
7871 +BASIC:
7872 + pag install <pkg>... Install packages
7873 + pag remove <pkg>... Remove packages
7874 + pag update Update PACKAGES (refreshes indexes first)
7875 + pag sync Refresh indexes + show pending package updates
7876 + pag upgrade Update SYSTEM (packages + kernel/initramfs/GRUB)
7877 + pag list [--installed] List available / installed
7878 + pag search <query> Search packages
7879 + pag info <pkg> Package details
7880 + pag files <pkg> List package files
7881 + pag verify [--deep] Verify integrity (--deep = SHA256 per file)
7882 + pag clean Clear download cache
7883 + pag stats System statistics
7884 + pag download <pkg>... Download packages to cache (offline prep)
7885 +
7886 +ROLLING (base baked into the image):
7887 + pag base [status] Image packages vs. repo (what pag manages)
7888 + pag base adopt [pkg...] Adopt base packages from the repo (--dry-run = preview)
7889 +
7890 +SECURITY:
7891 + pag key-add <url|file> Import GPG key
7892 + pag key-list List trusted keys
7893 + pag key-remove <id> Remove key
7894 + pag key-trust <repo> Pin repo signing key fingerprint (no TOFU)
7895 + pag key-untrust <repo> Forget repo fingerprint (back to TOFU)
7896 + pag key-trusted List pinned repo fingerprints
7897 +
7898 +ADVANCED:
7899 + pag why <pkg> Show why a package is installed
7900 + pag rdepends <pkg> Show which packages depend on a package
7901 + pag autoremove Auto-remove orphaned dependencies
7902 + pag pin <pkg> [ver] Pin package version
7903 + pag unpin <pkg> Unpin
7904 + pag pinned List pinned
7905 + pag history Transaction history
7906 + pag rollback Rollback last transaction
7907 + pag repair [--dry-run] Reinstall packages with missing files
7908 + pag remove-orphans Remove orphaned deps
7909 + pag repo-add <url> [name] Add repository (drop-in /etc/pag/repos/)
7910 + pag repo-list List repositories
7911 + pag sbom export [fmt] SBOM manifest (spdx|cyclonedx)
7912 +
7913 +FLATPAK:
7914 + pag flatpak [<query>] Search & install (smart)
7915 + pag flatpak search <q> Search Flathub
7916 + pag flatpak install <id> Install flatpak
7917 + pag flatpak remove <id> Remove flatpak
7918 + pag flatpak list List installed flatpaks
7919 + pag flatpak update Update all flatpaks
7920 + pag flatpak info <id> Show flatpak details
7921 +
7922 +SNAPSHOTS (btrfs CoW):
7923 + pag snapshot-list List system snapshots
7924 + pag snapshot-create [label] Create a snapshot now
7925 + pag snapshot-rollback [id] Start from snapshot at next boot (GRUB)
7926 + pag snapshot-delete <id> Delete a snapshot
7927 +
7928 +IMMUTABLE OS (PAG_IMMUTABLE=1):
7929 + pag deploy-list List all deployments
7930 + pag deploy-rollback Switch to previous deployment
7931 + pag deploy-cleanup [N] Remove old deployments (keep last N, default 3)
7932 + pag initramfs-update Rebuild initramfs for current kernel/deployment
7933 + pag grub-update Regenerate GRUB entries for all deployments
7934 +"""
7935 +
7936 +USAGE_PL = """pag v3 – Pagan Linux Package Manager
7937 +
7938 +PODSTAWOWE:
7939 + pag install <pkg>... Instalacja pakietów
7940 + pag remove <pkg>... Usuwanie pakietów
7941 + pag update Aktualizacja PAKIETÓW (odświeża indeksy)
7942 + pag sync Odśwież indeksy + info o aktualizacjach
7943 + pag upgrade Aktualizacja SYSTEMU (pakiety + kernel/initramfs/GRUB)
7944 + pag list [--installed] Lista dostępnych / zainstalowanych
7945 + pag search <query> Szukaj pakietów
7946 + pag info <pkg> Szczegóły pakietu
7947 + pag files <pkg> Lista plików pakietu
7948 + pag verify [--deep] Weryfikacja integralności
7949 + pag clean Wyczyść cache pobierania
7950 + pag stats Statystyki systemu
7951 + pag download <pkg>... Pobierz do cache (offline)
7952 +
7953 +ROLLING (baza wypalona w obrazie):
7954 + pag base [status] Pakiety z obrazu vs repo (czym pag zarządza)
7955 + pag base adopt [pkg...] Adoptuj pakiety bazy z repo (--dry-run = podgląd)
7956 +
7957 +BEZPIECZEŃSTWO:
7958 + pag key-add <url|file> Importuj klucz GPG
7959 + pag key-list Lista zaufanych kluczy
7960 + pag key-remove <id> Usuń klucz
7961 + pag key-trust <repo> Przypnij fingerprint klucza repo (bez TOFU)
7962 + pag key-untrust <repo> Zapomnij fingerprint repo (powrót do TOFU)
7963 + pag key-trusted Lista przypiętych fingerprintów repo
7964 +
7965 +ZAAWANSOWANE:
7966 + pag why <pkg> Dlaczego pakiet jest zainstalowany
7967 + pag rdepends <pkg> Które pakiety zależą od pakietu
7968 + pag autoremove Usuń osierocone zależności
7969 + pag pin <pkg> [ver] Przypnij wersję pakietu
7970 + pag unpin <pkg> Odepnij
7971 + pag pinned Lista przypiętych
7972 + pag history Historia transakcji
7973 + pag rollback Cofnij ostatnią transakcję
7974 + pag repair [--dry-run] Napraw brakujące pliki pakietów (reinstalacja)
7975 + pag remove-orphans Usuń osierocone zależności
7976 + pag repo-add <url> [nazwa] Dodaj repozytorium (drop-in w /etc/pag/repos/)
7977 + pag repo-list Lista repozytoriów
7978 + pag sbom export [fmt] Manifest SBOM (spdx|cyclonedx)
7979 +
7980 +FLATPAK:
7981 + pag flatpak [<query>] Szukaj i instaluj
7982 + pag flatpak search <q> Szukaj na Flathub
7983 + pag flatpak install <id> Zainstaluj flatpak
7984 + pag flatpak remove <id> Usuń flatpak
7985 + pag flatpak list Lista zainstalowanych
7986 + pag flatpak update Aktualizuj wszystkie
7987 + pag flatpak info <id> Szczegóły flatpaka
7988 +
7989 +SNAPSHOTY (btrfs CoW):
7990 + pag snapshot-list Lista snapshotów systemu
7991 + pag snapshot-create [opis] Utwórz snapshot teraz
7992 + pag snapshot-rollback [id] Uruchom snapshot przy następnym starcie (GRUB)
7993 + pag snapshot-delete <id> Usuń snapshot
7994 +
7995 +IMMUTABLE OS (PAG_IMMUTABLE=1):
7996 + pag deploy-list Lista wdrożeń
7997 + pag deploy-rollback Przełącz na poprzednie wdrożenie
7998 + pag deploy-cleanup [N] Usuń stare wdrożenia (zachowaj N, domyślnie 3)
7999 + pag initramfs-update Przebuduj initramfs
8000 + pag grub-update Regeneruj wpisy GRUB"""
8001 +
8002 +def _get_usage():
8003 + # Plik językowy może dostarczyć klucz "usage" – wtedy wygrywa z wbudowanym.
8004 + _u = T.get(LANG, {}).get("usage")
8005 + if _u:
8006 + return _u
8007 + if LANG == "pl":
8008 + return USAGE_PL
8009 + return USAGE_EN
8010 +
8011 +
8012 +# =============================================================================
8013 +# EASTER EGG: PAG WROOM – wyścigi ASCII w stylu Commodore
8014 +# -----------------------------------------------------------------------------
8015 +
8016 +def cmd_wroom():
8017 + """Ukryta gra: `pag wroom`.
8018 +
8019 + Animowany top-down wyścig w ASCII: trzy pasy, ruszający się tor, przeciwnicy,
8020 + punkty, ETA niepotrzebne – liczy się rekord. Sterowanie strzałkami (lub
8021 + WSAD), P pauza, Q wyjście. Gra działa tylko na terminalu; poza TTY wypisuje
8022 + krótką podpowiedź, a po wyjściu przywraca ekran i ustawienia terminala.
8023 + """
8024 + if not (sys.stdin.isatty() and sys.stdout.isatty()):
8025 + print(_('wroom_terminal'))
8026 + return 1
8027 + if os.environ.get("TERM", "") == "dumb":
8028 + print(_('wroom_terminal'))
8029 + return 1
8030 + try:
8031 + import random
8032 + import select
8033 + import termios
8034 + import tty
8035 + except ImportError:
8036 + print(_('wroom_terminal'))
8037 + return 1
8038 +
8039 + ANSI_RE = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]")
8040 +
8041 + def _vlen(text):
8042 + return len(ANSI_RE.sub("", text))
8043 +
8044 + def _vcut(text, width):
8045 + """Przytnij linię do `width` WIDOCZNYCH kolumn (nie licząc ANSI)."""
8046 + if _vlen(text) <= width:
8047 + return text
8048 + out, vis, i = [], 0, 0
8049 + while i < len(text) and vis < width:
8050 + m = ANSI_RE.match(text, i)
8051 + if m:
8052 + out.append(m.group(0))
8053 + i = m.end()
8054 + continue
8055 + out.append(text[i])
8056 + vis += 1
8057 + i += 1
8058 + return "".join(out)
8059 +
8060 + def _center(text, width):
8061 + v = _vlen(text)
8062 + if v >= width:
8063 + return _vcut(text, width)
8064 + pad = width - v
8065 + return " " * (pad // 2) + text + " " * (pad - pad // 2)
8066 +
8067 + # --- geometria toru i sprite'y (każdy znak = 1 kolumna) -------------------
8068 + SPR_ROOF = " ▄█▄ "
8069 + SPR_BODY = "▐███▌"
8070 + LANE_W = 8
8071 + N_LANES = 3
8072 + ROAD_W = LANE_W * N_LANES + 2
8073 + MIN_W, MIN_H = 56, 16
8074 +
8075 + GLYPHS = {
8076 + "P": ("████ ", "█ █", "████ ", "█ ", "█ "),
8077 + "A": (" ███ ", "█ █", "█████", "█ █", "█ █"),
8078 + "G": (" ████", "█ ", "█ ██", "█ █", " ████"),
8079 + "W": ("█ █", "█ █", "█ █ █", "██ ██", "█ █"),
8080 + "R": ("████ ", "█ █", "████ ", "█ █ ", "█ █ "),
8081 + "O": (" ███ ", "█ █", "█ █", "█ █", " ███ "),
8082 + "M": ("█ █", "██ ██", "█ █ █", "█ █", "█ █"),
8083 + }
8084 +
8085 + def _logo():
8086 + rows = []
8087 + for r in range(5):
8088 + line = ""
8089 + for ch in "PAG WROOM":
8090 + if ch == " ":
8091 + line += " "
8092 + else:
8093 + line += GLYPHS[ch][r] + " "
8094 + rows.append(line.rstrip())
8095 + return rows
8096 +
8097 + LOGO = _logo()
8098 +
8099 + state = {
8100 + "phase": "title", "best": 0, "paused": False,
8101 + "lane": 1, "x": 1.0, "speed": 90.0, "boost": 0.0,
8102 + "distance": 0.0, "lives": 3, "opponents": [],
8103 + "spawn": 0.8, "invuln": 1.0, "flash": 0.0,
8104 + "scroll": 0.0, "time": 0.0, "road_h": 12,
8105 + }
8106 +
8107 + def _new_game():
8108 + state.update(phase="play", paused=False, lane=1, x=1.0,
8109 + speed=90.0, boost=0.0, distance=0.0, lives=3,
8110 + opponents=[], spawn=0.8, invuln=1.0, flash=0.0,
8111 + scroll=0.0, time=0.0)
8112 +
8113 + # --- wejście (bez blokowania) --------------------------------------------
8114 + ARROWS = {"\x1b[D": "LEFT", "\x1b[C": "RIGHT",
8115 + "\x1b[A": "UP", "\x1b[B": "DOWN",
8116 + "\x1bOD": "LEFT", "\x1bOC": "RIGHT",
8117 + "\x1bOA": "UP", "\x1bOB": "DOWN"}
8118 + fd = sys.stdin.fileno()
8119 + pending = ""
8120 +
8121 + def _keys():
8122 + nonlocal pending
8123 + keys = []
8124 + try:
8125 + ready, _, _ = select.select([fd], [], [], 0)
8126 + if not ready:
8127 + return keys
8128 + data = pending + os.read(fd, 64).decode("utf-8", "ignore")
8129 + pending = ""
8130 + except (OSError, UnicodeDecodeError):
8131 + return keys
8132 + i = 0
8133 + while i < len(data):
8134 + if data[i] == "\x1b":
8135 + # Niekompletna sekwencja strzałki – dokończymy w następnej
8136 + # klatce. Sam ESC (bez reszty) nie wychodzi z gry: wyjściem
8137 + # jest Q, więc przypadkowy Alt/strzałka nie zabija wyścigu.
8138 + if i + 1 >= len(data):
8139 + pending = data[i:]
8140 + break
8141 + if data[i + 1] not in "[O":
8142 + i += 1
8143 + continue
8144 + if i + 2 >= len(data):
8145 + pending = data[i:]
8146 + break
8147 + seq = data[i:i + 3]
8148 + key = ARROWS.get(seq)
8149 + if key:
8150 + keys.append(key)
8151 + i += 3
8152 + continue
8153 + ch = data[i]
8154 + i += 1
8155 + if ch in "qQ":
8156 + keys.append("QUIT")
8157 + elif ch in "aA":
8158 + keys.append("LEFT")
8159 + elif ch in "dD":
8160 + keys.append("RIGHT")
8161 + elif ch in "wW":
8162 + keys.append("UP")
8163 + elif ch in "sS":
8164 + keys.append("DOWN")
8165 + elif ch in "pP":
8166 + keys.append("PAUSE")
8167 + elif ch in " \r\n rR":
8168 + keys.append("START")
8169 + return keys
8170 +
8171 + # --- rysowanie toru -------------------------------------------------------
8172 + def _paint(row, start, text, color):
8173 + cells, cols = row
8174 + for i, ch in enumerate(text):
8175 + pos = start + i
8176 + if 0 <= pos < len(cells) and ch != " ":
8177 + cells[pos] = ch
8178 + cols[pos] = color
8179 +
8180 + def _render_cells(row):
8181 + cells, cols = row
8182 + parts, i = [], 0
8183 + while i < len(cells):
8184 + j = i
8185 + while j + 1 < len(cells) and cols[j + 1] == cols[i]:
8186 + j += 1
8187 + seg = "".join(cells[i:j + 1])
8188 + parts.append(_c(cols[i], seg) if cols[i] else seg)
8189 + i = j + 1
8190 + return "".join(parts)
8191 +
8192 + def _road_row(r, phase):
8193 + cells = [" "] * ROAD_W
8194 + cols = [None] * ROAD_W
8195 + cells[0] = "║"
8196 + cols[0] = "yellow"
8197 + cells[-1] = "║"
8198 + cols[-1] = "yellow"
8199 + for sep in (LANE_W, LANE_W * 2):
8200 + if (r + phase) % 4 < 2:
8201 + cells[1 + sep] = "│"
8202 + cols[1 + sep] = "dim"
8203 + return cells, cols
8204 +
8205 + def _lane_start(pos, width):
8206 + return int(round(1 + pos * LANE_W + (LANE_W - width) / 2))
8207 +
8208 + def _play_lines(W, H):
8209 + road_h = max(6, H - 4)
8210 + rows = [_center(_c("cyan", "PAG WROOM"), W)]
8211 + hud = _('wroom_hud', arg1=(int(state["distance"])),
8212 + arg2=(int(state["speed"])), arg3=(state["lives"]))
8213 + rows.append(_center(hud, W))
8214 +
8215 + board = [_road_row(r, int(state["scroll"])) for r in range(road_h)]
8216 + for o in state["opponents"]:
8217 + base = int(round(o["y"]))
8218 + for dy, spr in ((0, SPR_ROOF), (1, SPR_BODY)):
8219 + rr = base + dy
8220 + if 0 <= rr < road_h:
8221 + _paint(board[rr], _lane_start(o["lane"], len(spr)),
8222 + spr, o["color"])
8223 +
8224 + if not (state["invuln"] > 0 and int(state["time"] * 10) % 2):
8225 + for dy, spr in ((0, SPR_ROOF), (1, SPR_BODY)):
8226 + rr = road_h - 2 + dy
8227 + _paint(board[rr], _lane_start(state["x"], len(spr)),
8228 + spr, "cyan")
8229 +
8230 + if state["flash"] > 0:
8231 + _paint(board[road_h - 2], ROAD_W // 2 - 2, "BUM!", "red")
8232 +
8233 + left = max(0, (W - ROAD_W) // 2)
8234 + right = max(0, W - ROAD_W - left)
8235 + for r in range(road_h):
8236 + rows.append(" " * left + _render_cells(board[r]) + " " * right)
8237 +
8238 + rows.append("")
8239 + rows.append(_center(_c("dim", _('wroom_controls')), W))
8240 + if state["paused"]:
8241 + rows[H // 2] = _center(_c("yellow", _('wroom_paused')), W)
8242 + return rows[:H]
8243 +
8244 + def _menu_lines(W, H, blink):
8245 + block = []
8246 + if W >= len(LOGO[0]) + 2:
8247 + block.extend(_c("cyan", ln) for ln in LOGO)
8248 + else:
8249 + block.append(_c("cyan", "P A G W R O O M"))
8250 + block.append("")
8251 + block.append(_c("dim", _('wroom_tagline')))
8252 + if H >= 18:
8253 + block.append("")
8254 + block.append(" " + _c("cyan", "▄███▄") + " " +
8255 + _c("red", "▄███▄") + " " +
8256 + _c("yellow", "▄███▄"))
8257 + if H >= 22:
8258 + block.extend(["", _c("dim", 'LOAD "WROOM",8,1'),
8259 + _c("dim", "READY."), _c("dim", "RUN")])
8260 + block.append("")
8261 + if state["phase"] == "over":
8262 + block.append(_c("red", _('wroom_over')))
8263 + block.append("")
8264 + block.append(_('wroom_score', arg1=(int(state["distance"]))))
8265 + block.append(_('wroom_best', arg1=(state["best"])))
8266 + block.append("")
8267 + block.append(_('wroom_restart'))
8268 + else:
8269 + block.append(_('wroom_controls'))
8270 + block.append("")
8271 + block.append(_c("yellow", _('wroom_press')) if blink else "")
8272 +
8273 + top = max(0, (H - len(block)) // 2)
8274 + rows = [""] * H
8275 + for i, line in enumerate(block):
8276 + if top + i < H:
8277 + rows[top + i] = _center(line, W)
8278 + return rows
8279 +
8280 + # --- fizyka i kolizje -----------------------------------------------------
8281 + def _spawn():
8282 + free = [lane for lane in range(N_LANES)
8283 + if not any(o["lane"] == lane and o["y"] < 4
8284 + for o in state["opponents"])]
8285 + if not free:
8286 + return
8287 + state["opponents"].append({
8288 + "lane": random.choice(free),
8289 + "y": -2.0,
8290 + "speed": state["speed"] * random.uniform(0.45, 0.78),
8291 + "color": random.choice(("red", "yellow", "green")),
8292 + })
8293 +
8294 + def _update(dt):
8295 + state["time"] += dt
8296 + if state["phase"] != "play" or state["paused"]:
8297 + return
8298 +
8299 + state["boost"] *= max(0.0, 1.0 - dt * 3.0)
8300 + base = 90.0 + min(120.0, state["distance"] * 0.02)
8301 + target = max(45.0, base + state["boost"])
8302 + state["speed"] += (target - state["speed"]) * min(1.0, dt * 2.0)
8303 + state["distance"] += state["speed"] * dt * 0.45
8304 + state["scroll"] += state["speed"] * dt * 0.09
8305 + state["x"] += (state["lane"] - state["x"]) * min(1.0, dt * 9.0)
8306 + if state["invuln"] > 0:
8307 + state["invuln"] = max(0.0, state["invuln"] - dt)
8308 + if state["flash"] > 0:
8309 + state["flash"] = max(0.0, state["flash"] - dt)
8310 +
8311 + state["spawn"] -= dt
8312 + if state["spawn"] <= 0:
8313 + _spawn()
8314 + state["spawn"] = max(0.45, 1.35 - state["speed"] / 320.0)
8315 +
8316 + for o in list(state["opponents"]):
8317 + o["y"] += (state["speed"] - o["speed"]) * dt * 0.06
8318 + if o["y"] > state["road_h"] + 2 or o["y"] < -4:
8319 + state["opponents"].remove(o)
8320 +
8321 + if state["invuln"] > 0:
8322 + return
8323 + player_cy = state["road_h"] - 1.0
8324 + for o in list(state["opponents"]):
8325 + if (abs((o["y"] + 1.0) - player_cy) < 1.25
8326 + and abs(o["lane"] - state["x"]) < 0.55):
8327 + state["lives"] -= 1
8328 + state["flash"] = 0.6
8329 + state["invuln"] = 1.8
8330 + state["speed"] = max(45.0, state["speed"] * 0.5)
8331 + state["boost"] = 0.0
8332 + state["opponents"].remove(o)
8333 + state["opponents"] = [x for x in state["opponents"]
8334 + if x["y"] < state["road_h"] - 5]
8335 + try:
8336 + out.write("\a")
8337 + out.flush()
8338 + except OSError:
8339 + pass
8340 + if state["lives"] <= 0:
8341 + state["phase"] = "over"
8342 + state["best"] = max(state["best"],
8343 + int(state["distance"]))
8344 + break
8345 +
8346 + # --- pętla gry ------------------------------------------------------------
8347 + old_attrs = termios.tcgetattr(fd)
8348 + out = sys.stdout
8349 + try:
8350 + tty.setcbreak(fd)
8351 + out.write("\x1b[?1049h\x1b[?25l\x1b[2J")
8352 + out.flush()
8353 + running = True
8354 + last = time.monotonic()
8355 + last_size = None
8356 + while running:
8357 + for key in _keys():
8358 + if key == "QUIT":
8359 + running = False
8360 + break
8361 + if state["phase"] in ("title", "over"):
8362 + if key == "START":
8363 + _new_game()
8364 + elif key == "PAUSE":
8365 + state["paused"] = not state["paused"]
8366 + elif state["paused"]:
8367 + continue
8368 + elif key == "LEFT":
8369 + state["lane"] = max(0, state["lane"] - 1)
8370 + elif key == "RIGHT":
8371 + state["lane"] = min(N_LANES - 1, state["lane"] + 1)
8372 + elif key == "UP":
8373 + state["boost"] = min(55.0, state["boost"] + 14.0)
8374 + elif key == "DOWN":
8375 + state["boost"] = max(-45.0, state["boost"] - 14.0)
8376 + if not running:
8377 + break
8378 +
8379 + size = shutil.get_terminal_size((80, 24))
8380 + W, H = size.columns, size.lines
8381 + if last_size != (W, H):
8382 + last_size = (W, H)
8383 + out.write("\x1b[2J")
8384 + state["road_h"] = max(6, H - 4)
8385 +
8386 + now = time.monotonic()
8387 + dt = min(0.1, max(0.0, now - last))
8388 + last = now
8389 + if W >= MIN_W and H >= MIN_H:
8390 + _update(dt)
8391 +
8392 + if W < MIN_W or H < MIN_H:
8393 + lines = [""] * H
8394 + msg = _('wroom_too_small', arg1=(MIN_W), arg2=(MIN_H))
8395 + lines[H // 2] = _center(_c("yellow", msg), W)
8396 + elif state["phase"] == "play":
8397 + lines = _play_lines(W, H)
8398 + else:
8399 + blink = int(time.monotonic() * 2) % 2 == 0
8400 + lines = _menu_lines(W, H, blink)
8401 +
8402 + buf = ["\x1b[H"]
8403 + for i, line in enumerate(lines):
8404 + buf.append(_vcut(line, W))
8405 + buf.append("\x1b[K")
8406 + if i != len(lines) - 1:
8407 + buf.append("\n")
8408 + out.write("".join(buf))
8409 + out.flush()
8410 +
8411 + spent = time.monotonic() - now
8412 + if spent < 1.0 / 20.0:
8413 + time.sleep(1.0 / 20.0 - spent)
8414 + finally:
8415 + try:
8416 + out.write("\x1b[0m\x1b[?25h\x1b[?1049l")
8417 + out.flush()
8418 + except OSError:
8419 + pass
8420 + termios.tcsetattr(fd, termios.TCSADRAIN, old_attrs)
8421 + return 0
8422 +
8423 +
8424 +def _extract_lang(outdir: str) -> int:
8425 + """Eksport wbudowanych tłumaczeń do outdir/{pl,en}.json (+ klucz "usage").
8426 +
8427 + Używane przez recepturę pakietu (pag.pag), żeby tłumaczenia jechały RAZEM
8428 + z wersją paga – po `pag install/upgrade pag` i self-update są zawsze zgodne.
8429 + """
8430 + os.makedirs(outdir, exist_ok=True)
8431 + for _code in ("pl", "en"):
8432 + _d = dict(T.get(_code, {}))
8433 + _u = globals().get(f"USAGE_{_code.upper()}", "")
8434 + if _u:
8435 + _d["usage"] = _u
8436 + _p = os.path.join(outdir, f"{_code}.json")
8437 + with open(_p, "w", encoding="utf-8") as _fh:
8438 + json.dump(_d, _fh, ensure_ascii=False, indent=2, sort_keys=True)
8439 + print(_(' ✓ {arg1} ({arg2} keys)', arg1=(_p), arg2=(len(_d))))
8440 + return 0
8441 +
8442 +
8443 +def main():
8444 + # Ukryte (używane przy budowie pakietu): eksport tłumaczeń do plików
8445 + if len(sys.argv) >= 3 and sys.argv[1] == "--lang-extract":
8446 + sys.exit(_extract_lang(sys.argv[2]))
8447 + if len(sys.argv) >= 2 and sys.argv[1] in ("--version", "-V", "version"):
8448 + print(f"pag {PAG_VERSION}")
8449 + sys.exit(0)
8450 + if len(sys.argv) == 2 and sys.argv[1] in ("--help", "-h", "help"):
8451 + print(_get_usage()); sys.exit(0)
8452 + if len(sys.argv) < 2:
8453 + print(_get_usage()); sys.exit(0)
8454 +
8455 + cmd = sys.argv[1]
8456 + args = sys.argv[2:]
8457 +
8458 + # Python bez modułu ssl = brak HTTPS w urllib. Powiedz to wprost, zamiast
8459 + # pokazywać mylące „unknown url type: https” przy każdej operacji sieciowej.
8460 + if not _ssl_ok():
8461 + print(f" ⚠ {_('ssl_broken')}", file=sys.stderr)
8462 +
8463 + # `pag repair --dry-run`: diagnostyka bez roota (nic nie zmienia).
8464 + if cmd == "repair" and "--dry-run" in args and os.geteuid() != 0:
8465 + sys.exit(cmd_repair(dry_run=True) or 0)
8466 +
8467 + # --- Komendy TYLKO DO ODCZYTU (nie wymagają roota) ---
8468 + READ_ONLY = {
8469 + "list": lambda: cmd_list("--installed" in args),
8470 + "search": lambda: cmd_search(args[0]) if args else print(_('Usage: pag search <query>')),
8471 + "info": lambda: cmd_info(args[0]) if args else print(_('Usage: pag info <pkg>')),
8472 + "files": lambda: cmd_files(args[0]) if args else print(_('Usage: pag files <pkg>')),
8473 + "verify": lambda: cmd_verify("--deep" in args),
8474 + "why": lambda: cmd_why(args[0]) if args else print(_('Usage: pag why <pkg>')),
8475 + "rdepends": lambda: cmd_rdepends(args[0]) if args else print(_('Usage: pag rdepends <pkg>')),
8476 + "stats": cmd_stats,
8477 + "pinned": cmd_pinned,
8478 + "history": cmd_history,
8479 + "repo-list": cmd_repo_list,
8480 + "key-list": cmd_key_list,
8481 + "key-trusted": cmd_key_trusted,
8482 + "flatpak": lambda: cmd_flatpak(args),
8483 + "flatpak-search": lambda: cmd_flatpak_search(args[0]) if args else print(_('Usage: pag flatpak-search <query>')),
8484 + "flatpak-list": cmd_flatpak_list,
8485 + "flatpak-info": lambda: cmd_flatpak_info(args[0]) if args else print(_('Usage: pag flatpak-info <id>')),
8486 + "deploy-list": cmd_deploy_list,
8487 + "deploy": cmd_deploy_list,
8488 + "snapshot-list": cmd_snapshot_list,
8489 + "snapshots": cmd_snapshot_list,
8490 + "snapshot-grub": cmd_snapshot_grub,
8491 + "sbom": lambda: cmd_sbom(args),
8492 + "wroom": cmd_wroom, # easter egg – działa bez roota
8493 + }
8494 +
8495 + if cmd in READ_ONLY:
8496 + sys.exit(READ_ONLY[cmd]() or 0)
8497 +
8498 + # --- `pag base` / `pag base status`: tylko odczyt (bez roota i bez locka) ---
8499 + # `pag base adopt` NIE wpada tutaj – idzie ścieżką komend zapisu (roota + lock
8500 + # pilnuje wspólna obsługa niżej), żeby transakcja była bezpieczna.
8501 + if cmd in ("base", "base-status") and not (args and args[0] in ("adopt", "register")):
8502 + sys.exit(cmd_base_status() or 0)
8503 +
8504 + # --- Smart search: `pag <nazwa-pakietu>` → repo + Flathub + sugestie ---
8505 + WRITE_CMDS = {
8506 + "install", "remove", "update", "sync", "upgrade", "clean", "download",
8507 + "autoremove", "remove-orphans", "pin", "unpin", "rollback",
8508 + "repo-add", "key-add", "key-remove", "key-trust", "key-untrust",
8509 + "self-update",
8510 + "flatpak", "flatpak-install", "flatpak-remove", "flatpak-update",
8511 + "deploy-rollback", "deploy-cleanup", "initramfs-update", "grub-update",
8512 + "snapshot-create", "snapshot-delete", "snapshot-rollback",
8513 + "base", "base-adopt", "base-register",
8514 + "repair",
8515 + }
8516 + if cmd not in WRITE_CMDS:
8517 + # Literówka komendy? (np. `pag instal steam` zamiast `pag install`) –
8518 + # zasugeruj poprawną komendę ZAMIAST wpadać w smart search (który
8519 + # potrafi wisieć na `flatpak search` aż do Ctrl-C).
8520 + _known = set(READ_ONLY) | set(WRITE_CMDS)
8521 + _known.discard("wroom") # easter egg – nie podpowiadaj go w literówkach
8522 + _close = difflib.get_close_matches(cmd, _known, n=1, cutoff=0.75)
8523 + if _close:
8524 + print(_("❌ Unknown command: '{arg1}'. Did you mean '{arg2}'?", arg1=(cmd), arg2=(_close[0])))
8525 + print(_(" Run 'pag' without arguments to see the command list."))
8526 + sys.exit(1)
8527 + sys.exit(_smart_search(" ".join([cmd] + args)) or 0)
8528 +
8529 + # Obsługa flag globalnych (-y/--yes oraz transakcji/snapshotów)
8530 + global_args = []
8531 + for a in args:
8532 + if a in ("-y", "--yes"):
8533 + os.environ["PAG_YES"] = "1"
8534 + elif a == "--dry-run":
8535 + os.environ["PAG_DRY_RUN"] = "1"
8536 + global_args.append(a) # `repair`/`base adopt` czytają flagę
8537 + elif a == "--snapshot":
8538 + os.environ["PAG_SNAPSHOT"] = "always"
8539 + elif a == "--no-snapshot":
8540 + os.environ["PAG_SNAPSHOT"] = "never"
8541 + elif a == "--atomic":
8542 + os.environ["PAG_ATOMIC"] = "1"
8543 + elif a == "--no-atomic":
8544 + os.environ["PAG_ATOMIC"] = "0"
8545 + else:
8546 + global_args.append(a)
8547 + args = global_args
8548 +
8549 + # --- Komendy ZAPISU (wymagają roota) ---
8550 + if os.geteuid() != 0:
8551 + print(f"❌ {_('root_required')}", file=sys.stderr); sys.exit(1)
8552 +
8553 + ensure_dirs()
8554 +
8555 + with DatabaseLock():
8556 + # Auto-naprawa: backup z przerwanej transakcji (bez wpisu „success")
8557 + # -> przywróć brakujące pliki, zanim cokolwiek innego zrobimy.
8558 + _recover_interrupted_transactions()
8559 + WRITE_COMMANDS = {
8560 + "install": lambda: cmd_install(
8561 + [a for a in args if a not in (
8562 + "-f", "--force", "--dry-run", "--snapshot", "--no-snapshot",
8563 + "--atomic", "--no-atomic", "--")],
8564 + upgrade=("-f" in args or "--force" in args)),
8565 + "remove": lambda: cmd_remove(args),
8566 + "update": lambda: cmd_update(do_upgrade=True),
8567 + "sync": lambda: cmd_update(do_upgrade=False),
8568 + "upgrade": cmd_upgrade,
8569 + "clean": cmd_clean,
8570 + "download": lambda: cmd_download(args),
8571 + "autoremove": cmd_autoremove,
8572 + "remove-orphans": cmd_remove_orphans,
8573 + "pin": lambda: cmd_pin(args[0], args[1] if len(args)>1 else ""),
8574 + "unpin": lambda: cmd_unpin(args[0]) if args else print(_('Usage: pag unpin <pkg>')),
8575 + "rollback": cmd_rollback,
8576 + "repair": lambda: cmd_repair(dry_run="--dry-run" in args),
8577 + "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]')),
8578 + "key-add": lambda: cmd_key_add(args[0]) if args else print(_('Usage: pag key-add <url|file>')),
8579 + "key-remove": lambda: cmd_key_remove(args[0]) if args else print(_('Usage: pag key-remove <id>')),
8580 + "key-trust": lambda: cmd_key_trust(args[0]) if args else print(_('Usage: pag key-trust <repo_url>')),
8581 + "key-untrust": lambda: cmd_key_untrust(args[0]) if args else print(_('Usage: pag key-untrust <repo_url>')),
8582 + "self-update": cmd_self_update,
8583 + "flatpak": lambda: cmd_flatpak(args),
8584 + "flatpak-install": lambda: _flatpak_smart_install(args) if args else print(_('Usage: pag flatpak-install <app>')),
8585 + "flatpak-remove": lambda: _flatpak_smart_remove(args) if args else print(_('Usage: pag flatpak-remove <app>')),
8586 + "flatpak-update": cmd_flatpak_update,
8587 + "deploy-rollback": cmd_deploy_rollback,
8588 + "deploy-cleanup": lambda: cmd_deploy_cleanup(int(args[0]) if args else 3),
8589 + "snapshot-create": lambda: cmd_snapshot_create(" ".join(
8590 + a for a in args if not a.startswith("-"))),
8591 + "snapshot-delete": lambda: cmd_snapshot_delete(args[0]) if args else print(
8592 + _('Usage: pag snapshot-delete <id>')),
8593 + "snapshot-rollback": lambda: cmd_snapshot_rollback(
8594 + args[0] if args else ""),
8595 + "initramfs-update": cmd_initramfs_update,
8596 + "grub-update": cmd_grub_update,
8597 + "base": lambda: cmd_base_register(args) if (args and args[0] == "register") else cmd_base_adopt(args),
8598 + "base-adopt": lambda: cmd_base_adopt(args),
8599 + "base-register": lambda: cmd_base_register(args),
8600 + }
8601 +
8602 + fn = WRITE_COMMANDS.get(cmd)
8603 + if fn:
8604 + sys.exit(fn() or 0)
8605 + # Should never reach here – _smart_search handles unknowns
8606 + sys.exit(_smart_search(" ".join([cmd] + args)) or 0)
8607 +
8608 +if __name__ == "__main__":
8609 + try:
8610 + main()
8611 + except KeyboardInterrupt:
8612 + # Ctrl-C (np. podczas flatpak search / pobierania) – bez tracebacka
8613 + print(_('\n ⚠ Interrupted (Ctrl-C).'))
8614 8614 sys.exit(130)