Commit e466287
0
plików
+0
dodanych
-0
usuniętych
@@ -1,4779 +1,4878 @@
1
-#!/usr/bin/env python3
2
-"""
3
-╔══════════════════════════════════════════════════════════════════════════════╗
4
-║ PAG - Pagan Linux Package Manager v3.3.15 ║
5
-║ Produkcyjny menedżer pakietów – atomowy, bezpieczny, i18n ║
6
-╚══════════════════════════════════════════════════════════════════════════════╝
7
-
8
-KLUCZOWE CECHY:
9
- - Atomowa instalacja przez staging (tmpdir → rename) – brak pół-instalacji
10
- - Bezpieczne usuwanie – sprawdza czy plik nie jest współdzielony
11
- - SQLite dla bazy plików – miliony plików bez problemu
12
- - GPG: weryfikacja repo.json + podpisy pakietów + pinning fingerprintu
13
- - Hooki: pre/post-install, pre/post-remove (piaskownica env, timeout, audit)
14
- - Głęboka weryfikacja SHA256 per-plik
15
- - Pełny rollback – cofa fizyczne pliki
16
- - Blokada flock – tylko jedna instancja
17
- - Transakcje z migawkami + rejestr wykonanych hooków
18
- - Cache HTTP (ETag/If-Modified-Since)
19
- - Wielojęzyczność (i18n) – PL, EN
20
-
21
-FORMAT PAKIETU (.pag):
22
- ├── data.tar.xz – pliki + sums.json (SHA256 per plik)
23
- ├── metadata.json – nazwa, wersja, zależności
24
- └── hooks/ – pre-install, post-install, pre-remove, post-remove
25
-
26
-MODEL ZAUFANIA / BEZPIECZEŃSTWO:
27
- - Repozytorium MUSI być zaufane: podpisy GPG zweryfikowane; fingerprint
28
- klucza przypiętego do repo (TOFU przy pierwszym użyciu, potem pinning).
29
- - Hooki uruchamiają dowolny plik z pakietu jako ROOT (jak apt/pacman).
30
- Ograniczamy je (czyste env, timeout, PAG_NO_HOOKS=1, log do
31
- /var/log/pag/audit.log) i rejestrujemy w transakcji, ale ostatecznie
32
- instalujesz kod, któremu ufasz.
33
- - self-update: weryfikacja podpisu + SHA256 + składnia, atomowa podmiana.
34
-"""
35
-
36
-import os, sys, json, shutil, hashlib, tarfile, tempfile, subprocess, time, fcntl, sqlite3, locale, re, difflib
37
-
38
-# Fix TLS trust inside the Pagan chroot: point Python at the CA bundle that
39
-# pag ships, otherwise urlopen() fails with "unable to get local issuer
40
-# certificate" (no default capath/cafile is resolved in the chroot).
41
-for _cafile in (
42
- "/etc/ssl/certs/ca-certificates.crt",
43
- "/etc/ssl/cert.pem",
44
-):
45
- if os.path.isfile(_cafile):
46
- os.environ["SSL_CERT_FILE"] = _cafile
47
- break
48
-
49
-from pathlib import Path
50
-from datetime import datetime, timezone
51
-from typing import Dict, List, Optional, Tuple, Set
52
-from concurrent.futures import ThreadPoolExecutor, as_completed
53
-from urllib.request import urlopen, Request
54
-import threading, itertools
55
-import uuid # serialNumber SBOM (CycloneDX)
56
-
57
-# Wersja klienta – do porównania z repo.json["pag_version"] (self-update)
58
-PAG_VERSION = "3.3.15"
59
-from urllib.error import URLError, HTTPError
60
-
61
-# =============================================================================
62
-# ProgressBar — minimalistyczny pasek postępu (bez zewnętrznych zależności)
63
-# =============================================================================
64
-
65
-class ProgressBar:
66
- """Czysty Python progress bar — działa z TTY i bez."""
67
- def __init__(self, total: int, desc: str = "", unit: str = "", width: int = 30):
68
- self.total = max(total, 1)
69
- self.desc = desc
70
- self.unit = unit
71
- self.width = width
72
- self.n = 0
73
- self.start = time.time()
74
- self.tty = sys.stderr.isatty()
75
- self._last_line_len = 0
76
-
77
- def update(self, n: Optional[int] = None, suffix: str = ""):
78
- if n is not None:
79
- self.n = n
80
- else:
81
- self.n += 1
82
- pct = self.n / self.total * 100
83
- elapsed = time.time() - self.start
84
- speed = self.n / elapsed if elapsed > 0 else 0
85
- if self.n >= self.total:
86
- eta_str = "done"
87
- elif speed > 0:
88
- eta = (self.total - self.n) / speed
89
- eta_str = f"{eta:.0f}s" if eta < 60 else f"{eta/60:.1f}m"
90
- else:
91
- eta_str = "?..."
92
- bar_len = int(self.width * pct / 100)
93
- bar = "█" * bar_len + "░" * (self.width - bar_len)
94
- line = f" {self.desc} [{bar}] {self.n}/{self.total} ({pct:.0f}%) ETA {eta_str}{suffix}"
95
- if self.tty:
96
- # Overwrite current line
97
- clear = " " * max(0, self._last_line_len - len(line))
98
- print(f"\r{line}{clear}", end="", file=sys.stderr, flush=True)
99
- self._last_line_len = len(line)
100
- else:
101
- # Print milestone lines only (every 10% or when done)
102
- if self.n == 1 or self.n >= self.total or self.n % max(1, self.total // 10) == 0:
103
- print(line, file=sys.stderr)
104
-
105
- def close(self):
106
- if self.tty:
107
- print(file=sys.stderr)
108
- self._last_line_len = 0
109
-
110
- def __enter__(self):
111
- return self
112
-
113
- def __exit__(self, *args):
114
- self.close()
115
-
116
-
117
-class DownloadBar:
118
- """Pasek postępu pobierania — na podstawie Content-Length."""
119
- def __init__(self, filename: str, total_bytes: int):
120
- self.filename = filename
121
- self.total = total_bytes
122
- self.downloaded = 0
123
- self.start = time.time()
124
- self.tty = sys.stderr.isatty()
125
- self._last_len = 0
126
-
127
- def update(self, chunk_size: int):
128
- self.downloaded += chunk_size
129
- if self.total <= 0:
130
- return
131
- pct = self.downloaded / self.total * 100
132
- elapsed = time.time() - self.start
133
- speed = self.downloaded / elapsed if elapsed > 0 else 0
134
- if speed > 0:
135
- eta = (self.total - self.downloaded) / speed
136
- eta_str = f"{eta:.0f}s" if eta < 60 else f"{eta/60:.1f}m"
137
- else:
138
- eta_str = "?..."
139
- bar_len = 25
140
- filled = int(bar_len * pct / 100)
141
- bar = "█" * filled + "░" * (bar_len - filled)
142
- sz = self._fmt_size(self.total)
143
- spd = self._fmt_size(int(speed))
144
- line = f" ↓ {self.filename} [{bar}] {pct:.0f}% {sz} {spd}/s ETA {eta_str}"
145
- if self.tty:
146
- clear = " " * max(0, self._last_len - len(line))
147
- print(f"\r{line}{clear}", end="", file=sys.stderr, flush=True)
148
- self._last_len = len(line)
149
-
150
- def close(self):
151
- if self.tty and self.total > 0:
152
- print(file=sys.stderr)
153
-
154
- @staticmethod
155
- def _fmt_size(n: int) -> str:
156
- for unit in ("B", "KB", "MB", "GB"):
157
- if n < 1024:
158
- return f"{n:.1f} {unit}"
159
- n /= 1024
160
- return f"{n:.1f} TB"
161
-
162
-# =============================================================================
163
-# GPG – BEZPIECZNE WYWOŁYWANIE (odporne na brak binarki gpg)
164
-# =============================================================================
165
-
166
-GPG_BINARY = shutil.which("gpg2") or shutil.which("gpg") or "gpg"
167
-GPG_HOME = "/etc/pag/gpg" # izolowany keyring (działa z keyboxd GPG 2.4+)
168
-
169
-def _gpg_run(*args, timeout: int = 30, **kwargs) -> subprocess.CompletedProcess:
170
- """
171
- Bezpieczne wywołanie GPG – przechwytuje FileNotFoundError,
172
- gdyby gpg/gpg2 nie było zainstalowane w minimalnym środowisku.
173
- Wymusza LC_ALL=C aby komunikaty GPG były zawsze po angielsku
174
- (niezależnie od locale systemu) – kluczowe dla parsowania stderr.
175
- """
176
- env = kwargs.pop("env", None) or os.environ.copy()
177
- env["LC_ALL"] = "C"
178
- env["GNUPGHOME"] = GPG_HOME
179
- try:
180
- return subprocess.run([GPG_BINARY, *args], timeout=timeout, env=env, **kwargs)
181
- except FileNotFoundError:
182
- # GPG nie jest dostępne – zwróć błąd z komunikatem
183
- # (szanuj text=True – inaczej caller dostaje bytes i może wybuchnąć TypeError)
184
- _text = bool(kwargs.get("text") or kwargs.get("universal_newlines"))
185
- _msg = f"GPG binary not found ({GPG_BINARY})"
186
- return subprocess.CompletedProcess(
187
- [GPG_BINARY, *args], 127,
188
- stdout=("" if _text else b""),
189
- stderr=(_msg if _text else _msg.encode()),
190
- )
191
- except subprocess.TimeoutExpired:
192
- return subprocess.CompletedProcess(
193
- [GPG_BINARY, *args], 124,
194
- stdout=b"", stderr=b"GPG operation timed out"
195
- )
196
-
197
-def _load_trust_db() -> dict:
198
- """Mapa repo_url → fingerprint klucza podpisującego (baza zaufania)."""
199
- try:
200
- with open(TRUST_DB) as f:
201
- return json.load(f)
202
- except (FileNotFoundError, json.JSONDecodeError):
203
- return {}
204
-
205
-
206
-def _save_trust_db(db: dict):
207
- os.makedirs(os.path.dirname(TRUST_DB), exist_ok=True)
208
- with open(TRUST_DB, "w") as f:
209
- json.dump(db, f, indent=2)
210
-
211
-
212
-def _gpg_verify_fp(sig_path: str, data_path: str, timeout: int = 30):
213
- """Weryfikuje podpis i odczytuje fingerprint podpisującego.
214
-
215
- Używa --status-fd=1 i linii VALIDSIG <fingerprint>. Zwraca (ok, fingerprint).
216
- """
217
- env = os.environ.copy()
218
- res = _gpg_run("--verify", "--status-fd", "1", sig_path, data_path,
219
- capture_output=True, text=True, timeout=timeout, env=env)
220
- if res.returncode != 0:
221
- return False, None
222
- m = re.search(r"\[GNUPG:\]\s+VALIDSIG\s+([0-9A-Fa-f]+)", res.stdout or "")
223
- if not m:
224
- m = re.search(r"VALIDSIG\s+([0-9A-Fa-f]{16,})", res.stdout or "")
225
- return True, (m.group(1).upper() if m else None)
226
-
227
-
228
-# =============================================================================
229
-# i18n – WIELOJĘZYCZNOŚĆ
230
-# =============================================================================
231
-
232
-LANG = os.environ.get("LANG", "en_US.UTF-8")[:2] # pl, en, de...
233
-COLOR = os.environ.get("NO_COLOR", "") == "" and sys.stdout.isatty()
234
-
235
-def _c(code: str, text: str) -> str:
236
- """Dodaje kody ANSI jeśli kolor jest włączony."""
237
- if not COLOR:
238
- return text
239
- colors = {
240
- "green": "\033[32m", "red": "\033[31m", "yellow": "\033[33m",
241
- "cyan": "\033[36m", "bold": "\033[1m", "dim": "\033[2m",
242
- "reset": "\033[0m",
243
- }
244
- return f"{colors.get(code,'')}{text}{colors['reset']}"
245
-
246
-T = {
247
- "en": {
248
- "root_required": "pag requires root privileges (sudo).",
249
- "db_locked": "Another pag instance is running.",
250
- "db_lock_hint": "If no other pag process is running, wait a moment and retry.",
251
- "no_index": "Cannot fetch repository indexes. Run 'pag update'.",
252
- "all_installed": "All packages are already installed.",
253
- "to_install": "To install: {} packages ({:.2f} MB)",
254
- "new": "NEW",
255
- "continue_q": "Continue? [Y/n] ",
256
- "no_tty": "No TTY / stdin closed (EOF) – cancelling.",
257
- "cancelled": "Cancelled.",
258
- "not_found": "not found in repos",
259
- "pkg_not_found": "Package not found: {} (not in any repo)",
260
- "not_found_hint": "Check the spelling or run 'pag search <query>'.",
261
- "downloading": "Downloading",
262
- "download_fail": "download failed",
263
- "gpg_fail": "GPG verification failed",
264
- "sha256_mismatch": "SHA256 mismatch",
265
- "installed": "Installed {} packages.",
266
- "rollback_restored": "Restored previous state from snapshot.",
267
- "rollback_files": "Rolled back {} files.",
268
- "no_history": "No transaction history.",
269
- "pinned_list": "Pinned packages ({}):",
270
- "no_pinned": "No pinned packages.",
271
- "pinned_to": "pinned to",
272
- "unpinned": "unpinned.",
273
- "not_pinned": "was not pinned.",
274
- "repo_added": "Added repository: {}",
275
- "repo_exists": "Repository already exists: {}",
276
- "updated_done": "Index refresh complete. {} packages cached.",
277
- "indexes_refreshed": "Indexes refreshed.",
278
- "updates_available": "⚠ {} packages have updates – run: pag update",
279
- "upgrading": "Upgrading: {} packages",
280
- "all_up_to_date": "All packages are up to date.",
281
- "removing": "Removing",
282
- "orphans_found": "Orphaned dependencies ({}): {}",
283
- "flatpak_missing": "Flatpak is not installed.",
284
- "flatpak_adding": "Adding Flathub remote...",
285
- "flatpak_searching": "Searching Flathub for '{}'...",
286
- "flatpak_found": "Found {} results:",
287
- "flatpak_not_found": "not found on Flathub",
288
- "flatpak_install_prompt": "Install {}? [Y/n] ",
289
- "flatpak_installing": "Installing {}...",
290
- "flatpak_installed": "Flatpak {} installed.",
291
- "flatpak_removed": "Flatpak {} removed.",
292
- "flatpak_not_installed": "Flatpak {} is not installed.",
293
- "flatpak_info_id": "ID",
294
- "flatpak_info_version": "Version",
295
- "flatpak_info_branch": "Branch",
296
- "flatpak_info_origin": "Origin",
297
- "flatpak_info_size": "Installed size",
298
- "flatpak_info_desc": "Description",
299
- "flatpak_updated": "Flatpaks updated.",
300
- "flatpak_usage": "Usage: pag flatpak <search|install|remove|list|update|info> [args]",
301
- "key_imported": "Key imported successfully.",
302
- "key_removed": "Key removed: {}",
303
- "no_keys": "No trusted GPG keys.",
304
- "verify_ok": "All {} files intact.",
305
- "verify_errors": "{} problems found:",
306
- "cache_cleared": "{} files ({:.2f} MB) cleared from cache.",
307
- "deployments_list": "Deployments ({}):",
308
- "no_deployments": "No deployments.",
309
- "active_deployment": "ACTIVE",
310
- "deploy_rollback_ok": "Switched to deployment: {}",
311
- "deploy_rollback_fail": "No previous deployment.",
312
- "deploy_cleanup_ok": "Removed {} old deployments.",
313
- "deploy_cleanup_none": "No deployments to clean (minimum {}).",
314
- "why_explicit": "explicitly installed",
315
- "why_dependency": "dependency of",
316
- "why_not_installed": "not installed",
317
- "autoremove_ok": "Removed {} orphaned packages.",
318
- "autoremove_none": "No orphaned packages.",
319
- "downloaded": "Downloaded {} to cache ({:.2f} MB).",
320
- "provides_mapped": "{} → {} (provides)",
321
- "stats_title": "PAG Statistics",
322
- "stats_packages": "Installed packages",
323
- "stats_files": "Tracked files",
324
- "stats_size": "Total size",
325
- "stats_cache": "Cache size",
326
- "stats_history": "Transactions",
327
- "stats_last_update": "Last update",
328
- },
329
- "pl": {
330
- "root_required": "pag wymaga uprawnień root (sudo).",
331
- "db_locked": "Inna instancja pag jest uruchomiona.",
332
- "db_lock_hint": "Jeśli żaden inny proces pag nie działa, poczekaj chwilę i spróbuj ponownie.",
333
- "no_index": "Nie można pobrać indeksów repozytoriów. Uruchom 'pag update'.",
334
- "all_installed": "Wszystkie pakiety są już zainstalowane.",
335
- "to_install": "Do zainstalowania: {} pakietów ({:.2f} MB)",
336
- "new": "NOWY",
337
- "continue_q": "Kontynuować? [T/n] ",
338
- "no_tty": "Brak terminala (EOF) – anuluję.",
339
- "cancelled": "Anulowano.",
340
- "not_found": "brak w repozytoriach",
341
- "pkg_not_found": "Nie znaleziono pakietu: {} (brak w repozytoriach)",
342
- "not_found_hint": "Sprawdź pisownię lub uruchom 'pag search <fraza>'.",
343
- "downloading": "Pobieranie",
344
- "download_fail": "błąd pobierania",
345
- "gpg_fail": "błąd weryfikacji GPG",
346
- "sha256_mismatch": "niezgodność SHA256",
347
- "installed": "Zainstalowano {} pakietów.",
348
- "rollback_restored": "Przywrócono poprzedni stan z migawki.",
349
- "rollback_files": "Wycofano {} plików.",
350
- "no_history": "Brak historii transakcji.",
351
- "pinned_list": "Przypięte pakiety ({}):",
352
- "no_pinned": "Brak przypiętych pakietów.",
353
- "pinned_to": "przypięty do",
354
- "unpinned": "odpięty.",
355
- "not_pinned": "nie był przypięty.",
356
- "repo_added": "Dodano repozytorium: {}",
357
- "repo_exists": "Repozytorium już istnieje: {}",
358
- "updated_done": "Odświeżanie zakończone. {} pakietów w cache.",
359
- "indexes_refreshed": "Indeksy odświeżone.",
360
- "updates_available": "⚠ jest {} pakietów do zaktualizowania – wpisz: pag update",
361
- "upgrading": "Aktualizacje: {} pakietów",
362
- "all_up_to_date": "Wszystkie pakiety są aktualne.",
363
- "removing": "Usuwanie",
364
- "orphans_found": "Osierocone zależności ({}): {}",
365
- "flatpak_missing": "Flatpak nie jest zainstalowany.",
366
- "flatpak_adding": "Dodaję zdalne repozytorium Flathub...",
367
- "flatpak_searching": "Szukam '{}' we Flathub...",
368
- "flatpak_found": "Znaleziono {} wyników:",
369
- "flatpak_not_found": "nie znaleziono we Flathub",
370
- "flatpak_install_prompt": "Zainstalować {}? [T/n] ",
371
- "flatpak_installing": "Instalowanie {}...",
372
- "flatpak_installed": "Flatpak {} zainstalowany.",
373
- "flatpak_removed": "Flatpak {} usunięty.",
374
- "flatpak_not_installed": "Flatpak {} nie jest zainstalowany.",
375
- "flatpak_info_id": "ID",
376
- "flatpak_info_version": "Wersja",
377
- "flatpak_info_branch": "Gałąź",
378
- "flatpak_info_origin": "Źródło",
379
- "flatpak_info_size": "Rozmiar",
380
- "flatpak_info_desc": "Opis",
381
- "flatpak_updated": "Flapaki zaktualizowane.",
382
- "flatpak_usage": "Użycie: pag flatpak <search|install|remove|list|update|info> [args]",
383
- "key_imported": "Klucz zaimportowany pomyślnie.",
384
- "key_removed": "Klucz usunięty: {}",
385
- "no_keys": "Brak zaufanych kluczy GPG.",
386
- "verify_ok": "Wszystkie {} plików sprawne.",
387
- "verify_errors": "Znaleziono {} problemów:",
388
- "cache_cleared": "{} plików ({:.2f} MB) usuniętych z cache.",
389
- "deployments_list": "Deploymenty ({}):",
390
- "no_deployments": "Brak deploymentów.",
391
- "active_deployment": "AKTYWNY",
392
- "deploy_rollback_ok": "Przełączono na deployment: {}",
393
- "deploy_rollback_fail": "Brak poprzedniego deploymentu.",
394
- "deploy_cleanup_ok": "Usunięto {} starych deploymentów.",
395
- "deploy_cleanup_none": "Nie ma deploymentów do wyczyszczenia (minimum {}).",
396
- "why_explicit": "zainstalowany jawnie",
397
- "why_dependency": "zależność od",
398
- "why_not_installed": "niezainstalowany",
399
- "autoremove_ok": "Usunięto {} osieroconych pakietów.",
400
- "autoremove_none": "Brak osieroconych pakietów.",
401
- "downloaded": "Pobrano {} do cache ({:.2f} MB).",
402
- "sec_downgrade": "Downgrade blocked: {pkg} {new} < {old}",
403
- "sec_suid": "SUID stripped from {path}",
404
- "sec_https": "HTTPS required for repos",
405
- "sec_badname": "Invalid package name: {name}",
406
- "sec_toobig": "Package too large: {size_mb}MB > {max_mb}MB",
407
- "sec_conflict": "File conflict: {path} owned by {owner}",
408
- "sec_audit": "{pkg} installed by {user}",
409
- "sec_locked": "Another pag process is running",
410
- "sec_downgrade_pl": "Blokada downgrade: {pkg} {new} < {old}",
411
- "sec_suid_pl": "SUID usuniety z {path}",
412
- "sec_https_pl": "Repozytorium wymaga HTTPS",
413
- "sec_badname_pl": "Nieprawidlowa nazwa pakietu: {name}",
414
- "sec_toobig_pl": "Paczka za duza: {size_mb}MB > {max_mb}MB",
415
- "sec_conflict_pl": "Konflikt plikow: {path} nalezy do {owner}",
416
- "sec_audit_pl": "{pkg} zainstalowany przez {user}",
417
- "sec_locked_pl": "Inny proces pag juz dziala",
418
-
419
- "provides_mapped": "{} → {} (provides)",
420
- "stats_title": "Statystyki PAG",
421
- "stats_packages": "Zainstalowane pakiety",
422
- "stats_files": "Śledzone pliki",
423
- "stats_size": "Całkowity rozmiar",
424
- "stats_cache": "Rozmiar cache",
425
- "stats_history": "Transakcje",
426
- "stats_last_update": "Ostatnia aktualizacja",
427
- },
428
-}
429
-
430
-def _(key: str, *args, **kwargs) -> str:
431
- """Tłumaczy klucz i formatuje argumenty."""
432
- msg = T.get(LANG, T["en"]).get(key, T["en"].get(key, key))
433
- if args or kwargs:
434
- return msg.format(*args, **kwargs)
435
- return msg
436
-
437
-
438
-def _ask_confirm() -> bool:
439
- """Pytanie potwierdzające (T/n). PAG_YES=1 → zawsze tak.
440
-
441
- EOF/brak terminala (stdin zamknięty, np. ssh bez TTY, cron, subprocess
442
- panelu webowego) → NIE – anuluj, nie wykonuj operacji bez potwierdzenia
443
- (inaczej input() rzuca EOFError i pag pada tracebackiem).
444
- Enter → tak (domyślne Y/n).
445
- """
446
- if os.environ.get("PAG_YES", "") == "1":
447
- print(_("continue_q") + " t (--yes)")
448
- return True
449
- try:
450
- ans = input(_("continue_q")).strip().lower()
451
- except (EOFError, KeyboardInterrupt):
452
- print(f"\n ⚠ {_('no_tty')}")
453
- return False
454
- return not ans or ans in ("t", "y")
455
-
456
-
457
-# =============================================================================
458
-# ŚCIEŻKI
459
-# =============================================================================
460
-PAG_ROOT = os.environ.get("PAG_ROOT", "/")
461
-PAG_DB = "/var/lib/pag"
462
-PAG_CACHE = "/var/cache/pag"
463
-PAG_CONF = "/etc/pag"
464
-REPO_CACHE = "/var/cache/pag/repos"
465
-REPOS_CONF = "/etc/pag/repos.conf"
466
-REPOS_DIR = PAG_CONF + "/repos" # drop-in: /etc/pag/repos/<nazwa>.conf
467
-INSTALLED_DB = "/var/lib/pag/installed.json"
468
-FILES_DB_SQL = "/var/lib/pag/files.db" # SQLite!
469
-WORLD_FILE = "/var/lib/pag/world"
470
-PINNED_FILE = "/var/lib/pag/pinned.json"
471
-HISTORY_FILE = "/var/lib/pag/history.json"
472
-LOCK_FILE = "/var/lib/pag/pag.lock"
473
-STAGING_DIR = "/.pag_staging" # na tej samej partycji co / (unikamy EXDEV)
474
-PKG_EXT = ".pag"
475
-REPO_CACHE_TTL = 3600
476
-MAX_PKG_SIZE = 2 * 1024 * 1024 * 1024 # 2 GB – maksymalny rozmiar paczki
477
-ALLOWED_PKG_RE = re.compile(r'^[a-zA-Z0-9][a-zA-Z0-9._+@-]*$')
478
-
479
-# Bezpieczeństwo / audyt
480
-AUDIT_LOG = "/var/log/pag/audit.log" # dziennik operacji krytycznych (hooki, self-update)
481
-TRUST_DB = "/etc/pag/trusted.json" # mapa repo_url → fingerprint klucza podpisującego
482
-HOOK_API_VERSION = "1" # wersjonowane API hooków (env PKG_HOOK_API)
483
-
484
-# =============================================================================
485
-# IMMUTABLE OS – DEPLOYMENTY
486
-# =============================================================================
487
-# Model: zamiast mutować /, każda operacja tworzy NOWY deployment.
488
-# /var, /etc, /home są współdzielone między deploymentami.
489
-#
490
-# STRUKTURA:
491
-# /.deployments/
492
-# active → 20260723T120000 (symlink do aktywnego)
493
-# 20260723T120000/
494
-# usr/ bin/ lib/ lib64/ ... (pełny system)
495
-# var → /var (symlink do współdzielonego)
496
-# etc → /etc
497
-# home → /home
498
-# ...
499
-#
500
-# Jak to działa:
501
-# 1. pag install → kopiuje active → nowy deployment + nakłada zmiany → switch symlinka
502
-# 2. pag remove → kopiuje active → nowy deployment - usuwa pliki → switch symlinka
503
-# 3. pag deploy-rollback → przełącza active symlink na poprzedni deployment
504
-# 4. Przy starcie systemu: initrd montuje /.deployments/active jako /
505
-# =============================================================================
506
-
507
-DEPLOYMENTS_DIR = "/.deployments"
508
-ACTIVE_LINK = "/.deployments/active"
509
-DEPLOYMENTS_DB = "/var/lib/pag/deployments.json"
510
-
511
-# Ścieżki współdzielone – NIE wchodzą do deploymentu (są symlinkami do /...)
512
-SHARED_PATHS = {
513
- "/var", "/etc", "/home", "/root", "/tmp", "/run",
514
- "/dev", "/proc", "/sys", "/mnt", "/media", "/srv",
515
- "/.deployments", "/.pag_staging",
516
-}
517
-
518
-def _is_shared_path(rel: str) -> bool:
519
- """Sprawdza czy ścieżka należy do katalogów współdzielonych (poza deploymentem)."""
520
- for sp in SHARED_PATHS:
521
- if rel == sp or rel.startswith(sp + "/"):
522
- return True
523
- return False
524
-
525
-def _get_deployment_root() -> str:
526
- """Zwraca ścieżkę do aktywnego deploymentu, lub PAG_ROOT jeśli tryb niemutowalny wyłączony."""
527
- if os.environ.get("PAG_IMMUTABLE", "") in ("0", "no", "false", ""):
528
- return PAG_ROOT
529
- if os.path.islink(ACTIVE_LINK):
530
- return os.readlink(ACTIVE_LINK)
531
- if os.path.isdir(ACTIVE_LINK):
532
- return ACTIVE_LINK
533
- # Brak deploymentów – użyj /
534
- return PAG_ROOT
535
-
536
-def _load_deployments() -> List[dict]:
537
- """Wczytuje historię deploymentów."""
538
- if not os.path.exists(DEPLOYMENTS_DB):
539
- return []
540
- try:
541
- return json.load(open(DEPLOYMENTS_DB))
542
- except Exception:
543
- return []
544
-
545
-def _save_deployments(deployments: List[dict]):
546
- os.makedirs(os.path.dirname(DEPLOYMENTS_DB), exist_ok=True)
547
- json.dump(deployments, open(DEPLOYMENTS_DB, "w"), indent=2)
548
-
549
-def _create_deployment(pkg_names: List[str], action: str) -> Tuple[str, str]:
550
- """
551
- Tworzy nowy deployment przez skopiowanie aktywnego (CoW) i zwraca jego ścieżkę.
552
- Zwraca (deployment_dir, deployment_id).
553
- """
554
- deploy_id = datetime.now().strftime("%Y%m%dT%H%M%S")
555
- deploy_dir = os.path.join(DEPLOYMENTS_DIR, deploy_id)
556
- os.makedirs(DEPLOYMENTS_DIR, exist_ok=True)
557
-
558
- active = _get_deployment_root()
559
-
560
- if os.path.isdir(active) and active != PAG_ROOT:
561
- # Trójstopniowa strategia kopiowania deploymentu:
562
- # 1. reflink (CoW – btrfs, xfs) → 0 MB kopiowane
563
- # 2. hardlink (linki twarde) → 0 MB kopiowane, tylko inody
564
- # 3. zwykłe cp (ostateczność) → pełna kopia
565
- print(f" ⚡ Kopiowanie aktywnego deploymentu...")
566
- copied = False
567
- for method, cmd, label in [
568
- ("reflink", ["cp", "--reflink=auto", "-a", active + "/.", deploy_dir + "/"], "CoW (reflink)"),
569
- ("hardlink", ["cp", "-al", active + "/.", deploy_dir + "/"], "hardlinki"),
570
- ("copy", ["cp", "-a", active + "/.", deploy_dir + "/"], "pełna kopia"),
571
- ]:
572
- try:
573
- subprocess.run(cmd, check=True, timeout=600, capture_output=True)
574
- print(f" ✅ Deployment: {deploy_id} ({label})")
575
- copied = True
576
- break
577
- except subprocess.CalledProcessError:
578
- if method == "copy":
579
- raise # ostatnia deska – niech leci wyjątek
580
- continue
581
- if not copied:
582
- raise RuntimeError("Nie udało się skopiować deploymentu żadną metodą")
583
- else:
584
- # Pierwszy deployment – tylko katalogi szkieletowe
585
- for d in ["/usr", "/lib", "/lib64", "/bin", "/sbin", "/boot", "/opt"]:
586
- if os.path.isdir(d):
587
- dest = os.path.join(deploy_dir, d.lstrip("/"))
588
- os.makedirs(dest, exist_ok=True)
589
- print(f" ✅ Pierwszy deployment: {deploy_id}")
590
-
591
- # Utwórz symlinki do współdzielonych katalogów
592
- for sp in SHARED_PATHS:
593
- link_dst = os.path.join(deploy_dir, sp.lstrip("/"))
594
- if not os.path.lexists(link_dst) and os.path.isdir(sp):
595
- os.symlink(sp, link_dst)
596
-
597
- # Zapisz w bazie deploymentów
598
- deployments = _load_deployments()
599
- deployments.append({
600
- "id": deploy_id,
601
- "action": action,
602
- "packages": pkg_names,
603
- "timestamp": datetime.now().isoformat(),
604
- "active": True,
605
- })
606
- # Oznacz poprzednie jako nieaktywne
607
- for d in deployments[:-1]:
608
- d["active"] = False
609
- _save_deployments(deployments)
610
-
611
- return deploy_dir, deploy_id
612
-
613
-def _switch_deployment(deploy_dir: str) -> bool:
614
- """Atomowo przełącza aktywny deployment przez podmianę symlinka."""
615
- tmp_link = ACTIVE_LINK + ".new"
616
- if os.path.lexists(tmp_link):
617
- os.remove(tmp_link)
618
- os.symlink(deploy_dir, tmp_link)
619
- os.rename(tmp_link, ACTIVE_LINK) # atomowe na tym samym FS
620
- return True
621
-
622
-DEFAULT_REPOS = [
623
- "https://repo.paganlinux.eu/stable/",
624
-]
625
-
626
-# =============================================================================
627
-# INICJALIZACJA
628
-# =============================================================================
629
-
630
-def ensure_dirs():
631
- for d in [PAG_DB, PAG_CACHE, PAG_CONF, REPO_CACHE, REPOS_DIR, STAGING_DIR, DEPLOYMENTS_DIR]:
632
- os.makedirs(d, exist_ok=True)
633
- for f, default in [
634
- (REPOS_CONF, "\n".join(DEFAULT_REPOS) + "\n"),
635
- (INSTALLED_DB, "{}"),
636
- (PINNED_FILE, "{}"),
637
- (HISTORY_FILE, "[]"),
638
- ]:
639
- if not os.path.exists(f):
640
- with open(f, "w") as fh: fh.write(default)
641
- if not os.path.exists(WORLD_FILE):
642
- Path(WORLD_FILE).touch()
643
- if not os.path.exists(GPG_HOME):
644
- os.makedirs(GPG_HOME, exist_ok=True)
645
- os.chmod(GPG_HOME, 0o700)
646
- _gpg_run("--list-keys", capture_output=True)
647
- # Inicjalizuj SQLite
648
- _db_init()
649
- # Wyczyść staging po poprzednim przerwanym buildzie/instalacji
650
- if os.path.isdir(STAGING_DIR):
651
- for entry in os.listdir(STAGING_DIR):
652
- if entry == "backups":
653
- continue # backupy starych wersji – potrzebne do `pag rollback`
654
- path = os.path.join(STAGING_DIR, entry)
655
- try:
656
- if os.path.isfile(path) or os.path.islink(path):
657
- os.unlink(path)
658
- elif os.path.isdir(path):
659
- shutil.rmtree(path, ignore_errors=True)
660
- except OSError:
661
- pass
662
-
663
-# =============================================================================
664
-# SQLITE – BAZA PLIKÓW (poprawne zarządzanie połączeniami)
665
-# =============================================================================
666
-
667
-from contextlib import contextmanager
668
-
669
-@contextmanager
670
-def _db_session():
671
- """Context manager – gwarantuje zamknięcie połączenia."""
672
- conn = sqlite3.connect(FILES_DB_SQL, timeout=15)
673
- conn.execute("PRAGMA journal_mode=WAL")
674
- conn.execute("PRAGMA synchronous=NORMAL")
675
- conn.execute("PRAGMA foreign_keys=ON")
676
- conn.execute("PRAGMA busy_timeout=15000")
677
- conn.row_factory = sqlite3.Row
678
- try:
679
- yield conn
680
- conn.commit()
681
- except Exception:
682
- conn.rollback()
683
- raise
684
- finally:
685
- conn.close()
686
-
687
-
688
-def _db_init():
689
- """Tworzy tabele SQLite jeśli nie istnieją."""
690
- with _db_session() as db:
691
- db.execute("""
692
- CREATE TABLE IF NOT EXISTS files (
693
- id INTEGER PRIMARY KEY AUTOINCREMENT,
694
- path TEXT NOT NULL,
695
- package TEXT NOT NULL,
696
- sha256 TEXT,
697
- size INTEGER,
698
- is_symlink INTEGER DEFAULT 0,
699
- symlink_target TEXT,
700
- UNIQUE(path, package)
701
- )
702
- """)
703
- db.execute("CREATE INDEX IF NOT EXISTS idx_files_path ON files(path)")
704
- db.execute("CREATE INDEX IF NOT EXISTS idx_files_pkg ON files(package)")
705
- db.execute("""
706
- CREATE TABLE IF NOT EXISTS file_checksums (
707
- path TEXT PRIMARY KEY,
708
- sha256 TEXT NOT NULL,
709
- installed_at TEXT
710
- )
711
- """)
712
- db.commit()
713
-
714
-def _db_record_files(pkg_name: str, files: List[dict]):
715
- """Zapisuje pliki do SQLite (obsługuje symlinki)."""
716
- with _db_session() as db:
717
- # Jawna transakcja – atomowość obu zapisów i szybsze wykrycie blokady
718
- try:
719
- db.execute("BEGIN IMMEDIATE")
720
- except sqlite3.OperationalError:
721
- pass # transakcja już otwarta (implicit)
722
- db.executemany(
723
- "INSERT OR REPLACE INTO files (path, package, sha256, size, is_symlink, symlink_target) "
724
- "VALUES (?,?,?,?,?,?)",
725
- [(f["path"], pkg_name, f.get("sha256",""), f.get("size",0),
726
- f.get("is_symlink", 0), f.get("symlink_target", ""))
727
- for f in files]
728
- )
729
- db.executemany(
730
- "INSERT OR REPLACE INTO file_checksums (path, sha256, installed_at) VALUES (?,?,?)",
731
- [(f["path"], f.get("sha256",""), datetime.now().isoformat())
732
- for f in files if f.get("sha256")]
733
- )
734
-
735
-def _db_get_package_files(pkg_name: str) -> List[str]:
736
- with _db_session() as db:
737
- return [r["path"] for r in db.execute(
738
- "SELECT DISTINCT path FROM files WHERE package=?", (pkg_name,)
739
- )]
740
-
741
-def _db_get_file_owners(filepath: str) -> List[str]:
742
- """Zwraca listę pakietów będących właścicielami pliku."""
743
- with _db_session() as db:
744
- return [r["package"] for r in db.execute(
745
- "SELECT package FROM files WHERE path=?", (filepath,)
746
- )]
747
-
748
-def _db_remove_package_files(pkg_name: str):
749
- with _db_session() as db:
750
- db.execute("DELETE FROM files WHERE package=?", (pkg_name,))
751
- db.commit()
752
-
753
-def _db_get_all_file_checksums() -> Dict[str, str]:
754
- with _db_session() as db:
755
- return {r["path"]: r["sha256"] for r in db.execute("SELECT path, sha256 FROM file_checksums")}
756
-
757
-def _db_count_files() -> int:
758
- with _db_session() as db:
759
- return db.execute("SELECT COUNT(*) FROM files").fetchone()[0]
760
-
761
-# =============================================================================
762
-# BLOKADA
763
-# =============================================================================
764
-
765
-class DatabaseLock:
766
- """Blokada plikowa (flock) – jądro zwalnia ją AUTOMATYCZNIE, gdy proces
767
- ginie (kill -9, twardy reset). Stary PID-file miał race condition: po
768
- śmierci pag PID mógł zostać przydzielony obcemu procesowi (PID reuse)
769
- i pag odmawiał działania na zawsze („baza zablokowana”).
770
- """
771
- def __init__(self):
772
- self._f = None
773
- def __enter__(self):
774
- os.makedirs(os.path.dirname(LOCK_FILE), exist_ok=True)
775
- self._f = open(LOCK_FILE, "w")
776
- try:
777
- # LOCK_NB: rzuca wyjątek zamiast czekać w nieskończoność
778
- fcntl.flock(self._f, fcntl.LOCK_EX | fcntl.LOCK_NB)
779
- except BlockingIOError:
780
- print(f"❌ {_('db_locked')}", file=sys.stderr)
781
- print(f" {_('db_lock_hint', LOCK_FILE)}", file=sys.stderr)
782
- sys.exit(1)
783
- self._f.write(str(os.getpid()))
784
- self._f.flush()
785
- return self
786
- def __exit__(self, *args):
787
- if self._f:
788
- try:
789
- fcntl.flock(self._f, fcntl.LOCK_UN)
790
- except OSError:
791
- pass
792
- self._f.close()
793
- self._f = None
794
- # Uwaga: NIE usuwamy pliku blokady. Stały plik + flock na inode to jedyny
795
- # bezpieczny wzorzec – os.remove(), gdy inny proces trzyma blokadę na starym
796
- # inode, otwiera wyścig (nowy proces blokowałby nowo utworzony inode).
797
-
798
-# =============================================================================
799
-# POMOCNICZE
800
-# =============================================================================
801
-
802
-
803
-_ALLOWED_PREFIXES = ("/usr/", "/etc/", "/var/", "/opt/",
804
- "/boot/", "/lib/", # kernel: vmlinuz/System.map + moduły (usrmerge: lib→usr/lib)
805
- # Pliki wewnętrzne paczki .pkg.tar.xz
806
- "metadata.json", "data.tar.xz", "hooks/",
807
- "sums.json")
808
-
809
-def _check_path_safety(name: str) -> bool:
810
- # Normalizuj – usuń leading ./
811
- if name.startswith("./"):
812
- name = name[2:]
813
- if name in (".", ""):
814
- return True
815
- # Porównuj z prefiksami BEZ wiodącego '/', by zarówno "/usr/bin/ls", jak i
816
- # wewnętrzne pliki pakietu ("hooks/pre-install", "data.tar.xz") przechodziły.
817
- norm = name.lstrip("/")
818
- for prefix in _ALLOWED_PREFIXES:
819
- p = prefix.lstrip("/").rstrip("/")
820
- if norm == p or norm.startswith(p + "/"):
821
- return True
822
- return False
823
-
824
-
825
-def _validate_pkg_name(name):
826
- return bool(ALLOWED_PKG_RE.match(name))
827
-
828
-
829
-
830
-def _audit(msg):
831
- from datetime import datetime, timezone
832
- os.makedirs(os.path.dirname(AUDIT_LOG), exist_ok=True)
833
- with open(AUDIT_LOG, "a") as f:
834
- f.write(datetime.now(timezone.utc).isoformat() + " " + msg + "\n")
835
-
836
-def _strip_suid(path):
837
- try:
838
- st = os.stat(path)
839
- if st.st_mode & 0o4000:
840
- os.chmod(path, st.st_mode & ~0o4000)
841
- print(f" {_("sec_suid", path=path)}")
842
- except OSError:
843
- pass
844
-
845
-def _check_downgrade(pkg_name, new_ver, installed_db):
846
- if pkg_name in installed_db:
847
- old = installed_db[pkg_name].get("version", "0")
848
- if new_ver < old:
849
- print(f" {_("sec_downgrade", pkg=pkg_name, new=new_ver, old=old)}")
850
- return False
851
- return True
852
-
853
-def _safe_extractall(tar: tarfile.TarFile, dest: str, *, preserve_perms: bool = True):
854
- """
855
- Bezpieczne rozpakowanie archiwum tar z ochroną przed Directory Traversal.
856
-
857
- Działa na Python < 3.12 (gdzie parametr 'filter' w extractall nie istnieje)
858
- oraz na Python 3.12+. W przeciwieństwie do filtra 'data' z Pythona 3.12,
859
- zachowuje bity uprawnień POSIX (SUID, SGID, sticky) – preserve_perms=True.
860
-
861
- Ochrona oparta jest na FINALNEJ ścieżce (os.path.realpath), nie tylko na
862
- prostym sprawdzaniu stringa:
863
- - Blokuje ścieżki absolutne i z '..' (path traversal)
864
- - Blokuje symlinki/hardlinki, których cel wychodzi poza dest
865
- - Blokuje zapis "przez" złośliwy symlink, który został wcześniej
866
- rozpakowany (np. katalog → /etc, potem zapis katalog/plik)
867
- - Zachowuje oryginalne uprawnienia plików
868
- """
869
- dest_real = os.path.realpath(dest)
870
- os.makedirs(dest_real, exist_ok=True)
871
-
872
- def _target_within(path: str) -> bool:
873
- try:
874
- return os.path.commonpath([dest_real, os.path.realpath(path)]) == dest_real
875
- except ValueError:
876
- # różne napędy / ścieżki nie da się wspólnie porównać → odrzuć
877
- return False
878
-
879
- for member in tar.getmembers():
880
- name = member.name
881
-
882
- # --- Ochrona przed Directory Traversal (szybkie string-checki) ---
883
- if name.startswith('/'):
884
- continue
885
- if '..' in name.split('/'):
886
- continue
887
- # Zablokuj bajt NUL i backslash (bugi/obejścia tarfile na niektórych platformach)
888
- if '\x00' in name or '\\' in name:
889
- continue
890
- if not _check_path_safety(name):
891
- print(f" BLOCKED: {name}")
892
- continue
893
-
894
- target = os.path.join(dest, name)
895
-
896
- # --- Ochrona na podstawie finalnej ścieżki ---
897
- # Jeśli którykolwiek komponent nadrzędny jest (złośliwym) symlinkiem
898
- # wskazującym poza dest, realpath to wykryje – zablokuj zapis.
899
- if not _target_within(target):
900
- print(f" BLOCKED (escape): {name}")
901
- continue
902
-
903
- # --- Ochrona dla symlinków i hardlinków ---
904
- if member.issym() or member.islnk():
905
- link = member.linkname
906
- # Szybkie odrzucenie linków absolutnych / z '..'
907
- if link.startswith('/') or '..' in link.split('/'):
908
- continue
909
- # Sprawdź, gdzie realnie prowadzi cel linku (względem katalogu linku)
910
- link_target = os.path.join(os.path.dirname(target), link)
911
- if not _target_within(link_target):
912
- print(f" BLOCKED (link escape): {name} -> {link}")
913
- continue
914
-
915
- # Rozpakuj z zachowaniem metadanych. Python 3.12+ wymaga jawnego
916
- # `filter=` (inaczej DeprecationWarning, w 3.14+ błąd) – nasza ręczna
917
- # walidacja powyżej już zabezpiecza ścieżki, więc 'fully_trusted'
918
- # (pomija filtr Pythona i zachowuje SUID/SGID/sticky z preserve_perms).
919
- try:
920
- if hasattr(tarfile, 'data_filter'):
921
- # Python 3.12+
922
- tar.extract(member, dest, set_attrs=preserve_perms, numeric_owner=False,
923
- filter='fully_trusted')
924
- else:
925
- tar.extract(member, dest, set_attrs=preserve_perms, numeric_owner=False)
926
- except Exception as e:
927
- print(f" ⚠ Nie rozpakowano {name}: {e}")
928
- continue
929
- _strip_suid(target)
930
-
931
-
932
-def _sha256_file(path: str) -> str:
933
- h = hashlib.sha256()
934
- with open(path, "rb") as f:
935
- for chunk in iter(lambda: f.read(65536), b""):
936
- h.update(chunk)
937
- return h.hexdigest()
938
-
939
-def _split_version(v: str):
940
- """Rozdziela wersję na (release_parts, prerelease_parts).
941
-
942
- Przykład: '1.2.0-rc1' → ([1,2,0], ['rc','1']).
943
- """
944
- v = v.strip().lower().lstrip("v")
945
- # build metadata po '+' jest ignorowane przy porównywaniu (semver)
946
- v = v.split("+", 1)[0]
947
- # prerelease po '-' lub '_' (np. 1.2.0-rc1, 1.2.0_rc1)
948
- if "-" in v:
949
- rel, pre = v.split("-", 1)
950
- elif "_" in v:
951
- rel, pre = v.split("_", 1)
952
- else:
953
- rel, pre = v, ""
954
- nums = []
955
- for part in rel.split("."):
956
- m = re.match(r"(\d+)", part)
957
- nums.append(int(m.group(1)) if m else 0)
958
- pre_parts = [p for p in pre.split(".") if p]
959
- return nums, pre_parts
960
-
961
-
962
-def _cmp_pre(a, b):
963
- """Porównuje ciągi identyfikatorów prerelease (reguły semver)."""
964
- for i in range(max(len(a), len(b))):
965
- if i >= len(a):
966
- return -1 # krótszy prerelease jest niższy
967
- if i >= len(b):
968
- return 1
969
- ia, ib = a[i], b[i]
970
- if ia == ib:
971
- continue
972
- na, nb = ia.isdigit(), ib.isdigit()
973
- if na and nb:
974
- return 1 if int(ia) > int(ib) else -1
975
- if na != nb:
976
- return -1 if na else 1 # identyfikator liczbowy < alfanumeryczny
977
- return 1 if ia > ib else -1
978
- return 0
979
-
980
-
981
-def _cmp_version(a: str, b: str) -> int:
982
- """Porównuje dwie wersje; zwraca -1/0/1. Obsługuje prerelease (rc1, beta...)."""
983
- a_rel, a_pre = _split_version(a)
984
- b_rel, b_pre = _split_version(b)
985
- # Porównaj część release (brakujące komponenty traktuj jako 0)
986
- for i in range(max(len(a_rel), len(b_rel))):
987
- xa = a_rel[i] if i < len(a_rel) else 0
988
- xb = b_rel[i] if i < len(b_rel) else 0
989
- if xa != xb:
990
- return 1 if xa > xb else -1
991
- # Część release równa → decyduje prerelease.
992
- # Wersja finalna (bez prerelease) jest ZAWSZE nowsza od prerelease.
993
- if not a_pre and not b_pre:
994
- return 0
995
- if not a_pre:
996
- return 1
997
- if not b_pre:
998
- return -1
999
- return _cmp_pre(a_pre, b_pre)
1000
-
1001
-
1002
-def _version_newer(a: str, b: str) -> bool:
1003
- """True gdy wersja a jest nowsza od b (z poprawną obsługą prerelease)."""
1004
- try:
1005
- return _cmp_version(a, b) > 0
1006
- except Exception:
1007
- return a != b
1008
-
1009
-def load_json(path):
1010
- try:
1011
- with open(path) as f:
1012
- return json.load(f)
1013
- except (FileNotFoundError, json.JSONDecodeError):
1014
- return {}
1015
-
1016
-def save_json(path, data):
1017
- with open(path, "w") as f:
1018
- json.dump(data, f, indent=2)
1019
-
1020
-class PackageInfo:
1021
- __slots__ = ("name","version","description","dependencies",
1022
- "size_bytes","sha256","gpg_fp","repo_url","filename","provides","license",
1023
- "provides_so","requires_so")
1024
- def __init__(self, d, repo=""):
1025
- self.name = d.get("name","?")
1026
- self.version = d.get("version","0")
1027
- self.description = d.get("description","")
1028
- self.dependencies = d.get("dependencies", d.get("depends", []))
1029
- self.size_bytes = d.get("size",0)
1030
- self.sha256 = d.get("sha256","")
1031
- self.gpg_fp = d.get("gpg_fingerprint","")
1032
- self.repo_url = repo
1033
- self.filename = d.get("filename", f"{self.name}-{self.version}{PKG_EXT}")
1034
- self.provides = d.get("provides", []) or []
1035
- self.license = d.get("license", []) or []
1036
- self.provides_so = d.get("provides_so", []) or []
1037
- self.requires_so = d.get("requires_so", []) or []
1038
-
1039
-# =============================================================================
1040
-# REPOZYTORIA (cache, ETag, GPG)
1041
-# =============================================================================
1042
-
1043
-def _parse_repos_config():
1044
- """Parsuje repozytoria z /etc/pag/repos.conf oraz /etc/pag/repos/*.conf.
1045
-
1046
- Format linii: <url> [fingerprint]
1047
- Opcjonalny `fingerprint` (40 znaków hex) pozwala przypiąć klucz
1048
- podpisujący repo do konkretnego adresu – wtedy TOFU (auto-zaufanie przy
1049
- pierwszym użyciu) nie jest potrzebne, a zmiana klucza = błąd bezpieczeństwa.
1050
-
1051
- Drop-iny (np. stable.conf) są czytane alfabetycznie – pozwalają na
1052
- wygodne dodawanie repo bez dotykania głównego repos.conf
1053
- (np. `echo 'https://repo.paganlinux.eu/stable' > /etc/pag/repos/stable.conf`).
1054
- """
1055
- entries = []
1056
-
1057
- def _read_lines(path):
1058
- if not os.path.exists(path):
1059
- return
1060
- for line in open(path):
1061
- line = line.strip()
1062
- if not line or line.startswith("#"):
1063
- continue
1064
- parts = line.split()
1065
- url = parts[0].rstrip("/")
1066
- fp = parts[1].lower() if len(parts) > 1 else ""
1067
- entries.append({"url": url, "fingerprint": fp or None})
1068
-
1069
- # 1) Legacy: pojedynczy plik /etc/pag/repos.conf
1070
- _read_lines(REPOS_CONF)
1071
- # 2) Drop-in: /etc/pag/repos/<nazwa>.conf (sortowane, stabilna kolejność)
1072
- if os.path.isdir(REPOS_DIR):
1073
- for drop in sorted(os.listdir(REPOS_DIR)):
1074
- if drop.endswith(".conf"):
1075
- _read_lines(os.path.join(REPOS_DIR, drop))
1076
-
1077
- # Dedupe po URL (zachowaj pierwszy wpis – może mieć fingerprint)
1078
- seen, unique = set(), []
1079
- for e in entries:
1080
- if e["url"] not in seen:
1081
- seen.add(e["url"])
1082
- unique.append(e)
1083
-
1084
- if not unique:
1085
- for url in DEFAULT_REPOS:
1086
- unique.append({"url": url, "fingerprint": None})
1087
- return unique
1088
-
1089
-
1090
-def get_repos():
1091
- return [e["url"] for e in _parse_repos_config()]
1092
-
1093
-
1094
-def _repo_pinned_fp(repo_url):
1095
- """Zwraca przypięty fingerprint klucza dla repo (z konfiguracji lub trust DB)."""
1096
- by_url = {e["url"]: e["fingerprint"] for e in _parse_repos_config()}
1097
- if by_url.get(repo_url):
1098
- return by_url[repo_url]
1099
- db = _load_trust_db()
1100
- fp = db.get(repo_url)
1101
- return fp.lower() if fp else None
1102
-
1103
-def _repo_cache_path(url):
1104
- return os.path.join(REPO_CACHE, url.replace("://","_").replace("/","_").replace(".","_") + ".json")
1105
-
1106
-def _repo_etag_path(url): return _repo_cache_path(url) + ".etag"
1107
-def _repo_ts_path(url): return _repo_cache_path(url) + ".ts"
1108
-
1109
-def fetch_repo_index(repo_url, force=False):
1110
- cp = _repo_cache_path(repo_url)
1111
- ep = _repo_etag_path(repo_url)
1112
- tp = _repo_ts_path(repo_url)
1113
-
1114
- if not force and os.path.exists(cp) and os.path.exists(tp):
1115
- try:
1116
- if time.time() - float(open(tp).read().strip()) < REPO_CACHE_TTL:
1117
- return json.load(open(cp)).get("packages",[])
1118
- except: pass
1119
-
1120
- headers = {"User-Agent": "pag/3.0"}
1121
- if os.path.exists(tp) and not force:
1122
- try:
1123
- lm = datetime.fromtimestamp(float(open(tp).read().strip()), tz=timezone.utc)
1124
- # Wymuś lokalizację C/POSIX dla nagłówków HTTP, aby unikać problemów z nazwami dni/miesięcy
1125
- try:
1126
- old_locale = locale.setlocale(locale.LC_TIME)
1127
- locale.setlocale(locale.LC_TIME, 'C')
1128
- headers["If-Modified-Since"] = lm.strftime("%a, %d %b %Y %H:%M:%S GMT")
1129
- locale.setlocale(locale.LC_TIME, old_locale)
1130
- except (locale.Error, ValueError):
1131
- # Jeśli ustawienie lokalizacji się nie powiedzie, użyj domyślnej
1132
- headers["If-Modified-Since"] = lm.strftime("%a, %d %b %Y %H:%M:%S GMT")
1133
- except: pass
1134
- if os.path.exists(ep) and not force:
1135
- try: headers["If-None-Match"] = open(ep).read().strip()
1136
- except: pass
1137
-
1138
- try:
1139
- req = Request(f"{repo_url}/repo.json", headers=headers)
1140
- with urlopen(req, timeout=30) as resp:
1141
- etag = resp.headers.get("ETag","")
1142
- if etag: open(ep,"w").write(etag)
1143
- raw = resp.read()
1144
- data = json.loads(raw.decode())
1145
- # Zapisuj SUROWE bajty (nie re-serializuj!) – podpis GPG jest nad
1146
- # oryginalnymi bajtami repo.json z serwera
1147
- with open(cp,"wb") as f: f.write(raw)
1148
- open(tp,"w").write(str(time.time()))
1149
- # SPRAWDŹ WYNIK WERYFIKACJI – nie ignoruj!
1150
- if not _verify_repo_sig(repo_url, cp):
1151
- return None # weryfikacja nie powiodła się, cache usunięty
1152
- return data.get("packages",[])
1153
- except HTTPError as e:
1154
- if e.code == 304:
1155
- open(tp,"w").write(str(time.time()))
1156
- if os.path.exists(cp):
1157
- return json.load(open(cp)).get("packages",[])
1158
- print(f" ⚠ HTTP {e.code} dla {repo_url}", file=sys.stderr)
1159
- return None
1160
- except Exception as e:
1161
- print(f" ⚠ Błąd pobierania indeksu {repo_url}: {e}", file=sys.stderr)
1162
- if os.path.exists(cp):
1163
- try: return json.load(open(cp)).get("packages",[])
1164
- except Exception: pass
1165
- return None
1166
-
1167
-def _verify_repo_sig(repo_url, cache_path) -> bool:
1168
- """Weryfikuje podpis GPG indeksu repozytorium i przypina fingerprint.
1169
-
1170
- FAIL-CLOSED: brak/nieprawidłowy podpis = False (chyba że PAG_INSECURE=1).
1171
- Zwraca True jeśli indeks jest zaufany, False jeśli należy go odrzucić.
1172
-
1173
- Model zaufania (TOFU + pinning):
1174
- - Pierwszy raz (brak przypiętego fingerprintu) → klucz jest importowany,
1175
- a fingerprint zapisywany w /etc/pag/trusted.json z JAWNYM ostrzeżeniem.
1176
- To świadomy kompromis wygody i bezpieczeństwa.
1177
- - Kolejne uruchomienia: fingerprint jest porównywany z przypiętym.
1178
- Zmiana klucza = ❌ SECURITY ERROR (fail-closed), wymagane ręczne:
1179
- pag key-trust <repo_url> (po weryfikacji nowego klucza)
1180
- """
1181
- insecure = os.environ.get("PAG_INSECURE", "") == "1"
1182
-
1183
- if not os.path.exists(GPG_HOME):
1184
- if insecure:
1185
- return True # brak GPG home – tryb insecure, akceptuj
1186
- print(f" ❌ {repo_url}: brak kluczy GPG – weryfikacja niemożliwa!")
1187
- print(f" Ustaw PAG_INSECURE=1 aby pominąć (niezalecane)")
1188
- os.remove(cache_path)
1189
- return False
1190
-
1191
- sig_path = cache_path + ".sig"
1192
- # Podpisy generowane jako .asc (armored) – próbuj .asc, potem .sig
1193
- sig_data = None
1194
- sig_ext = ""
1195
- for ext in (".asc", ".sig"):
1196
- try:
1197
- req = Request(f"{repo_url}/repo.json{ext}", headers={"User-Agent":"pag/3.0"})
1198
- with urlopen(req, timeout=15) as resp:
1199
- sig_data = resp.read()
1200
- sig_ext = ext
1201
- break
1202
- except Exception:
1203
- continue
1204
- if not sig_data:
1205
- if insecure:
1206
- return True # tryb insecure – akceptuj bez podpisu
1207
- print(f" ❌ {repo_url}: NIE MOŻNA POBRAĆ PODPISU repo.json.asc/.sig!")
1208
- print(f" Ustaw PAG_INSECURE=1 aby pominąć (niezalecane)")
1209
- os.remove(cache_path)
1210
- return False
1211
- sig_path = cache_path + sig_ext
1212
- with open(sig_path, "wb") as f:
1213
- f.write(sig_data)
1214
-
1215
- ok, fingerprint = _gpg_verify_fp(sig_path, cache_path)
1216
- if not ok:
1217
- # Automatyczny import klucza repo przy pierwszym uruchomieniu (TOFU,
1218
- # jak apt) – gdy w keyringu brakuje klucza (No public key).
1219
- res = _gpg_run("--verify", sig_path, cache_path,
1220
- capture_output=True, text=True, timeout=30)
1221
- _stderr = res.stderr.decode(errors="replace") if isinstance(res.stderr, bytes) else (res.stderr or "")
1222
- if "public key" in _stderr.lower() and "no public key" in _stderr.lower():
1223
- try:
1224
- with urlopen(Request(f"{repo_url}/paganos.asc", headers={"User-Agent": "pag/3.0"}), timeout=20) as r:
1225
- keydata = r.read()
1226
- with tempfile.NamedTemporaryFile(delete=False, suffix=".asc") as tmp:
1227
- tmp.write(keydata)
1228
- tmp.flush()
1229
- _gpg_run("--import", tmp.name, capture_output=True, timeout=30)
1230
- os.unlink(tmp.name)
1231
- print(f" 🔑 Importowano klucz repo z {repo_url}/paganos.asc")
1232
- ok, fingerprint = _gpg_verify_fp(sig_path, cache_path)
1233
- except Exception:
1234
- pass
1235
- if not ok:
1236
- if insecure:
1237
- print(f" ⚠ {repo_url}: nieprawidłowy podpis GPG (PAG_INSECURE – ignoruję)")
1238
- return True
1239
- os.remove(cache_path)
1240
- if not shutil.which(GPG_BINARY):
1241
- print(f" ❌ {repo_url}: GPG nie jest zainstalowane – nie można zweryfikować podpisu!")
1242
- print(f" Zainstaluj gnupg lub ustaw PAG_INSECURE=1 (niezalecane)")
1243
- else:
1244
- print(f" ❌ {repo_url}: NIEPRAWIDŁOWY PODPIS GPG indeksu repozytorium!")
1245
- return False
1246
-
1247
- # --- Wymuś przypięty fingerprint (TOFU + pinning) ---
1248
- pinned = _repo_pinned_fp(repo_url)
1249
- if pinned:
1250
- if not fingerprint:
1251
- if insecure:
1252
- print(f" ⚠ {repo_url}: nie można odczytać fingerprintu (PAG_INSECURE – ignoruję)")
1253
- return True
1254
- os.remove(cache_path)
1255
- print(f" ❌ [SECURITY ERROR] {repo_url}: nie można odczytać fingerprintu podpisu!")
1256
- print(f" Przypięty klucz: {pinned} – odrzucam indeks.")
1257
- return False
1258
- if fingerprint != pinned.upper():
1259
- if insecure:
1260
- print(f" ⚠ {repo_url}: ZMIENIONY KLUCZ PODPISU (PAG_INSECURE – ignoruję)")
1261
- return True
1262
- os.remove(cache_path)
1263
- print(f" ❌ [SECURITY ERROR] {repo_url}: Klucz podpisujący repo uległ zmianie!")
1264
- print(f" Oczekiwany: {pinned}")
1265
- print(f" Otrzymany: {fingerprint}")
1266
- print(f" Jeśli to celowa rotacja klucza: pag key-trust {repo_url}")
1267
- return False
1268
- return True
1269
-
1270
- if fingerprint:
1271
- # Brak przypiętego fingerprintu → TOFU: zapisz go w bazie zaufania.
1272
- db = _load_trust_db()
1273
- if db.get(repo_url) != fingerprint:
1274
- _save_trust_db({**db, repo_url: fingerprint})
1275
- print(f" 🔐 Przypięto fingerprint repo {repo_url}: {fingerprint}")
1276
- print(f" (TOFU – pierwsze zaufanie. Gdy klucz się zmieni, pag odmówi aktualizacji.)")
1277
- print(f" Aby uniknąć TOFU, dopisz fingerprint w /etc/pag/repos.conf.")
1278
- return True
1279
-
1280
-def fetch_all_packages(force=False):
1281
- all_pkgs = {}
1282
- for repo_url in get_repos():
1283
- pkgs = fetch_repo_index(repo_url, force)
1284
- if pkgs:
1285
- for pdata in pkgs:
1286
- name = pdata.get("name", pdata.get("filename","?").split("-")[0])
1287
- pkg = PackageInfo(pdata, repo_url)
1288
- if name not in all_pkgs or _version_newer(pkg.version, all_pkgs[name].version):
1289
- all_pkgs[name] = pkg
1290
- return all_pkgs
1291
-
1292
-# =============================================================================
1293
-# GPG
1294
-# =============================================================================
1295
-
1296
-def _verify_pkg_gpg(pkg_path, repo_url=None):
1297
- """Weryfikuje podpis GPG pakietu i (jeśli znamy repo) przypięty fingerprint.
1298
-
1299
- FAIL-CLOSED: brak podpisu = odrzucenie (chyba że PAG_INSECURE=1).
1300
- Zwraca (passed: bool, message: str).
1301
- """
1302
- insecure = os.environ.get("PAG_INSECURE", "") == "1"
1303
- sig_path = pkg_path + ".sig"
1304
- if not os.path.exists(sig_path) and os.path.exists(pkg_path + ".asc"):
1305
- sig_path = pkg_path + ".asc"
1306
-
1307
- if not os.path.exists(sig_path):
1308
- if insecure:
1309
- return True, "(no signature – PAG_INSECURE)"
1310
- return False, "BRAK PODPISU – pakiet odrzucony (ustaw PAG_INSECURE=1 aby pominąć)"
1311
-
1312
- ok, fp = _gpg_verify_fp(sig_path, pkg_path)
1313
- if not ok:
1314
- if insecure:
1315
- return True, "(invalid signature – PAG_INSECURE)"
1316
- return False, "NIEPRAWIDŁOWY PODPIS GPG"
1317
-
1318
- # Opcjonalnie: sprawdź, czy podpis pochodzi od klucza przypiętego dla repo.
1319
- if repo_url:
1320
- pinned = _repo_pinned_fp(repo_url)
1321
- if pinned and fp and fp != pinned.upper():
1322
- if insecure:
1323
- return True, "(pkg signer mismatch – PAG_INSECURE)"
1324
- return False, f"PAKIET PODPISANY INNYM KLUCZEM niż repo (oczekiwano {pinned})"
1325
-
1326
- return True, "GPG verified"
1327
-
1328
-def cmd_key_add(source):
1329
- ensure_dirs()
1330
- if source.startswith("http"):
1331
- try:
1332
- with urlopen(Request(source, headers={"User-Agent":"pag/3.0"}), timeout=30) as resp:
1333
- keydata = resp.read()
1334
- with tempfile.NamedTemporaryFile(delete=False, suffix=".gpg") as tmp:
1335
- tmp.write(keydata); tmp.flush()
1336
- _gpg_run("--import", tmp.name, capture_output=True, timeout=30)
1337
- os.unlink(tmp.name)
1338
- except Exception as e:
1339
- print(f"❌ Download error: {e}"); return 1
1340
- else:
1341
- _gpg_run("--import", source, capture_output=True, timeout=30)
1342
- print(f"✅ {_('key_imported')}")
1343
-
1344
-def cmd_key_list():
1345
- if not os.path.exists(GPG_HOME):
1346
- print(_("no_keys")); return
1347
- result = _gpg_run("--list-keys", "--keyid-format", "LONG",
1348
- capture_output=True, text=True, timeout=30)
1349
- print(result.stdout or _("no_keys"))
1350
-
1351
-def cmd_key_remove(key_id):
1352
- _gpg_run("--batch", "--yes", "--delete-key", key_id,
1353
- capture_output=True, timeout=30)
1354
- print(f"✅ {_('key_removed', key_id)}")
1355
-
1356
-def _repo_signer_fp(repo_url):
1357
- """Pobiera repo.json + podpis i zwraca fingerprint podpisującego (bez pinningu)."""
1358
- repo_url = repo_url.rstrip("/")
1359
- try:
1360
- with urlopen(Request(f"{repo_url}/repo.json", headers={"User-Agent":"pag/3.0"}), timeout=30) as r:
1361
- data = r.read()
1362
- except Exception:
1363
- return None
1364
- sig = None
1365
- sig_ext = ".asc"
1366
- for ext in (".asc", ".sig"):
1367
- try:
1368
- with urlopen(Request(f"{repo_url}/repo.json{ext}", headers={"User-Agent":"pag/3.0"}), timeout=20) as r:
1369
- sig = r.read()
1370
- sig_ext = ext
1371
- break
1372
- except Exception:
1373
- continue
1374
- if not sig:
1375
- return None
1376
- with tempfile.NamedTemporaryFile(delete=False, suffix=".json") as tf:
1377
- tf.write(data); tf.flush()
1378
- data_path = tf.name
1379
- sig_path = data_path + sig_ext
1380
- try:
1381
- with open(sig_path, "wb") as f:
1382
- f.write(sig)
1383
- ok, fp = _gpg_verify_fp(sig_path, data_path)
1384
- finally:
1385
- for p in (data_path, sig_path):
1386
- try: os.unlink(p)
1387
- except OSError: pass
1388
- return fp if ok else None
1389
-
1390
-
1391
-def cmd_key_trust(repo_url):
1392
- """Przypina fingerprint klucza podpisującego repo (koniec z TOFU dla tego repo)."""
1393
- repo_url = repo_url.rstrip("/")
1394
- print(f"🔐 Przypinam klucz repo {repo_url}...")
1395
- fp = _repo_signer_fp(repo_url)
1396
- if not fp:
1397
- print(" ❌ Nie można odczytać fingerprintu podpisu (brak/nieudany).")
1398
- print(" Upewnij się, że klucz repo jest w keyringu (pag key-add <url|file>).")
1399
- return 1
1400
- db = _load_trust_db()
1401
- _save_trust_db({**db, repo_url: fp})
1402
- print(f" ✅ Przypięto {fp} dla {repo_url}")
1403
- print(" Od teraz zmiana klucza zostanie zgłoszona jako SECURITY ERROR.")
1404
- return 0
1405
-
1406
-
1407
-def cmd_key_untrust(repo_url):
1408
- """Usuwa przypięcie fingerprintu dla repo (wraca do TOFU)."""
1409
- repo_url = repo_url.rstrip("/")
1410
- db = _load_trust_db()
1411
- if repo_url not in db:
1412
- print(f" ℹ {repo_url} nie ma przypiętego fingerprintu.")
1413
- return 0
1414
- del db[repo_url]
1415
- _save_trust_db(db)
1416
- print(f" ✅ Usunięto przypięcie dla {repo_url}.")
1417
- return 0
1418
-
1419
-
1420
-def cmd_key_trusted():
1421
- """Listuje przypięte fingerprinty repozytoriów."""
1422
- db = _load_trust_db()
1423
- if not db:
1424
- print(_("no_keys"))
1425
- return
1426
- for url, fp in sorted(db.items()):
1427
- print(f" {url}\n {fp}")
1428
-
1429
-# =============================================================================
1430
-# ATOMOWA INSTALACJA (STAGING)
1431
-# =============================================================================
1432
-
1433
-def _safe_rename(src: str, dst: str) -> bool:
1434
- """
1435
- Atomowe przeniesienie pliku. Jeśli src i dst są na różnych
1436
- systemach plików (EXDEV), kopiuje + usuwa źródło.
1437
- """
1438
- try:
1439
- os.rename(src, dst)
1440
- return True
1441
- except OSError as e:
1442
- if e.errno == 18: # EXDEV – cross-device link
1443
- shutil.copy2(src, dst)
1444
- os.remove(src)
1445
- return True
1446
- raise
1447
-
1448
-
1449
-def _install_file(src: str, rel: str, data_staging: str, sums: dict,
1450
- staging: str, journal: list, installed_files: list,
1451
- deploy_dir: str = "", backup_dir: str = "",
1452
- backup_journal: Optional[list] = None) -> bool:
1453
- """
1454
- Instaluje pojedynczy plik (zwykły lub symlink).
1455
- Obsługuje: cross-device rename, symlinki, weryfikację SHA256.
1456
-
1457
- Jeśli deploy_dir jest podany (tryb immutable), pliki systemowe trafiają
1458
- do deploymentu, a współdzielone (/var, /etc, ...) bezpośrednio do /.
1459
-
1460
- Jeśli backup_dir jest podany, a pod dst istnieje już plik (upgrade/reinstall),
1461
- stara wersja jest przenoszona do backup_dir, by rollback mógł ją przywrócić.
1462
- """
1463
- # W trybie immutable: pliki współdzielone idą do /, reszta do deploymentu
1464
- if deploy_dir and _is_shared_path("/" + rel):
1465
- dst_root = PAG_ROOT
1466
- elif deploy_dir:
1467
- dst_root = deploy_dir
1468
- else:
1469
- dst_root = PAG_ROOT
1470
-
1471
- dst = os.path.join(dst_root, rel)
1472
-
1473
- # --- SYMLINK ---
1474
- if os.path.islink(src):
1475
- link_target = os.readlink(src)
1476
- # Weryfikuj sums.json dla symlinka (hash ścieżki docelowej)
1477
- expected = sums.get("/" + rel, "")
1478
- if expected:
1479
- link_hash = hashlib.sha256(link_target.encode()).hexdigest()
1480
- if expected and link_hash != expected:
1481
- return False
1482
-
1483
- os.makedirs(os.path.dirname(dst), exist_ok=True)
1484
- # Backup istniejącego symlinka (upgrade) – dla poprawnego rollbacku
1485
- if backup_dir and backup_journal is not None and os.path.lexists(dst):
1486
- try:
1487
- backup_path = os.path.join(backup_dir, rel)
1488
- os.makedirs(os.path.dirname(backup_path), exist_ok=True)
1489
- os.replace(dst, backup_path)
1490
- backup_journal.append((backup_path, "/" + rel))
1491
- journal.append(("backup", backup_path, dst))
1492
- except OSError:
1493
- pass
1494
- # Jeśli docelowy symlink już istnieje, usuń go
1495
- if os.path.islink(dst) or os.path.exists(dst):
1496
- os.remove(dst)
1497
- os.symlink(link_target, dst)
1498
- journal.append(("symlink", "", dst))
1499
- installed_files.append({
1500
- "path": "/" + rel,
1501
- "sha256": hashlib.sha256(link_target.encode()).hexdigest(),
1502
- "size": len(link_target),
1503
- "is_symlink": True,
1504
- "symlink_target": link_target,
1505
- })
1506
- return True
1507
-
1508
- # --- ZWYKŁY PLIK ---
1509
- # Oblicz SHA256
1510
- try:
1511
- file_sha = _sha256_file(src)
1512
- except Exception:
1513
- file_sha = ""
1514
-
1515
- # Weryfikuj sums.json
1516
- expected = sums.get("/" + rel, "")
1517
- if expected and file_sha and file_sha != expected:
1518
- return False
1519
-
1520
- # Utwórz katalog docelowy
1521
- os.makedirs(os.path.dirname(dst), exist_ok=True)
1522
-
1523
- # Backup istniejącego pliku (upgrade) – dla poprawnego rollbacku
1524
- if backup_dir and backup_journal is not None and os.path.lexists(dst):
1525
- try:
1526
- backup_path = os.path.join(backup_dir, rel)
1527
- os.makedirs(os.path.dirname(backup_path), exist_ok=True)
1528
- os.replace(dst, backup_path)
1529
- backup_journal.append((backup_path, "/" + rel))
1530
- journal.append(("backup", backup_path, dst))
1531
- except OSError:
1532
- pass
1533
-
1534
- # Atomowe przeniesienie (z fallbackiem dla cross-device).
1535
- # Zachowuje bity uprawnień (SUID/SGID/sticky) – NIE używamy filter='data'.
1536
- _safe_rename(src, dst)
1537
-
1538
- # Wymuś właściciela root:root. UWAGA: os.chown() NIE czyści bitów SUID/SGID.
1539
- try:
1540
- os.chown(dst, 0, 0)
1541
- except (OSError, PermissionError):
1542
- # Na niektórych systemach plików (tmpfs, fat) chown może się nie powieść
1543
- pass
1544
-
1545
- journal.append(("file", src, dst))
1546
- installed_files.append({
1547
- "path": "/" + rel,
1548
- "sha256": file_sha,
1549
- "size": os.path.getsize(dst),
1550
- "is_symlink": False,
1551
- })
1552
- return True
1553
-
1554
-
1555
-def _atomic_install(pkg_path: str, pkg: PackageInfo, deploy_dir: str = "",
1556
- backup_dir: str = "") -> Tuple[bool, List[dict], List[Tuple[str, str]]]:
1557
- """
1558
- Rozpakowuje do staging area, potem atomowo przenosi pliki.
1559
- Jeśli deploy_dir podany – instaluje do deploymentu (tryb immutable).
1560
- Zwraca (success, [lista plików z SHA256], [(backup_path, dst), ...]).
1561
- """
1562
- staging = tempfile.mkdtemp(dir=STAGING_DIR, prefix=f".staging-{pkg.name}-")
1563
- journal = []
1564
- installed_files = []
1565
- backup_journal: List[Tuple[str, str]] = []
1566
-
1567
- try:
1568
- # Rozpakuj .pkg.tar.xz → staging (bezpieczne – ochrona Directory Traversal)
1569
- with tarfile.open(pkg_path, "r:xz") as tf:
1570
- _safe_extractall(tf, staging)
1571
-
1572
- data_tar = os.path.join(staging, "data.tar.xz")
1573
- if not os.path.exists(data_tar):
1574
- shutil.rmtree(staging, ignore_errors=True)
1575
- return False, [], backup_journal
1576
-
1577
- # Rozpakuj data.tar.xz → staging/data (bezpieczne – ochrona Directory Traversal)
1578
- data_staging = os.path.join(staging, "data")
1579
- os.makedirs(data_staging, exist_ok=True)
1580
- with tarfile.open(data_tar, "r:xz") as tf:
1581
- _safe_extractall(tf, data_staging)
1582
-
1583
- # Wczytaj sums.json
1584
- sums_path = os.path.join(data_staging, "sums.json")
1585
- sums = json.load(open(sums_path)) if os.path.exists(sums_path) else {}
1586
-
1587
- # Hook pre-install (przed przeniesieniem plików do systemu)
1588
- _run_hook(os.path.join(staging, "hooks"), "pre-install", pkg)
1589
-
1590
- # Przenieś pliki: staging/data/* → /
1591
- for root, dirs, files in os.walk(data_staging):
1592
- # Odtwórz katalogi z pakietu – w tym PUSTE (np. /etc/pulse/default.pa.d).
1593
- # Pętla plików tworzy tylko rodziców instalowanych plików, przez co
1594
- # puste katalogi z data.tar.xz ginęły przy instalacji.
1595
- for d in dirs:
1596
- src_dir = os.path.join(root, d)
1597
- rel_dir = os.path.relpath(src_dir, data_staging)
1598
- if deploy_dir and _is_shared_path("/" + rel_dir):
1599
- dst_root = PAG_ROOT
1600
- elif deploy_dir:
1601
- dst_root = deploy_dir
1602
- else:
1603
- dst_root = PAG_ROOT
1604
- dst_dir = os.path.join(dst_root, rel_dir)
1605
- if not os.path.isdir(dst_dir):
1606
- try:
1607
- os.makedirs(dst_dir, exist_ok=True)
1608
- except OSError:
1609
- pass
1610
- for fname in files:
1611
- if fname == "sums.json":
1612
- continue
1613
- src = os.path.join(root, fname)
1614
- rel = os.path.relpath(src, data_staging)
1615
-
1616
- ok = _install_file(src, rel, data_staging, sums,
1617
- staging, journal, installed_files, deploy_dir,
1618
- backup_dir, backup_journal)
1619
- if not ok:
1620
- # Cofnij wszystkie operacje
1621
- _rollback_journal(journal, staging)
1622
- return False, [], backup_journal
1623
-
1624
- # Odbuduj cache ikon GTK dla motywów dotkniętych instalacją.
1625
- # Bez icon-theme.cache aplikacje GTK nie widzą ikon mimo obecności
1626
- # motywu (np. /usr/share/icons/Papirus). Pomijamy, gdy narzędzie
1627
- # nie jest zainstalowane.
1628
- _icon_dirs = set()
1629
- for f in installed_files:
1630
- fp = f.get("path", "") or ""
1631
- if fp.startswith("/usr/share/icons/"):
1632
- _rest = fp[len("/usr/share/icons/"):]
1633
- _theme = _rest.split("/", 1)[0]
1634
- if _theme:
1635
- _icon_dirs.add(os.path.join(PAG_ROOT, "usr/share/icons", _theme))
1636
- if _icon_dirs:
1637
- try:
1638
- subprocess.run(["gtk-update-icon-cache", "--version"],
1639
- capture_output=True, timeout=10)
1640
- for _d in sorted(_icon_dirs):
1641
- if os.path.isdir(_d):
1642
- subprocess.run(["gtk-update-icon-cache", "-f", "-q", _d],
1643
- capture_output=True, timeout=300)
1644
- except Exception:
1645
- pass
1646
-
1647
- # Uruchom hooki post-install
1648
- hooks_dir = os.path.join(staging, "hooks")
1649
- _run_hook(hooks_dir, "post-install", pkg)
1650
-
1651
- # Zachowaj hooki na wypadek usunięcia pakietu (pre/post-remove)
1652
- try:
1653
- if os.path.isdir(hooks_dir):
1654
- persisted = os.path.join(PAG_DB, "hooks", pkg.name)
1655
- shutil.rmtree(persisted, ignore_errors=True)
1656
- shutil.copytree(hooks_dir, persisted)
1657
- except Exception:
1658
- pass
1659
-
1660
- # Zapisz do SQLite
1661
- _db_record_files(pkg.name, installed_files)
1662
-
1663
- shutil.rmtree(staging, ignore_errors=True)
1664
- return True, installed_files, backup_journal
1665
-
1666
- except Exception as e:
1667
- _rollback_journal(journal, staging)
1668
- return False, [], backup_journal
1669
-
1670
-
1671
-def _refresh_dynamic_linker_cache(deploy_dir: str = "") -> bool:
1672
- """Odświeża cache ld.so po udanej instalacji pakietów."""
1673
- ldconfig = shutil.which("ldconfig")
1674
- if not ldconfig:
1675
- print(" ⚠ Nie znaleziono ldconfig — cache linkera nie został odświeżony.",
1676
- file=sys.stderr)
1677
- return False
1678
-
1679
- target_root = deploy_dir or PAG_ROOT
1680
- command = [ldconfig]
1681
- if target_root != "/":
1682
- command.extend(["-r", target_root])
1683
-
1684
- try:
1685
- subprocess.run(command, check=True, timeout=60,
1686
- stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
1687
- text=True)
1688
- return True
1689
- except (OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc:
1690
- detail = getattr(exc, "stderr", None) or str(exc)
1691
- print(f" ⚠ Nie udało się odświeżyć cache'a ld.so: {detail.strip()}",
1692
- file=sys.stderr)
1693
- return False
1694
-
1695
-
1696
-def _rollback_journal(journal: list, staging_path: str):
1697
- """Cofa wszystkie operacje z journala (odwrotna kolejność)."""
1698
- for entry in reversed(journal):
1699
- op = entry[0]
1700
- if op == "file":
1701
- _, src, dst = entry
1702
- try:
1703
- if os.path.exists(dst) or os.path.islink(dst):
1704
- _safe_rename(dst, src)
1705
- except Exception:
1706
- pass
1707
- elif op == "symlink":
1708
- _, _, dst = entry
1709
- try:
1710
- if os.path.islink(dst) or os.path.exists(dst):
1711
- os.remove(dst)
1712
- except Exception:
1713
- pass
1714
- elif op == "backup":
1715
- # Przywróć starą wersję pliku z backupu (upgrade)
1716
- _, bpath, dst = entry
1717
- try:
1718
- if os.path.lexists(bpath):
1719
- os.replace(bpath, dst)
1720
- except Exception:
1721
- pass
1722
- shutil.rmtree(staging_path, ignore_errors=True)
1723
-
1724
-# =============================================================================
1725
-# BEZPIECZNE USUWANIE
1726
-# =============================================================================
1727
-
1728
-def _safe_remove_files(pkg_name: str, installed_db: dict) -> Tuple[int, List[str]]:
1729
- """
1730
- Usuwa pliki pakietu, ale tylko jeśli NIE są współdzielone z innym pakietem.
1731
- Zwraca (liczba usuniętych, [lista usuniętych ścieżek]).
1732
- """
1733
- pkg_files = _db_get_package_files(pkg_name)
1734
- removed = []
1735
- skipped_shared = []
1736
-
1737
- for fpath in pkg_files:
1738
- owners = _db_get_file_owners(fpath)
1739
- # Sprawdź czy inny ZAINSTALOWANY pakiet też jest właścicielem
1740
- other_owners = [o for o in owners if o != pkg_name and o in installed_db]
1741
-
1742
- if other_owners:
1743
- # Plik współdzielony – tylko usuń wpis w DB, nie kasuj pliku
1744
- skipped_shared.append(fpath)
1745
- continue
1746
-
1747
- full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
1748
- if os.path.isfile(full) or os.path.islink(full):
1749
- os.remove(full)
1750
- removed.append(fpath)
1751
-
1752
- # Usuń puste katalogi (od najgłębszych)
1753
- dirs = set()
1754
- for fpath in removed + skipped_shared:
1755
- parent = os.path.dirname(fpath)
1756
- while parent and parent != "/":
1757
- dirs.add(parent)
1758
- parent = os.path.dirname(parent)
1759
-
1760
- for d in sorted(dirs, key=len, reverse=True):
1761
- full_d = os.path.join(PAG_ROOT, d.lstrip("/"))
1762
- if os.path.isdir(full_d):
1763
- try:
1764
- os.rmdir(full_d)
1765
- except OSError:
1766
- pass # nie jest pusty – OK
1767
-
1768
- # Usuń z SQLite
1769
- _db_remove_package_files(pkg_name)
1770
-
1771
- if skipped_shared:
1772
- print(f" ⚠ {len(skipped_shared)} plików współdzielonych zachowanych")
1773
-
1774
- return len(removed) + len(skipped_shared), removed
1775
-
1776
-
1777
-def _remove_stale_files(pkg_name: str, old_files: List[str], new_paths: List[str],
1778
- installed_db: dict, deploy_dir: str = "",
1779
- backup_dir: str = "", backup_journal: Optional[list] = None) -> Tuple[int, List[str]]:
1780
- """
1781
- Po upgrade usuwa pliki starej wersji, których nie ma w nowej.
1782
-
1783
- - Pliki współdzielone z innym zainstalowanym pakietem są ZACHOWYWANE
1784
- (usuwany jest tylko wpis z bazy `files` dla tego pakietu).
1785
- - Sprząta puste katalogi i wpisy SQLite starej wersji.
1786
- Zwraca (liczba usuniętych, [usunięte ścieżki]).
1787
- """
1788
- new_set = set(new_paths)
1789
- stale = [f for f in old_files if f not in new_set]
1790
- if not stale:
1791
- return 0, []
1792
-
1793
- root = deploy_dir or PAG_ROOT
1794
- removed = []
1795
- skipped = 0
1796
- for fpath in stale:
1797
- owners = _db_get_file_owners(fpath)
1798
- other_owners = [o for o in owners if o != pkg_name and o in installed_db]
1799
- if other_owners:
1800
- # Współdzielony z innym pakietem – tylko usuń wpis z DB dla tego pakietu
1801
- skipped += 1
1802
- else:
1803
- full = os.path.join(root, fpath.lstrip("/"))
1804
- if os.path.isfile(full) or os.path.islink(full):
1805
- try:
1806
- if backup_dir and backup_journal is not None:
1807
- backup_path = os.path.join(backup_dir, fpath.lstrip("/"))
1808
- os.makedirs(os.path.dirname(backup_path), exist_ok=True)
1809
- os.replace(full, backup_path) # przenieś do backupu (rollback)
1810
- backup_journal.append((backup_path, fpath))
1811
- else:
1812
- os.remove(full)
1813
- removed.append(fpath)
1814
- except OSError:
1815
- pass
1816
- # Usuń wpis `files` dla tego pakietu (stara wersja już go nie zawiera)
1817
- with _db_session() as db:
1818
- db.execute("DELETE FROM files WHERE package=? AND path=?", (pkg_name, fpath))
1819
-
1820
- # Usuń puste katalogi (od najgłębszych)
1821
- dirs = set()
1822
- for fpath in removed:
1823
- parent = os.path.dirname(fpath)
1824
- while parent and parent != "/":
1825
- dirs.add(parent)
1826
- parent = os.path.dirname(parent)
1827
- for d in sorted(dirs, key=len, reverse=True):
1828
- full_d = os.path.join(root, d.lstrip("/"))
1829
- if os.path.isdir(full_d):
1830
- try:
1831
- os.rmdir(full_d)
1832
- except OSError:
1833
- pass # nie jest pusty – OK
1834
-
1835
- if removed:
1836
- print(f" 🧹 Usunięto {len(removed)} nieaktualnych plików ({pkg_name})")
1837
- if skipped:
1838
- print(f" ⚠ {skipped} plików współdzielonych zachowanych")
1839
-
1840
- return len(removed), removed
1841
-
1842
-
1843
-def _new_upgrade_backup_root() -> str:
1844
- """Tworzy katalog na backupy starych wersji dla bieżącej transakcji upgrade."""
1845
- txn = datetime.now().strftime("%Y%m%dT%H%M%S") + "-" + str(os.getpid())
1846
- root = os.path.join(STAGING_DIR, "backups", txn)
1847
- os.makedirs(root, exist_ok=True)
1848
- return root
1849
-
1850
-
1851
-def _purge_old_backups(keep_root: str = ""):
1852
- """Usuwa backupy starszych transakcji (zostawia bieżący – dla `pag rollback`)."""
1853
- base = os.path.join(STAGING_DIR, "backups")
1854
- if not os.path.isdir(base):
1855
- return
1856
- for entry in os.listdir(base):
1857
- p = os.path.join(base, entry)
1858
- if p != keep_root and os.path.isdir(p):
1859
- shutil.rmtree(p, ignore_errors=True)
1860
-
1861
-# =============================================================================
1862
-# HOOKI
1863
-# =============================================================================
1864
-# Hooki uruchamiają dowolny plik z pakietu jako root — to naturalna cecha
1865
-# menedżera pakietów (apt/pacman też tak mają), dlatego MUSISZ ufać repozytorium.
1866
-# Aby ograniczyć ryzyko:
1867
-# - hook dostaje minimalne, "czyste" środowisko (bez LD_PRELOAD, BASH_ENV itp.)
1868
-# - hooki można wyłączyć (PAG_NO_HOOKS=1) i ustawić timeout (PAG_HOOK_TIMEOUT)
1869
-# - każde uruchomienie jest logowane do /var/log/pag/audit.log
1870
-# - hook ma wersjonowane API (PKG_HOOK_API)
1871
-# =============================================================================
1872
-
1873
-# Lista wykonanych hooków — trafia do wpisu transakcji (informacja w rejestrze).
1874
-_HOOKS_RUN: List[str] = []
1875
-
1876
-
1877
-def _hook_env(pkg: PackageInfo, hook_name: str) -> dict:
1878
- """Buduje minimalne środowisko dla hooka (bez niebezpiecznych zmiennych)."""
1879
- return {
1880
- "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
1881
- "HOME": "/root",
1882
- "LANG": "C.UTF-8",
1883
- "LC_ALL": "C.UTF-8",
1884
- "PKG_NAME": pkg.name,
1885
- "PKG_VERSION": pkg.version,
1886
- "PKG_ACTION": hook_name,
1887
- "PKG_HOOK_API": HOOK_API_VERSION,
1888
- }
1889
-
1890
-
1891
-def _hook_timeout() -> int:
1892
- try:
1893
- return max(1, int(os.environ.get("PAG_HOOK_TIMEOUT", "60")))
1894
- except Exception:
1895
- return 60
1896
-
1897
-
1898
-def _run_hook(hooks_dir: str, hook_name: str, pkg: PackageInfo) -> bool:
1899
- """Uruchamia skrypt hooka jeśli istnieje.
1900
-
1901
- Zwraca True jeśli hook został WYKONANY (istniał i uruchomiono go), False w
1902
- pozostałych przypadkach (brak pliku, wyłączone hooki, błąd). Obsługuje
1903
- ograniczone środowisko, timeout, logowanie do audytu i rejestr w transakcji.
1904
- """
1905
- hook_path = os.path.join(hooks_dir, hook_name)
1906
- if not os.path.exists(hook_path):
1907
- return False
1908
-
1909
- if os.environ.get("PAG_NO_HOOKS", "") == "1":
1910
- print(f" ⚠ Hook pominięty (PAG_NO_HOOKS=1): {hook_name} dla {pkg.name}")
1911
- _audit(f"hook SKIP {hook_name} {pkg.name}-{pkg.version} (PAG_NO_HOOKS=1)")
1912
- return False
1913
-
1914
- os.chmod(hook_path, 0o755)
1915
- env = _hook_env(pkg, hook_name)
1916
- tag = f"{hook_name} {pkg.name}-{pkg.version}"
1917
- try:
1918
- result = subprocess.run([hook_path], env=env, timeout=_hook_timeout(),
1919
- check=False, capture_output=True, text=True,
1920
- cwd="/")
1921
- _HOOKS_RUN.append(tag)
1922
- if result.returncode != 0:
1923
- print(f" ⚠ Hook {hook_name} dla {pkg.name} zakończony z kodem {result.returncode}")
1924
- if result.stderr:
1925
- print(f" {result.stderr.strip()[-200:]}")
1926
- _audit(f"hook FAIL {tag} rc={result.returncode}")
1927
- else:
1928
- _audit(f"hook OK {tag}")
1929
- return True
1930
- except subprocess.TimeoutExpired:
1931
- print(f" ⚠ Hook {hook_name} dla {pkg.name} przekroczył timeout ({_hook_timeout()}s)")
1932
- _audit(f"hook TIMEOUT {tag}")
1933
- return False
1934
- except Exception as e:
1935
- print(f" ⚠ Hook {hook_name} dla {pkg.name}: {e}")
1936
- _audit(f"hook ERROR {tag}: {e}")
1937
- return False
1938
-
1939
-# =============================================================================
1940
-# TRANSAKCJE I ROLLBACK
1941
-# =============================================================================
1942
-
1943
-def _record_transaction(action, packages, success, snapshot, file_journal=None, hooks=None,
1944
- upgrade_backups=None, upgrade_backup_root=""):
1945
- history = load_json(HISTORY_FILE) if os.path.exists(HISTORY_FILE) else []
1946
- # Rejestr wykonanych hooków – informacja o tym, że uruchomiono kod pakietu
1947
- # jako root. Trafia do historii, by dało się później sprawdzić, co się działo.
1948
- executed_hooks = list(_HOOKS_RUN) if hooks is None else hooks
1949
- _HOOKS_RUN.clear()
1950
- entry = {
1951
- "action": action, "packages": packages, "success": success,
1952
- "timestamp": datetime.now().isoformat(),
1953
- "snapshot": snapshot,
1954
- "file_journal": file_journal, # lista plików do wycofania
1955
- "hooks": executed_hooks, # wykonane hooki (pre/post-install/remove)
1956
- }
1957
- if upgrade_backups:
1958
- entry["upgrade_backups"] = upgrade_backups # {dst: backup_path}
1959
- entry["upgrade_backup_root"] = upgrade_backup_root
1960
- history.append(entry)
1961
- if len(history) > 50:
1962
- history = history[-50:]
1963
- save_json(HISTORY_FILE, history)
1964
-
1965
-def cmd_history():
1966
- if not os.path.exists(HISTORY_FILE):
1967
- print(_("no_history")); return
1968
- history = load_json(HISTORY_FILE)
1969
- if not history:
1970
- print(_("no_history")); return
1971
- print(f"Ostatnie transakcje ({len(history)}):")
1972
- for i, e in enumerate(reversed(history), 1):
1973
- icon = "✅" if e["success"] else "❌"
1974
- pkgs = ", ".join(e["packages"][:5])
1975
- if len(e["packages"]) > 5: pkgs += f" (+{len(e['packages'])-5})"
1976
- print(f" {i}. {icon} {e['action']}: {pkgs}")
1977
- print(f" {e['timestamp']}")
1978
-
1979
-def cmd_rollback():
1980
- if not os.path.exists(HISTORY_FILE):
1981
- print(_("no_history")); return 1
1982
- history = load_json(HISTORY_FILE)
1983
- if not history:
1984
- print(_("no_history")); return 1
1985
-
1986
- last = None
1987
- for e in reversed(history):
1988
- if e["success"] and e.get("snapshot"):
1989
- last = e; break
1990
-
1991
- if not last:
1992
- print("❌ No snapshot to restore."); return 1
1993
-
1994
- print(f"⏪ Rolling back: {last['action']} ({last['timestamp']})")
1995
- print(f" Packages: {', '.join(last['packages'][:10])}")
1996
-
1997
- if not _ask_confirm():
1998
- return 0
1999
-
2000
- # Przywróć installed.json
2001
- save_json(INSTALLED_DB, last["snapshot"])
2002
-
2003
- # Wycofaj fizyczne pliki (jeśli zapisano journal)
2004
- file_journal = last.get("file_journal", [])
2005
- upgrade_backups = last.get("upgrade_backups", {}) or {}
2006
- backup_root = last.get("upgrade_backup_root", "")
2007
-
2008
- # Przywróć stare wersje z backupów (upgrade) – nadpisane i usunięte stale pliki
2009
- for dst, bpath in upgrade_backups.items():
2010
- full = os.path.join(PAG_ROOT, dst.lstrip("/"))
2011
- if bpath and os.path.lexists(bpath):
2012
- try:
2013
- os.makedirs(os.path.dirname(full), exist_ok=True)
2014
- os.replace(bpath, full)
2015
- except OSError:
2016
- pass
2017
-
2018
- # Usuń nowe pliki (które nie miały poprzedniej wersji)
2019
- backed = set(upgrade_backups)
2020
- if file_journal:
2021
- for fpath in reversed(file_journal):
2022
- if fpath in backed:
2023
- continue
2024
- full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
2025
- if os.path.exists(full) or os.path.islink(full):
2026
- os.remove(full)
2027
- print(f" {_('rollback_files', len(file_journal))}")
2028
-
2029
- # Sprzątanie pustych katalogów + katalogu backupów
2030
- dirs = set()
2031
- for fpath in file_journal:
2032
- parent = os.path.dirname(fpath)
2033
- while parent and parent != "/":
2034
- dirs.add(parent)
2035
- parent = os.path.dirname(parent)
2036
- for d in sorted(dirs, key=len, reverse=True):
2037
- full_d = os.path.join(PAG_ROOT, d.lstrip("/"))
2038
- if os.path.isdir(full_d):
2039
- try:
2040
- os.rmdir(full_d)
2041
- except OSError:
2042
- pass
2043
- if backup_root:
2044
- shutil.rmtree(backup_root, ignore_errors=True)
2045
-
2046
- print(f"✅ {_('rollback_restored')}")
2047
- _record_transaction("rollback", last["packages"], True, None)
2048
- return 0
2049
-
2050
-# =============================================================================
2051
-# INSTALACJA
2052
-# =============================================================================
2053
-
2054
-def _install_local_pkg_files(paths, install_succeeded):
2055
- """Instaluje lokalne pliki .pkg.tar.xz (bez repozytorium).
2056
- Zgodnie z _atomic_install każdy plik jest instalowany atomowo.
2057
- Zwraca (failed_count, installed_files)."""
2058
- failed = 0
2059
- all_files = []
2060
- for p in paths:
2061
- p = os.path.abspath(p)
2062
- if not os.path.isfile(p):
2063
- print(f" ❌ Nie znaleziono pakietu: {p}")
2064
- failed += 1
2065
- continue
2066
- try:
2067
- with tarfile.open(p, "r:xz") as tf:
2068
- meta = tf.extractfile("metadata.json")
2069
- if meta is None:
2070
- print(f" ❌ {p}: brak metadata.json")
2071
- failed += 1
2072
- continue
2073
- data = json.loads(meta.read())
2074
- except Exception as e:
2075
- print(f" ❌ {p}: nie udało się odczytać pakietu ({e})")
2076
- failed += 1
2077
- continue
2078
- pkg = PackageInfo(data, repo="local")
2079
- print(f" ↓ {pkg.name}-{pkg.version} (lokalny) ... ", end="", flush=True)
2080
- ok, files, _ = _atomic_install(p, pkg)
2081
- if ok:
2082
- install_succeeded(pkg, files)
2083
- all_files.extend(f["path"] for f in files)
2084
- print("✅")
2085
- else:
2086
- print("❌")
2087
- failed += 1
2088
- return failed, all_files
2089
-
2090
-
2091
-def _preflight_disk(total_bytes: int) -> bool:
2092
- """Pre-flight przed transakcją: wolne miejsce + mount read-only.
2093
-
2094
- Zwraca False (przerywa instalację) gdy na partycji docelowej brakuje
2095
- miejsca na pakiety albo katalog stagingu jest zamontowany read-only
2096
- (inaczej instalacja rwałaby się w połowie, zostawiając uszkodzony system).
2097
- """
2098
- target = PAG_ROOT or "/"
2099
- try:
2100
- st = os.statvfs(target)
2101
- free = st.f_bavail * st.f_frsize
2102
- except OSError:
2103
- return True # nie da się sprawdzić – nie blokuj
2104
- need_mb = total_bytes // 1048576
2105
- free_mb = free // 1048576
2106
- if free < total_bytes:
2107
- print(f" ❌ Za mało miejsca na dysku: potrzeba ~{need_mb} MB, "
2108
- f"wolne {free_mb} MB ({target})")
2109
- return False
2110
- if free < total_bytes * 3:
2111
- print(f" ⚠ Mało miejsca na dysku: wolne {free_mb} MB, "
2112
- f"pakiety ~{need_mb} MB (rozpakowane zajmą więcej)")
2113
- # Wykryj mount read-only (test zapisu w stagingu)
2114
- try:
2115
- probe = os.path.join(STAGING_DIR, ".pag-probe")
2116
- with open(probe, "w") as f:
2117
- f.write("x")
2118
- os.remove(probe)
2119
- except OSError:
2120
- print(f" ❌ {target} jest zamontowane tylko-do-odczytu – nie można instalować.")
2121
- return False
2122
- return True
2123
-
2124
-
2125
-def cmd_install(package_names, as_dep=False, upgrade=False):
2126
- ensure_dirs()
2127
- installed_db = load_json(INSTALLED_DB)
2128
- world = load_world()
2129
- pinned = load_json(PINNED_FILE)
2130
-
2131
- # Obsługa lokalnych plików .pkg.tar.xz (zbudowanych przez pagbuild) –
2132
- # nie wymaga repozytorium ani GPG.
2133
- local_files = [p for p in package_names if p.endswith(PKG_EXT) or
2134
- (os.sep in p and os.path.isfile(os.path.abspath(p)))]
2135
- if local_files:
2136
- _local_need = sum(
2137
- os.path.getsize(os.path.abspath(p))
2138
- for p in local_files if os.path.isfile(os.path.abspath(p))
2139
- )
2140
- if not _preflight_disk(_local_need):
2141
- return 1
2142
-
2143
- def _ok(pkg, files):
2144
- installed_db[pkg.name] = {
2145
- "version": pkg.version, "description": pkg.description,
2146
- "dependencies": pkg.dependencies, "size_bytes": pkg.size_bytes,
2147
- "sha256": pkg.sha256, "installed_at": datetime.now().isoformat(),
2148
- "repo": "local",
2149
- "provides": getattr(pkg, "provides", None) or [],
2150
- "provides_so": getattr(pkg, "provides_so", None) or [],
2151
- "requires_so": getattr(pkg, "requires_so", None) or [],
2152
- }
2153
- world.add(pkg.name)
2154
- failed_local, _fl = _install_local_pkg_files(local_files, _ok)
2155
- save_json(INSTALLED_DB, installed_db)
2156
- save_world(world)
2157
- if failed_local:
2158
- return 1
2159
- _refresh_dynamic_linker_cache()
2160
- package_names = [n for n in package_names if n not in
2161
- [os.path.abspath(x) for x in local_files] and
2162
- n not in local_files]
2163
- to_install = []
2164
- if not package_names:
2165
- return 0
2166
- # pozostałe argumenty to nazwy pakietów z repo – kontynuuj
2167
-
2168
- repo_pkgs = fetch_all_packages()
2169
-
2170
- if not repo_pkgs:
2171
- print(f"❌ {_('no_index')}"); return 1
2172
-
2173
- for name in list(package_names):
2174
- if name in pinned:
2175
- print(f"⚠ {name} {_('pinned_to')} {pinned[name]} – skipping")
2176
- package_names.remove(name)
2177
-
2178
- to_install, missing_deps = _resolve_deps(package_names, repo_pkgs, installed_db)
2179
-
2180
- # ── Pakiety, których NIE MA w repo ani nie są zainstalowane ──
2181
- # Zgłoś od razu zamiast mylącego „Do zainstalowania: N (0.00 MB)”
2182
- # i prośby o potwierdzenie (np. `pag install steam` gdy steam nie istnieje).
2183
- not_found = []
2184
- for n in package_names:
2185
- real = _resolve_provides(n, repo_pkgs, installed_db)
2186
- if real not in repo_pkgs and real not in installed_db \
2187
- and not os.path.exists(os.path.abspath(n)):
2188
- not_found.append(n)
2189
- if not_found:
2190
- print(f"\n ❌ {_('pkg_not_found', ', '.join(not_found))}")
2191
- print(f" {_('not_found_hint')}")
2192
- return 1
2193
-
2194
- # --- Tryb upgrade: pakiety już zainstalowane MUSZĄ zostać ponownie
2195
- # zainstalowane z nowszej wersji (zastąpienie w tej samej transakcji).
2196
- if upgrade:
2197
- # `pag update` przekazuje tu tylko pakiety z NOWSZĄ wersją (już
2198
- # przefiltrowane w _pending_updates), a `pag install -f` wymusza
2199
- # reinstalację nawet tej SAMEJ wersji – dlatego nie filtrujemy po
2200
- # _version_newer.
2201
- upgrade_targets = [
2202
- name for name in package_names
2203
- if name in repo_pkgs
2204
- and name in installed_db
2205
- and name not in pinned
2206
- ]
2207
- for name in upgrade_targets:
2208
- if name not in to_install:
2209
- to_install.append(name)
2210
-
2211
- if not to_install and not missing_deps:
2212
- print(f"✅ {_('all_installed')}"); return 0
2213
-
2214
- # ── WERYFIKACJA ZALEŻNOŚCI ──────────────────────────────────────────
2215
- fatal_missing = _verify_dependencies(to_install, repo_pkgs, installed_db)
2216
-
2217
- if fatal_missing > 0:
2218
- print(f"❌ Nie można kontynuować – {fatal_missing} brakujących zależności.")
2219
- print(f" Zainstaluj brakujące pakiety lub dodaj repozytoria.")
2220
- return 1
2221
-
2222
- so_missing = _verify_so_deps(to_install, repo_pkgs, installed_db)
2223
- if so_missing > 0:
2224
- print(" Zainstaluj dostawcę biblioteki lub zaktualizuj repozytorium.")
2225
- return 1
2226
-
2227
- if not to_install:
2228
- print(f"✅ {_('all_installed')}"); return 0
2229
-
2230
- MAX_MB = MAX_PKG_SIZE // 1048576
2231
- for n in to_install:
2232
- if not _validate_pkg_name(n):
2233
- print(f" {_("sec_badname", name=n)}")
2234
- return 1
2235
- sz = repo_pkgs[n].size_bytes if n in repo_pkgs else 0
2236
- if sz > MAX_PKG_SIZE:
2237
- mb = sz // 1048576
2238
- print(f" {_("sec_toobig", size_mb=mb, max_mb=MAX_MB)}")
2239
- return 1
2240
- total_size = sum(repo_pkgs[n].size_bytes for n in to_install if n in repo_pkgs)
2241
- if not _preflight_disk(total_size):
2242
- return 1
2243
- print(f"\n📦 {_('to_install', len(to_install), total_size/1048576)}")
2244
- for name in to_install:
2245
- p = repo_pkgs.get(name)
2246
- if p:
2247
- if name in installed_db:
2248
- marker = " [upgrade]" if upgrade else ""
2249
- else:
2250
- marker = f" [{_('new')}]"
2251
- print(f" {name}-{p.version}{marker}")
2252
-
2253
- if not as_dep and not upgrade:
2254
- if not _ask_confirm():
2255
- print(_("cancelled")); return 0
2256
-
2257
- snapshot = json.loads(json.dumps(installed_db))
2258
- all_installed_files = []
2259
- failed = []
2260
- # Pary (pkg, stare_pliki, nowe_pliki) do usunięcia martwych plików po upgrade
2261
- stale_candidates = []
2262
- # Katalog backupów starych wersji (upgrade) – dla poprawnego rollbacku
2263
- backup_root = ""
2264
- all_backups: List[Tuple[str, str]] = [] # (backup_path, dst)
2265
- if upgrade and to_install:
2266
- backup_root = _new_upgrade_backup_root()
2267
-
2268
- # --- Dziennik transakcji (dla pełnej atomowości) ---
2269
- # Jeśli którykolwiek pakiet zawiedzie, cofamy WSZYSTKIE zainstalowane
2270
- # w tej transakcji przez _rollback_transaction().
2271
- transaction_journal: List[Tuple[str, str, str]] = [] # (op, src, dst)
2272
-
2273
- # --- Tryb immutable: utwórz nowy deployment ---
2274
- immutable = os.environ.get("PAG_IMMUTABLE", "") == "1"
2275
- deploy_dir = ""
2276
- deploy_id = ""
2277
- if immutable:
2278
- print(f"\n 🏗️ Tworzenie nowego deploymentu...")
2279
- deploy_dir, deploy_id = _create_deployment(to_install, "upgrade" if upgrade else "install")
2280
- target_root = deploy_dir
2281
- else:
2282
- target_root = ""
2283
-
2284
- # --- Faza 1: Równoległe pobieranie wszystkich pakietów ---
2285
- to_download = [repo_pkgs[name] for name in to_install if name in repo_pkgs]
2286
- if len(to_download) > 1:
2287
- print(f"\n ⏬ Pobieranie {len(to_download)} pakietów równolegle...")
2288
- downloaded = _download_packages_parallel(to_download)
2289
- else:
2290
- downloaded = {}
2291
-
2292
- # --- Faza 2: Instalacja z paskiem postępu ---
2293
- t0 = time.time()
2294
-
2295
- for name in to_install:
2296
- pkg = repo_pkgs.get(name)
2297
- if not pkg:
2298
- print(f" ❌ {name}: {_('not_found')}")
2299
- failed.append(name)
2300
- break
2301
-
2302
- # Pasek postępu na stderr (nie koliduje z download barem)
2303
- idx = len(all_installed_files) + 1
2304
- pct = (idx - 1) / len(to_install) * 100
2305
- fl = int(25 * pct / 100)
2306
- pbar = "█" * fl + "░" * (25 - fl)
2307
- elapsed = time.time() - t0
2308
- if idx > 1 and elapsed > 0:
2309
- avg = elapsed / (idx - 1)
2310
- remaining = avg * (len(to_install) - idx + 1)
2311
- if remaining < 60:
2312
- eta_s = f" ~{remaining:.0f}s"
2313
- else:
2314
- eta_s = f" ~{remaining/60:.1f}m"
2315
- else:
2316
- eta_s = ""
2317
- status = f" [{pbar}] {idx}/{len(to_install)} ({pct:.0f}%){eta_s}"
2318
- print(status, file=sys.stderr, flush=True)
2319
-
2320
- print(f" ↓ {name}-{pkg.version} ...", end=" ", flush=True)
2321
-
2322
- # Pobierz (z cache fazy 1 lub bezpośrednio)
2323
- pkg_path = downloaded.get(name) if name in downloaded else _download_pkg(pkg)
2324
- if not pkg_path:
2325
- print(f"❌ {_('download_fail')}")
2326
- failed.append(name)
2327
- break # przerwij transakcję
2328
-
2329
- # GPG
2330
- gpg_ok, gpg_msg = _verify_pkg_gpg(pkg_path, repo_url=pkg.repo_url)
2331
- if not gpg_ok:
2332
- print(f"❌ {_('gpg_fail')}: {gpg_msg[:60]}")
2333
- failed.append(name)
2334
- break # PRZERWIJ – niezaufany pakiet
2335
-
2336
- # SHA256 całego pakietu
2337
- if pkg.sha256 and _sha256_file(pkg_path) != pkg.sha256:
2338
- print(f"❌ {_('sha256_mismatch')}")
2339
- failed.append(name)
2340
- break # PRZERWIJ – uszkodzony pakiet
2341
-
2342
- # Przed instalacją zapamiętaj pliki starej wersji (potrzebne w upgrade)
2343
- old_files = _db_get_package_files(name) if name in installed_db else []
2344
-
2345
- # Atomowa instalacja (w upgrade backupuje nadpisywane pliki)
2346
- ok, files, backup_j = _atomic_install(pkg_path, pkg, deploy_dir,
2347
- backup_dir=backup_root)
2348
- if ok:
2349
- installed_db[name] = {
2350
- "version": pkg.version, "description": pkg.description,
2351
- "dependencies": pkg.dependencies, "size_bytes": pkg.size_bytes,
2352
- "sha256": pkg.sha256, "installed_at": datetime.now().isoformat(),
2353
- "repo": pkg.repo_url,
2354
- "provides": getattr(pkg, "provides", None) or [],
2355
- "provides_so": getattr(pkg, "provides_so", None) or [],
2356
- "requires_so": getattr(pkg, "requires_so", None) or [],
2357
- }
2358
- if not as_dep and name in package_names:
2359
- world.add(name)
2360
- print("✅")
2361
- all_installed_files.extend(f["path"] for f in files)
2362
- all_backups.extend(backup_j)
2363
-
2364
- # Upgrade: zapamiętaj stare pliki, by po sukcesie usunąć te,
2365
- # których nie ma już w nowej wersji.
2366
- if upgrade and old_files:
2367
- stale_candidates.append((name, old_files, [f["path"] for f in files]))
2368
-
2369
- # Po instalacji kernela – przebuduj initramfs
2370
- if _is_kernel_package(name):
2371
- _rebuild_initramfs(deploy_dir)
2372
- else:
2373
- print("❌")
2374
- failed.append(name)
2375
- break # PRZERWIJ – błąd instalacji
2376
-
2377
- # --- Rollback całej transakcji jeśli cokolwiek zawiodło ---
2378
- if failed:
2379
- print(f"\n ↩ Cofanie transakcji ({len(failed)} błędów)...")
2380
- _rollback_transaction(installed_db, snapshot, all_installed_files,
2381
- deploy_dir, immutable, backups=all_backups)
2382
- if backup_root:
2383
- shutil.rmtree(backup_root, ignore_errors=True)
2384
- _record_transaction("upgrade" if upgrade else "install", to_install, False, snapshot)
2385
- return 1
2386
-
2387
- # --- Po sukcesie transakcji: usuń nieaktualne pliki starych wersji (upgrade).
2388
- # Usunięte pliki trafiają do backupu, aby `pag rollback` mógł je przywrócić.
2389
- for pkg_name, old_files, new_paths in stale_candidates:
2390
- _remove_stale_files(pkg_name, old_files, new_paths, installed_db, deploy_dir,
2391
- backup_root, all_backups)
2392
-
2393
- save_json(INSTALLED_DB, installed_db)
2394
- save_world(world)
2395
- _record_transaction("upgrade" if upgrade else "install", to_install, True, snapshot,
2396
- file_journal=all_installed_files,
2397
- upgrade_backups={dst: bp for bp, dst in all_backups} if all_backups else None,
2398
- upgrade_backup_root=backup_root)
2399
-
2400
- # Zachowaj backupy bieżącej transakcji (dla `pag rollback`), usuń starsze.
2401
- if backup_root:
2402
- _purge_old_backups(keep_root=backup_root)
2403
-
2404
- # --- Tryb immutable: przełącz na nowy deployment ---
2405
- if immutable and not failed:
2406
- _refresh_dynamic_linker_cache(deploy_dir)
2407
- print(f"\n 🔄 Przełączanie na deployment {deploy_id}...")
2408
- _switch_deployment(deploy_dir)
2409
- print(f" ✅ Aktywny deployment: {deploy_id}")
2410
- _update_grub_config()
2411
- cmd_deploy_cleanup(keep=5) # Zostawia 5 najnowszych deploymentów
2412
- print(f" 💡 Restart wymagany do przeładowania systemu.")
2413
- else:
2414
- _refresh_dynamic_linker_cache()
2415
- # Hooki zbiorcze – raz na transakcję (fc-cache itp.), tylko gdy pliki
2416
- # trafiły do realnego systemu (nie do deploymentu).
2417
- _process_triggers(all_installed_files)
2418
-
2419
- print(f"\n✅ {_('installed', len(to_install))}")
2420
- return 0
2421
-
2422
-
2423
-def _rollback_transaction(installed_db: dict, snapshot: dict,
2424
- installed_files: List[str],
2425
- deploy_dir: str, is_immutable: bool,
2426
- backups: Optional[List[Tuple[str, str]]] = None):
2427
- """
2428
- Cofa WSZYSTKIE pakiety zainstalowane w bieżącej transakcji.
2429
- Przywraca installed_db do stanu sprzed transakcji.
2430
- Usuwa fizyczne pliki z systemu (lub deploymentu w trybie immutable).
2431
- Jeśli podano `backups` (upgrade) – przywraca stare wersje nadpisanych plików.
2432
- """
2433
- # Przywróć installed_db
2434
- installed_db.clear()
2435
- installed_db.update(snapshot)
2436
-
2437
- root = deploy_dir if is_immutable else PAG_ROOT
2438
- backup_map = {dst: src for src, dst in (backups or [])}
2439
-
2440
- # Przywróć stare wersje z backupów (upgrade)
2441
- for dst, bpath in backup_map.items():
2442
- full = os.path.join(root, dst.lstrip("/"))
2443
- if os.path.lexists(bpath):
2444
- try:
2445
- os.makedirs(os.path.dirname(full), exist_ok=True)
2446
- os.replace(bpath, full)
2447
- except OSError:
2448
- pass
2449
-
2450
- # Usuń nowe pliki (które nie miały poprzedniej wersji)
2451
- for fpath in reversed(installed_files):
2452
- if fpath in backup_map:
2453
- continue
2454
- full = os.path.join(root, fpath.lstrip("/"))
2455
- if os.path.isfile(full) or os.path.islink(full):
2456
- try:
2457
- os.remove(full)
2458
- except OSError:
2459
- pass
2460
-
2461
- # Wyczyść puste katalogi
2462
- dirs_to_check = set()
2463
- for fpath in installed_files:
2464
- parent = os.path.dirname(fpath)
2465
- while parent and parent != "/":
2466
- dirs_to_check.add(parent)
2467
- parent = os.path.dirname(parent)
2468
- for d in sorted(dirs_to_check, key=len, reverse=True):
2469
- full_d = os.path.join(root, d.lstrip("/"))
2470
- if os.path.isdir(full_d):
2471
- try:
2472
- os.rmdir(full_d)
2473
- except OSError:
2474
- pass
2475
-
2476
- # W trybie immutable: usuń nieudany deployment
2477
- if is_immutable and deploy_dir:
2478
- shutil.rmtree(deploy_dir, ignore_errors=True)
2479
-
2480
- save_json(INSTALLED_DB, snapshot)
2481
-
2482
-
2483
-# =============================================================================
2484
-# USUWANIE
2485
-# =============================================================================
2486
-
2487
-def cmd_remove(package_names):
2488
- installed_db = load_json(INSTALLED_DB)
2489
- world = load_world()
2490
- snapshot = json.loads(json.dumps(installed_db))
2491
- removed = []
2492
- removed_files = []
2493
-
2494
- total = len(package_names)
2495
- for i, name in enumerate(package_names, 1):
2496
- if name not in installed_db:
2497
- print(f" ⚠ {name}: not installed"); continue
2498
-
2499
- # Pasek postępu
2500
- pct = (i - 1) / total * 100
2501
- filled = int(25 * pct / 100)
2502
- print(f" 🗑 [{'█' * filled + '░' * (25 - filled)}] {i}/{total} ({pct:.0f}%) ", end="\r", file=sys.stderr, flush=True)
2503
-
2504
- print(f"🗑 {name}-{installed_db[name]['version']} ...", end=" ", flush=True)
2505
-
2506
- # Pre-remove hook (jeśli dostępny w staging)
2507
- _run_hook_for_installed(name, "pre-remove")
2508
-
2509
- count, rm_files = _safe_remove_files(name, installed_db)
2510
- del installed_db[name]
2511
- world.discard(name)
2512
- removed.append(name)
2513
- removed_files.extend(rm_files)
2514
- print(f"✅ ({count} files)")
2515
-
2516
- # Post-remove hook + sprzątanie zapisanych hooków
2517
- _run_hook_for_installed(name, "post-remove")
2518
- shutil.rmtree(os.path.join(PAG_DB, "hooks", name), ignore_errors=True)
2519
-
2520
- save_json(INSTALLED_DB, installed_db)
2521
- save_world(world)
2522
- _record_transaction("remove", removed, True, snapshot)
2523
-
2524
- print(file=sys.stderr) # wyczyść linię paska postępu
2525
-
2526
- if not removed: return 0
2527
- print(f"\n✅ Removed {len(removed)}.")
2528
- _process_triggers(removed_files)
2529
-
2530
- orphans = _find_orphans(installed_db, world)
2531
- if orphans:
2532
- print(f"\n💡 {_('orphans_found', len(orphans), ', '.join(sorted(orphans)[:10]))}")
2533
- print(" 'pag remove-orphans' to clean up.")
2534
- return 0
2535
-
2536
-def _run_hook_for_installed(pkg_name, hook_name):
2537
- """Próbuje uruchomić hook z katalogu pakietu (jeśli został zapisany)."""
2538
- hook_dir = os.path.join(PAG_DB, "hooks", pkg_name)
2539
- if os.path.isdir(hook_dir):
2540
- ver = load_json(INSTALLED_DB).get(pkg_name, {}).get("version", "")
2541
- _run_hook(hook_dir, hook_name, PackageInfo({"name": pkg_name, "version": ver}))
2542
-
2543
-
2544
-# =============================================================================
2545
-# TRIGGERS – hooki zbiorcze (raz na transakcję, nie per pakiet)
2546
-# =============================================================================
2547
-# Wzorem pacman/dpkg: pakiet/administrator deklaruje zainteresowanie ścieżkami,
2548
-# a pasujący trigger uruchamia się DOKŁADNIE RAZ na końcu transakcji
2549
-# (np. fc-cache, glib-compile-schemas, update-desktop-database) zamiast po
2550
-# każdym pakiecie z osobna.
2551
-
2552
-TRIGGERS_DIR = PAG_CONF + "/triggers"
2553
-
2554
-DEFAULT_TRIGGERS = [
2555
- {"name": "font-cache", "paths": ["/usr/share/fonts/", "/usr/local/share/fonts/"],
2556
- "run": "fc-cache -fs"},
2557
- {"name": "glib-schemas", "paths": ["/usr/share/glib-2.0/schemas/"],
2558
- "run": "glib-compile-schemas /usr/share/glib-2.0/schemas"},
2559
- {"name": "desktop-database", "paths": ["/usr/share/applications/"],
2560
- "run": "update-desktop-database -q /usr/share/applications"},
2561
- {"name": "mime-database", "paths": ["/usr/share/mime/"],
2562
- "run": "update-mime-database /usr/share/mime"},
2563
-]
2564
-
2565
-def _load_triggers() -> List[dict]:
2566
- """Ładuje triggery: domyślne (tylko gdy binarka istnieje) + /etc/pag/triggers/*.json."""
2567
- out = []
2568
- for t in DEFAULT_TRIGGERS:
2569
- bin_name = t["run"].split()[0]
2570
- if shutil.which(bin_name):
2571
- out.append(dict(t))
2572
- if os.path.isdir(TRIGGERS_DIR):
2573
- for fn in sorted(os.listdir(TRIGGERS_DIR)):
2574
- if not fn.endswith(".json"):
2575
- continue
2576
- try:
2577
- with open(os.path.join(TRIGGERS_DIR, fn)) as f:
2578
- data = json.load(f)
2579
- except (OSError, json.JSONDecodeError):
2580
- continue
2581
- if isinstance(data, dict):
2582
- data = [data]
2583
- for t in data:
2584
- if isinstance(t, dict) and t.get("name") and t.get("paths") and t.get("run"):
2585
- out.append(t)
2586
- return out
2587
-
2588
-def _process_triggers(touched_paths: List[str]):
2589
- """Uruchamia pasujące triggery RAZ na końcu transakcji (best-effort)."""
2590
- if not touched_paths:
2591
- return
2592
- if os.environ.get("PAG_NO_HOOKS", "") == "1":
2593
- return
2594
- import shlex as _shlex
2595
- matched = []
2596
- for trig in _load_triggers():
2597
- if any(path.startswith(p) for p in trig["paths"] for path in touched_paths):
2598
- matched.append(trig)
2599
- for trig in matched:
2600
- run = trig["run"]
2601
- print(f" ⚡ Trigger: {trig['name']} ({run})")
2602
- try:
2603
- r = subprocess.run(_shlex.split(run), capture_output=True, text=True, timeout=120)
2604
- _audit(f"TRIGGER {trig['name']}: {run} rc={r.returncode}")
2605
- if r.returncode != 0:
2606
- print(f" ⚠ rc={r.returncode}: {(r.stderr or r.stdout or '').strip()[:160]}")
2607
- except subprocess.TimeoutExpired:
2608
- print(f" ⚠ trigger {trig['name']} przekroczył limit czasu (120 s)")
2609
- _audit(f"TRIGGER {trig['name']} TIMEOUT")
2610
- except Exception as e:
2611
- print(f" ⚠ trigger {trig['name']}: {e}")
2612
-
2613
-# =============================================================================
2614
-# UPDATE / UPGRADE / LIST / SEARCH / INFO / VERIFY
2615
-# =============================================================================
2616
-
2617
-def _cleanup_tmp_files(*paths):
2618
- """Usuwa tymczasowe pliki (np. .pag.new) po nieudanej operacji."""
2619
- for p in paths:
2620
- try:
2621
- if os.path.isfile(p):
2622
- os.remove(p)
2623
- except OSError:
2624
- pass
2625
-
2626
-
2627
-def cmd_self_update():
2628
- """Aktualizuje samego klienta pag z repo (podpisany /stable/pag).
2629
-
2630
- Kolejność: pobierz → weryfikacja GPG (+ fingerprint repo) → SHA256 →
2631
- kontrola składni (compile) → backup → atomowe os.replace. Nowa wersja
2632
- idzie do tego samego katalogu (/usr/local/bin/.pag.new), dzięki czemu
2633
- podmiana jest atomowa; jeśli system padnie w trakcie, stary pag zostaje.
2634
- """
2635
- repos = get_repos()
2636
- if not repos:
2637
- print("❌ Brak repozytoriów w konfiguracji.")
2638
- return 1
2639
- base = repos[0]
2640
- dst = "/usr/local/bin/pag"
2641
- dst_new = dst + ".new"
2642
- dst_bak = dst + ".bak"
2643
- print(f"🔄 Sprawdzam aktualizację pag z {base}...")
2644
- try:
2645
- with urlopen(Request(f"{base}/pag", headers={"User-Agent": "pag/3.0"}), timeout=20) as r:
2646
- data = r.read()
2647
- with urlopen(Request(f"{base}/pag.asc", headers={"User-Agent": "pag/3.0"}), timeout=20) as r:
2648
- sig = r.read()
2649
- except Exception as e:
2650
- print(f" ❌ Nie można pobrać pag: {e}")
2651
- return 1
2652
-
2653
- # Zapisz nową wersję w katalogu docelowym (ta sama partycja → atomowy rename)
2654
- with open(dst_new, "wb") as f:
2655
- f.write(data)
2656
- with open(dst_new + ".asc", "wb") as f:
2657
- f.write(sig)
2658
-
2659
- # --- 1. Weryfikacja podpisu GPG – bez tego nie instalujemy ---
2660
- insecure = os.environ.get("PAG_INSECURE", "") == "1"
2661
- ok, fp = _gpg_verify_fp(dst_new + ".asc", dst_new)
2662
- if not ok:
2663
- # Automatyczny import klucza (TOFU) – jak w _verify_repo_sig
2664
- res = _gpg_run("--verify", dst_new + ".asc", dst_new,
2665
- capture_output=True, text=True)
2666
- _stderr = res.stderr.decode(errors="replace") if isinstance(res.stderr, bytes) else (res.stderr or "")
2667
- if "public key" in _stderr.lower() and "no public key" in _stderr.lower():
2668
- try:
2669
- with urlopen(Request(f"{base}/paganos.asc", headers={"User-Agent": "pag/3.0"}), timeout=20) as r:
2670
- keydata = r.read()
2671
- with tempfile.NamedTemporaryFile(delete=False, suffix=".asc") as tmp:
2672
- tmp.write(keydata); tmp.flush()
2673
- _gpg_run("--import", tmp.name, capture_output=True, timeout=30)
2674
- os.unlink(tmp.name)
2675
- print(f" 🔑 Importowano klucz repo z {base}/paganos.asc")
2676
- ok, fp = _gpg_verify_fp(dst_new + ".asc", dst_new)
2677
- except Exception:
2678
- pass
2679
- if not ok:
2680
- if insecure:
2681
- print(" ⚠ Nieprawidłowy podpis aktualizacji (PAG_INSECURE – ignoruję)")
2682
- else:
2683
- print(" ❌ Nieprawidłowy podpis aktualizacji – nie aktualizuję.")
2684
- _cleanup_tmp_files(dst_new, dst_new + ".asc")
2685
- return 1
2686
- # Sprawdź fingerprint względem przypiętego klucza repo
2687
- pinned = _repo_pinned_fp(base)
2688
- if pinned:
2689
- if not fp:
2690
- print(" ❌ Nie można potwierdzić fingerprintu podpisu aktualizacji.")
2691
- _cleanup_tmp_files(dst_new, dst_new + ".asc")
2692
- return 1
2693
- if fp != pinned.upper():
2694
- if insecure:
2695
- print(" ⚠ Podpis aktualizacji innym kluczem (PAG_INSECURE – ignoruję)")
2696
- else:
2697
- print(" ❌ [SECURITY ERROR] Podpis aktualizacji innym kluczem niż repo!")
2698
- print(f" Oczekiwany: {pinned}, Otrzymany: {fp}")
2699
- _cleanup_tmp_files(dst_new, dst_new + ".asc")
2700
- return 1
2701
-
2702
- # --- 2. Weryfikacja SHA256 (jeśli repo publikuje pag.sha256) ---
2703
- try:
2704
- with urlopen(Request(f"{base}/pag.sha256", headers={"User-Agent": "pag/3.0"}), timeout=15) as r:
2705
- sha = r.read().decode().strip().split()[0]
2706
- if sha:
2707
- actual = hashlib.sha256(data).hexdigest()
2708
- if actual.lower() != sha.lower():
2709
- print(f" ❌ SHA256 niezgodny! Oczekiwano {sha}, jest {actual}")
2710
- _cleanup_tmp_files(dst_new, dst_new + ".asc")
2711
- return 1
2712
- print(" ✅ SHA256 zgodny")
2713
- except Exception:
2714
- # Brak pag.sha256 w repo – opcjonalne; nie blokuj aktualizacji.
2715
- pass
2716
-
2717
- # --- 3. Kontrola składni (nie uruchamiaj uszkodzonego/poddanego edycji pliku) ---
2718
- try:
2719
- compile(data, "pag", "exec")
2720
- except SyntaxError as e:
2721
- print(f" ❌ Błąd składni w nowym pag: {e}")
2722
- _cleanup_tmp_files(dst_new, dst_new + ".asc")
2723
- return 1
2724
-
2725
- m = (re.search(rb'PAG_VERSION\s*=\s*"(\d+\.\d+\.\d+[a-z]?)"', data[:3000])
2726
- or re.search(rb"v(\d+\.\d+\.\d+[a-z]?)", data[:3000]))
2727
- new_ver = m.group(1).decode() if m else "?"
2728
- print(f" ✅ Pobrano pag {new_ver} (obecny {PAG_VERSION}), podpis zweryfikowany")
2729
-
2730
- # --- 4. Backup + atomowa podmiana ---
2731
- if os.path.exists(dst):
2732
- shutil.copy2(dst, dst_bak)
2733
- os.chmod(dst_new, 0o755)
2734
- os.replace(dst_new, dst) # atomowe na tym samym FS
2735
- try:
2736
- if os.path.exists(dst_new + ".asc"):
2737
- os.remove(dst_new + ".asc")
2738
- except OSError:
2739
- pass
2740
- print(f" ✅ Zainstalowano nowy pag. Stary zachowany jako {dst_bak}")
2741
- print(" Uruchom ponownie pag, aby użyć nowej wersji.")
2742
- return 0
2743
-
2744
-
2745
-def _pending_updates() -> List[str]:
2746
- """Zainstalowane pakiety z nowszą wersją w repo (bez przypiętych)."""
2747
- installed = load_json(INSTALLED_DB)
2748
- pinned = load_json(PINNED_FILE)
2749
- repo = fetch_all_packages()
2750
- if not repo:
2751
- return []
2752
- return [n for n, i in installed.items()
2753
- if n not in pinned and (rp := repo.get(n)) and _version_newer(rp.version, i["version"])]
2754
-
2755
-def cmd_update(do_upgrade: bool = False):
2756
- """`pag sync` / `pag update` – odświeżenie indeksów + raport aktualizacji.
2757
-
2758
- sync → tylko odświeżenie indeksów + info: „jest X pakietów do
2759
- zaktualizowania – wpisz: pag update".
2760
- update → odświeżenie indeksów + AKTUALIZACJA PAKIETÓW (pakiety, nie system).
2761
- Pomijamy cache TTL (inaczej nowe pakiety/aktualizacje są niewidoczne nawet
2762
- przez godzinę). Pełne pobranie + weryfikacja GPG przy każdym odświeżeniu.
2763
- """
2764
- force = True
2765
- print("🔄 Refreshing indexes...")
2766
- for repo_url in get_repos():
2767
- pkgs = fetch_repo_index(repo_url, force=force)
2768
- cp = _repo_cache_path(repo_url)
2769
- has_sig = os.path.exists(cp + ".sig")
2770
- print(f" {'✅' if pkgs is not None else '❌'} {repo_url}: {len(pkgs or [])} pkgs {'🔐' if has_sig else '⚠'}")
2771
- print(f"✅ {_('indexes_refreshed')}")
2772
-
2773
- # Powiadomienie o nowszej wersji pag (repo.json["pag_version"])
2774
- try:
2775
- for r in get_repos():
2776
- cp = _repo_cache_path(r)
2777
- if os.path.exists(cp):
2778
- d = json.load(open(cp))
2779
- rv = d.get("pag_version", "")
2780
- if rv and rv != PAG_VERSION:
2781
- print(f" ⚠ Nowa wersja pag {rv} dostępna – uruchom: pag self-update")
2782
- except Exception:
2783
- pass
2784
-
2785
- # Raport: pakiety do aktualizacji
2786
- pending = _pending_updates()
2787
- if not pending:
2788
- print(f"✅ {_('all_up_to_date')}")
2789
- return 0
2790
- print(f"{_('updates_available', len(pending))}")
2791
- installed = load_json(INSTALLED_DB)
2792
- repo = fetch_all_packages()
2793
- for n in pending:
2794
- print(f" {n}: {installed.get(n, {}).get('version', '?')} → {repo[n].version}")
2795
- if not do_upgrade:
2796
- return 0 # sync: tylko informacja
2797
- if not _ask_confirm():
2798
- return 0
2799
- return cmd_install(pending, upgrade=True)
2800
-
2801
-def _initramfs_stale() -> bool:
2802
- """Czy initramfs jest starszy niż najnowsze jądro (wymaga przebudowy)."""
2803
- try:
2804
- kernels = [k for k in os.listdir("/boot") if k.startswith("vmlinuz-")] if os.path.isdir("/boot") else []
2805
- if not kernels:
2806
- return False
2807
- newest = max(os.path.getmtime(os.path.join("/boot", k)) for k in kernels)
2808
- initrd = "/boot/initramfs.img"
2809
- return (not os.path.exists(initrd)) or os.path.getmtime(initrd) < newest
2810
- except Exception:
2811
- return False
2812
-
2813
-def cmd_upgrade():
2814
- """`pag upgrade` – aktualizacja SYSTEMU: pakiety + kernel/initramfs/GRUB."""
2815
- rc = cmd_update(do_upgrade=True)
2816
- if rc != 0:
2817
- return rc
2818
- # System: dopilnuj initramfs (gdyby kernel był nowszy) + GRUB (immutable)
2819
- if _initramfs_stale():
2820
- print(" 🐧 Przebudowa initramfs (nowsze jądro)...")
2821
- _rebuild_initramfs()
2822
- try:
2823
- if _load_deployments():
2824
- _update_grub_config()
2825
- except Exception:
2826
- pass
2827
- return 0
2828
-
2829
-def cmd_list(installed_only=False):
2830
- if installed_only:
2831
- db = load_json(INSTALLED_DB)
2832
- pinned = load_json(PINNED_FILE)
2833
- if not db: print("No packages installed."); return
2834
- print(f"Installed ({len(db)}):")
2835
- for n, i in sorted(db.items()):
2836
- pin = " 📌" if n in pinned else ""
2837
- print(f" {n}-{i['version']}{pin} – {i.get('description','')}")
2838
- else:
2839
- pkgs = fetch_all_packages()
2840
- installed = load_json(INSTALLED_DB)
2841
- pinned = load_json(PINNED_FILE)
2842
- print(f"Available ({len(pkgs)}):")
2843
- for n, p in sorted(pkgs.items()):
2844
- m = "✓" if n in installed else " "
2845
- extra = f" [installed: {installed[n]['version']}]" if n in installed else ""
2846
- if n in pinned: extra += " 📌"
2847
- print(f" [{m}] {n}-{p.version} – {p.description}{extra}")
2848
-
2849
-def cmd_search(query):
2850
- pkgs = fetch_all_packages()
2851
- results = [(n,p) for n,p in pkgs.items() if query.lower() in n.lower() or query.lower() in p.description.lower()]
2852
- if not results: print(f"❌ No results for: {query}"); return
2853
- installed = load_json(INSTALLED_DB)
2854
- print(f"Results for '{query}' ({len(results)}):")
2855
- for n,p in sorted(results):
2856
- print(f" [{'✓' if n in installed else ' '}] {n}-{p.version}")
2857
- print(f" {p.description}")
2858
-
2859
-
2860
-def _smart_search(query: str) -> int:
2861
- """
2862
- Inteligentne wyszukiwanie: repo PaganOS + Flathub.
2863
- Uruchamiane gdy użytkownik wpisze `pag <nazwa>` zamiast `pag install <nazwa>`.
2864
- Pokazuje dostępne źródła i sugeruje komendy instalacji.
2865
- """
2866
- # 1. Repo PaganOS
2867
- try:
2868
- pkgs = fetch_all_packages()
2869
- except Exception:
2870
- pkgs = {}
2871
- repo_lower = [(n, p) for n, p in pkgs.items()
2872
- if query.lower() in n.lower() or query.lower() in p.description.lower()]
2873
-
2874
- # 2. Flathub (jeśli dostępny)
2875
- flat = _flatpak_search_raw(query) if _check_flatpak(quiet=True) else []
2876
-
2877
- if not repo_lower and not flat:
2878
- print(f"\n ❌ '{query}' — nie znaleziono.")
2879
- print(f" Repo PaganOS: pag search {query}")
2880
- if _check_flatpak(quiet=True):
2881
- print(f" Flathub: pag flatpak search {query}")
2882
- print(f" Dodaj repo: pag repo-add <url>")
2883
- return 1
2884
-
2885
- installed = load_json(INSTALLED_DB)
2886
-
2887
- # ── Repo PaganOS ──
2888
- if repo_lower:
2889
- exact = [(n, p) for n, p in repo_lower if n.lower() == query.lower()]
2890
- show = (exact or repo_lower)[:6]
2891
- print(f"\n 📦 PaganOS — '{query}':")
2892
- for n, p in sorted(show):
2893
- mark = "✓" if n in installed else " "
2894
- desc = p.description[:70] if len(p.description) > 75 else p.description
2895
- print(f" [{mark}] {n}-{p.version}")
2896
- if desc:
2897
- print(f" {desc}")
2898
- if len(repo_lower) > 6:
2899
- print(f" ... i {len(repo_lower) - 6} więcej (pag search {query})")
2900
-
2901
- # ── Flathub ──
2902
- if flat:
2903
- print(f"\n 📦 Flathub — '{query}':")
2904
- for r in flat[:5]:
2905
- mark = "✓" if r.get("installed") else " "
2906
- name = r.get("name") or r.get("application", "?")
2907
- desc = (r.get("description") or "")[:65]
2908
- print(f" [{mark}] {name}")
2909
- if desc:
2910
- print(f" {desc}")
2911
- if len(flat) > 5:
2912
- print(f" ... i {len(flat) - 5} więcej (pag flatpak search {query})")
2913
-
2914
- # ── Sugestie instalacji ──
2915
- print()
2916
- if repo_lower:
2917
- 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]
2918
- if best in installed:
2919
- print(f" ✓ {best} jest już zainstalowany ({installed[best]['version']})")
2920
- else:
2921
- print(f" 💡 sudo pag install {best}")
2922
- if flat:
2923
- best_fp = flat[0].get("application") or flat[0].get("name", query)
2924
- print(f" 💡 pag flatpak install {best_fp}")
2925
-
2926
- return 0
2927
-
2928
-def cmd_info(name):
2929
- pkgs = fetch_all_packages()
2930
- p = pkgs.get(name)
2931
- info = load_json(INSTALLED_DB).get(name)
2932
- if not p and not info: print(f"❌ '{name}' not found."); return 1
2933
- print(f"📦 {name}")
2934
- if p:
2935
- print(f" Version (repo): {p.version}")
2936
- print(f" Description: {p.description}")
2937
- print(f" Size: {p.size_bytes/1048576:.1f} MB")
2938
- print(f" SHA256: {p.sha256[:32]}...")
2939
- print(f" GPG: {p.gpg_fp or 'none'}")
2940
- print(f" Dependencies: {', '.join(p.dependencies) if p.dependencies else '(none)'}")
2941
- if info:
2942
- print(f" Installed: {info['version']} ({info.get('installed_at','?')})")
2943
-
2944
-def cmd_files(name):
2945
- if name not in load_json(INSTALLED_DB):
2946
- print(f"❌ '{name}' not installed."); return 1
2947
- files = _db_get_package_files(name)
2948
- print(f"Files in {name} ({len(files)}):")
2949
- for f in sorted(files): print(f" {f}")
2950
-
2951
-def cmd_verify(deep=False):
2952
- installed = load_json(INSTALLED_DB)
2953
- if not installed: print("Nothing to verify."); return
2954
- errors = []
2955
-
2956
- for name in installed:
2957
- for fpath in _db_get_package_files(name):
2958
- full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
2959
- if not (os.path.exists(full) or os.path.islink(full)):
2960
- errors.append(f" ❌ {name}: missing {fpath}")
2961
- elif deep:
2962
- checksums = _db_get_all_file_checksums()
2963
- expected = checksums.get(fpath, "")
2964
- if expected:
2965
- actual = _sha256_file(full)
2966
- if actual != expected:
2967
- errors.append(f" ❌ {name}: SHA256 mismatch {fpath}")
2968
-
2969
- if errors:
2970
- print(f"❌ {_('verify_errors', len(errors))}")
2971
- for e in errors[:50]: print(e)
2972
- return 1
2973
- total = _db_count_files()
2974
- print(f"✅ {_('verify_ok', total)}")
2975
-
2976
-# =============================================================================
2977
-# PINNING / CLEAN / ORPHANS / REPO / FLATPAK
2978
-# =============================================================================
2979
-
2980
-def cmd_pin(name, version=""):
2981
- pinned = load_json(PINNED_FILE)
2982
- if version:
2983
- pinned[name] = version
2984
- else:
2985
- info = load_json(INSTALLED_DB).get(name, {})
2986
- pinned[name] = info.get("version", "?")
2987
- save_json(PINNED_FILE, pinned)
2988
- print(f"📌 {name} {_('pinned_to')} {pinned[name]}")
2989
-
2990
-def cmd_unpin(name):
2991
- pinned = load_json(PINNED_FILE)
2992
- if name in pinned:
2993
- del pinned[name]; save_json(PINNED_FILE, pinned)
2994
- print(f"🔓 {name} {_('unpinned')}")
2995
- else:
2996
- print(f"⚠ {name} {_('not_pinned')}")
2997
-
2998
-def cmd_pinned():
2999
- pinned = load_json(PINNED_FILE)
3000
- if not pinned: print(_("no_pinned")); return
3001
- print(_("pinned_list", len(pinned)))
3002
- for n,v in sorted(pinned.items()): print(f" 📌 {n} = {v}")
3003
-
3004
-def cmd_clean():
3005
- if os.path.isdir(PAG_CACHE):
3006
- count = size = 0
3007
- for f in os.listdir(PAG_CACHE):
3008
- fp = os.path.join(PAG_CACHE, f)
3009
- if os.path.isfile(fp):
3010
- size += os.path.getsize(fp); os.remove(fp); count += 1
3011
- print(f"✅ {_('cache_cleared', count, size/1048576)}")
3012
-
3013
-def cmd_remove_orphans():
3014
- installed = load_json(INSTALLED_DB)
3015
- world = load_world()
3016
- orphans = _find_orphans(installed, world)
3017
- if not orphans: print("✅ No orphans."); return
3018
- print(f"Orphans ({len(orphans)}):")
3019
- for n in sorted(orphans): print(f" {n}-{installed[n]['version']}")
3020
- if not _ask_confirm():
3021
- return
3022
- cmd_remove(list(orphans))
3023
-
3024
-
3025
-# =============================================================================
3026
-# PROVIDES – PAKIETY WIRTUALNE
3027
-# =============================================================================
3028
-
3029
-PROVIDES_MAP = {
3030
- "pkgconfig(glib-2.0)": "glib",
3031
- "pkgconfig(gobject-introspection-1.0)": "gobject-introspection",
3032
- "pkgconfig(gtk+-3.0)": "gtk",
3033
- "pkgconfig(gtk4)": "gtk",
3034
- "pkgconfig(zlib)": "zlib",
3035
- "pkgconfig(libffi)": "libffi",
3036
- "pkgconfig(expat)": "expat",
3037
- "pkgconfig(libsystemd)": "systemd",
3038
- "pkgconfig(dbus-1)": "dbus",
3039
- "pkgconfig(mount)": "util-linux",
3040
- "pkgconfig(blkid)": "util-linux",
3041
- "pkgconfig(libcap)": "libcap",
3042
- "pkgconfig(liblzma)": "xz",
3043
- "pkgconfig(libzstd)": "zstd",
3044
- "pkgconfig(bzip2)": "bzip2",
3045
- "pkgconfig(libcurl)": "curl",
3046
- "pkgconfig(openssl)": "openssl",
3047
- "pkgconfig(libpcre2-8)": "pcre2",
3048
- "pkgconfig(libxml-2.0)": "libxml2",
3049
- "pkgconfig(libxslt)": "libxslt",
3050
- "pkgconfig(freetype2)": "freetype",
3051
- "pkgconfig(fontconfig)": "fontconfig",
3052
- "pkgconfig(harfbuzz)": "harfbuzz",
3053
- "pkgconfig(cairo)": "cairo",
3054
- "pkgconfig(pango)": "pango",
3055
- "pkgconfig(xt)": "xorg-libxt",
3056
- "pkgconfig(xmu)": "xorg-libxmu",
3057
- "pkgconfig(ice)": "xorg-libice",
3058
- "pkgconfig(sm)": "xorg-libsm",
3059
- "pkgconfig(x11)": "xorg-libx11",
3060
- "pkgconfig(xext)": "xorg-libxext",
3061
- "pkgconfig(xrandr)": "xorg-libxrandr",
3062
- "pkgconfig(xfixes)": "xorg-libxfixes",
3063
- "pkgconfig(xcursor)": "xorg-libxcursor",
3064
- "pkgconfig(xinerama)": "xorg-libxinerama",
3065
- "pkgconfig(xrender)": "xorg-libxrender",
3066
- "pkgconfig(xau)": "xorg-libxau",
3067
- "pkgconfig(xcb)": "xorg-libxcb",
3068
- "pkgconfig(xdamage)": "xorg-libxdamage",
3069
- "pkgconfig(xcomposite)": "xorg-libxcomposite",
3070
- "pkgconfig(xft)": "xorg-libxft",
3071
- "pkgconfig(xss)": "xorg-libxss",
3072
- "pkgconfig(libsoup-3.0)": "libsoup3",
3073
- "pkgconfig(libsoup-2.4)": "libsoup2",
3074
- "pkgconfig(gdk-pixbuf-2.0)": "gdk-pixbuf2",
3075
- "pkgconfig(libpng)": "libpng",
3076
- "pkgconfig(libjpeg)": "libjpeg-turbo",
3077
- "pkgconfig(libtiff-4)": "libtiff",
3078
- "pkgconfig(ffi)": "libffi",
3079
- # ── system / baza ──
3080
- "pkgconfig(libcrypto)": "openssl",
3081
- "pkgconfig(libssl)": "openssl",
3082
- "pkgconfig(libudev)": "systemd",
3083
- "pkgconfig(libmount)": "util-linux",
3084
- "pkgconfig(libblkid)": "util-linux",
3085
- "pkgconfig(uuid)": "util-linux",
3086
- "pkgconfig(libexpat)": "expat",
3087
- "pkgconfig(libpcre)": "pcre",
3088
- "pkgconfig(ncursesw)": "ncurses",
3089
- "pkgconfig(tinfo)": "ncurses",
3090
- "pkgconfig(panel)": "ncurses",
3091
- "pkgconfig(readline)": "readline",
3092
- "pkgconfig(libseccomp)": "libseccomp",
3093
- "pkgconfig(pam)": "linux-pam",
3094
- "pkgconfig(libxcrypt)": "libxcrypt",
3095
- "pkgconfig(libcrypt)": "libxcrypt",
3096
- "pkgconfig(libnsl)": "libnsl",
3097
- "pkgconfig(liblz4)": "lz4",
3098
- "pkgconfig(libevent)": "libevent",
3099
- "pkgconfig(libarchive)": "libarchive",
3100
- "pkgconfig(sqlite3)": "sqlite",
3101
- "pkgconfig(libpq)": "postgresql",
3102
- "pkgconfig(mysqlclient)": "mariadb",
3103
- "pkgconfig(json-c)": "json-c",
3104
- "pkgconfig(json-glib-1.0)": "json-glib",
3105
- "pkgconfig(libunistring)": "libunistring",
3106
- "pkgconfig(libidn2)": "libidn2",
3107
- "pkgconfig(libpsl)": "libpsl",
3108
- "pkgconfig(icu-uc)": "icu",
3109
- "pkgconfig(icu-i18n)": "icu",
3110
- "pkgconfig(icu-io)": "icu",
3111
- "pkgconfig(gnutls)": "gnutls",
3112
- "pkgconfig(nettle)": "nettle",
3113
- "pkgconfig(hogweed)": "nettle",
3114
- "pkgconfig(libgcrypt)": "libgcrypt",
3115
- "pkgconfig(libgpg-error)": "libgpg-error",
3116
- "pkgconfig(libassuan)": "libassuan",
3117
- "pkgconfig(libusb-1.0)": "libusb",
3118
- "pkgconfig(libusb)": "libusb",
3119
- "pkgconfig(libgudev-1.0)": "libgudev",
3120
- "pkgconfig(gudev-1.0)": "libgudev",
3121
- "pkgconfig(polkit-gobject-1)": "polkit",
3122
- "pkgconfig(polkit-agent-1)": "polkit",
3123
- "pkgconfig(libpciaccess)": "libpciaccess",
3124
- "pkgconfig(pixman-1)": "pixman",
3125
- "pkgconfig(libdrm)": "libdrm",
3126
- "pkgconfig(libva)": "libva",
3127
- "pkgconfig(libva-drm)": "libva",
3128
- "pkgconfig(libva-x11)": "libva",
3129
- "pkgconfig(libva-wayland)": "libva",
3130
- "pkgconfig(vdpau)": "libvdpau",
3131
- "pkgconfig(libvdpau)": "libvdpau",
3132
- "pkgconfig(libinput)": "libinput",
3133
- "pkgconfig(libevdev)": "libevdev",
3134
- "pkgconfig(mtdev)": "mtdev",
3135
- # ── grafika / GL / multimedia ──
3136
- "pkgconfig(gbm)": "mesa",
3137
- "pkgconfig(gl)": "libglvnd",
3138
- "pkgconfig(egl)": "libglvnd",
3139
- "pkgconfig(glesv2)": "libglvnd",
3140
- "pkgconfig(glx)": "libglvnd",
3141
- "pkgconfig(vulkan)": "vulkan-loader",
3142
- "pkgconfig(libxkbcommon)": "libxkbcommon",
3143
- "pkgconfig(xkbcommon)": "libxkbcommon",
3144
- "pkgconfig(xkbcommon-x11)": "libxkbcommon",
3145
- "pkgconfig(xcb)": "xorg-libxcb",
3146
- "pkgconfig(xcb-util)": "xcb-util",
3147
- "pkgconfig(xcb-keysyms)": "xcb-util-keysyms",
3148
- "pkgconfig(xcb-icccm)": "xcb-util-wm",
3149
- "pkgconfig(xcb-cursor)": "xcb-util-cursor",
3150
- "pkgconfig(xcb-renderutil)": "xcb-util-renderutil",
3151
- "pkgconfig(xcb-image)": "xcb-util-image",
3152
- "pkgconfig(xcb-errors)": "xcb-util-errors",
3153
- "pkgconfig(wayland-client)": "wayland",
3154
- "pkgconfig(wayland-server)": "wayland",
3155
- "pkgconfig(wayland-cursor)": "wayland",
3156
- "pkgconfig(wayland-egl)": "wayland",
3157
- "pkgconfig(wayland-protocols)": "wayland-protocols",
3158
- "pkgconfig(gstreamer-1.0)": "gstreamer",
3159
- "pkgconfig(gstreamer-base-1.0)": "gstreamer",
3160
- "pkgconfig(gstreamer-check-1.0)": "gstreamer",
3161
- "pkgconfig(gstreamer-controller-1.0)": "gstreamer",
3162
- "pkgconfig(gstreamer-app-1.0)": "gst-plugins-base",
3163
- "pkgconfig(gstreamer-video-1.0)": "gst-plugins-base",
3164
- "pkgconfig(gstreamer-audio-1.0)": "gst-plugins-base",
3165
- "pkgconfig(gstreamer-pbutils-1.0)": "gst-plugins-base",
3166
- "pkgconfig(gstreamer-fft-1.0)": "gst-plugins-base",
3167
- "pkgconfig(gstreamer-riff-1.0)": "gst-plugins-base",
3168
- "pkgconfig(gstreamer-rtp-1.0)": "gst-plugins-base",
3169
- "pkgconfig(gstreamer-rtsp-1.0)": "gst-plugins-base",
3170
- "pkgconfig(gstreamer-sdp-1.0)": "gst-plugins-base",
3171
- "pkgconfig(gstreamer-net-1.0)": "gst-plugins-base",
3172
- "pkgconfig(gstreamer-gl-1.0)": "gst-plugins-base",
3173
- "pkgconfig(libpulse)": "libpulse",
3174
- "pkgconfig(libpulse-simple)": "libpulse",
3175
- "pkgconfig(libpulse-mainloop-glib)": "libpulse",
3176
- "pkgconfig(alsa)": "alsa-lib",
3177
- "pkgconfig(jack)": "jack2",
3178
- "pkgconfig(libsamplerate)": "libsamplerate",
3179
- "pkgconfig(sndfile)": "libsndfile",
3180
- "pkgconfig(libavcodec)": "ffmpeg",
3181
- "pkgconfig(libavformat)": "ffmpeg",
3182
- "pkgconfig(libavutil)": "ffmpeg",
3183
- "pkgconfig(libavfilter)": "ffmpeg",
3184
- "pkgconfig(libswscale)": "ffmpeg",
3185
- "pkgconfig(libswresample)": "ffmpeg",
3186
- "pkgconfig(libpostproc)": "ffmpeg",
3187
- "pkgconfig(SDL2)": "sdl2",
3188
- "pkgconfig(SDL)": "sdl",
3189
- "pkgconfig(SDL2_image)": "sdl2-image",
3190
- "pkgconfig(SDL2_ttf)": "sdl2-ttf",
3191
- "pkgconfig(SDL2_mixer)": "sdl2-mixer",
3192
- "pkgconfig(SDL2_net)": "sdl2-net",
3193
- "pkgconfig(libpng16)": "libpng",
3194
- "pkgconfig(libwebp)": "libwebp",
3195
- "pkgconfig(libwebpmux)": "libwebp",
3196
- "pkgconfig(libwebpdemux)": "libwebp",
3197
- "pkgconfig(libopenjp2)": "openjpeg2",
3198
- "pkgconfig(lcms2)": "lcms2",
3199
- "pkgconfig(libheif)": "libheif",
3200
- "pkgconfig(libde265)": "libde265",
3201
- "pkgconfig(x264)": "x264",
3202
- "pkgconfig(x265)": "x265",
3203
- # ── glib / gio ──
3204
- "pkgconfig(gio-unix-2.0)": "glib",
3205
- "pkgconfig(gmodule-2.0)": "glib",
3206
- "pkgconfig(gthread-2.0)": "glib",
3207
- "pkgconfig(girepository-2.0)": "gobject-introspection",
3208
- "pkgconfig(girepository-1.0)": "gobject-introspection",
3209
- "pkgconfig(libglib-2.0)": "glib",
3210
- "pkgconfig(libgobject-2.0)": "glib",
3211
-}
3212
-
3213
-def _resolve_provides(name: str, repo: dict, installed: Optional[dict] = None) -> str:
3214
- """Rozwija wirtualną nazwę pakietu do rzeczywistej nazwy.
3215
-
3216
- Kolejność: repo → PROVIDES_MAP → wzorce → provides z repo.json →
3217
- provides ZAINSTALOWANYCH pakietów (lokalnie zbudowane poza repo też
3218
- dostarczają wirtualne zależności) → fallback pkgconfig (czyszczenie nazwy).
3219
- """
3220
- if name in repo:
3221
- return name
3222
- if name in PROVIDES_MAP:
3223
- real = PROVIDES_MAP[name]
3224
- if real in repo:
3225
- return real
3226
- # Wzorce: moduły Qt (Qt5Core/Qt6Widgets) i GStreamer (gstreamer-video-1.0)
3227
- if name.startswith("pkgconfig(Qt5"):
3228
- real = "qt5"
3229
- if real in repo:
3230
- return real
3231
- if name.startswith("pkgconfig(Qt6"):
3232
- real = "qt6"
3233
- if real in repo:
3234
- return real
3235
- if name.startswith("pkgconfig(gstreamer-") and name.endswith("-1.0)"):
3236
- real = "gstreamer"
3237
- if real in repo:
3238
- return real
3239
- if name.startswith("pkgconfig(gst-"):
3240
- real = "gst-plugins-base"
3241
- if real in repo:
3242
- return real
3243
- # Dynamiczne provides z repo.json (sekcja provides: w PAGBUILD.yaml)
3244
- for _pkg_name, _pkg in repo.items():
3245
- _provs = getattr(_pkg, "provides", None) or []
3246
- if name in _provs:
3247
- return _pkg_name
3248
- # provides ZAINSTALOWANYCH pakietów – lokalnie zbudowane (pagbuild, poza
3249
- # repo) też dostarczają wirtualne zależności i muszą być rozpoznawane.
3250
- if installed:
3251
- for _pkg_name, _meta in installed.items():
3252
- _provs = _meta.get("provides") or [] if isinstance(_meta, dict) else []
3253
- if name in _provs:
3254
- return _pkg_name
3255
- clean = name
3256
- if name.startswith("pkgconfig(") and ")" in name:
3257
- clean = name.split("(", 1)[1].rstrip(")")
3258
- elif name.startswith("pkgconfig32(") and ")" in name:
3259
- clean = name.split("(", 1)[1].rstrip(")")
3260
- if clean != name and clean in repo:
3261
- return clean
3262
- return name
3263
-
3264
-
3265
-def cmd_why(pkg_name: str):
3266
- """Pokazuje dlaczego pakiet jest zainstalowany."""
3267
- installed = load_json(INSTALLED_DB)
3268
- world = load_world()
3269
- if pkg_name not in installed:
3270
- print(f" {pkg_name}: {_('why_not_installed')}"); return 1
3271
- if pkg_name in world:
3272
- print(f" {pkg_name}-{installed[pkg_name]['version']}: {_('why_explicit')}")
3273
- return 0
3274
- parents = set()
3275
- for w in world:
3276
- _find_dep_path(w, pkg_name, installed, set(), [], parents)
3277
- if parents:
3278
- for pp in sorted(parents):
3279
- print(f" {pkg_name}: {_('why_dependency')} {' → '.join(pp)}")
3280
- else:
3281
- print(f" {pkg_name}: {_('why_dependency')} (unknown/orphan)")
3282
- return 0
3283
-
3284
-
3285
-def _find_dep_path(cur, target, installed, visited, path, results):
3286
- if cur in visited: return
3287
- visited.add(cur); path.append(cur)
3288
- if cur == target:
3289
- results.add(tuple(path))
3290
- else:
3291
- for dep in installed.get(cur, {}).get("dependencies", []):
3292
- _find_dep_path(dep, target, installed, visited, path, results)
3293
- path.pop(); visited.discard(cur)
3294
-
3295
-
3296
-def cmd_autoremove():
3297
- """Automatycznie usuwa osierocone zależności bez pytania."""
3298
- installed = load_json(INSTALLED_DB)
3299
- world = load_world()
3300
- orphans = _find_orphans(installed, world)
3301
- if not orphans: print(f"✅ {_('autoremove_none')}"); return 0
3302
- print(f"🗑 {_('orphans_found', len(orphans), ', '.join(sorted(orphans)[:10]))}")
3303
- return cmd_remove(list(orphans))
3304
-
3305
-
3306
-def cmd_download(package_names):
3307
- """Pobiera pakiety do cache bez instalowania."""
3308
- ensure_dirs()
3309
- repo = fetch_all_packages()
3310
- if not repo: print(f"❌ {_('no_index')}"); return 1
3311
- total_size = 0; downloaded = []
3312
- for name in package_names:
3313
- pkg = repo.get(name)
3314
- if not pkg:
3315
- print(f" ❌ {name}: {_('not_found')}"); continue
3316
- print(f" ↓ {name}-{pkg.version} ...", end=" ", flush=True)
3317
- path = _download_pkg(pkg)
3318
- if path:
3319
- total_size += os.path.getsize(path)
3320
- downloaded.append(name)
3321
- print(_c("green", "✓"))
3322
- else:
3323
- print(_c("red", "✗"))
3324
- if downloaded:
3325
- print(f"\n✅ {_('downloaded', len(downloaded), total_size/1048576)}")
3326
- return 0 if len(downloaded) == len(package_names) else 1
3327
-
3328
-
3329
-def cmd_stats():
3330
- """Wyświetla statystyki PAG."""
3331
- installed = load_json(INSTALLED_DB)
3332
- history = load_json(HISTORY_FILE) if os.path.exists(HISTORY_FILE) else []
3333
- total_size = sum(i.get("size_bytes", 0) for i in installed.values())
3334
- total_files = _db_count_files()
3335
- cache_size = sum(
3336
- os.path.getsize(os.path.join(PAG_CACHE, f))
3337
- for f in os.listdir(PAG_CACHE)
3338
- if os.path.isfile(os.path.join(PAG_CACHE, f))
3339
- ) if os.path.isdir(PAG_CACHE) else 0
3340
- last_update = "never"
3341
- for e in reversed(history):
3342
- if e.get("action") in ("install", "upgrade") and e.get("success"):
3343
- last_update = e.get("timestamp", "?")[:19]; break
3344
- print(f"\n {_c('bold', _('stats_title'))}")
3345
- print(f" {'─' * 40}")
3346
- print(f" {_('stats_packages'):<30} {len(installed)}")
3347
- print(f" {_('stats_files'):<30} {total_files}")
3348
- print(f" {_('stats_size'):<30} {total_size/1048576:.1f} MB")
3349
- print(f" {_('stats_cache'):<30} {cache_size/1048576:.1f} MB")
3350
- print(f" {_('stats_history'):<30} {len(history)}")
3351
- print(f" {_('stats_last_update'):<30} {last_update}")
3352
- by_size = sorted(installed.items(), key=lambda x: x[1].get("size_bytes", 0), reverse=True)[:5]
3353
- if by_size:
3354
- print(f"\n {_c('dim', 'Top 5:')}")
3355
- for n, i in by_size:
3356
- print(f" {n}-{i['version']} {i.get('size_bytes',0)/1048576:.1f} MB")
3357
- return 0
3358
-
3359
-
3360
-def cmd_repo_add(url, name=None):
3361
- if not url.startswith("https://") and not os.environ.get("PAG_INSECURE"):
3362
- print(f" {_('sec_https')}"); return 1
3363
- ensure_dirs()
3364
- url = url.rstrip("/")
3365
- repos = get_repos()
3366
- if url in repos: print(f"⚠ {_('repo_exists', url)}"); return
3367
- if name:
3368
- # Drop-in: /etc/pag/repos/<nazwa>.conf (jak `echo url > .../stable.conf`)
3369
- os.makedirs(REPOS_DIR, exist_ok=True)
3370
- target = os.path.join(REPOS_DIR, name.rstrip("/").replace("/", "_") + ".conf")
3371
- with open(target, "w") as f: f.write(f"{url}\n")
3372
- print(f"✅ {_('repo_added', url)} → {target}")
3373
- return
3374
- with open(REPOS_CONF, "a") as f: f.write(f"{url}\n")
3375
- print(f"✅ {_('repo_added', url)}")
3376
-
3377
-def cmd_repo_list():
3378
- for i, url in enumerate(get_repos(), 1): print(f" {i}. {url}")
3379
-
3380
-def _check_flatpak(quiet: bool = False):
3381
- if not shutil.which("flatpak"):
3382
- if not quiet:
3383
- print(f"❌ {_('flatpak_missing')}")
3384
- return False
3385
- r = subprocess.run(["flatpak","remotes"], capture_output=True, text=True)
3386
- if "flathub" not in r.stdout:
3387
- print(f"⚠ {_('flatpak_adding')}")
3388
- subprocess.run(["flatpak","remote-add","--if-not-exists","flathub",
3389
- "https://flathub.org/repo/flathub.flatpakrepo"], check=False)
3390
- return True
3391
-
3392
-def _spinner(msg: str):
3393
- """Prosty spinner „myślenia” w osobnym wątku. Zwraca funkcję stop()."""
3394
- stop = threading.Event()
3395
- def _spin():
3396
- for c in itertools.cycle("|/-\\"):
3397
- if stop.is_set():
3398
- break
3399
- sys.stdout.write(f"\r {msg} {c}")
3400
- sys.stdout.flush()
3401
- time.sleep(0.1)
3402
- t = threading.Thread(target=_spin, daemon=True)
3403
- t.start()
3404
- def _stop():
3405
- stop.set()
3406
- t.join(timeout=0.3)
3407
- sys.stdout.write("\r" + " " * (len(msg) + 4) + "\r")
3408
- sys.stdout.flush()
3409
- return _stop
3410
-
3411
-
3412
-def _flatpak_search_raw(query: str) -> List[dict]:
3413
- """Szuka we Flathub i zwraca listę wyników jako słowniki."""
3414
- if not _check_flatpak():
3415
- return []
3416
- stop = _spinner("Szukam we Flathub...")
3417
- try:
3418
- try:
3419
- r = subprocess.run(
3420
- ["flatpak", "search", "--columns=name,description,application,version,branch,remotes", query],
3421
- capture_output=True, text=True, timeout=120
3422
- )
3423
- finally:
3424
- stop()
3425
- if r.returncode != 0 and "No matches found" not in r.stdout and not r.stdout.strip():
3426
- print(f" ⚠ flatpak search: {r.stderr.strip()[:150]}")
3427
- results = []
3428
- for line in r.stdout.strip().split("\n"):
3429
- parts = line.split("\t")
3430
- if len(parts) >= 3:
3431
- results.append({
3432
- "name": parts[0].strip(),
3433
- "description": parts[1].strip() if len(parts) > 1 else "",
3434
- "app_id": parts[2].strip() if len(parts) > 2 else "",
3435
- "version": parts[3].strip() if len(parts) > 3 else "",
3436
- "branch": parts[4].strip() if len(parts) > 4 else "stable",
3437
- "origin": parts[5].strip() if len(parts) > 5 else "flathub",
3438
- })
3439
- return results
3440
- except Exception as e:
3441
- print(f" ⚠ Błąd wyszukiwania: {e}", file=sys.stderr)
3442
- return []
3443
-
3444
-def _flatpak_find_best(query: str) -> Optional[dict]:
3445
- """
3446
- Szuka we Flathub i próbuje znaleźć najlepsze dopasowanie.
3447
- - Jeśli query dokładnie pasuje do app_id → zwraca od razu
3448
- - Jeśli query pasuje do nazwy → zwraca pierwsze
3449
- - Jeśli wiele wyników → wyświetla listę i pyta użytkownika
3450
- - Jeśli brak → zwraca None
3451
- """
3452
- results = _flatpak_search_raw(query)
3453
- if not results:
3454
- return None
3455
-
3456
- # Dokładne dopasowanie app_id
3457
- exact = [r for r in results if r["app_id"].lower() == query.lower()]
3458
- if exact:
3459
- return exact[0]
3460
-
3461
- # Dokładne dopasowanie nazwy
3462
- exact_name = [r for r in results if r["name"].lower() == query.lower()]
3463
- if exact_name:
3464
- return exact_name[0]
3465
-
3466
- # Jednoznaczne dopasowanie (tylko 1 wynik)
3467
- if len(results) == 1:
3468
- return results[0]
3469
-
3470
- # Wiele wyników – pokaż użytkownikowi
3471
- print(f"\n {_('flatpak_found', len(results))}")
3472
- for i, r in enumerate(results):
3473
- print(f" {i+1}. {_c('bold', r['name'])} ({r['app_id']})")
3474
- if r["version"]:
3475
- print(f" {_('flatpak_info_version')}: {r['version']}")
3476
- if r["description"]:
3477
- desc = r["description"][:80] + ("..." if len(r["description"]) > 80 else "")
3478
- print(f" {desc}")
3479
-
3480
- try:
3481
- choice = input(f"\n Wybierz numer (1-{len(results)}) lub Enter aby anulować: ").strip()
3482
- if not choice:
3483
- return None
3484
- idx = int(choice) - 1
3485
- if 0 <= idx < len(results):
3486
- return results[idx]
3487
- except (EOFError, ValueError, IndexError):
3488
- pass
3489
- return None
3490
-
3491
-def _flatpak_get_installed_info(app_id: str) -> Optional[dict]:
3492
- """Zwraca info o zainstalowanym flatpaku lub None."""
3493
- try:
3494
- r = subprocess.run(
3495
- ["flatpak", "info", "--columns=name,version,branch,origin,installed-size,description", app_id],
3496
- capture_output=True, text=True, timeout=10
3497
- )
3498
- if r.returncode != 0:
3499
- return None
3500
- parts = r.stdout.strip().split("\t")
3501
- if len(parts) < 3:
3502
- return None
3503
- return {
3504
- "name": parts[0].strip(),
3505
- "version": parts[1].strip() if len(parts) > 1 else "",
3506
- "branch": parts[2].strip() if len(parts) > 2 else "",
3507
- "origin": parts[3].strip() if len(parts) > 3 else "",
3508
- "size": parts[4].strip() if len(parts) > 4 else "",
3509
- "description": parts[5].strip() if len(parts) > 5 else "",
3510
- }
3511
- except Exception:
3512
- return None
3513
-
3514
-def _flatpak_is_installed(app_id: str) -> bool:
3515
- """Sprawdza czy flatpak o danym ID jest zainstalowany."""
3516
- try:
3517
- r = subprocess.run(
3518
- ["flatpak", "info", app_id],
3519
- capture_output=True, text=True, timeout=10
3520
- )
3521
- return r.returncode == 0
3522
- except Exception:
3523
- return False
3524
-
3525
-# =============================================================================
3526
-# FLATPAK – KOMENDY GŁÓWNE (zunifikowany interfejs)
3527
-# =============================================================================
3528
-# pag flatpak <query> → szuka i proponuje instalację (jeśli nie zainstalowany)
3529
-# pag flatpak search <query> → tylko szuka
3530
-# pag flatpak install <query> → instaluje
3531
-# pag flatpak remove <id> → usuwa
3532
-# pag flatpak list → lista zainstalowanych
3533
-# pag flatpak update → aktualizuje wszystkie
3534
-# pag flatpak info <id> → szczegóły flatpaka
3535
-
3536
-def cmd_flatpak(args: list):
3537
- """
3538
- Główna komenda flatpak – inteligentnie rozpoznaje intencję:
3539
- pag flatpak firefox → szuka i instaluje (jeśli nieznaleziony → szuka)
3540
- pag flatpak search firefox → tylko wyszukiwanie
3541
- pag flatpak install ... → bezpośrednia instalacja
3542
- pag flatpak remove ... → odinstalowanie
3543
- pag flatpak list → lista
3544
- pag flatpak update → aktualizacja
3545
- pag flatpak info ... → szczegóły
3546
- """
3547
- if not _check_flatpak():
3548
- return 1
3549
-
3550
- if not args:
3551
- # Bez argumentów – domyślnie lista
3552
- return cmd_flatpak_list()
3553
-
3554
- subcmd = args[0].lower()
3555
- rest = args[1:]
3556
-
3557
- # ── Podkomendy jawne ────────────────────────────────────────────────
3558
- if subcmd == "search":
3559
- if not rest:
3560
- print(_("flatpak_usage")); return 1
3561
- return cmd_flatpak_search(" ".join(rest))
3562
-
3563
- elif subcmd == "install":
3564
- if not rest:
3565
- print(_("flatpak_usage")); return 1
3566
- return _flatpak_smart_install(rest)
3567
-
3568
- elif subcmd == "remove" or subcmd == "uninstall":
3569
- if not rest:
3570
- print(_("flatpak_usage")); return 1
3571
- return _flatpak_smart_remove(rest)
3572
-
3573
- elif subcmd == "list":
3574
- return cmd_flatpak_list()
3575
-
3576
- elif subcmd == "update":
3577
- return cmd_flatpak_update()
3578
-
3579
- elif subcmd == "info":
3580
- if not rest:
3581
- print(_("flatpak_usage")); return 1
3582
- return cmd_flatpak_info(rest[0])
3583
-
3584
- else:
3585
- # ── Inteligentne wykrywanie: pag flatpak <nazwa> ────────────────
3586
- # Sprawdź czy to zainstalowany flatpak → pokaż info
3587
- # Jeśli nie → szukaj i zaproponuj instalację
3588
- query = " ".join(args)
3589
-
3590
- # Najpierw sprawdź czy już zainstalowany
3591
- if _flatpak_is_installed(query):
3592
- print(f" 📦 {_c('green', query)} – already installed (use 'pag flatpak info {query}' for details)")
3593
- return cmd_flatpak_info(query)
3594
-
3595
- # Szukaj we Flathub
3596
- print(f" {_('flatpak_searching', query)}")
3597
- best = _flatpak_find_best(query)
3598
- if not best:
3599
- print(f" ❌ '{query}' – {_('flatpak_not_found')}")
3600
- return 1
3601
-
3602
- print(f"\n {_c('cyan', best['name'])} ({best['app_id']})")
3603
- if best["version"]:
3604
- print(f" {_('flatpak_info_version')}: {best['version']}")
3605
- if best["description"]:
3606
- print(f" {best['description']}")
3607
-
3608
- try:
3609
- ans = input(f"\n {_('flatpak_install_prompt', best['name'])}").strip().lower()
3610
- except (EOFError, KeyboardInterrupt):
3611
- print(f"\n ⚠ {_('no_tty')}")
3612
- return 0
3613
- if ans and ans not in ("t", "y"):
3614
- print(_("cancelled"))
3615
- return 0
3616
-
3617
- return _flatpak_do_install(best["app_id"])
3618
-
3619
-def _flatpak_smart_install(names: list) -> int:
3620
- """Instaluje flatpaki – obsługuje nazwy częściowe (wyszukuje przed instalacją)."""
3621
- failed = 0
3622
- for name in names:
3623
- if "." in name and "/" not in name:
3624
- # Wygląda na pełne app_id (np. org.mozilla.firefox)
3625
- app_id = name
3626
- else:
3627
- # Szukaj najlepszego dopasowania
3628
- best = _flatpak_find_best(name)
3629
- if not best:
3630
- print(f" ❌ '{name}' – {_('flatpak_not_found')}")
3631
- failed += 1
3632
- continue
3633
- app_id = best["app_id"]
3634
- print(f" → {best['name']} ({app_id})")
3635
-
3636
- if _flatpak_do_install(app_id) != 0:
3637
- failed += 1
3638
- return 1 if failed else 0
3639
-
3640
-def _flatpak_do_install(app_id: str) -> int:
3641
- """Wykonuje właściwą instalację flatpaka."""
3642
- print(f" {_('flatpak_installing', app_id)}")
3643
- result = subprocess.run(
3644
- ["flatpak", "install", "-y", "flathub", app_id],
3645
- check=False, timeout=600
3646
- )
3647
- if result.returncode == 0:
3648
- print(f" ✅ {_('flatpak_installed', app_id)}")
3649
- return 0
3650
- else:
3651
- print(f" ❌ {_('download_fail')}: {app_id}")
3652
- return 1
3653
-
3654
-def _flatpak_smart_remove(names: list) -> int:
3655
- """Usuwa flatpaki – obsługuje nazwy częściowe."""
3656
- # Pobierz listę zainstalowanych
3657
- try:
3658
- r = subprocess.run(
3659
- ["flatpak", "list", "--columns=application,name"],
3660
- capture_output=True, text=True, timeout=10
3661
- )
3662
- installed = {}
3663
- for line in r.stdout.strip().split("\n"):
3664
- parts = line.split("\t")
3665
- if len(parts) >= 2:
3666
- installed[parts[0].strip()] = parts[1].strip()
3667
- except Exception:
3668
- installed = {}
3669
-
3670
- failed = 0
3671
- for name in names:
3672
- app_id = name
3673
-
3674
- # Jeśli nie podano pełnego ID – spróbuj dopasować
3675
- if name not in installed:
3676
- matches = {aid: aname for aid, aname in installed.items()
3677
- if name.lower() in aid.lower() or name.lower() in aname.lower()}
3678
- if len(matches) == 0:
3679
- print(f" ❌ '{name}' – {_('flatpak_not_installed', name)}")
3680
- failed += 1
3681
- continue
3682
- elif len(matches) == 1:
3683
- app_id = list(matches.keys())[0]
3684
- print(f" → {matches[app_id]} ({app_id})")
3685
- else:
3686
- print(f"\n Wiele dopasowań dla '{name}':")
3687
- for i, (aid, aname) in enumerate(sorted(matches.items()), 1):
3688
- print(f" {i}. {aname} ({aid})")
3689
- try:
3690
- choice = input(f"\n Wybierz numer (1-{len(matches)}) lub Enter: ").strip()
3691
- if not choice:
3692
- failed += 1
3693
- continue
3694
- aid_list = sorted(matches.keys())
3695
- app_id = aid_list[int(choice) - 1]
3696
- except (EOFError, ValueError, IndexError):
3697
- failed += 1
3698
- continue
3699
-
3700
- print(f" 🗑 {app_id} ...", end=" ", flush=True)
3701
- result = subprocess.run(
3702
- ["flatpak", "uninstall", "-y", app_id],
3703
- capture_output=True, text=True, timeout=120
3704
- )
3705
- if result.returncode == 0:
3706
- print("✅")
3707
- print(f" {_('flatpak_removed', app_id)}")
3708
- else:
3709
- print("❌")
3710
- failed += 1
3711
- return 1 if failed else 0
3712
-
3713
-def cmd_flatpak_search(q: str):
3714
- """Wyszukuje we Flathub i wyświetla wyniki (z możliwością wyboru do instalacji)."""
3715
- if not _check_flatpak():
3716
- return 1
3717
- results = _flatpak_search_raw(q)
3718
- if not results:
3719
- print(f" ❌ '{q}' – {_('flatpak_not_found')}")
3720
- return 1
3721
- print(f"\n {_('flatpak_found', len(results))}")
3722
- shown = results[:30] # max 30 wyników
3723
- for i, r in enumerate(shown, 1):
3724
- installed = "📦 " if _flatpak_is_installed(r["app_id"]) else " "
3725
- print(f" {i:>2}. {installed}{_c('bold', r['name'])} ({r['app_id']})")
3726
- if r["version"]:
3727
- print(f" {_('flatpak_info_version')}: {r['version']} | {_('flatpak_info_branch')}: {r['branch']}")
3728
- if r["description"]:
3729
- desc = r["description"][:100] + ("..." if len(r["description"]) > 100 else "")
3730
- print(f" {_c('dim', desc)}")
3731
- if len(results) > 30:
3732
- print(f" ... i {len(results) - 30} więcej. Doprecyzuj zapytanie.")
3733
-
3734
- # Interaktywny wybór – wpisz numer, aby zainstalować (Enter = anuluj)
3735
- try:
3736
- ans = input(f"\n Wybierz numer do zainstalowania (1-{len(shown)}) lub Enter aby anulować: ").strip()
3737
- except (EOFError, KeyboardInterrupt):
3738
- return 0
3739
- if ans:
3740
- try:
3741
- idx = int(ans) - 1
3742
- if 0 <= idx < len(shown):
3743
- return _flatpak_do_install(shown[idx]["app_id"])
3744
- print(_("cancelled"))
3745
- except (ValueError, IndexError):
3746
- print(_("cancelled"))
3747
- return 0
3748
-
3749
-def cmd_flatpak_list():
3750
- """Wyświetla zainstalowane flatpaki."""
3751
- if not _check_flatpak():
3752
- return 1
3753
- r = subprocess.run(
3754
- ["flatpak", "list", "--columns=application,name,version,origin,installed-size"],
3755
- capture_output=True, text=True, timeout=10
3756
- )
3757
- lines = [l for l in r.stdout.strip().split("\n") if l.strip()]
3758
- if not lines:
3759
- print(" (brak zainstalowanych flatpaków)")
3760
- return 0
3761
- print(f" Zainstalowane flatpaki ({len(lines)}):")
3762
- for line in lines:
3763
- parts = line.split("\t")
3764
- if len(parts) >= 3:
3765
- app_id, name, version = parts[0], parts[1], parts[2]
3766
- size = parts[4] if len(parts) > 4 else ""
3767
- size_str = f" ({size})" if size else ""
3768
- print(f" 📦 {_c('bold', name)} {version}{size_str}")
3769
- print(f" {_c('dim', app_id)}")
3770
- return 0
3771
-
3772
-def cmd_flatpak_update():
3773
- """Aktualizuje wszystkie flatpaki."""
3774
- if not _check_flatpak():
3775
- return 1
3776
- print(" 🔄 Aktualizacja flatpaków...")
3777
- result = subprocess.run(["flatpak", "update", "-y"], check=False, timeout=600)
3778
- if result.returncode == 0:
3779
- print(f" ✅ {_('flatpak_updated')}")
3780
- return result.returncode
3781
-
3782
-def cmd_flatpak_info(app_id: str):
3783
- """Wyświetla szczegóły flatpaka (zainstalowanego lub z Flathub)."""
3784
- if not _check_flatpak():
3785
- return 1
3786
-
3787
- # Najpierw sprawdź zainstalowany
3788
- info = _flatpak_get_installed_info(app_id)
3789
- if info:
3790
- print(f"\n 📦 {_c('bold', info['name'])} {_c('green', '[zainstalowany]')}")
3791
- print(f" {'─' * 45}")
3792
- print(f" {_('flatpak_info_id'):<16} {app_id}")
3793
- print(f" {_('flatpak_info_version'):<16} {info['version']}")
3794
- print(f" {_('flatpak_info_branch'):<16} {info['branch']}")
3795
- print(f" {_('flatpak_info_origin'):<16} {info['origin']}")
3796
- if info["size"]:
3797
- print(f" {_('flatpak_info_size'):<16} {info['size']}")
3798
- if info["description"]:
3799
- print(f" {_('flatpak_info_desc'):<16} {info['description']}")
3800
- return 0
3801
-
3802
- # Szukaj we Flathub
3803
- results = _flatpak_search_raw(app_id)
3804
- exact = [r for r in results if r["app_id"].lower() == app_id.lower()]
3805
- if not exact:
3806
- # Spróbuj częściowego dopasowania
3807
- if results:
3808
- exact = [results[0]]
3809
- else:
3810
- print(f" ❌ '{app_id}' – {_('flatpak_not_found')}")
3811
- return 1
3812
-
3813
- r = exact[0]
3814
- print(f"\n 📦 {_c('bold', r['name'])} (Flathub)")
3815
- print(f" {'─' * 45}")
3816
- print(f" {_('flatpak_info_id'):<16} {r['app_id']}")
3817
- print(f" {_('flatpak_info_version'):<16} {r['version']}")
3818
- if r["description"]:
3819
- print(f" {_('flatpak_info_desc'):<16} {r['description']}")
3820
- print(f"\n 💡 Aby zainstalować: pag flatpak install {r['app_id']}")
3821
- return 0
3822
-
3823
-# =============================================================================
3824
-# IMMUTABLE OS – KOMENDY DEPLOYMENTOWE
3825
-# =============================================================================
3826
-
3827
-# Pakiety jądra – po ich instalacji trzeba przebudować initramfs
3828
-KERNEL_PACKAGE_PATTERNS = ["linux", "kernel", "linux-kernel", "linux-lts"]
3829
-
3830
-def _is_kernel_package(name: str) -> bool:
3831
- """Sprawdza czy pakiet to jądro (wymaga przebudowy initramfs)."""
3832
- name_lower = name.lower()
3833
- return any(pattern in name_lower for pattern in KERNEL_PACKAGE_PATTERNS)
3834
-
3835
-def _rebuild_initramfs(deploy_dir: str = "") -> bool:
3836
- """
3837
- Przebudowuje initramfs dla aktywnego (lub podanego) deploymentu.
3838
- Używa skryptu pag-initramfs lub ręcznego cpio.
3839
- """
3840
- if deploy_dir:
3841
- root = deploy_dir
3842
- else:
3843
- root = _get_deployment_root()
3844
-
3845
- if root == PAG_ROOT:
3846
- # Zwykły system – użyj dracut jeśli dostępny
3847
- if shutil.which("dracut"):
3848
- print(" 🔧 Przebudowa initramfs (dracut)...")
3849
- result = subprocess.run(
3850
- ["dracut", "--force", "/boot/initramfs.img"],
3851
- capture_output=True, text=True, timeout=120
3852
- )
3853
- return result.returncode == 0
3854
- elif shutil.which("mkinitcpio"):
3855
- print(" 🔧 Przebudowa initramfs (mkinitcpio)...")
3856
- result = subprocess.run(
3857
- ["mkinitcpio", "-g", "/boot/initramfs.img"],
3858
- capture_output=True, text=True, timeout=120
3859
- )
3860
- return result.returncode == 0
3861
- else:
3862
- print(" ⚠ Brak dracut/mkinitcpio – initramfs nie został przebudowany")
3863
- return False
3864
-
3865
- # Tryb immutable – budujemy initramfs dla deploymentu
3866
- print(" 🔧 Budowanie initramfs dla deploymentu...")
3867
-
3868
- # Sprawdź czy mamy nasz skrypt init
3869
- pag_init_script = "/usr/share/pag/initramfs-init"
3870
- if not os.path.exists(pag_init_script):
3871
- # Szukaj w źródłach (developerski fallback)
3872
- alt_paths = [
3873
- os.path.join(os.path.dirname(os.path.abspath(__file__)), "scripts", "initramfs-init"),
3874
- "/usr/share/pag/init",
3875
- ]
3876
- for p in alt_paths:
3877
- if os.path.exists(p):
3878
- pag_init_script = p
3879
- break
3880
-
3881
- if not os.path.exists(pag_init_script):
3882
- print(" ⚠ Nie znaleziono pag-initramfs-init – pomijam budowę initramfs")
3883
- return False
3884
-
3885
- boot_dir = os.path.join(root, "boot")
3886
- os.makedirs(boot_dir, exist_ok=True)
3887
-
3888
- # Znajdź jądro (vmlinuz-*)
3889
- kernels = sorted(
3890
- [f for f in os.listdir(boot_dir) if f.startswith("vmlinuz-")],
3891
- reverse=True
3892
- ) if os.path.exists(boot_dir) else []
3893
- if not kernels:
3894
- print(" ⚠ Nie znaleziono vmlinuz-* w /boot deploymentu")
3895
- return False
3896
-
3897
- kernel_ver = kernels[0].replace("vmlinuz-", "")
3898
- print(f" 🐧 Jądro: {kernel_ver}")
3899
-
3900
- # Buduj initramfs ręcznie (cpio)
3901
- tmpdir = tempfile.mkdtemp(prefix="pag-initramfs-")
3902
- try:
3903
- # Podstawowa struktura
3904
- for d in ["bin", "sbin", "dev", "proc", "sys", "run", "new_root",
3905
- "usr/bin", "usr/sbin", "lib", "lib64", "etc"]:
3906
- os.makedirs(os.path.join(tmpdir, d), exist_ok=True)
3907
-
3908
- # Skopiuj init
3909
- shutil.copy2(pag_init_script, os.path.join(tmpdir, "init"))
3910
- os.chmod(os.path.join(tmpdir, "init"), 0o755)
3911
-
3912
- # Skopiuj niezbędne binaria (busybox lub podstawowe narzędzia)
3913
- busybox_paths = [
3914
- os.path.join(root, "usr/bin/busybox"),
3915
- os.path.join(root, "bin/busybox"),
3916
- "/usr/bin/busybox",
3917
- "/bin/busybox",
3918
- ]
3919
- busybox = None
3920
- for bp in busybox_paths:
3921
- if os.path.exists(bp):
3922
- busybox = bp
3923
- break
3924
-
3925
- if busybox:
3926
- shutil.copy2(busybox, os.path.join(tmpdir, "bin/busybox"))
3927
- # Utwórz symlinki dla podstawowych komend
3928
- for cmd in ["sh", "mount", "umount", "ls", "cat", "echo", "sleep",
3929
- "readlink", "mkdir", "switch_root", "cp", "rm"]:
3930
- link = os.path.join(tmpdir, "bin", cmd)
3931
- if not os.path.exists(link):
3932
- os.symlink("busybox", link)
3933
- # /bin/sh → busybox
3934
- if not os.path.exists(os.path.join(tmpdir, "bin/sh")):
3935
- os.symlink("busybox", os.path.join(tmpdir, "bin/sh"))
3936
- else:
3937
- # Bez busybox – kopiuj podstawowe narzędzia z deploymentu
3938
- for tool in ["bash", "mount", "umount", "readlink", "mkdir", "cat", "sleep", "cp", "rm"]:
3939
- src = os.path.join(root, "usr/bin", tool)
3940
- if not os.path.exists(src):
3941
- src = os.path.join(root, "bin", tool)
3942
- if os.path.exists(src):
3943
- dest = os.path.join(tmpdir, "bin", os.path.basename(tool))
3944
- shutil.copy2(src, dest)
3945
- # Kopiuj zależności .so
3946
- _copy_libs_for_binary(src, tmpdir, root)
3947
-
3948
- # Dodaj moduły jądra (opcjonalnie – dla sterowników dyskowych)
3949
- modules_src = os.path.join(root, "lib/modules", kernel_ver)
3950
- if os.path.isdir(modules_src):
3951
- modules_dst = os.path.join(tmpdir, "lib/modules", kernel_ver)
3952
- # Kopiuj tylko niezbędne (fs, block, drivers/ata, drivers/nvme)
3953
- for sub in ["kernel/fs", "kernel/drivers/ata", "kernel/drivers/nvme",
3954
- "kernel/drivers/scsi", "kernel/drivers/virtio",
3955
- "modules.order", "modules.builtin"]:
3956
- src_sub = os.path.join(modules_src, sub)
3957
- if os.path.exists(src_sub):
3958
- dst_sub = os.path.join(modules_dst, sub)
3959
- os.makedirs(os.path.dirname(dst_sub), exist_ok=True)
3960
- if os.path.isdir(src_sub):
3961
- try:
3962
- shutil.copytree(src_sub, dst_sub, dirs_exist_ok=True, symlinks=True,
3963
- ignore_dangling_symlinks=True)
3964
- except (FileNotFoundError, PermissionError):
3965
- print(f" ⚠ Pomijam niedostępne pliki: {sub}")
3966
- else:
3967
- try:
3968
- shutil.copy2(src_sub, dst_sub)
3969
- except (FileNotFoundError, PermissionError):
3970
- print(f" ⚠ Pomijam niedostępny plik: {sub}")
3971
-
3972
- # Pakuj do initramfs.img
3973
- initramfs_path = os.path.join(boot_dir, "initramfs.img")
3974
- old_cwd = os.getcwd()
3975
- os.chdir(tmpdir)
3976
- try:
3977
- with open(initramfs_path + ".tmp", "wb") as out:
3978
- _run_cpio_pipeline(tmpdir, out)
3979
- os.rename(initramfs_path + ".tmp", initramfs_path)
3980
- finally:
3981
- os.chdir(old_cwd)
3982
-
3983
- size_mb = os.path.getsize(initramfs_path) / 1048576
3984
- print(f" ✅ initramfs.img ({size_mb:.1f} MB) → {initramfs_path}")
3985
- return True
3986
-
3987
- except Exception as e:
3988
- print(f" ❌ Błąd budowy initramfs: {e}")
3989
- return False
3990
- finally:
3991
- shutil.rmtree(tmpdir, ignore_errors=True)
3992
-
3993
-
3994
-def _run_cpio_pipeline(tmpdir: str, out):
3995
- """find . -print0 | cpio --null -oH newc | gzip — bez shell=True.
3996
-
3997
- Buduje pipeline przez subprocess.Popen, unikając pośrednika powłoki
3998
- (brak ryzyka injection i niepotrzebnego procesu sh). Wykonuje się w cwd=tmpdir.
3999
- Separatory NUL (\0): plik/katalog ze znakiem nowej linii w nazwie nie
4000
- rozjeżdża cpio (inaczej uszkodzone archiwum → kernel panic przy rozruchu).
4001
- """
4002
- find = subprocess.Popen(["find", ".", "-print0"], cwd=tmpdir, stdout=subprocess.PIPE)
4003
- cpio = subprocess.Popen(["cpio", "--null", "-oH", "newc"], cwd=tmpdir,
4004
- stdin=find.stdout, stdout=subprocess.PIPE)
4005
- find.stdout.close() # zwolnij uchwyt – cpio dostanie SIGPIPE po zakończeniu find
4006
- gzip = subprocess.Popen(["gzip"], stdin=cpio.stdout, stdout=out)
4007
- cpio.stdout.close()
4008
- try:
4009
- gzip.wait(timeout=120)
4010
- if gzip.returncode != 0:
4011
- raise subprocess.CalledProcessError(gzip.returncode, ["gzip"])
4012
- cpio.wait(timeout=30)
4013
- find.wait(timeout=30)
4014
- except subprocess.TimeoutExpired:
4015
- for p in (gzip, cpio, find):
4016
- p.kill()
4017
- raise
4018
- finally:
4019
- for p in (find, cpio, gzip):
4020
- if p.poll() is None:
4021
- p.kill()
4022
- # Skontroluj też kody procesów pośrednich (cpio/find mogą zawieść, a gzip zwrócić 0)
4023
- if cpio.returncode != 0:
4024
- raise subprocess.CalledProcessError(cpio.returncode, ["cpio"])
4025
- if find.returncode != 0:
4026
- raise subprocess.CalledProcessError(find.returncode, ["find"])
4027
-
4028
-
4029
-def _copy_libs_for_binary(binary: str, dest_dir: str, root: str):
4030
- """Kopiuje zależności .so dla binarki do initramfs (uproszczone ldd)."""
4031
- try:
4032
- result = subprocess.run(
4033
- ["ldd", binary], capture_output=True, text=True, timeout=10
4034
- )
4035
- for line in result.stdout.split("\n"):
4036
- m = re.search(r'=>\s+(/\S+)', line)
4037
- if m:
4038
- lib_path = m.group(1)
4039
- lib_rel = lib_path.lstrip("/")
4040
- lib_dest = os.path.join(dest_dir, lib_rel)
4041
- if not os.path.exists(lib_dest):
4042
- os.makedirs(os.path.dirname(lib_dest), exist_ok=True)
4043
- # Szukaj w deployment root lub systemie
4044
- if os.path.exists(lib_path):
4045
- shutil.copy2(lib_path, lib_dest)
4046
- else:
4047
- alt = os.path.join(root, lib_rel)
4048
- if os.path.exists(alt):
4049
- shutil.copy2(alt, lib_dest)
4050
- except Exception:
4051
- pass
4052
-
4053
-
4054
-def cmd_initramfs_update():
4055
- """Ręcznie przebudowuje initramfs dla bieżącego deploymentu."""
4056
- ensure_dirs()
4057
- deploy_dir = _get_deployment_root()
4058
- if deploy_dir != PAG_ROOT:
4059
- print(f"🏗️ Deployment: {os.path.basename(deploy_dir)}")
4060
- ok = _rebuild_initramfs(deploy_dir)
4061
- if ok:
4062
- print("✅ Initramfs zaktualizowany.")
4063
- # Po initramfs – zaktualizuj też GRUB
4064
- _update_grub_config()
4065
- else:
4066
- print("❌ Błąd aktualizacji initramfs.")
4067
- return 0 if ok else 1
4068
-
4069
-
4070
-def _update_grub_config():
4071
- """
4072
- Generuje wpisy GRUB dla wszystkich deploymentów.
4073
- Każdy deployment dostaje własny wpis – rollback możliwy z bootloadera.
4074
- """
4075
- grub_cfg = "/boot/grub/grub.cfg"
4076
- if not os.path.exists(os.path.dirname(grub_cfg)):
4077
- return # brak GRUB
4078
-
4079
- deployments = _load_deployments()
4080
- root_dev = _detect_root_device()
4081
-
4082
- lines = [
4083
- "# =====================================================================",
4084
- "# Pagan Linux – GRUB config (wygenerowane przez pag grub-update)",
4085
- f"# Data: {datetime.now().isoformat()}",
4086
- "# =====================================================================",
4087
- "",
4088
- ]
4089
-
4090
- # Domyślny – ostatni (najnowszy) deployment
4091
- if deployments:
4092
- latest = deployments[-1]["id"]
4093
- lines.append(f"set default=0")
4094
- lines.append(f"set timeout=5")
4095
- else:
4096
- lines.append("set default=0")
4097
- lines.append("set timeout=5")
4098
- lines.append("")
4099
-
4100
- # Wpisy dla każdego deploymentu (od najnowszego)
4101
- entry_num = 0
4102
- for d in reversed(deployments):
4103
- deploy_dir = os.path.join(DEPLOYMENTS_DIR, d["id"])
4104
- boot_dir = os.path.join(deploy_dir, "boot")
4105
- kernels = sorted(
4106
- [f for f in os.listdir(boot_dir) if f.startswith("vmlinuz-")],
4107
- reverse=True
4108
- ) if os.path.isdir(boot_dir) else []
4109
-
4110
- kernel_path = f"/.deployments/{d['id']}/boot/{kernels[0]}" if kernels else ""
4111
- initrd_path = f"/.deployments/{d['id']}/boot/initramfs.img"
4112
- initrd_line = f"initrd {initrd_path}" if os.path.exists(os.path.join(boot_dir, "initramfs.img")) else ""
4113
-
4114
- active_mark = " [AKTYWNY]" if d.get("active") else ""
4115
- pkg_list = ", ".join(d.get("packages", [])[:3])
4116
- label = f"Pagan Linux – {d['id']}{active_mark}"
4117
-
4118
- lines.append(f"menuentry '{label}' {{")
4119
- if kernel_path:
4120
- lines.append(f" linux {kernel_path} root={root_dev} rw quiet")
4121
- else:
4122
- lines.append(f" # Brak jądra w tym deploymencie")
4123
- if initrd_line:
4124
- lines.append(f" {initrd_line}")
4125
- lines.append("}")
4126
- lines.append("")
4127
- entry_num += 1
4128
-
4129
- # Wpis fallback: zwykły root (gdyby wszystko padło)
4130
- lines.append("menuentry 'Pagan Linux – fallback (zwykły root)' {")
4131
- lines.append(f" linux /boot/vmlinuz-* root={root_dev} rw quiet")
4132
- lines.append(f" initrd /boot/initramfs.img")
4133
- lines.append("}")
4134
- lines.append("")
4135
-
4136
- # Zapisz
4137
- os.makedirs(os.path.dirname(grub_cfg), exist_ok=True)
4138
- with open(grub_cfg, "w") as f:
4139
- f.write("\n".join(lines))
4140
-
4141
- print(" 📋 GRUB config zaktualizowany – wpisy dla każdego deploymentu")
4142
-
4143
-
4144
-def _detect_root_device() -> str:
4145
- """Wykrywa device partycji root (np. /dev/sda1)."""
4146
- try:
4147
- result = subprocess.run(
4148
- ["findmnt", "-n", "-o", "SOURCE", "/"],
4149
- capture_output=True, text=True, timeout=5
4150
- )
4151
- if result.returncode == 0 and result.stdout.strip():
4152
- return result.stdout.strip()
4153
- except Exception:
4154
- pass
4155
- return "/dev/sda1" # fallback
4156
-
4157
-
4158
-def cmd_grub_update():
4159
- """Ręcznie regeneruje konfigurację GRUB (wpisy dla deploymentów)."""
4160
- ensure_dirs()
4161
- print("📋 Aktualizacja konfiguracji GRUB...")
4162
- _update_grub_config()
4163
- print("✅ GRUB zaktualizowany.")
4164
- return 0
4165
-
4166
-def cmd_deploy_list():
4167
- """Wyświetla listę wszystkich deploymentów."""
4168
- deployments = _load_deployments()
4169
- if not deployments:
4170
- print(_("no_deployments")); return
4171
-
4172
- print(_("deployments_list", len(deployments)))
4173
- active = os.readlink(ACTIVE_LINK) if os.path.islink(ACTIVE_LINK) else ""
4174
-
4175
- for d in reversed(deployments):
4176
- marker = f" ◀ {_('active_deployment')}" if d.get("active") or d["id"] == os.path.basename(active) else ""
4177
- print(f" {d['id']}{marker}")
4178
- print(f" {d['action']}: {', '.join(d['packages'][:5])}")
4179
- if len(d.get('packages', [])) > 5:
4180
- print(f" +{len(d['packages']) - 5} więcej...")
4181
- print(f" {d['timestamp']}")
4182
-
4183
-
4184
-def cmd_deploy_rollback():
4185
- """Przełącza na poprzedni deployment."""
4186
- deployments = _load_deployments()
4187
- active_indices = [i for i, d in enumerate(deployments) if d.get("active")]
4188
-
4189
- if len(deployments) < 2:
4190
- print(f"❌ {_('deploy_rollback_fail')}"); return 1
4191
-
4192
- current_idx = active_indices[0] if active_indices else len(deployments) - 1
4193
- prev_idx = current_idx - 1 if current_idx > 0 else -1
4194
-
4195
- if prev_idx < 0:
4196
- print(f"❌ {_('deploy_rollback_fail')}"); return 1
4197
-
4198
- prev = deployments[prev_idx]
4199
- prev_dir = os.path.join(DEPLOYMENTS_DIR, prev["id"])
4200
-
4201
- if not os.path.isdir(prev_dir):
4202
- print(f"❌ Deployment {prev['id']} nie istnieje na dysku"); return 1
4203
-
4204
- print(f"⏪ Przywracanie deploymentu: {prev['id']}")
4205
- print(f" {prev['action']}: {', '.join(prev['packages'][:5])}")
4206
-
4207
- if not _ask_confirm():
4208
- return 0
4209
-
4210
- _switch_deployment(prev_dir)
4211
-
4212
- for d in deployments:
4213
- d["active"] = (d["id"] == prev["id"])
4214
- _save_deployments(deployments)
4215
-
4216
- _update_grub_config()
4217
- print(f"✅ {_('deploy_rollback_ok', prev['id'])}")
4218
- print(" 💡 Restart wymagany do przeładowania systemu.")
4219
- return 0
4220
-
4221
-
4222
-def cmd_deploy_cleanup(keep: int = 3):
4223
- """Usuwa stare deploymenty, zachowując ostatnie `keep`."""
4224
- deployments = _load_deployments()
4225
-
4226
- if len(deployments) <= keep:
4227
- print(f"✅ {_('deploy_cleanup_none', keep)}"); return 0
4228
-
4229
- to_remove = deployments[:-keep]
4230
- removed = 0
4231
-
4232
- for d in to_remove:
4233
- deploy_dir = os.path.join(DEPLOYMENTS_DIR, d["id"])
4234
- if os.path.isdir(deploy_dir):
4235
- shutil.rmtree(deploy_dir, ignore_errors=True)
4236
- removed += 1
4237
-
4238
- remaining = deployments[-keep:]
4239
- _save_deployments(remaining)
4240
-
4241
- print(f"✅ {_('deploy_cleanup_ok', removed)}")
4242
- return 0
4243
-
4244
-
4245
-# =============================================================================
4246
-# POMOCNICZE
4247
-# =============================================================================
4248
-
4249
-def _resolve_deps(names, repo, installed):
4250
- resolved, visited = [], set()
4251
- missing = [] # zależności których nie ma ani w repo ani zainstalowane
4252
-
4253
- def visit(name):
4254
- if name in visited: return
4255
-
4256
- # Rozwijanie wirtualnych zależności przez provides
4257
- target = _resolve_provides(name, repo, installed)
4258
-
4259
- if target in visited: return
4260
- visited.add(target)
4261
- if target in repo:
4262
- for dep in repo[target].dependencies:
4263
- real_dep = _resolve_provides(dep, repo, installed)
4264
- real_target = real_dep if real_dep in repo else dep
4265
-
4266
- # Sprawdź czy zależność jest dostępna
4267
- if real_target not in installed and real_target not in repo:
4268
- if dep not in missing:
4269
- missing.append(dep)
4270
-
4271
- if dep not in installed:
4272
- visit(real_target)
4273
- elif target not in installed:
4274
- # Pakiet nie istnieje ani w repo ani zainstalowany
4275
- if target not in missing:
4276
- missing.append(target)
4277
-
4278
- if target not in installed and target not in resolved:
4279
- resolved.append(target)
4280
-
4281
- for name in names:
4282
- visit(name)
4283
-
4284
- # Zwróć brakujące (do sprawdzenia przez wywołującego)
4285
- return resolved, missing
4286
-
4287
-def _verify_dependencies(to_install: list, repo: dict, installed: dict) -> int:
4288
- """
4289
- Sprawdza czy wszystkie zależności pakietów do instalacji są spełnione.
4290
- Zwraca liczbę brakujących zależności.
4291
- """
4292
- # Pakiety dostarczane przez bazowy system (zawsze "zainstalowane")
4293
- SYSTEM_BASE = {
4294
- "glibc", "libc", "gcc", "g++", "make", "binutils", "coreutils", "bash",
4295
- "linux-api-headers", "kernel-headers", "zlib", "pkg-config", "pkgconf",
4296
- "tar", "gzip", "xz", "bzip2", "findutils", "grep", "sed", "gawk", "awk",
4297
- "diffutils", "patch", "file", "m4", "perl", "python3", "sh",
4298
- }
4299
- all_missing = []
4300
- all_warnings = []
4301
-
4302
- for pkg_name in to_install:
4303
- pkg = repo.get(pkg_name)
4304
- if not pkg:
4305
- continue
4306
-
4307
- for dep in pkg.dependencies:
4308
- if dep in SYSTEM_BASE:
4309
- continue # bazowy system dostarcza tę zależność
4310
- real_dep = _resolve_provides(dep, repo, installed)
4311
- # Sprawdź czy zależność jest dostępna (w repo lub już zainstalowana)
4312
- in_repo = real_dep in repo
4313
- in_installed = real_dep in installed
4314
- will_be_installed = real_dep in to_install
4315
-
4316
- if not in_repo and not in_installed and not will_be_installed:
4317
- if dep not in all_missing:
4318
- all_missing.append((pkg_name, dep))
4319
- elif in_repo and not in_installed and not will_be_installed:
4320
- if dep not in [w[1] for w in all_warnings]:
4321
- all_warnings.append((pkg_name, dep, real_dep))
4322
-
4323
- if all_missing:
4324
- print(f"\n❌ {_c('red', 'BRAKUJĄCE ZALEŻNOŚCI')} – nie można zainstalować:")
4325
- for pkg, dep in all_missing:
4326
- print(f" {pkg} → potrzebuje {_c('red', dep)} (brak w repozytoriach)")
4327
- print()
4328
-
4329
- if all_warnings:
4330
- print(f"\n⚠ {_c('yellow', 'NIESPEŁNIONE ZALEŻNOŚCI')} – zostaną doinstalowane:")
4331
- for pkg, dep, real in all_warnings:
4332
- print(f" {pkg} → {dep} ({_c('green', real)} – będzie pobrane)")
4333
- print()
4334
-
4335
- return len(all_missing)
4336
-
4337
-# Biblioteki bazowe (glibc/gcc runtime) – zawsze dostępne, nie wymagają pakietu
4338
-BASE_SO = {
4339
- "libc.so.6", "libm.so.6", "libpthread.so.0", "libdl.so.2", "librt.so.1",
4340
- "libutil.so.1", "libresolv.so.2", "libnsl.so.1", "libcrypt.so.1",
4341
- "ld-linux.so.2", "ld-linux-x86-64.so.2", "ld-linux-aarch64.so.1",
4342
- "libgcc_s.so.1", "linux-vdso.so.1",
4343
-}
4344
-
4345
-def _verify_so_deps(to_install: list, repo: dict, installed: dict) -> int:
4346
- """Sprawdza wymagania ABI (provides_so / requires_so z metadata.json).
4347
-
4348
- Fail-closed TYLKO gdy metadata jawnie deklaruje requires_so, a żaden pakiet
4349
- (bazowy, zainstalowany lub instalowany w tej transakcji) nie dostarcza
4350
- wymaganej wersji biblioteki. Stare pakiety bez tych pól są pomijane.
4351
- """
4352
- provided = set(BASE_SO)
4353
- for n in to_install:
4354
- p = repo.get(n)
4355
- if p:
4356
- provided.update(p.provides_so or [])
4357
- for n, info in installed.items():
4358
- provided.update(info.get("provides_so", []) or [])
4359
-
4360
- missing = []
4361
- for n in sorted(to_install):
4362
- p = repo.get(n)
4363
- if not p:
4364
- continue
4365
- for so in (p.requires_so or []):
4366
- if so not in provided:
4367
- missing.append((n, so))
4368
-
4369
- if missing:
4370
- print(f"\n❌ {_c('red', 'BRAK WYMAGANYCH BIBLIOTEK (ABI so-name)')}:")
4371
- for n, so in missing:
4372
- print(f" {n} → wymaga {_c('red', so)} – żaden pakiet nie dostarcza tej wersji")
4373
- print()
4374
- return len(missing)
4375
-
4376
-def _download_pkg(pkg):
4377
- url = f"{pkg.repo_url}/{pkg.filename}"
4378
- dest = os.path.join(PAG_CACHE, pkg.filename)
4379
- if os.path.exists(dest) and (not pkg.sha256 or _sha256_file(dest) == pkg.sha256):
4380
- _download_pkg_sig(pkg, dest) # upewnij się, że sygnatura jest w cache
4381
- return dest
4382
- try:
4383
- req = Request(url, headers={"User-Agent":"pag/3.0"})
4384
- with urlopen(req, timeout=600) as resp:
4385
- total = int(resp.headers.get("Content-Length", 0))
4386
- bar = DownloadBar(pkg.filename, total)
4387
- with open(dest, "wb") as f:
4388
- while True:
4389
- chunk = resp.read(65536)
4390
- if not chunk:
4391
- break
4392
- f.write(chunk)
4393
- bar.update(len(chunk))
4394
- bar.close()
4395
- if pkg.sha256 and _sha256_file(dest) != pkg.sha256:
4396
- os.remove(dest); return None
4397
- _download_pkg_sig(pkg, dest)
4398
- return dest
4399
- except Exception as e:
4400
- print(f" ⚠ Błąd pobierania {pkg.filename}: {e}", file=sys.stderr)
4401
- return None
4402
-
4403
-def _download_pkg_sig(pkg, dest):
4404
- """Pobiera podpis pakietu (.asc, fallback .sig) obok paczki w cache."""
4405
- for ext in (".asc", ".sig"):
4406
- sig_dest = dest + ext
4407
- if os.path.exists(sig_dest):
4408
- return
4409
- try:
4410
- req = Request(f"{pkg.repo_url}/{pkg.filename}{ext}", headers={"User-Agent":"pag/3.0"})
4411
- with urlopen(req, timeout=30) as resp:
4412
- with open(sig_dest, "wb") as f:
4413
- f.write(resp.read())
4414
- return
4415
- except Exception:
4416
- continue
4417
-
4418
-def _download_packages_parallel(pkgs: List[PackageInfo], max_workers: int = 4) -> Dict[str, Optional[str]]:
4419
- """
4420
- Równoległe pobieranie wielu pakietów przez ThreadPoolExecutor.
4421
- Znacząco przyspiesza przy dużych aktualizacjach (50+ pakietów).
4422
- Zwraca słownik {nazwa_pakietu: ścieżka_lub_None}.
4423
- """
4424
- results = {}
4425
- total = len(pkgs)
4426
- completed = 0
4427
- with ThreadPoolExecutor(max_workers=max_workers) as executor:
4428
- future_to_pkg = {executor.submit(_download_pkg, pkg): pkg for pkg in pkgs}
4429
- for future in as_completed(future_to_pkg):
4430
- pkg = future_to_pkg[future]
4431
- try:
4432
- results[pkg.name] = future.result()
4433
- except Exception:
4434
- results[pkg.name] = None
4435
- completed += 1
4436
- # Pasek postępu
4437
- pct = completed / total * 100
4438
- filled = int(20 * pct / 100)
4439
- bar = "█" * filled + "░" * (20 - filled)
4440
- print(f"\r ⏬ [{bar}] {completed}/{total} ({pct:.0f}%)", end="", file=sys.stderr, flush=True)
4441
- print(file=sys.stderr) # nowa linia po zakończeniu
4442
- return results
4443
-
4444
-def load_world():
4445
- if not os.path.exists(WORLD_FILE): return set()
4446
- return {l.strip() for l in open(WORLD_FILE) if l.strip()}
4447
-
4448
-def save_world(w):
4449
- with open(WORLD_FILE,"w") as f:
4450
- for n in sorted(w): f.write(f"{n}\n")
4451
-
4452
-def _find_orphans(installed, world):
4453
- needed = set(world)
4454
- changed = True
4455
- while changed:
4456
- changed = False
4457
- for n in list(needed):
4458
- for dep in installed.get(n,{}).get("dependencies",[]):
4459
- if dep not in needed and dep in installed:
4460
- needed.add(dep); changed = True
4461
- return {n for n in installed if n not in needed}
4462
-
4463
-# =============================================================================
4464
-# MAIN
4465
-# =============================================================================
4466
-
4467
-def cmd_sbom(argv):
4468
- """pag sbom export [spdx|cyclonedx] – manifest SBOM zainstalowanych pakietów.
4469
-
4470
- Wypisuje na stdout JSON (SPDX 2.3 lub CycloneDX 1.5) z listą
4471
- zainstalowanych pakietów, wersji, licencji i sum SHA256.
4472
- """
4473
- fmt = (argv[0] if argv else "spdx").lower()
4474
- if fmt not in ("spdx", "cyclonedx"):
4475
- print("❌ Format: spdx | cyclonedx")
4476
- return 1
4477
- installed = load_json(INSTALLED_DB)
4478
- if not installed:
4479
- print("{}") if fmt == "cyclonedx" else print("{\"packages\": []}")
4480
- return 0
4481
- # metadata repo (licencje) – best-effort
4482
- try:
4483
- repo = fetch_all_packages()
4484
- except Exception:
4485
- repo = {}
4486
- names = sorted(installed)
4487
- created = datetime.now().astimezone().isoformat(timespec="seconds")
4488
-
4489
- def _license_of(name):
4490
- p = repo.get(name)
4491
- lic = getattr(p, "license", None) or []
4492
- if isinstance(lic, list):
4493
- lic = ", ".join(x for x in lic if x)
4494
- return lic or "NOASSERTION"
4495
-
4496
- if fmt == "spdx":
4497
- doc = {
4498
- "spdxVersion": "SPDX-2.3",
4499
- "dataLicense": "CC0-1.0",
4500
- "SPDXID": "SPDXRef-DOCUMENT",
4501
- "name": "PaganOS-installed",
4502
- "documentNamespace": f"https://repo.paganlinux.eu/sbom/installed-{int(time.time())}",
4503
- "creationInfo": {
4504
- "created": created,
4505
- "creators": [f"Tool: pag-{PAG_VERSION}"],
4506
- },
4507
- "packages": [],
4508
- }
4509
- for i, n in enumerate(names):
4510
- info = installed[n]
4511
- doc["packages"].append({
4512
- "SPDXID": f"SPDXRef-Package-{i+1}",
4513
- "name": n,
4514
- "versionInfo": info.get("version", ""),
4515
- "downloadLocation": info.get("repo", "NOASSERTION"),
4516
- "filesAnalyzed": False,
4517
- "licenseConcluded": _license_of(n),
4518
- "checksums": [{"algorithm": "SHA256", "checksumValue": info.get("sha256", "")}],
4519
- })
4520
- else: # cyclonedx
4521
- doc = {
4522
- "bomFormat": "CycloneDX",
4523
- "specVersion": "1.5",
4524
- "serialNumber": f"urn:uuid:{str(uuid.uuid4())}",
4525
- "version": 1,
4526
- "metadata": {
4527
- "timestamp": created,
4528
- "tools": [{"vendor": "PaganOS", "name": "pag", "version": PAG_VERSION}],
4529
- },
4530
- "components": [],
4531
- }
4532
- for n in names:
4533
- info = installed[n]
4534
- lic = _license_of(n)
4535
- comp = {
4536
- "type": "library",
4537
- "name": n,
4538
- "version": info.get("version", ""),
4539
- "hashes": [{"alg": "SHA-256", "content": info.get("sha256", "")}],
4540
- }
4541
- if lic != "NOASSERTION":
4542
- comp["licenses"] = [{"license": {"id": lic}}]
4543
- doc["components"].append(comp)
4544
- print(json.dumps(doc, indent=2, ensure_ascii=False))
4545
- return 0
4546
-
4547
-
4548
-USAGE_EN = """pag v3 – Pagan Linux Package Manager
4549
-
4550
-BASIC:
4551
- pag install <pkg>... Install packages
4552
- pag remove <pkg>... Remove packages
4553
- pag update Update PACKAGES (refreshes indexes first)
4554
- pag sync Refresh indexes + show pending package updates
4555
- pag upgrade Update SYSTEM (packages + kernel/initramfs/GRUB)
4556
- pag list [--installed] List available / installed
4557
- pag search <query> Search packages
4558
- pag info <pkg> Package details
4559
- pag files <pkg> List package files
4560
- pag verify [--deep] Verify integrity (--deep = SHA256 per file)
4561
- pag clean Clear download cache
4562
- pag stats System statistics
4563
- pag download <pkg>... Download packages to cache (offline prep)
4564
-
4565
-SECURITY:
4566
- pag key-add <url|file> Import GPG key
4567
- pag key-list List trusted keys
4568
- pag key-remove <id> Remove key
4569
- pag key-trust <repo> Pin repo signing key fingerprint (no TOFU)
4570
- pag key-untrust <repo> Forget repo fingerprint (back to TOFU)
4571
- pag key-trusted List pinned repo fingerprints
4572
-
4573
-ADVANCED:
4574
- pag why <pkg> Show why a package is installed
4575
- pag autoremove Auto-remove orphaned dependencies
4576
- pag pin <pkg> [ver] Pin package version
4577
- pag unpin <pkg> Unpin
4578
- pag pinned List pinned
4579
- pag history Transaction history
4580
- pag rollback Rollback last transaction
4581
- pag remove-orphans Remove orphaned deps
4582
- pag repo-add <url> [name] Add repository (drop-in /etc/pag/repos/)
4583
- pag repo-list List repositories
4584
- pag sbom export [fmt] SBOM manifest (spdx|cyclonedx)
4585
-
4586
-FLATPAK:
4587
- pag flatpak [<query>] Search & install (smart)
4588
- pag flatpak search <q> Search Flathub
4589
- pag flatpak install <id> Install flatpak
4590
- pag flatpak remove <id> Remove flatpak
4591
- pag flatpak list List installed flatpaks
4592
- pag flatpak update Update all flatpaks
4593
- pag flatpak info <id> Show flatpak details
4594
-
4595
-IMMUTABLE OS (PAG_IMMUTABLE=1):
4596
- pag deploy-list List all deployments
4597
- pag deploy-rollback Switch to previous deployment
4598
- pag deploy-cleanup [N] Remove old deployments (keep last N, default 3)
4599
- pag initramfs-update Rebuild initramfs for current kernel/deployment
4600
- pag grub-update Regenerate GRUB entries for all deployments
4601
-"""
4602
-
4603
-USAGE_PL = """pag v3 – Pagan Linux Package Manager
4604
-
4605
-PODSTAWOWE:
4606
- pag install <pkg>... Instalacja pakietów
4607
- pag remove <pkg>... Usuwanie pakietów
4608
- pag update Aktualizacja PAKIETÓW (odświeża indeksy)
4609
- pag sync Odśwież indeksy + info o aktualizacjach
4610
- pag upgrade Aktualizacja SYSTEMU (pakiety + kernel/initramfs/GRUB)
4611
- pag list [--installed] Lista dostępnych / zainstalowanych
4612
- pag search <query> Szukaj pakietów
4613
- pag info <pkg> Szczegóły pakietu
4614
- pag files <pkg> Lista plików pakietu
4615
- pag verify [--deep] Weryfikacja integralności
4616
- pag clean Wyczyść cache pobierania
4617
- pag stats Statystyki systemu
4618
- pag download <pkg>... Pobierz do cache (offline)
4619
-
4620
-BEZPIECZEŃSTWO:
4621
- pag key-add <url|file> Importuj klucz GPG
4622
- pag key-list Lista zaufanych kluczy
4623
- pag key-remove <id> Usuń klucz
4624
- pag key-trust <repo> Przypnij fingerprint klucza repo (bez TOFU)
4625
- pag key-untrust <repo> Zapomnij fingerprint repo (powrót do TOFU)
4626
- pag key-trusted Lista przypiętych fingerprintów repo
4627
-
4628
-ZAAWANSOWANE:
4629
- pag why <pkg> Dlaczego pakiet jest zainstalowany
4630
- pag autoremove Usuń osierocone zależności
4631
- pag pin <pkg> [ver] Przypnij wersję pakietu
4632
- pag unpin <pkg> Odepnij
4633
- pag pinned Lista przypiętych
4634
- pag history Historia transakcji
4635
- pag rollback Cofnij ostatnią transakcję
4636
- pag remove-orphans Usuń osierocone zależności
4637
- pag repo-add <url> [nazwa] Dodaj repozytorium (drop-in w /etc/pag/repos/)
4638
- pag repo-list Lista repozytoriów
4639
- pag sbom export [fmt] Manifest SBOM (spdx|cyclonedx)
4640
-
4641
-FLATPAK:
4642
- pag flatpak [<query>] Szukaj i instaluj
4643
- pag flatpak search <q> Szukaj na Flathub
4644
- pag flatpak install <id> Zainstaluj flatpak
4645
- pag flatpak remove <id> Usuń flatpak
4646
- pag flatpak list Lista zainstalowanych
4647
- pag flatpak update Aktualizuj wszystkie
4648
- pag flatpak info <id> Szczegóły flatpaka
4649
-
4650
-IMMUTABLE OS (PAG_IMMUTABLE=1):
4651
- pag deploy-list Lista wdrożeń
4652
- pag deploy-rollback Przełącz na poprzednie wdrożenie
4653
- pag deploy-cleanup [N] Usuń stare wdrożenia (zachowaj N, domyślnie 3)
4654
- pag initramfs-update Przebuduj initramfs
4655
- pag grub-update Regeneruj wpisy GRUB"""
4656
-
4657
-def _get_usage():
4658
- if LANG == "pl":
4659
- return USAGE_PL
4660
- return USAGE_EN
4661
-
4662
-
4663
-def main():
4664
- if len(sys.argv) >= 2 and sys.argv[1] in ("--version", "-V", "version"):
4665
- print(f"pag {PAG_VERSION}")
4666
- sys.exit(0)
4667
- if len(sys.argv) < 2:
4668
- print(_get_usage()); sys.exit(0)
4669
-
4670
- cmd = sys.argv[1]
4671
- args = sys.argv[2:]
4672
-
4673
- # --- Komendy TYLKO DO ODCZYTU (nie wymagają roota) ---
4674
- READ_ONLY = {
4675
- "list": lambda: cmd_list("--installed" in args),
4676
- "search": lambda: cmd_search(args[0]) if args else print("Usage: pag search <query>"),
4677
- "info": lambda: cmd_info(args[0]) if args else print("Usage: pag info <pkg>"),
4678
- "files": lambda: cmd_files(args[0]) if args else print("Usage: pag files <pkg>"),
4679
- "verify": lambda: cmd_verify("--deep" in args),
4680
- "why": lambda: cmd_why(args[0]) if args else print("Usage: pag why <pkg>"),
4681
- "stats": cmd_stats,
4682
- "pinned": cmd_pinned,
4683
- "history": cmd_history,
4684
- "repo-list": cmd_repo_list,
4685
- "key-list": cmd_key_list,
4686
- "key-trusted": cmd_key_trusted,
4687
- "flatpak": lambda: cmd_flatpak(args),
4688
- "flatpak-search": lambda: cmd_flatpak_search(args[0]) if args else print("Usage: pag flatpak-search <query>"),
4689
- "flatpak-list": cmd_flatpak_list,
4690
- "flatpak-info": lambda: cmd_flatpak_info(args[0]) if args else print("Usage: pag flatpak-info <id>"),
4691
- "deploy-list": cmd_deploy_list,
4692
- "deploy": cmd_deploy_list,
4693
- "sbom": lambda: cmd_sbom(args),
4694
- }
4695
-
4696
- if cmd in READ_ONLY:
4697
- sys.exit(READ_ONLY[cmd]() or 0)
4698
-
4699
- # --- Smart search: `pag <nazwa-pakietu>` → repo + Flathub + sugestie ---
4700
- WRITE_CMDS = {
4701
- "install", "remove", "update", "sync", "upgrade", "clean", "download",
4702
- "autoremove", "remove-orphans", "pin", "unpin", "rollback",
4703
- "repo-add", "key-add", "key-remove", "key-trust", "key-untrust",
4704
- "self-update",
4705
- "flatpak", "flatpak-install", "flatpak-remove", "flatpak-update",
4706
- "deploy-rollback", "deploy-cleanup", "initramfs-update", "grub-update",
4707
- }
4708
- if cmd not in WRITE_CMDS:
4709
- # Literówka komendy? (np. `pag instal steam` zamiast `pag install`) –
4710
- # zasugeruj poprawną komendę ZAMIAST wpadać w smart search (który
4711
- # potrafi wisieć na `flatpak search` aż do Ctrl-C).
4712
- _known = set(READ_ONLY) | set(WRITE_CMDS)
4713
- _close = difflib.get_close_matches(cmd, _known, n=1, cutoff=0.75)
4714
- if _close:
4715
- print(f"❌ Nieznana komenda: '{cmd}'. Czy chodziło o '{_close[0]}'?")
4716
- print(f" Uruchom 'pag' bez argumentów, aby zobaczyć listę komend.")
4717
- sys.exit(1)
4718
- sys.exit(_smart_search(" ".join([cmd] + args)) or 0)
4719
-
4720
- # Obsługa flag globalnych (-y/--yes)
4721
- global_args = []
4722
- for a in args:
4723
- if a in ("-y", "--yes"):
4724
- os.environ["PAG_YES"] = "1"
4725
- else:
4726
- global_args.append(a)
4727
- args = global_args
4728
-
4729
- # --- Komendy ZAPISU (wymagają roota) ---
4730
- if os.geteuid() != 0:
4731
- print(f"❌ {_('root_required')}", file=sys.stderr); sys.exit(1)
4732
-
4733
- ensure_dirs()
4734
-
4735
- with DatabaseLock():
4736
- WRITE_COMMANDS = {
4737
- "install": lambda: cmd_install(
4738
- [a for a in args if a not in ("-f", "--force")],
4739
- upgrade=("-f" in args or "--force" in args)),
4740
- "remove": lambda: cmd_remove(args),
4741
- "update": lambda: cmd_update(do_upgrade=True),
4742
- "sync": lambda: cmd_update(do_upgrade=False),
4743
- "upgrade": cmd_upgrade,
4744
- "clean": cmd_clean,
4745
- "download": lambda: cmd_download(args),
4746
- "autoremove": cmd_autoremove,
4747
- "remove-orphans": cmd_remove_orphans,
4748
- "pin": lambda: cmd_pin(args[0], args[1] if len(args)>1 else ""),
4749
- "unpin": lambda: cmd_unpin(args[0]) if args else print("Usage: pag unpin <pkg>"),
4750
- "rollback": cmd_rollback,
4751
- "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]"),
4752
- "key-add": lambda: cmd_key_add(args[0]) if args else print("Usage: pag key-add <url|file>"),
4753
- "key-remove": lambda: cmd_key_remove(args[0]) if args else print("Usage: pag key-remove <id>"),
4754
- "key-trust": lambda: cmd_key_trust(args[0]) if args else print("Usage: pag key-trust <repo_url>"),
4755
- "key-untrust": lambda: cmd_key_untrust(args[0]) if args else print("Usage: pag key-untrust <repo_url>"),
4756
- "self-update": cmd_self_update,
4757
- "flatpak": lambda: cmd_flatpak(args),
4758
- "flatpak-install": lambda: _flatpak_smart_install(args) if args else print("Usage: pag flatpak-install <app>"),
4759
- "flatpak-remove": lambda: _flatpak_smart_remove(args) if args else print("Usage: pag flatpak-remove <app>"),
4760
- "flatpak-update": cmd_flatpak_update,
4761
- "deploy-rollback": cmd_deploy_rollback,
4762
- "deploy-cleanup": lambda: cmd_deploy_cleanup(int(args[0]) if args else 3),
4763
- "initramfs-update": cmd_initramfs_update,
4764
- "grub-update": cmd_grub_update,
4765
- }
4766
-
4767
- fn = WRITE_COMMANDS.get(cmd)
4768
- if fn:
4769
- sys.exit(fn() or 0)
4770
- # Should never reach here – _smart_search handles unknowns
4771
- sys.exit(_smart_search(" ".join([cmd] + args)) or 0)
4772
-
4773
-if __name__ == "__main__":
4774
- try:
4775
- main()
4776
- except KeyboardInterrupt:
4777
- # Ctrl-C (np. podczas flatpak search / pobierania) – bez tracebacka
4778
- print("\n ⚠ Przerwano (Ctrl-C).")
1
+#!/usr/bin/env python3
2
+"""
3
+╔══════════════════════════════════════════════════════════════════════════════╗
4
+║ PAG - Pagan Linux Package Manager v3.3.16 ║
5
+║ Produkcyjny menedżer pakietów – atomowy, bezpieczny, i18n ║
6
+╚══════════════════════════════════════════════════════════════════════════════╝
7
+
8
+KLUCZOWE CECHY:
9
+ - Atomowa instalacja przez staging (tmpdir → rename) – brak pół-instalacji
10
+ - Bezpieczne usuwanie – sprawdza czy plik nie jest współdzielony
11
+ - SQLite dla bazy plików – miliony plików bez problemu
12
+ - GPG: weryfikacja repo.json + podpisy pakietów + pinning fingerprintu
13
+ - Hooki: pre/post-install, pre/post-remove (piaskownica env, timeout, audit)
14
+ - Głęboka weryfikacja SHA256 per-plik
15
+ - Pełny rollback – cofa fizyczne pliki
16
+ - Blokada flock – tylko jedna instancja
17
+ - Transakcje z migawkami + rejestr wykonanych hooków
18
+ - Cache HTTP (ETag/If-Modified-Since)
19
+ - Wielojęzyczność (i18n) – PL, EN
20
+
21
+FORMAT PAKIETU (.pag):
22
+ ├── data.tar.xz – pliki + sums.json (SHA256 per plik)
23
+ ├── metadata.json – nazwa, wersja, zależności
24
+ └── hooks/ – pre-install, post-install, pre-remove, post-remove
25
+
26
+MODEL ZAUFANIA / BEZPIECZEŃSTWO:
27
+ - Repozytorium MUSI być zaufane: podpisy GPG zweryfikowane; fingerprint
28
+ klucza przypiętego do repo (TOFU przy pierwszym użyciu, potem pinning).
29
+ - Hooki uruchamiają dowolny plik z pakietu jako ROOT (jak apt/pacman).
30
+ Ograniczamy je (czyste env, timeout, PAG_NO_HOOKS=1, log do
31
+ /var/log/pag/audit.log) i rejestrujemy w transakcji, ale ostatecznie
32
+ instalujesz kod, któremu ufasz.
33
+ - self-update: weryfikacja podpisu + SHA256 + składnia, atomowa podmiana.
34
+"""
35
+
36
+import os, sys, json, shutil, hashlib, tarfile, tempfile, subprocess, time, fcntl, sqlite3, locale, re, difflib
37
+
38
+# Fix TLS trust inside the Pagan chroot: point Python at the CA bundle that
39
+# pag ships, otherwise urlopen() fails with "unable to get local issuer
40
+# certificate" (no default capath/cafile is resolved in the chroot).
41
+for _cafile in (
42
+ "/etc/ssl/certs/ca-certificates.crt",
43
+ "/etc/ssl/cert.pem",
44
+):
45
+ if os.path.isfile(_cafile):
46
+ os.environ["SSL_CERT_FILE"] = _cafile
47
+ break
48
+
49
+from pathlib import Path
50
+from datetime import datetime, timezone
51
+from typing import Dict, List, Optional, Tuple, Set
52
+from concurrent.futures import ThreadPoolExecutor, as_completed
53
+from urllib.request import urlopen, Request
54
+import threading, itertools
55
+import uuid # serialNumber SBOM (CycloneDX)
56
+
57
+# Wersja klienta – do porównania z repo.json["pag_version"] (self-update)
58
+PAG_VERSION = "3.3.16"
59
+from urllib.error import URLError, HTTPError
60
+
61
+# =============================================================================
62
+# ProgressBar — minimalistyczny pasek postępu (bez zewnętrznych zależności)
63
+# =============================================================================
64
+
65
+class ProgressBar:
66
+ """Czysty Python progress bar — działa z TTY i bez."""
67
+ def __init__(self, total: int, desc: str = "", unit: str = "", width: int = 30):
68
+ self.total = max(total, 1)
69
+ self.desc = desc
70
+ self.unit = unit
71
+ self.width = width
72
+ self.n = 0
73
+ self.start = time.time()
74
+ self.tty = sys.stderr.isatty()
75
+ self._last_line_len = 0
76
+
77
+ def update(self, n: Optional[int] = None, suffix: str = ""):
78
+ if n is not None:
79
+ self.n = n
80
+ else:
81
+ self.n += 1
82
+ pct = self.n / self.total * 100
83
+ elapsed = time.time() - self.start
84
+ speed = self.n / elapsed if elapsed > 0 else 0
85
+ if self.n >= self.total:
86
+ eta_str = "done"
87
+ elif speed > 0:
88
+ eta = (self.total - self.n) / speed
89
+ eta_str = f"{eta:.0f}s" if eta < 60 else f"{eta/60:.1f}m"
90
+ else:
91
+ eta_str = "?..."
92
+ bar_len = int(self.width * pct / 100)
93
+ bar = "█" * bar_len + "░" * (self.width - bar_len)
94
+ line = f" {self.desc} [{bar}] {self.n}/{self.total} ({pct:.0f}%) ETA {eta_str}{suffix}"
95
+ if self.tty:
96
+ # Overwrite current line
97
+ clear = " " * max(0, self._last_line_len - len(line))
98
+ print(f"\r{line}{clear}", end="", file=sys.stderr, flush=True)
99
+ self._last_line_len = len(line)
100
+ else:
101
+ # Print milestone lines only (every 10% or when done)
102
+ if self.n == 1 or self.n >= self.total or self.n % max(1, self.total // 10) == 0:
103
+ print(line, file=sys.stderr)
104
+
105
+ def close(self):
106
+ if self.tty:
107
+ print(file=sys.stderr)
108
+ self._last_line_len = 0
109
+
110
+ def __enter__(self):
111
+ return self
112
+
113
+ def __exit__(self, *args):
114
+ self.close()
115
+
116
+
117
+class DownloadBar:
118
+ """Pasek postępu pobierania — na podstawie Content-Length."""
119
+ def __init__(self, filename: str, total_bytes: int):
120
+ self.filename = filename
121
+ self.total = total_bytes
122
+ self.downloaded = 0
123
+ self.start = time.time()
124
+ self.tty = sys.stderr.isatty()
125
+ self._last_len = 0
126
+
127
+ def update(self, chunk_size: int):
128
+ self.downloaded += chunk_size
129
+ if self.total <= 0:
130
+ return
131
+ pct = self.downloaded / self.total * 100
132
+ elapsed = time.time() - self.start
133
+ speed = self.downloaded / elapsed if elapsed > 0 else 0
134
+ if speed > 0:
135
+ eta = (self.total - self.downloaded) / speed
136
+ eta_str = f"{eta:.0f}s" if eta < 60 else f"{eta/60:.1f}m"
137
+ else:
138
+ eta_str = "?..."
139
+ bar_len = 25
140
+ filled = int(bar_len * pct / 100)
141
+ bar = "█" * filled + "░" * (bar_len - filled)
142
+ sz = self._fmt_size(self.total)
143
+ spd = self._fmt_size(int(speed))
144
+ line = f" ↓ {self.filename} [{bar}] {pct:.0f}% {sz} {spd}/s ETA {eta_str}"
145
+ if self.tty:
146
+ clear = " " * max(0, self._last_len - len(line))
147
+ print(f"\r{line}{clear}", end="", file=sys.stderr, flush=True)
148
+ self._last_len = len(line)
149
+
150
+ def close(self):
151
+ if self.tty and self.total > 0:
152
+ print(file=sys.stderr)
153
+
154
+ @staticmethod
155
+ def _fmt_size(n: int) -> str:
156
+ for unit in ("B", "KB", "MB", "GB"):
157
+ if n < 1024:
158
+ return f"{n:.1f} {unit}"
159
+ n /= 1024
160
+ return f"{n:.1f} TB"
161
+
162
+# =============================================================================
163
+# GPG – BEZPIECZNE WYWOŁYWANIE (odporne na brak binarki gpg)
164
+# =============================================================================
165
+
166
+GPG_BINARY = shutil.which("gpg2") or shutil.which("gpg") or "gpg"
167
+GPG_HOME = "/etc/pag/gpg" # izolowany keyring (działa z keyboxd GPG 2.4+)
168
+
169
+def _gpg_run(*args, timeout: int = 30, **kwargs) -> subprocess.CompletedProcess:
170
+ """
171
+ Bezpieczne wywołanie GPG – przechwytuje FileNotFoundError,
172
+ gdyby gpg/gpg2 nie było zainstalowane w minimalnym środowisku.
173
+ Wymusza LC_ALL=C aby komunikaty GPG były zawsze po angielsku
174
+ (niezależnie od locale systemu) – kluczowe dla parsowania stderr.
175
+ """
176
+ env = kwargs.pop("env", None) or os.environ.copy()
177
+ env["LC_ALL"] = "C"
178
+ env["GNUPGHOME"] = GPG_HOME
179
+ try:
180
+ return subprocess.run([GPG_BINARY, *args], timeout=timeout, env=env, **kwargs)
181
+ except FileNotFoundError:
182
+ # GPG nie jest dostępne – zwróć błąd z komunikatem
183
+ # (szanuj text=True – inaczej caller dostaje bytes i może wybuchnąć TypeError)
184
+ _text = bool(kwargs.get("text") or kwargs.get("universal_newlines"))
185
+ _msg = f"GPG binary not found ({GPG_BINARY})"
186
+ return subprocess.CompletedProcess(
187
+ [GPG_BINARY, *args], 127,
188
+ stdout=("" if _text else b""),
189
+ stderr=(_msg if _text else _msg.encode()),
190
+ )
191
+ except subprocess.TimeoutExpired:
192
+ return subprocess.CompletedProcess(
193
+ [GPG_BINARY, *args], 124,
194
+ stdout=b"", stderr=b"GPG operation timed out"
195
+ )
196
+
197
+def _load_trust_db() -> dict:
198
+ """Mapa repo_url → fingerprint klucza podpisującego (baza zaufania)."""
199
+ try:
200
+ with open(TRUST_DB) as f:
201
+ return json.load(f)
202
+ except (FileNotFoundError, json.JSONDecodeError):
203
+ return {}
204
+
205
+
206
+def _save_trust_db(db: dict):
207
+ os.makedirs(os.path.dirname(TRUST_DB), exist_ok=True)
208
+ with open(TRUST_DB, "w") as f:
209
+ json.dump(db, f, indent=2)
210
+
211
+
212
+def _gpg_verify_fp(sig_path: str, data_path: str, timeout: int = 30):
213
+ """Weryfikuje podpis i odczytuje fingerprint podpisującego.
214
+
215
+ Używa --status-fd=1 i linii VALIDSIG <fingerprint>. Zwraca (ok, fingerprint).
216
+ """
217
+ env = os.environ.copy()
218
+ res = _gpg_run("--verify", "--status-fd", "1", sig_path, data_path,
219
+ capture_output=True, text=True, timeout=timeout, env=env)
220
+ if res.returncode != 0:
221
+ return False, None
222
+ m = re.search(r"\[GNUPG:\]\s+VALIDSIG\s+([0-9A-Fa-f]+)", res.stdout or "")
223
+ if not m:
224
+ m = re.search(r"VALIDSIG\s+([0-9A-Fa-f]{16,})", res.stdout or "")
225
+ return True, (m.group(1).upper() if m else None)
226
+
227
+
228
+# =============================================================================
229
+# i18n – WIELOJĘZYCZNOŚĆ
230
+# =============================================================================
231
+
232
+LANG = os.environ.get("LANG", "en_US.UTF-8")[:2] # pl, en, de...
233
+COLOR = os.environ.get("NO_COLOR", "") == "" and sys.stdout.isatty()
234
+
235
+def _c(code: str, text: str) -> str:
236
+ """Dodaje kody ANSI jeśli kolor jest włączony."""
237
+ if not COLOR:
238
+ return text
239
+ colors = {
240
+ "green": "\033[32m", "red": "\033[31m", "yellow": "\033[33m",
241
+ "cyan": "\033[36m", "bold": "\033[1m", "dim": "\033[2m",
242
+ "reset": "\033[0m",
243
+ }
244
+ return f"{colors.get(code,'')}{text}{colors['reset']}"
245
+
246
+T = {
247
+ "en": {
248
+ "root_required": "pag requires root privileges (sudo).",
249
+ "db_locked": "Another pag instance is running.",
250
+ "db_lock_hint": "If no other pag process is running, wait a moment and retry.",
251
+ "no_index": "Cannot fetch repository indexes. Run 'pag update'.",
252
+ "cache_ro": "Repo cache is read-only ({cache}) – using local index (may be outdated).\n Refresh as root: sudo pag sync",
253
+ "all_installed": "All packages are already installed.",
254
+ "to_install": "To install: {} packages ({:.2f} MB)",
255
+ "new": "NEW",
256
+ "continue_q": "Continue? [Y/n] ",
257
+ "no_tty": "No TTY / stdin closed (EOF) – cancelling.",
258
+ "cancelled": "Cancelled.",
259
+ "not_found": "not found in repos",
260
+ "pkg_not_found": "Package not found: {} (not in any repo)",
261
+ "not_found_hint": "Check the spelling or run 'pag search <query>'.",
262
+ "downloading": "Downloading",
263
+ "download_fail": "download failed",
264
+ "gpg_fail": "GPG verification failed",
265
+ "sha256_mismatch": "SHA256 mismatch",
266
+ "installed": "Installed {} packages.",
267
+ "rollback_restored": "Restored previous state from snapshot.",
268
+ "rollback_files": "Rolled back {} files.",
269
+ "no_history": "No transaction history.",
270
+ "pinned_list": "Pinned packages ({}):",
271
+ "no_pinned": "No pinned packages.",
272
+ "pinned_to": "pinned to",
273
+ "unpinned": "unpinned.",
274
+ "not_pinned": "was not pinned.",
275
+ "repo_added": "Added repository: {}",
276
+ "repo_exists": "Repository already exists: {}",
277
+ "updated_done": "Index refresh complete. {} packages cached.",
278
+ "indexes_refreshed": "Indexes refreshed.",
279
+ "updates_available": "⚠ {} packages have updates – run: pag update",
280
+ "upgrading": "Upgrading: {} packages",
281
+ "all_up_to_date": "All packages are up to date.",
282
+ "removing": "Removing",
283
+ "orphans_found": "Orphaned dependencies ({}): {}",
284
+ "flatpak_missing": "Flatpak is not installed.",
285
+ "flatpak_adding": "Adding Flathub remote...",
286
+ "flatpak_searching": "Searching Flathub for '{}'...",
287
+ "flatpak_found": "Found {} results:",
288
+ "flatpak_not_found": "not found on Flathub",
289
+ "flatpak_install_prompt": "Install {}? [Y/n] ",
290
+ "flatpak_installing": "Installing {}...",
291
+ "flatpak_installed": "Flatpak {} installed.",
292
+ "flatpak_removed": "Flatpak {} removed.",
293
+ "flatpak_not_installed": "Flatpak {} is not installed.",
294
+ "flatpak_info_id": "ID",
295
+ "flatpak_info_version": "Version",
296
+ "flatpak_info_branch": "Branch",
297
+ "flatpak_info_origin": "Origin",
298
+ "flatpak_info_size": "Installed size",
299
+ "flatpak_info_desc": "Description",
300
+ "flatpak_updated": "Flatpaks updated.",
301
+ "flatpak_usage": "Usage: pag flatpak <search|install|remove|list|update|info> [args]",
302
+ "key_imported": "Key imported successfully.",
303
+ "key_removed": "Key removed: {}",
304
+ "no_keys": "No trusted GPG keys.",
305
+ "verify_ok": "All {} files intact.",
306
+ "verify_errors": "{} problems found:",
307
+ "cache_cleared": "{} files ({:.2f} MB) cleared from cache.",
308
+ "deployments_list": "Deployments ({}):",
309
+ "no_deployments": "No deployments.",
310
+ "active_deployment": "ACTIVE",
311
+ "deploy_rollback_ok": "Switched to deployment: {}",
312
+ "deploy_rollback_fail": "No previous deployment.",
313
+ "deploy_cleanup_ok": "Removed {} old deployments.",
314
+ "deploy_cleanup_none": "No deployments to clean (minimum {}).",
315
+ "why_explicit": "explicitly installed",
316
+ "why_dependency": "dependency of",
317
+ "why_not_installed": "not installed",
318
+ "autoremove_ok": "Removed {} orphaned packages.",
319
+ "autoremove_none": "No orphaned packages.",
320
+ "downloaded": "Downloaded {} to cache ({:.2f} MB).",
321
+ "provides_mapped": "{} → {} (provides)",
322
+ "stats_title": "PAG Statistics",
323
+ "stats_packages": "Installed packages",
324
+ "stats_files": "Tracked files",
325
+ "stats_size": "Total size",
326
+ "stats_cache": "Cache size",
327
+ "stats_history": "Transactions",
328
+ "stats_last_update": "Last update",
329
+ },
330
+ "pl": {
331
+ "root_required": "pag wymaga uprawnień root (sudo).",
332
+ "db_locked": "Inna instancja pag jest uruchomiona.",
333
+ "db_lock_hint": "Jeśli żaden inny proces pag nie działa, poczekaj chwilę i spróbuj ponownie.",
334
+ "no_index": "Nie można pobrać indeksów repozytoriów. Uruchom 'pag update'.",
335
+ "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",
336
+ "all_installed": "Wszystkie pakiety są już zainstalowane.",
337
+ "to_install": "Do zainstalowania: {} pakietów ({:.2f} MB)",
338
+ "new": "NOWY",
339
+ "continue_q": "Kontynuować? [T/n] ",
340
+ "no_tty": "Brak terminala (EOF) – anuluję.",
341
+ "cancelled": "Anulowano.",
342
+ "not_found": "brak w repozytoriach",
343
+ "pkg_not_found": "Nie znaleziono pakietu: {} (brak w repozytoriach)",
344
+ "not_found_hint": "Sprawdź pisownię lub uruchom 'pag search <fraza>'.",
345
+ "downloading": "Pobieranie",
346
+ "download_fail": "błąd pobierania",
347
+ "gpg_fail": "błąd weryfikacji GPG",
348
+ "sha256_mismatch": "niezgodność SHA256",
349
+ "installed": "Zainstalowano {} pakietów.",
350
+ "rollback_restored": "Przywrócono poprzedni stan z migawki.",
351
+ "rollback_files": "Wycofano {} plików.",
352
+ "no_history": "Brak historii transakcji.",
353
+ "pinned_list": "Przypięte pakiety ({}):",
354
+ "no_pinned": "Brak przypiętych pakietów.",
355
+ "pinned_to": "przypięty do",
356
+ "unpinned": "odpięty.",
357
+ "not_pinned": "nie był przypięty.",
358
+ "repo_added": "Dodano repozytorium: {}",
359
+ "repo_exists": "Repozytorium już istnieje: {}",
360
+ "updated_done": "Odświeżanie zakończone. {} pakietów w cache.",
361
+ "indexes_refreshed": "Indeksy odświeżone.",
362
+ "updates_available": "⚠ jest {} pakietów do zaktualizowania – wpisz: pag update",
363
+ "upgrading": "Aktualizacje: {} pakietów",
364
+ "all_up_to_date": "Wszystkie pakiety są aktualne.",
365
+ "removing": "Usuwanie",
366
+ "orphans_found": "Osierocone zależności ({}): {}",
367
+ "flatpak_missing": "Flatpak nie jest zainstalowany.",
368
+ "flatpak_adding": "Dodaję zdalne repozytorium Flathub...",
369
+ "flatpak_searching": "Szukam '{}' we Flathub...",
370
+ "flatpak_found": "Znaleziono {} wyników:",
371
+ "flatpak_not_found": "nie znaleziono we Flathub",
372
+ "flatpak_install_prompt": "Zainstalować {}? [T/n] ",
373
+ "flatpak_installing": "Instalowanie {}...",
374
+ "flatpak_installed": "Flatpak {} zainstalowany.",
375
+ "flatpak_removed": "Flatpak {} usunięty.",
376
+ "flatpak_not_installed": "Flatpak {} nie jest zainstalowany.",
377
+ "flatpak_info_id": "ID",
378
+ "flatpak_info_version": "Wersja",
379
+ "flatpak_info_branch": "Gałąź",
380
+ "flatpak_info_origin": "Źródło",
381
+ "flatpak_info_size": "Rozmiar",
382
+ "flatpak_info_desc": "Opis",
383
+ "flatpak_updated": "Flapaki zaktualizowane.",
384
+ "flatpak_usage": "Użycie: pag flatpak <search|install|remove|list|update|info> [args]",
385
+ "key_imported": "Klucz zaimportowany pomyślnie.",
386
+ "key_removed": "Klucz usunięty: {}",
387
+ "no_keys": "Brak zaufanych kluczy GPG.",
388
+ "verify_ok": "Wszystkie {} plików sprawne.",
389
+ "verify_errors": "Znaleziono {} problemów:",
390
+ "cache_cleared": "{} plików ({:.2f} MB) usuniętych z cache.",
391
+ "deployments_list": "Deploymenty ({}):",
392
+ "no_deployments": "Brak deploymentów.",
393
+ "active_deployment": "AKTYWNY",
394
+ "deploy_rollback_ok": "Przełączono na deployment: {}",
395
+ "deploy_rollback_fail": "Brak poprzedniego deploymentu.",
396
+ "deploy_cleanup_ok": "Usunięto {} starych deploymentów.",
397
+ "deploy_cleanup_none": "Nie ma deploymentów do wyczyszczenia (minimum {}).",
398
+ "why_explicit": "zainstalowany jawnie",
399
+ "why_dependency": "zależność od",
400
+ "why_not_installed": "niezainstalowany",
401
+ "autoremove_ok": "Usunięto {} osieroconych pakietów.",
402
+ "autoremove_none": "Brak osieroconych pakietów.",
403
+ "downloaded": "Pobrano {} do cache ({:.2f} MB).",
404
+ "sec_downgrade": "Downgrade blocked: {pkg} {new} < {old}",
405
+ "sec_suid": "SUID stripped from {path}",
406
+ "sec_https": "HTTPS required for repos",
407
+ "sec_badname": "Invalid package name: {name}",
408
+ "sec_toobig": "Package too large: {size_mb}MB > {max_mb}MB",
409
+ "sec_conflict": "File conflict: {path} owned by {owner}",
410
+ "sec_audit": "{pkg} installed by {user}",
411
+ "sec_locked": "Another pag process is running",
412
+ "sec_downgrade_pl": "Blokada downgrade: {pkg} {new} < {old}",
413
+ "sec_suid_pl": "SUID usuniety z {path}",
414
+ "sec_https_pl": "Repozytorium wymaga HTTPS",
415
+ "sec_badname_pl": "Nieprawidlowa nazwa pakietu: {name}",
416
+ "sec_toobig_pl": "Paczka za duza: {size_mb}MB > {max_mb}MB",
417
+ "sec_conflict_pl": "Konflikt plikow: {path} nalezy do {owner}",
418
+ "sec_audit_pl": "{pkg} zainstalowany przez {user}",
419
+ "sec_locked_pl": "Inny proces pag juz dziala",
420
+
421
+ "provides_mapped": "{} → {} (provides)",
422
+ "stats_title": "Statystyki PAG",
423
+ "stats_packages": "Zainstalowane pakiety",
424
+ "stats_files": "Śledzone pliki",
425
+ "stats_size": "Całkowity rozmiar",
426
+ "stats_cache": "Rozmiar cache",
427
+ "stats_history": "Transakcje",
428
+ "stats_last_update": "Ostatnia aktualizacja",
429
+ },
430
+}
431
+
432
+def _(key: str, *args, **kwargs) -> str:
433
+ """Tłumaczy klucz i formatuje argumenty."""
434
+ msg = T.get(LANG, T["en"]).get(key, T["en"].get(key, key))
435
+ if args or kwargs:
436
+ return msg.format(*args, **kwargs)
437
+ return msg
438
+
439
+
440
+def _ask_confirm() -> bool:
441
+ """Pytanie potwierdzające (T/n). PAG_YES=1 → zawsze tak.
442
+
443
+ EOF/brak terminala (stdin zamknięty, np. ssh bez TTY, cron, subprocess
444
+ panelu webowego) → NIE – anuluj, nie wykonuj operacji bez potwierdzenia
445
+ (inaczej input() rzuca EOFError i pag pada tracebackiem).
446
+ Enter → tak (domyślne Y/n).
447
+ """
448
+ if os.environ.get("PAG_YES", "") == "1":
449
+ print(_("continue_q") + " t (--yes)")
450
+ return True
451
+ try:
452
+ ans = input(_("continue_q")).strip().lower()
453
+ except (EOFError, KeyboardInterrupt):
454
+ print(f"\n ⚠ {_('no_tty')}")
455
+ return False
456
+ return not ans or ans in ("t", "y")
457
+
458
+
459
+# =============================================================================
460
+# ŚCIEŻKI
461
+# =============================================================================
462
+PAG_ROOT = os.environ.get("PAG_ROOT", "/")
463
+PAG_DB = "/var/lib/pag"
464
+PAG_CACHE = "/var/cache/pag"
465
+PAG_CONF = "/etc/pag"
466
+REPO_CACHE = "/var/cache/pag/repos"
467
+REPOS_CONF = "/etc/pag/repos.conf"
468
+REPOS_DIR = PAG_CONF + "/repos" # drop-in: /etc/pag/repos/<nazwa>.conf
469
+INSTALLED_DB = "/var/lib/pag/installed.json"
470
+FILES_DB_SQL = "/var/lib/pag/files.db" # SQLite!
471
+WORLD_FILE = "/var/lib/pag/world"
472
+PINNED_FILE = "/var/lib/pag/pinned.json"
473
+HISTORY_FILE = "/var/lib/pag/history.json"
474
+LOCK_FILE = "/var/lib/pag/pag.lock"
475
+STAGING_DIR = "/.pag_staging" # na tej samej partycji co / (unikamy EXDEV)
476
+PKG_EXT = ".pag"
477
+REPO_CACHE_TTL = 3600
478
+MAX_PKG_SIZE = 2 * 1024 * 1024 * 1024 # 2 GB – maksymalny rozmiar paczki
479
+ALLOWED_PKG_RE = re.compile(r'^[a-zA-Z0-9][a-zA-Z0-9._+@-]*$')
480
+
481
+# Bezpieczeństwo / audyt
482
+AUDIT_LOG = "/var/log/pag/audit.log" # dziennik operacji krytycznych (hooki, self-update)
483
+TRUST_DB = "/etc/pag/trusted.json" # mapa repo_url → fingerprint klucza podpisującego
484
+HOOK_API_VERSION = "1" # wersjonowane API hooków (env PKG_HOOK_API)
485
+
486
+# =============================================================================
487
+# IMMUTABLE OS – DEPLOYMENTY
488
+# =============================================================================
489
+# Model: zamiast mutować /, każda operacja tworzy NOWY deployment.
490
+# /var, /etc, /home są współdzielone między deploymentami.
491
+#
492
+# STRUKTURA:
493
+# /.deployments/
494
+# active → 20260723T120000 (symlink do aktywnego)
495
+# 20260723T120000/
496
+# usr/ bin/ lib/ lib64/ ... (pełny system)
497
+# var → /var (symlink do współdzielonego)
498
+# etc → /etc
499
+# home → /home
500
+# ...
501
+#
502
+# Jak to działa:
503
+# 1. pag install → kopiuje active → nowy deployment + nakłada zmiany → switch symlinka
504
+# 2. pag remove → kopiuje active → nowy deployment - usuwa pliki → switch symlinka
505
+# 3. pag deploy-rollback → przełącza active symlink na poprzedni deployment
506
+# 4. Przy starcie systemu: initrd montuje /.deployments/active jako /
507
+# =============================================================================
508
+
509
+DEPLOYMENTS_DIR = "/.deployments"
510
+ACTIVE_LINK = "/.deployments/active"
511
+DEPLOYMENTS_DB = "/var/lib/pag/deployments.json"
512
+
513
+# Ścieżki współdzielone – NIE wchodzą do deploymentu (są symlinkami do /...)
514
+SHARED_PATHS = {
515
+ "/var", "/etc", "/home", "/root", "/tmp", "/run",
516
+ "/dev", "/proc", "/sys", "/mnt", "/media", "/srv",
517
+ "/.deployments", "/.pag_staging",
518
+}
519
+
520
+def _is_shared_path(rel: str) -> bool:
521
+ """Sprawdza czy ścieżka należy do katalogów współdzielonych (poza deploymentem)."""
522
+ for sp in SHARED_PATHS:
523
+ if rel == sp or rel.startswith(sp + "/"):
524
+ return True
525
+ return False
526
+
527
+def _get_deployment_root() -> str:
528
+ """Zwraca ścieżkę do aktywnego deploymentu, lub PAG_ROOT jeśli tryb niemutowalny wyłączony."""
529
+ if os.environ.get("PAG_IMMUTABLE", "") in ("0", "no", "false", ""):
530
+ return PAG_ROOT
531
+ if os.path.islink(ACTIVE_LINK):
532
+ return os.readlink(ACTIVE_LINK)
533
+ if os.path.isdir(ACTIVE_LINK):
534
+ return ACTIVE_LINK
535
+ # Brak deploymentów – użyj /
536
+ return PAG_ROOT
537
+
538
+def _load_deployments() -> List[dict]:
539
+ """Wczytuje historię deploymentów."""
540
+ if not os.path.exists(DEPLOYMENTS_DB):
541
+ return []
542
+ try:
543
+ return json.load(open(DEPLOYMENTS_DB))
544
+ except Exception:
545
+ return []
546
+
547
+def _save_deployments(deployments: List[dict]):
548
+ os.makedirs(os.path.dirname(DEPLOYMENTS_DB), exist_ok=True)
549
+ json.dump(deployments, open(DEPLOYMENTS_DB, "w"), indent=2)
550
+
551
+def _create_deployment(pkg_names: List[str], action: str) -> Tuple[str, str]:
552
+ """
553
+ Tworzy nowy deployment przez skopiowanie aktywnego (CoW) i zwraca jego ścieżkę.
554
+ Zwraca (deployment_dir, deployment_id).
555
+ """
556
+ deploy_id = datetime.now().strftime("%Y%m%dT%H%M%S")
557
+ deploy_dir = os.path.join(DEPLOYMENTS_DIR, deploy_id)
558
+ os.makedirs(DEPLOYMENTS_DIR, exist_ok=True)
559
+
560
+ active = _get_deployment_root()
561
+
562
+ if os.path.isdir(active) and active != PAG_ROOT:
563
+ # Trójstopniowa strategia kopiowania deploymentu:
564
+ # 1. reflink (CoW – btrfs, xfs) → 0 MB kopiowane
565
+ # 2. hardlink (linki twarde) → 0 MB kopiowane, tylko inody
566
+ # 3. zwykłe cp (ostateczność) → pełna kopia
567
+ print(f" ⚡ Kopiowanie aktywnego deploymentu...")
568
+ copied = False
569
+ for method, cmd, label in [
570
+ ("reflink", ["cp", "--reflink=auto", "-a", active + "/.", deploy_dir + "/"], "CoW (reflink)"),
571
+ ("hardlink", ["cp", "-al", active + "/.", deploy_dir + "/"], "hardlinki"),
572
+ ("copy", ["cp", "-a", active + "/.", deploy_dir + "/"], "pełna kopia"),
573
+ ]:
574
+ try:
575
+ subprocess.run(cmd, check=True, timeout=600, capture_output=True)
576
+ print(f" ✅ Deployment: {deploy_id} ({label})")
577
+ copied = True
578
+ break
579
+ except subprocess.CalledProcessError:
580
+ if method == "copy":
581
+ raise # ostatnia deska – niech leci wyjątek
582
+ continue
583
+ if not copied:
584
+ raise RuntimeError("Nie udało się skopiować deploymentu żadną metodą")
585
+ else:
586
+ # Pierwszy deployment – tylko katalogi szkieletowe
587
+ for d in ["/usr", "/lib", "/lib64", "/bin", "/sbin", "/boot", "/opt"]:
588
+ if os.path.isdir(d):
589
+ dest = os.path.join(deploy_dir, d.lstrip("/"))
590
+ os.makedirs(dest, exist_ok=True)
591
+ print(f" ✅ Pierwszy deployment: {deploy_id}")
592
+
593
+ # Utwórz symlinki do współdzielonych katalogów
594
+ for sp in SHARED_PATHS:
595
+ link_dst = os.path.join(deploy_dir, sp.lstrip("/"))
596
+ if not os.path.lexists(link_dst) and os.path.isdir(sp):
597
+ os.symlink(sp, link_dst)
598
+
599
+ # Zapisz w bazie deploymentów
600
+ deployments = _load_deployments()
601
+ deployments.append({
602
+ "id": deploy_id,
603
+ "action": action,
604
+ "packages": pkg_names,
605
+ "timestamp": datetime.now().isoformat(),
606
+ "active": True,
607
+ })
608
+ # Oznacz poprzednie jako nieaktywne
609
+ for d in deployments[:-1]:
610
+ d["active"] = False
611
+ _save_deployments(deployments)
612
+
613
+ return deploy_dir, deploy_id
614
+
615
+def _switch_deployment(deploy_dir: str) -> bool:
616
+ """Atomowo przełącza aktywny deployment przez podmianę symlinka."""
617
+ tmp_link = ACTIVE_LINK + ".new"
618
+ if os.path.lexists(tmp_link):
619
+ os.remove(tmp_link)
620
+ os.symlink(deploy_dir, tmp_link)
621
+ os.rename(tmp_link, ACTIVE_LINK) # atomowe na tym samym FS
622
+ return True
623
+
624
+DEFAULT_REPOS = [
625
+ "https://repo.paganlinux.eu/stable/",
626
+]
627
+
628
+# =============================================================================
629
+# INICJALIZACJA
630
+# =============================================================================
631
+
632
+def ensure_dirs():
633
+ for d in [PAG_DB, PAG_CACHE, PAG_CONF, REPO_CACHE, REPOS_DIR, STAGING_DIR, DEPLOYMENTS_DIR]:
634
+ os.makedirs(d, exist_ok=True)
635
+ for f, default in [
636
+ (REPOS_CONF, "\n".join(DEFAULT_REPOS) + "\n"),
637
+ (INSTALLED_DB, "{}"),
638
+ (PINNED_FILE, "{}"),
639
+ (HISTORY_FILE, "[]"),
640
+ ]:
641
+ if not os.path.exists(f):
642
+ with open(f, "w") as fh: fh.write(default)
643
+ if not os.path.exists(WORLD_FILE):
644
+ Path(WORLD_FILE).touch()
645
+ if not os.path.exists(GPG_HOME):
646
+ os.makedirs(GPG_HOME, exist_ok=True)
647
+ os.chmod(GPG_HOME, 0o700)
648
+ _gpg_run("--list-keys", capture_output=True)
649
+ # Inicjalizuj SQLite
650
+ _db_init()
651
+ # Wyczyść staging po poprzednim przerwanym buildzie/instalacji
652
+ if os.path.isdir(STAGING_DIR):
653
+ for entry in os.listdir(STAGING_DIR):
654
+ if entry == "backups":
655
+ continue # backupy starych wersji – potrzebne do `pag rollback`
656
+ path = os.path.join(STAGING_DIR, entry)
657
+ try:
658
+ if os.path.isfile(path) or os.path.islink(path):
659
+ os.unlink(path)
660
+ elif os.path.isdir(path):
661
+ shutil.rmtree(path, ignore_errors=True)
662
+ except OSError:
663
+ pass
664
+
665
+# =============================================================================
666
+# SQLITE – BAZA PLIKÓW (poprawne zarządzanie połączeniami)
667
+# =============================================================================
668
+
669
+from contextlib import contextmanager
670
+
671
+@contextmanager
672
+def _db_session():
673
+ """Context manager – gwarantuje zamknięcie połączenia."""
674
+ conn = sqlite3.connect(FILES_DB_SQL, timeout=15)
675
+ conn.execute("PRAGMA journal_mode=WAL")
676
+ conn.execute("PRAGMA synchronous=NORMAL")
677
+ conn.execute("PRAGMA foreign_keys=ON")
678
+ conn.execute("PRAGMA busy_timeout=15000")
679
+ conn.row_factory = sqlite3.Row
680
+ try:
681
+ yield conn
682
+ conn.commit()
683
+ except Exception:
684
+ conn.rollback()
685
+ raise
686
+ finally:
687
+ conn.close()
688
+
689
+
690
+def _db_init():
691
+ """Tworzy tabele SQLite jeśli nie istnieją."""
692
+ with _db_session() as db:
693
+ db.execute("""
694
+ CREATE TABLE IF NOT EXISTS files (
695
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
696
+ path TEXT NOT NULL,
697
+ package TEXT NOT NULL,
698
+ sha256 TEXT,
699
+ size INTEGER,
700
+ is_symlink INTEGER DEFAULT 0,
701
+ symlink_target TEXT,
702
+ UNIQUE(path, package)
703
+ )
704
+ """)
705
+ db.execute("CREATE INDEX IF NOT EXISTS idx_files_path ON files(path)")
706
+ db.execute("CREATE INDEX IF NOT EXISTS idx_files_pkg ON files(package)")
707
+ db.execute("""
708
+ CREATE TABLE IF NOT EXISTS file_checksums (
709
+ path TEXT PRIMARY KEY,
710
+ sha256 TEXT NOT NULL,
711
+ installed_at TEXT
712
+ )
713
+ """)
714
+ db.commit()
715
+
716
+def _db_record_files(pkg_name: str, files: List[dict]):
717
+ """Zapisuje pliki do SQLite (obsługuje symlinki)."""
718
+ with _db_session() as db:
719
+ # Jawna transakcja – atomowość obu zapisów i szybsze wykrycie blokady
720
+ try:
721
+ db.execute("BEGIN IMMEDIATE")
722
+ except sqlite3.OperationalError:
723
+ pass # transakcja już otwarta (implicit)
724
+ db.executemany(
725
+ "INSERT OR REPLACE INTO files (path, package, sha256, size, is_symlink, symlink_target) "
726
+ "VALUES (?,?,?,?,?,?)",
727
+ [(f["path"], pkg_name, f.get("sha256",""), f.get("size",0),
728
+ f.get("is_symlink", 0), f.get("symlink_target", ""))
729
+ for f in files]
730
+ )
731
+ db.executemany(
732
+ "INSERT OR REPLACE INTO file_checksums (path, sha256, installed_at) VALUES (?,?,?)",
733
+ [(f["path"], f.get("sha256",""), datetime.now().isoformat())
734
+ for f in files if f.get("sha256")]
735
+ )
736
+
737
+def _db_get_package_files(pkg_name: str) -> List[str]:
738
+ with _db_session() as db:
739
+ return [r["path"] for r in db.execute(
740
+ "SELECT DISTINCT path FROM files WHERE package=?", (pkg_name,)
741
+ )]
742
+
743
+def _db_get_file_owners(filepath: str) -> List[str]:
744
+ """Zwraca listę pakietów będących właścicielami pliku."""
745
+ with _db_session() as db:
746
+ return [r["package"] for r in db.execute(
747
+ "SELECT package FROM files WHERE path=?", (filepath,)
748
+ )]
749
+
750
+def _db_remove_package_files(pkg_name: str):
751
+ with _db_session() as db:
752
+ db.execute("DELETE FROM files WHERE package=?", (pkg_name,))
753
+ db.commit()
754
+
755
+def _db_get_all_file_checksums() -> Dict[str, str]:
756
+ with _db_session() as db:
757
+ return {r["path"]: r["sha256"] for r in db.execute("SELECT path, sha256 FROM file_checksums")}
758
+
759
+def _db_count_files() -> int:
760
+ with _db_session() as db:
761
+ return db.execute("SELECT COUNT(*) FROM files").fetchone()[0]
762
+
763
+# =============================================================================
764
+# BLOKADA
765
+# =============================================================================
766
+
767
+class DatabaseLock:
768
+ """Blokada plikowa (flock) – jądro zwalnia ją AUTOMATYCZNIE, gdy proces
769
+ ginie (kill -9, twardy reset). Stary PID-file miał race condition: po
770
+ śmierci pag PID mógł zostać przydzielony obcemu procesowi (PID reuse)
771
+ i pag odmawiał działania na zawsze („baza zablokowana”).
772
+ """
773
+ def __init__(self):
774
+ self._f = None
775
+ def __enter__(self):
776
+ os.makedirs(os.path.dirname(LOCK_FILE), exist_ok=True)
777
+ self._f = open(LOCK_FILE, "w")
778
+ try:
779
+ # LOCK_NB: rzuca wyjątek zamiast czekać w nieskończoność
780
+ fcntl.flock(self._f, fcntl.LOCK_EX | fcntl.LOCK_NB)
781
+ except BlockingIOError:
782
+ print(f"❌ {_('db_locked')}", file=sys.stderr)
783
+ print(f" {_('db_lock_hint', LOCK_FILE)}", file=sys.stderr)
784
+ sys.exit(1)
785
+ self._f.write(str(os.getpid()))
786
+ self._f.flush()
787
+ return self
788
+ def __exit__(self, *args):
789
+ if self._f:
790
+ try:
791
+ fcntl.flock(self._f, fcntl.LOCK_UN)
792
+ except OSError:
793
+ pass
794
+ self._f.close()
795
+ self._f = None
796
+ # Uwaga: NIE usuwamy pliku blokady. Stały plik + flock na inode to jedyny
797
+ # bezpieczny wzorzec – os.remove(), gdy inny proces trzyma blokadę na starym
798
+ # inode, otwiera wyścig (nowy proces blokowałby nowo utworzony inode).
799
+
800
+# =============================================================================
801
+# POMOCNICZE
802
+# =============================================================================
803
+
804
+
805
+_ALLOWED_PREFIXES = ("/usr/", "/etc/", "/var/", "/opt/",
806
+ "/boot/", "/lib/", # kernel: vmlinuz/System.map + moduły (usrmerge: lib→usr/lib)
807
+ # Pliki wewnętrzne paczki .pkg.tar.xz
808
+ "metadata.json", "data.tar.xz", "hooks/",
809
+ "sums.json")
810
+
811
+def _check_path_safety(name: str) -> bool:
812
+ # Normalizuj – usuń leading ./
813
+ if name.startswith("./"):
814
+ name = name[2:]
815
+ if name in (".", ""):
816
+ return True
817
+ # Porównuj z prefiksami BEZ wiodącego '/', by zarówno "/usr/bin/ls", jak i
818
+ # wewnętrzne pliki pakietu ("hooks/pre-install", "data.tar.xz") przechodziły.
819
+ norm = name.lstrip("/")
820
+ for prefix in _ALLOWED_PREFIXES:
821
+ p = prefix.lstrip("/").rstrip("/")
822
+ if norm == p or norm.startswith(p + "/"):
823
+ return True
824
+ return False
825
+
826
+
827
+def _validate_pkg_name(name):
828
+ return bool(ALLOWED_PKG_RE.match(name))
829
+
830
+
831
+
832
+def _audit(msg):
833
+ from datetime import datetime, timezone
834
+ os.makedirs(os.path.dirname(AUDIT_LOG), exist_ok=True)
835
+ with open(AUDIT_LOG, "a") as f:
836
+ f.write(datetime.now(timezone.utc).isoformat() + " " + msg + "\n")
837
+
838
+def _strip_suid(path):
839
+ try:
840
+ st = os.stat(path)
841
+ if st.st_mode & 0o4000:
842
+ os.chmod(path, st.st_mode & ~0o4000)
843
+ print(f" {_("sec_suid", path=path)}")
844
+ except OSError:
845
+ pass
846
+
847
+def _check_downgrade(pkg_name, new_ver, installed_db):
848
+ if pkg_name in installed_db:
849
+ old = installed_db[pkg_name].get("version", "0")
850
+ if new_ver < old:
851
+ print(f" {_("sec_downgrade", pkg=pkg_name, new=new_ver, old=old)}")
852
+ return False
853
+ return True
854
+
855
+def _safe_extractall(tar: tarfile.TarFile, dest: str, *, preserve_perms: bool = True):
856
+ """
857
+ Bezpieczne rozpakowanie archiwum tar z ochroną przed Directory Traversal.
858
+
859
+ Działa na Python < 3.12 (gdzie parametr 'filter' w extractall nie istnieje)
860
+ oraz na Python 3.12+. W przeciwieństwie do filtra 'data' z Pythona 3.12,
861
+ zachowuje bity uprawnień POSIX (SUID, SGID, sticky) – preserve_perms=True.
862
+
863
+ Ochrona oparta jest na FINALNEJ ścieżce (os.path.realpath), nie tylko na
864
+ prostym sprawdzaniu stringa:
865
+ - Blokuje ścieżki absolutne i z '..' (path traversal)
866
+ - Blokuje symlinki/hardlinki, których cel wychodzi poza dest
867
+ - Blokuje zapis "przez" złośliwy symlink, który został wcześniej
868
+ rozpakowany (np. katalog → /etc, potem zapis katalog/plik)
869
+ - Zachowuje oryginalne uprawnienia plików
870
+ """
871
+ dest_real = os.path.realpath(dest)
872
+ os.makedirs(dest_real, exist_ok=True)
873
+
874
+ def _target_within(path: str) -> bool:
875
+ try:
876
+ return os.path.commonpath([dest_real, os.path.realpath(path)]) == dest_real
877
+ except ValueError:
878
+ # różne napędy / ścieżki nie da się wspólnie porównać → odrzuć
879
+ return False
880
+
881
+ for member in tar.getmembers():
882
+ name = member.name
883
+
884
+ # --- Ochrona przed Directory Traversal (szybkie string-checki) ---
885
+ if name.startswith('/'):
886
+ continue
887
+ if '..' in name.split('/'):
888
+ continue
889
+ # Zablokuj bajt NUL i backslash (bugi/obejścia tarfile na niektórych platformach)
890
+ if '\x00' in name or '\\' in name:
891
+ continue
892
+ if not _check_path_safety(name):
893
+ print(f" BLOCKED: {name}")
894
+ continue
895
+
896
+ target = os.path.join(dest, name)
897
+
898
+ # --- Ochrona na podstawie finalnej ścieżki ---
899
+ # Jeśli którykolwiek komponent nadrzędny jest (złośliwym) symlinkiem
900
+ # wskazującym poza dest, realpath to wykryje – zablokuj zapis.
901
+ if not _target_within(target):
902
+ print(f" BLOCKED (escape): {name}")
903
+ continue
904
+
905
+ # --- Ochrona dla symlinków i hardlinków ---
906
+ if member.issym() or member.islnk():
907
+ link = member.linkname
908
+ # Szybkie odrzucenie linków absolutnych / z '..'
909
+ if link.startswith('/') or '..' in link.split('/'):
910
+ continue
911
+ # Sprawdź, gdzie realnie prowadzi cel linku (względem katalogu linku)
912
+ link_target = os.path.join(os.path.dirname(target), link)
913
+ if not _target_within(link_target):
914
+ print(f" BLOCKED (link escape): {name} -> {link}")
915
+ continue
916
+
917
+ # Rozpakuj z zachowaniem metadanych. Python 3.12+ wymaga jawnego
918
+ # `filter=` (inaczej DeprecationWarning, w 3.14+ błąd) – nasza ręczna
919
+ # walidacja powyżej już zabezpiecza ścieżki, więc 'fully_trusted'
920
+ # (pomija filtr Pythona i zachowuje SUID/SGID/sticky z preserve_perms).
921
+ try:
922
+ if hasattr(tarfile, 'data_filter'):
923
+ # Python 3.12+
924
+ tar.extract(member, dest, set_attrs=preserve_perms, numeric_owner=False,
925
+ filter='fully_trusted')
926
+ else:
927
+ tar.extract(member, dest, set_attrs=preserve_perms, numeric_owner=False)
928
+ except Exception as e:
929
+ print(f" ⚠ Nie rozpakowano {name}: {e}")
930
+ continue
931
+ _strip_suid(target)
932
+
933
+
934
+def _sha256_file(path: str) -> str:
935
+ h = hashlib.sha256()
936
+ with open(path, "rb") as f:
937
+ for chunk in iter(lambda: f.read(65536), b""):
938
+ h.update(chunk)
939
+ return h.hexdigest()
940
+
941
+def _split_version(v: str):
942
+ """Rozdziela wersję na (release_parts, prerelease_parts).
943
+
944
+ Przykład: '1.2.0-rc1' → ([1,2,0], ['rc','1']).
945
+ """
946
+ v = v.strip().lower().lstrip("v")
947
+ # build metadata po '+' jest ignorowane przy porównywaniu (semver)
948
+ v = v.split("+", 1)[0]
949
+ # prerelease po '-' lub '_' (np. 1.2.0-rc1, 1.2.0_rc1)
950
+ if "-" in v:
951
+ rel, pre = v.split("-", 1)
952
+ elif "_" in v:
953
+ rel, pre = v.split("_", 1)
954
+ else:
955
+ rel, pre = v, ""
956
+ nums = []
957
+ for part in rel.split("."):
958
+ m = re.match(r"(\d+)", part)
959
+ nums.append(int(m.group(1)) if m else 0)
960
+ pre_parts = [p for p in pre.split(".") if p]
961
+ return nums, pre_parts
962
+
963
+
964
+def _cmp_pre(a, b):
965
+ """Porównuje ciągi identyfikatorów prerelease (reguły semver)."""
966
+ for i in range(max(len(a), len(b))):
967
+ if i >= len(a):
968
+ return -1 # krótszy prerelease jest niższy
969
+ if i >= len(b):
970
+ return 1
971
+ ia, ib = a[i], b[i]
972
+ if ia == ib:
973
+ continue
974
+ na, nb = ia.isdigit(), ib.isdigit()
975
+ if na and nb:
976
+ return 1 if int(ia) > int(ib) else -1
977
+ if na != nb:
978
+ return -1 if na else 1 # identyfikator liczbowy < alfanumeryczny
979
+ return 1 if ia > ib else -1
980
+ return 0
981
+
982
+
983
+def _cmp_version(a: str, b: str) -> int:
984
+ """Porównuje dwie wersje; zwraca -1/0/1. Obsługuje prerelease (rc1, beta...)."""
985
+ a_rel, a_pre = _split_version(a)
986
+ b_rel, b_pre = _split_version(b)
987
+ # Porównaj część release (brakujące komponenty traktuj jako 0)
988
+ for i in range(max(len(a_rel), len(b_rel))):
989
+ xa = a_rel[i] if i < len(a_rel) else 0
990
+ xb = b_rel[i] if i < len(b_rel) else 0
991
+ if xa != xb:
992
+ return 1 if xa > xb else -1
993
+ # Część release równa → decyduje prerelease.
994
+ # Wersja finalna (bez prerelease) jest ZAWSZE nowsza od prerelease.
995
+ if not a_pre and not b_pre:
996
+ return 0
997
+ if not a_pre:
998
+ return 1
999
+ if not b_pre:
1000
+ return -1
1001
+ return _cmp_pre(a_pre, b_pre)
1002
+
1003
+
1004
+def _version_newer(a: str, b: str) -> bool:
1005
+ """True gdy wersja a jest nowsza od b (z poprawną obsługą prerelease)."""
1006
+ try:
1007
+ return _cmp_version(a, b) > 0
1008
+ except Exception:
1009
+ return a != b
1010
+
1011
+def load_json(path):
1012
+ try:
1013
+ with open(path) as f:
1014
+ return json.load(f)
1015
+ except (FileNotFoundError, json.JSONDecodeError):
1016
+ return {}
1017
+
1018
+def save_json(path, data):
1019
+ with open(path, "w") as f:
1020
+ json.dump(data, f, indent=2)
1021
+
1022
+class PackageInfo:
1023
+ __slots__ = ("name","version","release","description","dependencies",
1024
+ "size_bytes","sha256","gpg_fp","repo_url","filename","provides","license",
1025
+ "provides_so","requires_so")
1026
+ def __init__(self, d, repo=""):
1027
+ self.name = d.get("name","?")
1028
+ self.version = d.get("version","0")
1029
+ self.release = d.get("release", 1)
1030
+ self.description = d.get("description","")
1031
+ self.dependencies = d.get("dependencies", d.get("depends", []))
1032
+ self.size_bytes = d.get("size",0)
1033
+ self.sha256 = d.get("sha256","")
1034
+ self.gpg_fp = d.get("gpg_fingerprint","")
1035
+ self.repo_url = repo
1036
+ self.filename = d.get("filename", f"{self.name}-{self.version}{PKG_EXT}")
1037
+ self.provides = d.get("provides", []) or []
1038
+ self.license = d.get("license", []) or []
1039
+ self.provides_so = d.get("provides_so", []) or []
1040
+ self.requires_so = d.get("requires_so", []) or []
1041
+
1042
+# =============================================================================
1043
+# REPOZYTORIA (cache, ETag, GPG)
1044
+# =============================================================================
1045
+
1046
+def _parse_repos_config():
1047
+ """Parsuje repozytoria z /etc/pag/repos.conf oraz /etc/pag/repos/*.conf.
1048
+
1049
+ Format linii: <url> [fingerprint]
1050
+ Opcjonalny `fingerprint` (40 znaków hex) pozwala przypiąć klucz
1051
+ podpisujący repo do konkretnego adresu – wtedy TOFU (auto-zaufanie przy
1052
+ pierwszym użyciu) nie jest potrzebne, a zmiana klucza = błąd bezpieczeństwa.
1053
+
1054
+ Drop-iny (np. stable.conf) są czytane alfabetycznie – pozwalają na
1055
+ wygodne dodawanie repo bez dotykania głównego repos.conf
1056
+ (np. `echo 'https://repo.paganlinux.eu/stable' > /etc/pag/repos/stable.conf`).
1057
+ """
1058
+ entries = []
1059
+
1060
+ def _read_lines(path):
1061
+ if not os.path.exists(path):
1062
+ return
1063
+ for line in open(path):
1064
+ line = line.strip()
1065
+ if not line or line.startswith("#"):
1066
+ continue
1067
+ parts = line.split()
1068
+ url = parts[0].rstrip("/")
1069
+ fp = parts[1].lower() if len(parts) > 1 else ""
1070
+ entries.append({"url": url, "fingerprint": fp or None})
1071
+
1072
+ # 1) Legacy: pojedynczy plik /etc/pag/repos.conf
1073
+ _read_lines(REPOS_CONF)
1074
+ # 2) Drop-in: /etc/pag/repos/<nazwa>.conf (sortowane, stabilna kolejność)
1075
+ if os.path.isdir(REPOS_DIR):
1076
+ for drop in sorted(os.listdir(REPOS_DIR)):
1077
+ if drop.endswith(".conf"):
1078
+ _read_lines(os.path.join(REPOS_DIR, drop))
1079
+
1080
+ # Dedupe po URL (zachowaj pierwszy wpis – może mieć fingerprint)
1081
+ seen, unique = set(), []
1082
+ for e in entries:
1083
+ if e["url"] not in seen:
1084
+ seen.add(e["url"])
1085
+ unique.append(e)
1086
+
1087
+ if not unique:
1088
+ for url in DEFAULT_REPOS:
1089
+ unique.append({"url": url, "fingerprint": None})
1090
+ return unique
1091
+
1092
+
1093
+def get_repos():
1094
+ return [e["url"] for e in _parse_repos_config()]
1095
+
1096
+
1097
+def _repo_pinned_fp(repo_url):
1098
+ """Zwraca przypięty fingerprint klucza dla repo (z konfiguracji lub trust DB)."""
1099
+ by_url = {e["url"]: e["fingerprint"] for e in _parse_repos_config()}
1100
+ if by_url.get(repo_url):
1101
+ return by_url[repo_url]
1102
+ db = _load_trust_db()
1103
+ fp = db.get(repo_url)
1104
+ return fp.lower() if fp else None
1105
+
1106
+def _repo_cache_path(url):
1107
+ return os.path.join(REPO_CACHE, url.replace("://","_").replace("/","_").replace(".","_") + ".json")
1108
+
1109
+def _repo_etag_path(url): return _repo_cache_path(url) + ".etag"
1110
+def _repo_ts_path(url): return _repo_cache_path(url) + ".ts"
1111
+
1112
+# Informacja (raz na uruchomienie), gdy cache repozytoriów jest tylko-do-odczytu –
1113
+# np. komendy read-only (`pag info`, `pag search`…) jako zwykły user: nie ma sensu
1114
+# ani prawa odświeżać /var/cache/pag/repos, więc używamy lokalnej kopii indeksu.
1115
+_cache_ro_notice_done = False
1116
+
1117
+def _cache_ro_notice():
1118
+ global _cache_ro_notice_done
1119
+ if _cache_ro_notice_done:
1120
+ return
1121
+ _cache_ro_notice_done = True
1122
+ print(f" ⚠ {_('cache_ro', cache=REPO_CACHE)}", file=sys.stderr)
1123
+
1124
+def fetch_repo_index(repo_url, force=False):
1125
+ cp = _repo_cache_path(repo_url)
1126
+ ep = _repo_etag_path(repo_url)
1127
+ tp = _repo_ts_path(repo_url)
1128
+
1129
+ if not force and os.path.exists(cp) and os.path.exists(tp):
1130
+ try:
1131
+ if time.time() - float(open(tp).read().strip()) < REPO_CACHE_TTL:
1132
+ return json.load(open(cp)).get("packages",[])
1133
+ except: pass
1134
+
1135
+ # --- Cache tylko-do-odczytu (np. `pag info` jako zwykły user) ---
1136
+ # /var/cache/pag/repos należy do roota. Nie próbuj odświeżać ani pisać –
1137
+ # zwykły user i tak nie zapisze indeksu; użyj lokalnej kopii (może być
1138
+ # nieaktualna). Pełne odświeżenie indeksu: sudo pag sync
1139
+ if not (os.path.isdir(REPO_CACHE) and os.access(REPO_CACHE, os.W_OK)):
1140
+ if force:
1141
+ print(f" ❌ {repo_url}: nie można odświeżyć indeksu – {REPO_CACHE} jest tylko-do-odczytu",
1142
+ file=sys.stderr)
1143
+ return None
1144
+ _cache_ro_notice()
1145
+ if os.path.exists(cp):
1146
+ try:
1147
+ return json.load(open(cp)).get("packages",[])
1148
+ except Exception:
1149
+ pass
1150
+ return None
1151
+
1152
+ headers = {"User-Agent": "pag/3.0"}
1153
+ if os.path.exists(tp) and not force:
1154
+ try:
1155
+ lm = datetime.fromtimestamp(float(open(tp).read().strip()), tz=timezone.utc)
1156
+ # Wymuś lokalizację C/POSIX dla nagłówków HTTP, aby unikać problemów z nazwami dni/miesięcy
1157
+ try:
1158
+ old_locale = locale.setlocale(locale.LC_TIME)
1159
+ locale.setlocale(locale.LC_TIME, 'C')
1160
+ headers["If-Modified-Since"] = lm.strftime("%a, %d %b %Y %H:%M:%S GMT")
1161
+ locale.setlocale(locale.LC_TIME, old_locale)
1162
+ except (locale.Error, ValueError):
1163
+ # Jeśli ustawienie lokalizacji się nie powiedzie, użyj domyślnej
1164
+ headers["If-Modified-Since"] = lm.strftime("%a, %d %b %Y %H:%M:%S GMT")
1165
+ except: pass
1166
+ if os.path.exists(ep) and not force:
1167
+ try: headers["If-None-Match"] = open(ep).read().strip()
1168
+ except: pass
1169
+
1170
+ # --- Pobranie indeksu (błędy SIECI nie są błędami zapisu cache) ---
1171
+ try:
1172
+ req = Request(f"{repo_url}/repo.json", headers=headers)
1173
+ with urlopen(req, timeout=30) as resp:
1174
+ etag = resp.headers.get("ETag","")
1175
+ raw = resp.read()
1176
+ data = json.loads(raw.decode())
1177
+ except HTTPError as e:
1178
+ if e.code == 304:
1179
+ # Serwer: indeks bez zmian – odśwież tylko znacznik czasu (best-effort)
1180
+ try:
1181
+ open(tp,"w").write(str(time.time()))
1182
+ except OSError:
1183
+ pass
1184
+ if os.path.exists(cp):
1185
+ try:
1186
+ return json.load(open(cp)).get("packages",[])
1187
+ except Exception:
1188
+ pass # uszkodzona kopia – potraktuj jak brak (ostrzeżenie niżej)
1189
+ print(f" ⚠ HTTP {e.code} dla {repo_url}", file=sys.stderr)
1190
+ return None
1191
+ except Exception as e:
1192
+ print(f" ⚠ Błąd pobierania indeksu {repo_url}: {e}", file=sys.stderr)
1193
+ if os.path.exists(cp):
1194
+ try:
1195
+ return json.load(open(cp)).get("packages",[])
1196
+ except Exception:
1197
+ pass
1198
+ return None
1199
+
1200
+ # Indeks pobrany – zapisz SUROWE bajty (nie re-serializuj! podpis GPG jest
1201
+ # nad oryginalnymi bajtami repo.json z serwera) i zweryfikuj podpis.
1202
+ # Najpierw zapis tymczasowy + weryfikacja GPG, dopiero potem podmiana cp:
1203
+ # błąd zapisu (np. pełny dysk) nie niszczy starej, zweryfikowanej kopii
1204
+ # i NIGDY nie zwracamy danych, które nie przeszły weryfikacji.
1205
+ tmp_path = cp + ".tmp"
1206
+ try:
1207
+ with open(tmp_path, "wb") as f:
1208
+ f.write(raw)
1209
+ if not _verify_repo_sig(repo_url, tmp_path):
1210
+ return None # weryfikacja nie powiodła się – stary cache zostaje
1211
+ os.replace(tmp_path, cp)
1212
+ # przenieś podpis obok docelowego pliku (marker „repo ma podpis")
1213
+ for _ext in (".asc", ".sig"):
1214
+ if os.path.exists(tmp_path + _ext):
1215
+ try:
1216
+ os.replace(tmp_path + _ext, cp + _ext)
1217
+ except OSError:
1218
+ pass
1219
+ break
1220
+ if etag:
1221
+ try:
1222
+ open(ep,"w").write(etag)
1223
+ except OSError:
1224
+ pass
1225
+ try:
1226
+ open(tp,"w").write(str(time.time()))
1227
+ except OSError:
1228
+ pass
1229
+ return data.get("packages",[])
1230
+ except OSError as e:
1231
+ print(f" ⚠ Indeks pobrany, ale nie udało się zapisać cache ({REPO_CACHE}): {e}",
1232
+ file=sys.stderr)
1233
+ # cp nie został podmieniony (podmiana jest po weryfikacji) – lokalna kopia
1234
+ # to wciąż stare, zweryfikowane dane
1235
+ if os.path.exists(cp):
1236
+ try:
1237
+ return json.load(open(cp)).get("packages",[])
1238
+ except Exception:
1239
+ pass
1240
+ return None
1241
+ finally:
1242
+ for _p in (tmp_path, tmp_path + ".asc", tmp_path + ".sig"):
1243
+ try:
1244
+ os.unlink(_p)
1245
+ except OSError:
1246
+ pass
1247
+
1248
+def _verify_repo_sig(repo_url, cache_path) -> bool:
1249
+ """Weryfikuje podpis GPG indeksu repozytorium i przypina fingerprint.
1250
+
1251
+ FAIL-CLOSED: brak/nieprawidłowy podpis = False (chyba że PAG_INSECURE=1).
1252
+ Zwraca True jeśli indeks jest zaufany, False jeśli należy go odrzucić.
1253
+
1254
+ Model zaufania (TOFU + pinning):
1255
+ - Pierwszy raz (brak przypiętego fingerprintu) → klucz jest importowany,
1256
+ a fingerprint zapisywany w /etc/pag/trusted.json z JAWNYM ostrzeżeniem.
1257
+ To świadomy kompromis wygody i bezpieczeństwa.
1258
+ - Kolejne uruchomienia: fingerprint jest porównywany z przypiętym.
1259
+ Zmiana klucza = ❌ SECURITY ERROR (fail-closed), wymagane ręczne:
1260
+ pag key-trust <repo_url> (po weryfikacji nowego klucza)
1261
+ """
1262
+ insecure = os.environ.get("PAG_INSECURE", "") == "1"
1263
+
1264
+ if not os.path.exists(GPG_HOME):
1265
+ if insecure:
1266
+ return True # brak GPG home – tryb insecure, akceptuj
1267
+ print(f" ❌ {repo_url}: brak kluczy GPG – weryfikacja niemożliwa!")
1268
+ print(f" Ustaw PAG_INSECURE=1 aby pominąć (niezalecane)")
1269
+ os.remove(cache_path)
1270
+ return False
1271
+
1272
+ sig_path = cache_path + ".sig"
1273
+ # Podpisy generowane jako .asc (armored) – próbuj .asc, potem .sig
1274
+ sig_data = None
1275
+ sig_ext = ""
1276
+ for ext in (".asc", ".sig"):
1277
+ try:
1278
+ req = Request(f"{repo_url}/repo.json{ext}", headers={"User-Agent":"pag/3.0"})
1279
+ with urlopen(req, timeout=15) as resp:
1280
+ sig_data = resp.read()
1281
+ sig_ext = ext
1282
+ break
1283
+ except Exception:
1284
+ continue
1285
+ if not sig_data:
1286
+ if insecure:
1287
+ return True # tryb insecure – akceptuj bez podpisu
1288
+ print(f" ❌ {repo_url}: NIE MOŻNA POBRAĆ PODPISU repo.json.asc/.sig!")
1289
+ print(f" Ustaw PAG_INSECURE=1 aby pominąć (niezalecane)")
1290
+ os.remove(cache_path)
1291
+ return False
1292
+ sig_path = cache_path + sig_ext
1293
+ with open(sig_path, "wb") as f:
1294
+ f.write(sig_data)
1295
+
1296
+ ok, fingerprint = _gpg_verify_fp(sig_path, cache_path)
1297
+ if not ok:
1298
+ # Automatyczny import klucza repo przy pierwszym uruchomieniu (TOFU,
1299
+ # jak apt) – gdy w keyringu brakuje klucza (No public key).
1300
+ res = _gpg_run("--verify", sig_path, cache_path,
1301
+ capture_output=True, text=True, timeout=30)
1302
+ _stderr = res.stderr.decode(errors="replace") if isinstance(res.stderr, bytes) else (res.stderr or "")
1303
+ if "public key" in _stderr.lower() and "no public key" in _stderr.lower():
1304
+ try:
1305
+ with urlopen(Request(f"{repo_url}/paganos.asc", headers={"User-Agent": "pag/3.0"}), timeout=20) as r:
1306
+ keydata = r.read()
1307
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".asc") as tmp:
1308
+ tmp.write(keydata)
1309
+ tmp.flush()
1310
+ _gpg_run("--import", tmp.name, capture_output=True, timeout=30)
1311
+ os.unlink(tmp.name)
1312
+ print(f" 🔑 Importowano klucz repo z {repo_url}/paganos.asc")
1313
+ ok, fingerprint = _gpg_verify_fp(sig_path, cache_path)
1314
+ except Exception:
1315
+ pass
1316
+ if not ok:
1317
+ if insecure:
1318
+ print(f" ⚠ {repo_url}: nieprawidłowy podpis GPG (PAG_INSECURE – ignoruję)")
1319
+ return True
1320
+ os.remove(cache_path)
1321
+ if not shutil.which(GPG_BINARY):
1322
+ print(f" ❌ {repo_url}: GPG nie jest zainstalowane – nie można zweryfikować podpisu!")
1323
+ print(f" Zainstaluj gnupg lub ustaw PAG_INSECURE=1 (niezalecane)")
1324
+ else:
1325
+ print(f" ❌ {repo_url}: NIEPRAWIDŁOWY PODPIS GPG indeksu repozytorium!")
1326
+ return False
1327
+
1328
+ # --- Wymuś przypięty fingerprint (TOFU + pinning) ---
1329
+ pinned = _repo_pinned_fp(repo_url)
1330
+ if pinned:
1331
+ if not fingerprint:
1332
+ if insecure:
1333
+ print(f" ⚠ {repo_url}: nie można odczytać fingerprintu (PAG_INSECURE – ignoruję)")
1334
+ return True
1335
+ os.remove(cache_path)
1336
+ print(f" ❌ [SECURITY ERROR] {repo_url}: nie można odczytać fingerprintu podpisu!")
1337
+ print(f" Przypięty klucz: {pinned} – odrzucam indeks.")
1338
+ return False
1339
+ if fingerprint != pinned.upper():
1340
+ if insecure:
1341
+ print(f" ⚠ {repo_url}: ZMIENIONY KLUCZ PODPISU (PAG_INSECURE – ignoruję)")
1342
+ return True
1343
+ os.remove(cache_path)
1344
+ print(f" ❌ [SECURITY ERROR] {repo_url}: Klucz podpisujący repo uległ zmianie!")
1345
+ print(f" Oczekiwany: {pinned}")
1346
+ print(f" Otrzymany: {fingerprint}")
1347
+ print(f" Jeśli to celowa rotacja klucza: pag key-trust {repo_url}")
1348
+ return False
1349
+ return True
1350
+
1351
+ if fingerprint:
1352
+ # Brak przypiętego fingerprintu → TOFU: zapisz go w bazie zaufania.
1353
+ db = _load_trust_db()
1354
+ if db.get(repo_url) != fingerprint:
1355
+ _save_trust_db({**db, repo_url: fingerprint})
1356
+ print(f" 🔐 Przypięto fingerprint repo {repo_url}: {fingerprint}")
1357
+ print(f" (TOFU – pierwsze zaufanie. Gdy klucz się zmieni, pag odmówi aktualizacji.)")
1358
+ print(f" Aby uniknąć TOFU, dopisz fingerprint w /etc/pag/repos.conf.")
1359
+ return True
1360
+
1361
+def fetch_all_packages(force=False):
1362
+ all_pkgs = {}
1363
+ for repo_url in get_repos():
1364
+ pkgs = fetch_repo_index(repo_url, force)
1365
+ if pkgs:
1366
+ for pdata in pkgs:
1367
+ name = pdata.get("name", pdata.get("filename","?").split("-")[0])
1368
+ pkg = PackageInfo(pdata, repo_url)
1369
+ if name not in all_pkgs or _version_newer(pkg.version, all_pkgs[name].version):
1370
+ all_pkgs[name] = pkg
1371
+ return all_pkgs
1372
+
1373
+# =============================================================================
1374
+# GPG
1375
+# =============================================================================
1376
+
1377
+def _verify_pkg_gpg(pkg_path, repo_url=None):
1378
+ """Weryfikuje podpis GPG pakietu i (jeśli znamy repo) przypięty fingerprint.
1379
+
1380
+ FAIL-CLOSED: brak podpisu = odrzucenie (chyba że PAG_INSECURE=1).
1381
+ Zwraca (passed: bool, message: str).
1382
+ """
1383
+ insecure = os.environ.get("PAG_INSECURE", "") == "1"
1384
+ sig_path = pkg_path + ".sig"
1385
+ if not os.path.exists(sig_path) and os.path.exists(pkg_path + ".asc"):
1386
+ sig_path = pkg_path + ".asc"
1387
+
1388
+ if not os.path.exists(sig_path):
1389
+ if insecure:
1390
+ return True, "(no signature – PAG_INSECURE)"
1391
+ return False, "BRAK PODPISU – pakiet odrzucony (ustaw PAG_INSECURE=1 aby pominąć)"
1392
+
1393
+ ok, fp = _gpg_verify_fp(sig_path, pkg_path)
1394
+ if not ok:
1395
+ if insecure:
1396
+ return True, "(invalid signature – PAG_INSECURE)"
1397
+ return False, "NIEPRAWIDŁOWY PODPIS GPG"
1398
+
1399
+ # Opcjonalnie: sprawdź, czy podpis pochodzi od klucza przypiętego dla repo.
1400
+ if repo_url:
1401
+ pinned = _repo_pinned_fp(repo_url)
1402
+ if pinned and fp and fp != pinned.upper():
1403
+ if insecure:
1404
+ return True, "(pkg signer mismatch – PAG_INSECURE)"
1405
+ return False, f"PAKIET PODPISANY INNYM KLUCZEM niż repo (oczekiwano {pinned})"
1406
+
1407
+ return True, "GPG verified"
1408
+
1409
+def cmd_key_add(source):
1410
+ ensure_dirs()
1411
+ if source.startswith("http"):
1412
+ try:
1413
+ with urlopen(Request(source, headers={"User-Agent":"pag/3.0"}), timeout=30) as resp:
1414
+ keydata = resp.read()
1415
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".gpg") as tmp:
1416
+ tmp.write(keydata); tmp.flush()
1417
+ _gpg_run("--import", tmp.name, capture_output=True, timeout=30)
1418
+ os.unlink(tmp.name)
1419
+ except Exception as e:
1420
+ print(f"❌ Download error: {e}"); return 1
1421
+ else:
1422
+ _gpg_run("--import", source, capture_output=True, timeout=30)
1423
+ print(f"✅ {_('key_imported')}")
1424
+
1425
+def cmd_key_list():
1426
+ if not os.path.exists(GPG_HOME):
1427
+ print(_("no_keys")); return
1428
+ result = _gpg_run("--list-keys", "--keyid-format", "LONG",
1429
+ capture_output=True, text=True, timeout=30)
1430
+ print(result.stdout or _("no_keys"))
1431
+
1432
+def cmd_key_remove(key_id):
1433
+ _gpg_run("--batch", "--yes", "--delete-key", key_id,
1434
+ capture_output=True, timeout=30)
1435
+ print(f"✅ {_('key_removed', key_id)}")
1436
+
1437
+def _repo_signer_fp(repo_url):
1438
+ """Pobiera repo.json + podpis i zwraca fingerprint podpisującego (bez pinningu)."""
1439
+ repo_url = repo_url.rstrip("/")
1440
+ try:
1441
+ with urlopen(Request(f"{repo_url}/repo.json", headers={"User-Agent":"pag/3.0"}), timeout=30) as r:
1442
+ data = r.read()
1443
+ except Exception:
1444
+ return None
1445
+ sig = None
1446
+ sig_ext = ".asc"
1447
+ for ext in (".asc", ".sig"):
1448
+ try:
1449
+ with urlopen(Request(f"{repo_url}/repo.json{ext}", headers={"User-Agent":"pag/3.0"}), timeout=20) as r:
1450
+ sig = r.read()
1451
+ sig_ext = ext
1452
+ break
1453
+ except Exception:
1454
+ continue
1455
+ if not sig:
1456
+ return None
1457
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".json") as tf:
1458
+ tf.write(data); tf.flush()
1459
+ data_path = tf.name
1460
+ sig_path = data_path + sig_ext
1461
+ try:
1462
+ with open(sig_path, "wb") as f:
1463
+ f.write(sig)
1464
+ ok, fp = _gpg_verify_fp(sig_path, data_path)
1465
+ finally:
1466
+ for p in (data_path, sig_path):
1467
+ try: os.unlink(p)
1468
+ except OSError: pass
1469
+ return fp if ok else None
1470
+
1471
+
1472
+def cmd_key_trust(repo_url):
1473
+ """Przypina fingerprint klucza podpisującego repo (koniec z TOFU dla tego repo)."""
1474
+ repo_url = repo_url.rstrip("/")
1475
+ print(f"🔐 Przypinam klucz repo {repo_url}...")
1476
+ fp = _repo_signer_fp(repo_url)
1477
+ if not fp:
1478
+ print(" ❌ Nie można odczytać fingerprintu podpisu (brak/nieudany).")
1479
+ print(" Upewnij się, że klucz repo jest w keyringu (pag key-add <url|file>).")
1480
+ return 1
1481
+ db = _load_trust_db()
1482
+ _save_trust_db({**db, repo_url: fp})
1483
+ print(f" ✅ Przypięto {fp} dla {repo_url}")
1484
+ print(" Od teraz zmiana klucza zostanie zgłoszona jako SECURITY ERROR.")
1485
+ return 0
1486
+
1487
+
1488
+def cmd_key_untrust(repo_url):
1489
+ """Usuwa przypięcie fingerprintu dla repo (wraca do TOFU)."""
1490
+ repo_url = repo_url.rstrip("/")
1491
+ db = _load_trust_db()
1492
+ if repo_url not in db:
1493
+ print(f" ℹ {repo_url} nie ma przypiętego fingerprintu.")
1494
+ return 0
1495
+ del db[repo_url]
1496
+ _save_trust_db(db)
1497
+ print(f" ✅ Usunięto przypięcie dla {repo_url}.")
1498
+ return 0
1499
+
1500
+
1501
+def cmd_key_trusted():
1502
+ """Listuje przypięte fingerprinty repozytoriów."""
1503
+ db = _load_trust_db()
1504
+ if not db:
1505
+ print(_("no_keys"))
1506
+ return
1507
+ for url, fp in sorted(db.items()):
1508
+ print(f" {url}\n {fp}")
1509
+
1510
+# =============================================================================
1511
+# ATOMOWA INSTALACJA (STAGING)
1512
+# =============================================================================
1513
+
1514
+def _safe_rename(src: str, dst: str) -> bool:
1515
+ """
1516
+ Atomowe przeniesienie pliku. Jeśli src i dst są na różnych
1517
+ systemach plików (EXDEV), kopiuje + usuwa źródło.
1518
+ """
1519
+ try:
1520
+ os.rename(src, dst)
1521
+ return True
1522
+ except OSError as e:
1523
+ if e.errno == 18: # EXDEV – cross-device link
1524
+ shutil.copy2(src, dst)
1525
+ os.remove(src)
1526
+ return True
1527
+ raise
1528
+
1529
+
1530
+def _install_file(src: str, rel: str, data_staging: str, sums: dict,
1531
+ staging: str, journal: list, installed_files: list,
1532
+ deploy_dir: str = "", backup_dir: str = "",
1533
+ backup_journal: Optional[list] = None) -> bool:
1534
+ """
1535
+ Instaluje pojedynczy plik (zwykły lub symlink).
1536
+ Obsługuje: cross-device rename, symlinki, weryfikację SHA256.
1537
+
1538
+ Jeśli deploy_dir jest podany (tryb immutable), pliki systemowe trafiają
1539
+ do deploymentu, a współdzielone (/var, /etc, ...) bezpośrednio do /.
1540
+
1541
+ Jeśli backup_dir jest podany, a pod dst istnieje już plik (upgrade/reinstall),
1542
+ stara wersja jest przenoszona do backup_dir, by rollback mógł ją przywrócić.
1543
+ """
1544
+ # W trybie immutable: pliki współdzielone idą do /, reszta do deploymentu
1545
+ if deploy_dir and _is_shared_path("/" + rel):
1546
+ dst_root = PAG_ROOT
1547
+ elif deploy_dir:
1548
+ dst_root = deploy_dir
1549
+ else:
1550
+ dst_root = PAG_ROOT
1551
+
1552
+ dst = os.path.join(dst_root, rel)
1553
+
1554
+ # --- SYMLINK ---
1555
+ if os.path.islink(src):
1556
+ link_target = os.readlink(src)
1557
+ # Weryfikuj sums.json dla symlinka (hash ścieżki docelowej)
1558
+ expected = sums.get("/" + rel, "")
1559
+ if expected:
1560
+ link_hash = hashlib.sha256(link_target.encode()).hexdigest()
1561
+ if expected and link_hash != expected:
1562
+ return False
1563
+
1564
+ os.makedirs(os.path.dirname(dst), exist_ok=True)
1565
+ # Backup istniejącego symlinka (upgrade) – dla poprawnego rollbacku
1566
+ if backup_dir and backup_journal is not None and os.path.lexists(dst):
1567
+ try:
1568
+ backup_path = os.path.join(backup_dir, rel)
1569
+ os.makedirs(os.path.dirname(backup_path), exist_ok=True)
1570
+ os.replace(dst, backup_path)
1571
+ backup_journal.append((backup_path, "/" + rel))
1572
+ journal.append(("backup", backup_path, dst))
1573
+ except OSError:
1574
+ pass
1575
+ # Jeśli docelowy symlink już istnieje, usuń go
1576
+ if os.path.islink(dst) or os.path.exists(dst):
1577
+ os.remove(dst)
1578
+ os.symlink(link_target, dst)
1579
+ journal.append(("symlink", "", dst))
1580
+ installed_files.append({
1581
+ "path": "/" + rel,
1582
+ "sha256": hashlib.sha256(link_target.encode()).hexdigest(),
1583
+ "size": len(link_target),
1584
+ "is_symlink": True,
1585
+ "symlink_target": link_target,
1586
+ })
1587
+ return True
1588
+
1589
+ # --- ZWYKŁY PLIK ---
1590
+ # Oblicz SHA256
1591
+ try:
1592
+ file_sha = _sha256_file(src)
1593
+ except Exception:
1594
+ file_sha = ""
1595
+
1596
+ # Weryfikuj sums.json
1597
+ expected = sums.get("/" + rel, "")
1598
+ if expected and file_sha and file_sha != expected:
1599
+ return False
1600
+
1601
+ # Utwórz katalog docelowy
1602
+ os.makedirs(os.path.dirname(dst), exist_ok=True)
1603
+
1604
+ # Backup istniejącego pliku (upgrade) – dla poprawnego rollbacku
1605
+ if backup_dir and backup_journal is not None and os.path.lexists(dst):
1606
+ try:
1607
+ backup_path = os.path.join(backup_dir, rel)
1608
+ os.makedirs(os.path.dirname(backup_path), exist_ok=True)
1609
+ os.replace(dst, backup_path)
1610
+ backup_journal.append((backup_path, "/" + rel))
1611
+ journal.append(("backup", backup_path, dst))
1612
+ except OSError:
1613
+ pass
1614
+
1615
+ # Atomowe przeniesienie (z fallbackiem dla cross-device).
1616
+ # Zachowuje bity uprawnień (SUID/SGID/sticky) – NIE używamy filter='data'.
1617
+ _safe_rename(src, dst)
1618
+
1619
+ # Wymuś właściciela root:root. UWAGA: os.chown() NIE czyści bitów SUID/SGID.
1620
+ try:
1621
+ os.chown(dst, 0, 0)
1622
+ except (OSError, PermissionError):
1623
+ # Na niektórych systemach plików (tmpfs, fat) chown może się nie powieść
1624
+ pass
1625
+
1626
+ journal.append(("file", src, dst))
1627
+ installed_files.append({
1628
+ "path": "/" + rel,
1629
+ "sha256": file_sha,
1630
+ "size": os.path.getsize(dst),
1631
+ "is_symlink": False,
1632
+ })
1633
+ return True
1634
+
1635
+
1636
+def _atomic_install(pkg_path: str, pkg: PackageInfo, deploy_dir: str = "",
1637
+ backup_dir: str = "") -> Tuple[bool, List[dict], List[Tuple[str, str]]]:
1638
+ """
1639
+ Rozpakowuje do staging area, potem atomowo przenosi pliki.
1640
+ Jeśli deploy_dir podany – instaluje do deploymentu (tryb immutable).
1641
+ Zwraca (success, [lista plików z SHA256], [(backup_path, dst), ...]).
1642
+ """
1643
+ staging = tempfile.mkdtemp(dir=STAGING_DIR, prefix=f".staging-{pkg.name}-")
1644
+ journal = []
1645
+ installed_files = []
1646
+ backup_journal: List[Tuple[str, str]] = []
1647
+
1648
+ try:
1649
+ # Rozpakuj .pkg.tar.xz → staging (bezpieczne – ochrona Directory Traversal)
1650
+ with tarfile.open(pkg_path, "r:xz") as tf:
1651
+ _safe_extractall(tf, staging)
1652
+
1653
+ data_tar = os.path.join(staging, "data.tar.xz")
1654
+ if not os.path.exists(data_tar):
1655
+ shutil.rmtree(staging, ignore_errors=True)
1656
+ return False, [], backup_journal
1657
+
1658
+ # Rozpakuj data.tar.xz → staging/data (bezpieczne – ochrona Directory Traversal)
1659
+ data_staging = os.path.join(staging, "data")
1660
+ os.makedirs(data_staging, exist_ok=True)
1661
+ with tarfile.open(data_tar, "r:xz") as tf:
1662
+ _safe_extractall(tf, data_staging)
1663
+
1664
+ # Wczytaj sums.json
1665
+ sums_path = os.path.join(data_staging, "sums.json")
1666
+ sums = json.load(open(sums_path)) if os.path.exists(sums_path) else {}
1667
+
1668
+ # Hook pre-install (przed przeniesieniem plików do systemu)
1669
+ _run_hook(os.path.join(staging, "hooks"), "pre-install", pkg)
1670
+
1671
+ # Przenieś pliki: staging/data/* → /
1672
+ for root, dirs, files in os.walk(data_staging):
1673
+ # Odtwórz katalogi z pakietu – w tym PUSTE (np. /etc/pulse/default.pa.d).
1674
+ # Pętla plików tworzy tylko rodziców instalowanych plików, przez co
1675
+ # puste katalogi z data.tar.xz ginęły przy instalacji.
1676
+ for d in dirs:
1677
+ src_dir = os.path.join(root, d)
1678
+ rel_dir = os.path.relpath(src_dir, data_staging)
1679
+ if deploy_dir and _is_shared_path("/" + rel_dir):
1680
+ dst_root = PAG_ROOT
1681
+ elif deploy_dir:
1682
+ dst_root = deploy_dir
1683
+ else:
1684
+ dst_root = PAG_ROOT
1685
+ dst_dir = os.path.join(dst_root, rel_dir)
1686
+ if not os.path.isdir(dst_dir):
1687
+ try:
1688
+ os.makedirs(dst_dir, exist_ok=True)
1689
+ except OSError:
1690
+ pass
1691
+ for fname in files:
1692
+ if fname == "sums.json":
1693
+ continue
1694
+ src = os.path.join(root, fname)
1695
+ rel = os.path.relpath(src, data_staging)
1696
+
1697
+ ok = _install_file(src, rel, data_staging, sums,
1698
+ staging, journal, installed_files, deploy_dir,
1699
+ backup_dir, backup_journal)
1700
+ if not ok:
1701
+ # Cofnij wszystkie operacje
1702
+ _rollback_journal(journal, staging)
1703
+ return False, [], backup_journal
1704
+
1705
+ # Odbuduj cache ikon GTK dla motywów dotkniętych instalacją.
1706
+ # Bez icon-theme.cache aplikacje GTK nie widzą ikon mimo obecności
1707
+ # motywu (np. /usr/share/icons/Papirus). Pomijamy, gdy narzędzie
1708
+ # nie jest zainstalowane.
1709
+ _icon_dirs = set()
1710
+ for f in installed_files:
1711
+ fp = f.get("path", "") or ""
1712
+ if fp.startswith("/usr/share/icons/"):
1713
+ _rest = fp[len("/usr/share/icons/"):]
1714
+ _theme = _rest.split("/", 1)[0]
1715
+ if _theme:
1716
+ _icon_dirs.add(os.path.join(PAG_ROOT, "usr/share/icons", _theme))
1717
+ if _icon_dirs:
1718
+ try:
1719
+ subprocess.run(["gtk-update-icon-cache", "--version"],
1720
+ capture_output=True, timeout=10)
1721
+ for _d in sorted(_icon_dirs):
1722
+ if os.path.isdir(_d):
1723
+ subprocess.run(["gtk-update-icon-cache", "-f", "-q", _d],
1724
+ capture_output=True, timeout=300)
1725
+ except Exception:
1726
+ pass
1727
+
1728
+ # Uruchom hooki post-install
1729
+ hooks_dir = os.path.join(staging, "hooks")
1730
+ _run_hook(hooks_dir, "post-install", pkg)
1731
+
1732
+ # Zachowaj hooki na wypadek usunięcia pakietu (pre/post-remove)
1733
+ try:
1734
+ if os.path.isdir(hooks_dir):
1735
+ persisted = os.path.join(PAG_DB, "hooks", pkg.name)
1736
+ shutil.rmtree(persisted, ignore_errors=True)
1737
+ shutil.copytree(hooks_dir, persisted)
1738
+ except Exception:
1739
+ pass
1740
+
1741
+ # Zapisz do SQLite
1742
+ _db_record_files(pkg.name, installed_files)
1743
+
1744
+ shutil.rmtree(staging, ignore_errors=True)
1745
+ return True, installed_files, backup_journal
1746
+
1747
+ except Exception as e:
1748
+ _rollback_journal(journal, staging)
1749
+ return False, [], backup_journal
1750
+
1751
+
1752
+def _refresh_dynamic_linker_cache(deploy_dir: str = "") -> bool:
1753
+ """Odświeża cache ld.so po udanej instalacji pakietów."""
1754
+ ldconfig = shutil.which("ldconfig")
1755
+ if not ldconfig:
1756
+ print(" ⚠ Nie znaleziono ldconfig — cache linkera nie został odświeżony.",
1757
+ file=sys.stderr)
1758
+ return False
1759
+
1760
+ target_root = deploy_dir or PAG_ROOT
1761
+ command = [ldconfig]
1762
+ if target_root != "/":
1763
+ command.extend(["-r", target_root])
1764
+
1765
+ try:
1766
+ subprocess.run(command, check=True, timeout=60,
1767
+ stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
1768
+ text=True)
1769
+ return True
1770
+ except (OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc:
1771
+ detail = getattr(exc, "stderr", None) or str(exc)
1772
+ print(f" ⚠ Nie udało się odświeżyć cache'a ld.so: {detail.strip()}",
1773
+ file=sys.stderr)
1774
+ return False
1775
+
1776
+
1777
+def _rollback_journal(journal: list, staging_path: str):
1778
+ """Cofa wszystkie operacje z journala (odwrotna kolejność)."""
1779
+ for entry in reversed(journal):
1780
+ op = entry[0]
1781
+ if op == "file":
1782
+ _, src, dst = entry
1783
+ try:
1784
+ if os.path.exists(dst) or os.path.islink(dst):
1785
+ _safe_rename(dst, src)
1786
+ except Exception:
1787
+ pass
1788
+ elif op == "symlink":
1789
+ _, _, dst = entry
1790
+ try:
1791
+ if os.path.islink(dst) or os.path.exists(dst):
1792
+ os.remove(dst)
1793
+ except Exception:
1794
+ pass
1795
+ elif op == "backup":
1796
+ # Przywróć starą wersję pliku z backupu (upgrade)
1797
+ _, bpath, dst = entry
1798
+ try:
1799
+ if os.path.lexists(bpath):
1800
+ os.replace(bpath, dst)
1801
+ except Exception:
1802
+ pass
1803
+ shutil.rmtree(staging_path, ignore_errors=True)
1804
+
1805
+# =============================================================================
1806
+# BEZPIECZNE USUWANIE
1807
+# =============================================================================
1808
+
1809
+def _safe_remove_files(pkg_name: str, installed_db: dict) -> Tuple[int, List[str]]:
1810
+ """
1811
+ Usuwa pliki pakietu, ale tylko jeśli NIE są współdzielone z innym pakietem.
1812
+ Zwraca (liczba usuniętych, [lista usuniętych ścieżek]).
1813
+ """
1814
+ pkg_files = _db_get_package_files(pkg_name)
1815
+ removed = []
1816
+ skipped_shared = []
1817
+
1818
+ for fpath in pkg_files:
1819
+ owners = _db_get_file_owners(fpath)
1820
+ # Sprawdź czy inny ZAINSTALOWANY pakiet też jest właścicielem
1821
+ other_owners = [o for o in owners if o != pkg_name and o in installed_db]
1822
+
1823
+ if other_owners:
1824
+ # Plik współdzielony – tylko usuń wpis w DB, nie kasuj pliku
1825
+ skipped_shared.append(fpath)
1826
+ continue
1827
+
1828
+ full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
1829
+ if os.path.isfile(full) or os.path.islink(full):
1830
+ os.remove(full)
1831
+ removed.append(fpath)
1832
+
1833
+ # Usuń puste katalogi (od najgłębszych)
1834
+ dirs = set()
1835
+ for fpath in removed + skipped_shared:
1836
+ parent = os.path.dirname(fpath)
1837
+ while parent and parent != "/":
1838
+ dirs.add(parent)
1839
+ parent = os.path.dirname(parent)
1840
+
1841
+ for d in sorted(dirs, key=len, reverse=True):
1842
+ full_d = os.path.join(PAG_ROOT, d.lstrip("/"))
1843
+ if os.path.isdir(full_d):
1844
+ try:
1845
+ os.rmdir(full_d)
1846
+ except OSError:
1847
+ pass # nie jest pusty – OK
1848
+
1849
+ # Usuń z SQLite
1850
+ _db_remove_package_files(pkg_name)
1851
+
1852
+ if skipped_shared:
1853
+ print(f" ⚠ {len(skipped_shared)} plików współdzielonych zachowanych")
1854
+
1855
+ return len(removed) + len(skipped_shared), removed
1856
+
1857
+
1858
+def _remove_stale_files(pkg_name: str, old_files: List[str], new_paths: List[str],
1859
+ installed_db: dict, deploy_dir: str = "",
1860
+ backup_dir: str = "", backup_journal: Optional[list] = None) -> Tuple[int, List[str]]:
1861
+ """
1862
+ Po upgrade usuwa pliki starej wersji, których nie ma w nowej.
1863
+
1864
+ - Pliki współdzielone z innym zainstalowanym pakietem są ZACHOWYWANE
1865
+ (usuwany jest tylko wpis z bazy `files` dla tego pakietu).
1866
+ - Sprząta puste katalogi i wpisy SQLite starej wersji.
1867
+ Zwraca (liczba usuniętych, [usunięte ścieżki]).
1868
+ """
1869
+ new_set = set(new_paths)
1870
+ stale = [f for f in old_files if f not in new_set]
1871
+ if not stale:
1872
+ return 0, []
1873
+
1874
+ root = deploy_dir or PAG_ROOT
1875
+ removed = []
1876
+ skipped = 0
1877
+ for fpath in stale:
1878
+ owners = _db_get_file_owners(fpath)
1879
+ other_owners = [o for o in owners if o != pkg_name and o in installed_db]
1880
+ if other_owners:
1881
+ # Współdzielony z innym pakietem – tylko usuń wpis z DB dla tego pakietu
1882
+ skipped += 1
1883
+ else:
1884
+ full = os.path.join(root, fpath.lstrip("/"))
1885
+ if os.path.isfile(full) or os.path.islink(full):
1886
+ try:
1887
+ if backup_dir and backup_journal is not None:
1888
+ backup_path = os.path.join(backup_dir, fpath.lstrip("/"))
1889
+ os.makedirs(os.path.dirname(backup_path), exist_ok=True)
1890
+ os.replace(full, backup_path) # przenieś do backupu (rollback)
1891
+ backup_journal.append((backup_path, fpath))
1892
+ else:
1893
+ os.remove(full)
1894
+ removed.append(fpath)
1895
+ except OSError:
1896
+ pass
1897
+ # Usuń wpis `files` dla tego pakietu (stara wersja już go nie zawiera)
1898
+ with _db_session() as db:
1899
+ db.execute("DELETE FROM files WHERE package=? AND path=?", (pkg_name, fpath))
1900
+
1901
+ # Usuń puste katalogi (od najgłębszych)
1902
+ dirs = set()
1903
+ for fpath in removed:
1904
+ parent = os.path.dirname(fpath)
1905
+ while parent and parent != "/":
1906
+ dirs.add(parent)
1907
+ parent = os.path.dirname(parent)
1908
+ for d in sorted(dirs, key=len, reverse=True):
1909
+ full_d = os.path.join(root, d.lstrip("/"))
1910
+ if os.path.isdir(full_d):
1911
+ try:
1912
+ os.rmdir(full_d)
1913
+ except OSError:
1914
+ pass # nie jest pusty – OK
1915
+
1916
+ if removed:
1917
+ print(f" 🧹 Usunięto {len(removed)} nieaktualnych plików ({pkg_name})")
1918
+ if skipped:
1919
+ print(f" ⚠ {skipped} plików współdzielonych zachowanych")
1920
+
1921
+ return len(removed), removed
1922
+
1923
+
1924
+def _new_upgrade_backup_root() -> str:
1925
+ """Tworzy katalog na backupy starych wersji dla bieżącej transakcji upgrade."""
1926
+ txn = datetime.now().strftime("%Y%m%dT%H%M%S") + "-" + str(os.getpid())
1927
+ root = os.path.join(STAGING_DIR, "backups", txn)
1928
+ os.makedirs(root, exist_ok=True)
1929
+ return root
1930
+
1931
+
1932
+def _purge_old_backups(keep_root: str = ""):
1933
+ """Usuwa backupy starszych transakcji (zostawia bieżący – dla `pag rollback`)."""
1934
+ base = os.path.join(STAGING_DIR, "backups")
1935
+ if not os.path.isdir(base):
1936
+ return
1937
+ for entry in os.listdir(base):
1938
+ p = os.path.join(base, entry)
1939
+ if p != keep_root and os.path.isdir(p):
1940
+ shutil.rmtree(p, ignore_errors=True)
1941
+
1942
+# =============================================================================
1943
+# HOOKI
1944
+# =============================================================================
1945
+# Hooki uruchamiają dowolny plik z pakietu jako root — to naturalna cecha
1946
+# menedżera pakietów (apt/pacman też tak mają), dlatego MUSISZ ufać repozytorium.
1947
+# Aby ograniczyć ryzyko:
1948
+# - hook dostaje minimalne, "czyste" środowisko (bez LD_PRELOAD, BASH_ENV itp.)
1949
+# - hooki można wyłączyć (PAG_NO_HOOKS=1) i ustawić timeout (PAG_HOOK_TIMEOUT)
1950
+# - każde uruchomienie jest logowane do /var/log/pag/audit.log
1951
+# - hook ma wersjonowane API (PKG_HOOK_API)
1952
+# =============================================================================
1953
+
1954
+# Lista wykonanych hooków — trafia do wpisu transakcji (informacja w rejestrze).
1955
+_HOOKS_RUN: List[str] = []
1956
+
1957
+
1958
+def _hook_env(pkg: PackageInfo, hook_name: str) -> dict:
1959
+ """Buduje minimalne środowisko dla hooka (bez niebezpiecznych zmiennych)."""
1960
+ return {
1961
+ "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
1962
+ "HOME": "/root",
1963
+ "LANG": "C.UTF-8",
1964
+ "LC_ALL": "C.UTF-8",
1965
+ "PKG_NAME": pkg.name,
1966
+ "PKG_VERSION": pkg.version,
1967
+ "PKG_ACTION": hook_name,
1968
+ "PKG_HOOK_API": HOOK_API_VERSION,
1969
+ }
1970
+
1971
+
1972
+def _hook_timeout() -> int:
1973
+ try:
1974
+ return max(1, int(os.environ.get("PAG_HOOK_TIMEOUT", "60")))
1975
+ except Exception:
1976
+ return 60
1977
+
1978
+
1979
+def _run_hook(hooks_dir: str, hook_name: str, pkg: PackageInfo) -> bool:
1980
+ """Uruchamia skrypt hooka jeśli istnieje.
1981
+
1982
+ Zwraca True jeśli hook został WYKONANY (istniał i uruchomiono go), False w
1983
+ pozostałych przypadkach (brak pliku, wyłączone hooki, błąd). Obsługuje
1984
+ ograniczone środowisko, timeout, logowanie do audytu i rejestr w transakcji.
1985
+ """
1986
+ hook_path = os.path.join(hooks_dir, hook_name)
1987
+ if not os.path.exists(hook_path):
1988
+ return False
1989
+
1990
+ if os.environ.get("PAG_NO_HOOKS", "") == "1":
1991
+ print(f" ⚠ Hook pominięty (PAG_NO_HOOKS=1): {hook_name} dla {pkg.name}")
1992
+ _audit(f"hook SKIP {hook_name} {pkg.name}-{pkg.version} (PAG_NO_HOOKS=1)")
1993
+ return False
1994
+
1995
+ os.chmod(hook_path, 0o755)
1996
+ env = _hook_env(pkg, hook_name)
1997
+ tag = f"{hook_name} {pkg.name}-{pkg.version}"
1998
+ try:
1999
+ result = subprocess.run([hook_path], env=env, timeout=_hook_timeout(),
2000
+ check=False, capture_output=True, text=True,
2001
+ cwd="/")
2002
+ _HOOKS_RUN.append(tag)
2003
+ if result.returncode != 0:
2004
+ print(f" ⚠ Hook {hook_name} dla {pkg.name} zakończony z kodem {result.returncode}")
2005
+ if result.stderr:
2006
+ print(f" {result.stderr.strip()[-200:]}")
2007
+ _audit(f"hook FAIL {tag} rc={result.returncode}")
2008
+ else:
2009
+ _audit(f"hook OK {tag}")
2010
+ return True
2011
+ except subprocess.TimeoutExpired:
2012
+ print(f" ⚠ Hook {hook_name} dla {pkg.name} przekroczył timeout ({_hook_timeout()}s)")
2013
+ _audit(f"hook TIMEOUT {tag}")
2014
+ return False
2015
+ except Exception as e:
2016
+ print(f" ⚠ Hook {hook_name} dla {pkg.name}: {e}")
2017
+ _audit(f"hook ERROR {tag}: {e}")
2018
+ return False
2019
+
2020
+# =============================================================================
2021
+# TRANSAKCJE I ROLLBACK
2022
+# =============================================================================
2023
+
2024
+def _record_transaction(action, packages, success, snapshot, file_journal=None, hooks=None,
2025
+ upgrade_backups=None, upgrade_backup_root=""):
2026
+ history = load_json(HISTORY_FILE) if os.path.exists(HISTORY_FILE) else []
2027
+ # Rejestr wykonanych hooków – informacja o tym, że uruchomiono kod pakietu
2028
+ # jako root. Trafia do historii, by dało się później sprawdzić, co się działo.
2029
+ executed_hooks = list(_HOOKS_RUN) if hooks is None else hooks
2030
+ _HOOKS_RUN.clear()
2031
+ entry = {
2032
+ "action": action, "packages": packages, "success": success,
2033
+ "timestamp": datetime.now().isoformat(),
2034
+ "snapshot": snapshot,
2035
+ "file_journal": file_journal, # lista plików do wycofania
2036
+ "hooks": executed_hooks, # wykonane hooki (pre/post-install/remove)
2037
+ }
2038
+ if upgrade_backups:
2039
+ entry["upgrade_backups"] = upgrade_backups # {dst: backup_path}
2040
+ entry["upgrade_backup_root"] = upgrade_backup_root
2041
+ history.append(entry)
2042
+ if len(history) > 50:
2043
+ history = history[-50:]
2044
+ save_json(HISTORY_FILE, history)
2045
+
2046
+def cmd_history():
2047
+ if not os.path.exists(HISTORY_FILE):
2048
+ print(_("no_history")); return
2049
+ history = load_json(HISTORY_FILE)
2050
+ if not history:
2051
+ print(_("no_history")); return
2052
+ print(f"Ostatnie transakcje ({len(history)}):")
2053
+ for i, e in enumerate(reversed(history), 1):
2054
+ icon = "✅" if e["success"] else "❌"
2055
+ pkgs = ", ".join(e["packages"][:5])
2056
+ if len(e["packages"]) > 5: pkgs += f" (+{len(e['packages'])-5})"
2057
+ print(f" {i}. {icon} {e['action']}: {pkgs}")
2058
+ print(f" {e['timestamp']}")
2059
+
2060
+def cmd_rollback():
2061
+ if not os.path.exists(HISTORY_FILE):
2062
+ print(_("no_history")); return 1
2063
+ history = load_json(HISTORY_FILE)
2064
+ if not history:
2065
+ print(_("no_history")); return 1
2066
+
2067
+ last = None
2068
+ for e in reversed(history):
2069
+ if e["success"] and e.get("snapshot"):
2070
+ last = e; break
2071
+
2072
+ if not last:
2073
+ print("❌ No snapshot to restore."); return 1
2074
+
2075
+ print(f"⏪ Rolling back: {last['action']} ({last['timestamp']})")
2076
+ print(f" Packages: {', '.join(last['packages'][:10])}")
2077
+
2078
+ if not _ask_confirm():
2079
+ return 0
2080
+
2081
+ # Przywróć installed.json
2082
+ save_json(INSTALLED_DB, last["snapshot"])
2083
+
2084
+ # Wycofaj fizyczne pliki (jeśli zapisano journal)
2085
+ file_journal = last.get("file_journal", [])
2086
+ upgrade_backups = last.get("upgrade_backups", {}) or {}
2087
+ backup_root = last.get("upgrade_backup_root", "")
2088
+
2089
+ # Przywróć stare wersje z backupów (upgrade) – nadpisane i usunięte stale pliki
2090
+ for dst, bpath in upgrade_backups.items():
2091
+ full = os.path.join(PAG_ROOT, dst.lstrip("/"))
2092
+ if bpath and os.path.lexists(bpath):
2093
+ try:
2094
+ os.makedirs(os.path.dirname(full), exist_ok=True)
2095
+ os.replace(bpath, full)
2096
+ except OSError:
2097
+ pass
2098
+
2099
+ # Usuń nowe pliki (które nie miały poprzedniej wersji)
2100
+ backed = set(upgrade_backups)
2101
+ if file_journal:
2102
+ for fpath in reversed(file_journal):
2103
+ if fpath in backed:
2104
+ continue
2105
+ full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
2106
+ if os.path.exists(full) or os.path.islink(full):
2107
+ os.remove(full)
2108
+ print(f" {_('rollback_files', len(file_journal))}")
2109
+
2110
+ # Sprzątanie pustych katalogów + katalogu backupów
2111
+ dirs = set()
2112
+ for fpath in file_journal:
2113
+ parent = os.path.dirname(fpath)
2114
+ while parent and parent != "/":
2115
+ dirs.add(parent)
2116
+ parent = os.path.dirname(parent)
2117
+ for d in sorted(dirs, key=len, reverse=True):
2118
+ full_d = os.path.join(PAG_ROOT, d.lstrip("/"))
2119
+ if os.path.isdir(full_d):
2120
+ try:
2121
+ os.rmdir(full_d)
2122
+ except OSError:
2123
+ pass
2124
+ if backup_root:
2125
+ shutil.rmtree(backup_root, ignore_errors=True)
2126
+
2127
+ print(f"✅ {_('rollback_restored')}")
2128
+ _record_transaction("rollback", last["packages"], True, None)
2129
+ return 0
2130
+
2131
+# =============================================================================
2132
+# INSTALACJA
2133
+# =============================================================================
2134
+
2135
+def _install_local_pkg_files(paths, install_succeeded):
2136
+ """Instaluje lokalne pliki .pkg.tar.xz (bez repozytorium).
2137
+ Zgodnie z _atomic_install każdy plik jest instalowany atomowo.
2138
+ Zwraca (failed_count, installed_files)."""
2139
+ failed = 0
2140
+ all_files = []
2141
+ for p in paths:
2142
+ p = os.path.abspath(p)
2143
+ if not os.path.isfile(p):
2144
+ print(f" ❌ Nie znaleziono pakietu: {p}")
2145
+ failed += 1
2146
+ continue
2147
+ try:
2148
+ with tarfile.open(p, "r:xz") as tf:
2149
+ meta = tf.extractfile("metadata.json")
2150
+ if meta is None:
2151
+ print(f" ❌ {p}: brak metadata.json")
2152
+ failed += 1
2153
+ continue
2154
+ data = json.loads(meta.read())
2155
+ except Exception as e:
2156
+ print(f" ❌ {p}: nie udało się odczytać pakietu ({e})")
2157
+ failed += 1
2158
+ continue
2159
+ pkg = PackageInfo(data, repo="local")
2160
+ print(f" ↓ {pkg.name}-{pkg.version} (lokalny) ... ", end="", flush=True)
2161
+ ok, files, _ = _atomic_install(p, pkg)
2162
+ if ok:
2163
+ install_succeeded(pkg, files)
2164
+ all_files.extend(f["path"] for f in files)
2165
+ print("✅")
2166
+ else:
2167
+ print("❌")
2168
+ failed += 1
2169
+ return failed, all_files
2170
+
2171
+
2172
+def _preflight_disk(total_bytes: int) -> bool:
2173
+ """Pre-flight przed transakcją: wolne miejsce + mount read-only.
2174
+
2175
+ Zwraca False (przerywa instalację) gdy na partycji docelowej brakuje
2176
+ miejsca na pakiety albo katalog stagingu jest zamontowany read-only
2177
+ (inaczej instalacja rwałaby się w połowie, zostawiając uszkodzony system).
2178
+ """
2179
+ target = PAG_ROOT or "/"
2180
+ try:
2181
+ st = os.statvfs(target)
2182
+ free = st.f_bavail * st.f_frsize
2183
+ except OSError:
2184
+ return True # nie da się sprawdzić – nie blokuj
2185
+ need_mb = total_bytes // 1048576
2186
+ free_mb = free // 1048576
2187
+ if free < total_bytes:
2188
+ print(f" ❌ Za mało miejsca na dysku: potrzeba ~{need_mb} MB, "
2189
+ f"wolne {free_mb} MB ({target})")
2190
+ return False
2191
+ if free < total_bytes * 3:
2192
+ print(f" ⚠ Mało miejsca na dysku: wolne {free_mb} MB, "
2193
+ f"pakiety ~{need_mb} MB (rozpakowane zajmą więcej)")
2194
+ # Wykryj mount read-only (test zapisu w stagingu)
2195
+ try:
2196
+ probe = os.path.join(STAGING_DIR, ".pag-probe")
2197
+ with open(probe, "w") as f:
2198
+ f.write("x")
2199
+ os.remove(probe)
2200
+ except OSError:
2201
+ print(f" ❌ {target} jest zamontowane tylko-do-odczytu – nie można instalować.")
2202
+ return False
2203
+ return True
2204
+
2205
+
2206
+def cmd_install(package_names, as_dep=False, upgrade=False):
2207
+ ensure_dirs()
2208
+ installed_db = load_json(INSTALLED_DB)
2209
+ world = load_world()
2210
+ pinned = load_json(PINNED_FILE)
2211
+
2212
+ # Obsługa lokalnych plików .pkg.tar.xz (zbudowanych przez pagbuild) –
2213
+ # nie wymaga repozytorium ani GPG.
2214
+ local_files = [p for p in package_names if p.endswith(PKG_EXT) or
2215
+ (os.sep in p and os.path.isfile(os.path.abspath(p)))]
2216
+ if local_files:
2217
+ _local_need = sum(
2218
+ os.path.getsize(os.path.abspath(p))
2219
+ for p in local_files if os.path.isfile(os.path.abspath(p))
2220
+ )
2221
+ if not _preflight_disk(_local_need):
2222
+ return 1
2223
+
2224
+ def _ok(pkg, files):
2225
+ installed_db[pkg.name] = {
2226
+ "version": pkg.version, "release": pkg.release, "description": pkg.description,
2227
+ "dependencies": pkg.dependencies, "size_bytes": pkg.size_bytes,
2228
+ "sha256": pkg.sha256, "installed_at": datetime.now().isoformat(),
2229
+ "repo": "local",
2230
+ "provides": getattr(pkg, "provides", None) or [],
2231
+ "provides_so": getattr(pkg, "provides_so", None) or [],
2232
+ "requires_so": getattr(pkg, "requires_so", None) or [],
2233
+ }
2234
+ world.add(pkg.name)
2235
+ failed_local, _fl = _install_local_pkg_files(local_files, _ok)
2236
+ save_json(INSTALLED_DB, installed_db)
2237
+ save_world(world)
2238
+ if failed_local:
2239
+ return 1
2240
+ _refresh_dynamic_linker_cache()
2241
+ package_names = [n for n in package_names if n not in
2242
+ [os.path.abspath(x) for x in local_files] and
2243
+ n not in local_files]
2244
+ to_install = []
2245
+ if not package_names:
2246
+ return 0
2247
+ # pozostałe argumenty to nazwy pakietów z repo – kontynuuj
2248
+
2249
+ repo_pkgs = fetch_all_packages()
2250
+
2251
+ if not repo_pkgs:
2252
+ print(f"❌ {_('no_index')}"); return 1
2253
+
2254
+ for name in list(package_names):
2255
+ if name in pinned:
2256
+ print(f"⚠ {name} {_('pinned_to')} {pinned[name]} – skipping")
2257
+ package_names.remove(name)
2258
+
2259
+ to_install, missing_deps = _resolve_deps(package_names, repo_pkgs, installed_db)
2260
+
2261
+ # ── Pakiety, których NIE MA w repo ani nie są zainstalowane ──
2262
+ # Zgłoś od razu zamiast mylącego „Do zainstalowania: N (0.00 MB)”
2263
+ # i prośby o potwierdzenie (np. `pag install steam` gdy steam nie istnieje).
2264
+ not_found = []
2265
+ for n in package_names:
2266
+ real = _resolve_provides(n, repo_pkgs, installed_db)
2267
+ if real not in repo_pkgs and real not in installed_db \
2268
+ and not os.path.exists(os.path.abspath(n)):
2269
+ not_found.append(n)
2270
+ if not_found:
2271
+ print(f"\n ❌ {_('pkg_not_found', ', '.join(not_found))}")
2272
+ print(f" {_('not_found_hint')}")
2273
+ return 1
2274
+
2275
+ # --- Tryb upgrade: pakiety już zainstalowane MUSZĄ zostać ponownie
2276
+ # zainstalowane z nowszej wersji (zastąpienie w tej samej transakcji).
2277
+ if upgrade:
2278
+ # `pag update` przekazuje tu tylko pakiety z NOWSZĄ wersją (już
2279
+ # przefiltrowane w _pending_updates), a `pag install -f` wymusza
2280
+ # reinstalację nawet tej SAMEJ wersji – dlatego nie filtrujemy po
2281
+ # _version_newer.
2282
+ upgrade_targets = [
2283
+ name for name in package_names
2284
+ if name in repo_pkgs
2285
+ and name in installed_db
2286
+ and name not in pinned
2287
+ ]
2288
+ for name in upgrade_targets:
2289
+ if name not in to_install:
2290
+ to_install.append(name)
2291
+
2292
+ if not to_install and not missing_deps:
2293
+ print(f"✅ {_('all_installed')}"); return 0
2294
+
2295
+ # ── WERYFIKACJA ZALEŻNOŚCI ──────────────────────────────────────────
2296
+ fatal_missing = _verify_dependencies(to_install, repo_pkgs, installed_db)
2297
+
2298
+ if fatal_missing > 0:
2299
+ print(f"❌ Nie można kontynuować – {fatal_missing} brakujących zależności.")
2300
+ print(f" Zainstaluj brakujące pakiety lub dodaj repozytoria.")
2301
+ return 1
2302
+
2303
+ so_missing = _verify_so_deps(to_install, repo_pkgs, installed_db)
2304
+ if so_missing > 0:
2305
+ print(" Zainstaluj dostawcę biblioteki lub zaktualizuj repozytorium.")
2306
+ return 1
2307
+
2308
+ if not to_install:
2309
+ print(f"✅ {_('all_installed')}"); return 0
2310
+
2311
+ MAX_MB = MAX_PKG_SIZE // 1048576
2312
+ for n in to_install:
2313
+ if not _validate_pkg_name(n):
2314
+ print(f" {_("sec_badname", name=n)}")
2315
+ return 1
2316
+ sz = repo_pkgs[n].size_bytes if n in repo_pkgs else 0
2317
+ if sz > MAX_PKG_SIZE:
2318
+ mb = sz // 1048576
2319
+ print(f" {_("sec_toobig", size_mb=mb, max_mb=MAX_MB)}")
2320
+ return 1
2321
+ total_size = sum(repo_pkgs[n].size_bytes for n in to_install if n in repo_pkgs)
2322
+ if not _preflight_disk(total_size):
2323
+ return 1
2324
+ print(f"\n📦 {_('to_install', len(to_install), total_size/1048576)}")
2325
+ for name in to_install:
2326
+ p = repo_pkgs.get(name)
2327
+ if p:
2328
+ if name in installed_db:
2329
+ marker = " [upgrade]" if upgrade else ""
2330
+ else:
2331
+ marker = f" [{_('new')}]"
2332
+ print(f" {name}-{p.version}{marker}")
2333
+
2334
+ if not as_dep and not upgrade:
2335
+ if not _ask_confirm():
2336
+ print(_("cancelled")); return 0
2337
+
2338
+ snapshot = json.loads(json.dumps(installed_db))
2339
+ all_installed_files = []
2340
+ failed = []
2341
+ # Pary (pkg, stare_pliki, nowe_pliki) do usunięcia martwych plików po upgrade
2342
+ stale_candidates = []
2343
+ # Katalog backupów starych wersji (upgrade) – dla poprawnego rollbacku
2344
+ backup_root = ""
2345
+ all_backups: List[Tuple[str, str]] = [] # (backup_path, dst)
2346
+ if upgrade and to_install:
2347
+ backup_root = _new_upgrade_backup_root()
2348
+
2349
+ # --- Dziennik transakcji (dla pełnej atomowości) ---
2350
+ # Jeśli którykolwiek pakiet zawiedzie, cofamy WSZYSTKIE zainstalowane
2351
+ # w tej transakcji przez _rollback_transaction().
2352
+ transaction_journal: List[Tuple[str, str, str]] = [] # (op, src, dst)
2353
+
2354
+ # --- Tryb immutable: utwórz nowy deployment ---
2355
+ immutable = os.environ.get("PAG_IMMUTABLE", "") == "1"
2356
+ deploy_dir = ""
2357
+ deploy_id = ""
2358
+ if immutable:
2359
+ print(f"\n 🏗️ Tworzenie nowego deploymentu...")
2360
+ deploy_dir, deploy_id = _create_deployment(to_install, "upgrade" if upgrade else "install")
2361
+ target_root = deploy_dir
2362
+ else:
2363
+ target_root = ""
2364
+
2365
+ # --- Faza 1: Równoległe pobieranie wszystkich pakietów ---
2366
+ to_download = [repo_pkgs[name] for name in to_install if name in repo_pkgs]
2367
+ if len(to_download) > 1:
2368
+ print(f"\n ⏬ Pobieranie {len(to_download)} pakietów równolegle...")
2369
+ downloaded = _download_packages_parallel(to_download)
2370
+ else:
2371
+ downloaded = {}
2372
+
2373
+ # --- Faza 2: Instalacja z paskiem postępu ---
2374
+ t0 = time.time()
2375
+
2376
+ for name in to_install:
2377
+ pkg = repo_pkgs.get(name)
2378
+ if not pkg:
2379
+ print(f" ❌ {name}: {_('not_found')}")
2380
+ failed.append(name)
2381
+ break
2382
+
2383
+ # Pasek postępu na stderr (nie koliduje z download barem)
2384
+ idx = len(all_installed_files) + 1
2385
+ pct = (idx - 1) / len(to_install) * 100
2386
+ fl = int(25 * pct / 100)
2387
+ pbar = "█" * fl + "░" * (25 - fl)
2388
+ elapsed = time.time() - t0
2389
+ if idx > 1 and elapsed > 0:
2390
+ avg = elapsed / (idx - 1)
2391
+ remaining = avg * (len(to_install) - idx + 1)
2392
+ if remaining < 60:
2393
+ eta_s = f" ~{remaining:.0f}s"
2394
+ else:
2395
+ eta_s = f" ~{remaining/60:.1f}m"
2396
+ else:
2397
+ eta_s = ""
2398
+ status = f" [{pbar}] {idx}/{len(to_install)} ({pct:.0f}%){eta_s}"
2399
+ print(status, file=sys.stderr, flush=True)
2400
+
2401
+ print(f" ↓ {name}-{pkg.version} ...", end=" ", flush=True)
2402
+
2403
+ # Pobierz (z cache fazy 1 lub bezpośrednio)
2404
+ pkg_path = downloaded.get(name) if name in downloaded else _download_pkg(pkg)
2405
+ if not pkg_path:
2406
+ print(f"❌ {_('download_fail')}")
2407
+ failed.append(name)
2408
+ break # przerwij transakcję
2409
+
2410
+ # GPG
2411
+ gpg_ok, gpg_msg = _verify_pkg_gpg(pkg_path, repo_url=pkg.repo_url)
2412
+ if not gpg_ok:
2413
+ print(f"❌ {_('gpg_fail')}: {gpg_msg[:60]}")
2414
+ failed.append(name)
2415
+ break # PRZERWIJ – niezaufany pakiet
2416
+
2417
+ # SHA256 całego pakietu
2418
+ if pkg.sha256 and _sha256_file(pkg_path) != pkg.sha256:
2419
+ print(f"❌ {_('sha256_mismatch')}")
2420
+ failed.append(name)
2421
+ break # PRZERWIJ – uszkodzony pakiet
2422
+
2423
+ # Przed instalacją zapamiętaj pliki starej wersji (potrzebne w upgrade)
2424
+ old_files = _db_get_package_files(name) if name in installed_db else []
2425
+
2426
+ # Atomowa instalacja (w upgrade backupuje nadpisywane pliki)
2427
+ ok, files, backup_j = _atomic_install(pkg_path, pkg, deploy_dir,
2428
+ backup_dir=backup_root)
2429
+ if ok:
2430
+ installed_db[name] = {
2431
+ "version": pkg.version, "release": pkg.release, "description": pkg.description,
2432
+ "dependencies": pkg.dependencies, "size_bytes": pkg.size_bytes,
2433
+ "sha256": pkg.sha256, "installed_at": datetime.now().isoformat(),
2434
+ "repo": pkg.repo_url,
2435
+ "provides": getattr(pkg, "provides", None) or [],
2436
+ "provides_so": getattr(pkg, "provides_so", None) or [],
2437
+ "requires_so": getattr(pkg, "requires_so", None) or [],
2438
+ }
2439
+ if not as_dep and name in package_names:
2440
+ world.add(name)
2441
+ print("✅")
2442
+ all_installed_files.extend(f["path"] for f in files)
2443
+ all_backups.extend(backup_j)
2444
+
2445
+ # Upgrade: zapamiętaj stare pliki, by po sukcesie usunąć te,
2446
+ # których nie ma już w nowej wersji.
2447
+ if upgrade and old_files:
2448
+ stale_candidates.append((name, old_files, [f["path"] for f in files]))
2449
+
2450
+ # Po instalacji kernela – przebuduj initramfs
2451
+ if _is_kernel_package(name):
2452
+ _rebuild_initramfs(deploy_dir)
2453
+ else:
2454
+ print("❌")
2455
+ failed.append(name)
2456
+ break # PRZERWIJ – błąd instalacji
2457
+
2458
+ # --- Rollback całej transakcji jeśli cokolwiek zawiodło ---
2459
+ if failed:
2460
+ print(f"\n ↩ Cofanie transakcji ({len(failed)} błędów)...")
2461
+ _rollback_transaction(installed_db, snapshot, all_installed_files,
2462
+ deploy_dir, immutable, backups=all_backups)
2463
+ if backup_root:
2464
+ shutil.rmtree(backup_root, ignore_errors=True)
2465
+ _record_transaction("upgrade" if upgrade else "install", to_install, False, snapshot)
2466
+ return 1
2467
+
2468
+ # --- Po sukcesie transakcji: usuń nieaktualne pliki starych wersji (upgrade).
2469
+ # Usunięte pliki trafiają do backupu, aby `pag rollback` mógł je przywrócić.
2470
+ for pkg_name, old_files, new_paths in stale_candidates:
2471
+ _remove_stale_files(pkg_name, old_files, new_paths, installed_db, deploy_dir,
2472
+ backup_root, all_backups)
2473
+
2474
+ save_json(INSTALLED_DB, installed_db)
2475
+ save_world(world)
2476
+ _record_transaction("upgrade" if upgrade else "install", to_install, True, snapshot,
2477
+ file_journal=all_installed_files,
2478
+ upgrade_backups={dst: bp for bp, dst in all_backups} if all_backups else None,
2479
+ upgrade_backup_root=backup_root)
2480
+
2481
+ # Zachowaj backupy bieżącej transakcji (dla `pag rollback`), usuń starsze.
2482
+ if backup_root:
2483
+ _purge_old_backups(keep_root=backup_root)
2484
+
2485
+ # --- Tryb immutable: przełącz na nowy deployment ---
2486
+ if immutable and not failed:
2487
+ _refresh_dynamic_linker_cache(deploy_dir)
2488
+ print(f"\n 🔄 Przełączanie na deployment {deploy_id}...")
2489
+ _switch_deployment(deploy_dir)
2490
+ print(f" ✅ Aktywny deployment: {deploy_id}")
2491
+ _update_grub_config()
2492
+ cmd_deploy_cleanup(keep=5) # Zostawia 5 najnowszych deploymentów
2493
+ print(f" 💡 Restart wymagany do przeładowania systemu.")
2494
+ else:
2495
+ _refresh_dynamic_linker_cache()
2496
+ # Hooki zbiorcze – raz na transakcję (fc-cache itp.), tylko gdy pliki
2497
+ # trafiły do realnego systemu (nie do deploymentu).
2498
+ _process_triggers(all_installed_files)
2499
+
2500
+ print(f"\n✅ {_('installed', len(to_install))}")
2501
+ return 0
2502
+
2503
+
2504
+def _rollback_transaction(installed_db: dict, snapshot: dict,
2505
+ installed_files: List[str],
2506
+ deploy_dir: str, is_immutable: bool,
2507
+ backups: Optional[List[Tuple[str, str]]] = None):
2508
+ """
2509
+ Cofa WSZYSTKIE pakiety zainstalowane w bieżącej transakcji.
2510
+ Przywraca installed_db do stanu sprzed transakcji.
2511
+ Usuwa fizyczne pliki z systemu (lub deploymentu w trybie immutable).
2512
+ Jeśli podano `backups` (upgrade) – przywraca stare wersje nadpisanych plików.
2513
+ """
2514
+ # Przywróć installed_db
2515
+ installed_db.clear()
2516
+ installed_db.update(snapshot)
2517
+
2518
+ root = deploy_dir if is_immutable else PAG_ROOT
2519
+ backup_map = {dst: src for src, dst in (backups or [])}
2520
+
2521
+ # Przywróć stare wersje z backupów (upgrade)
2522
+ for dst, bpath in backup_map.items():
2523
+ full = os.path.join(root, dst.lstrip("/"))
2524
+ if os.path.lexists(bpath):
2525
+ try:
2526
+ os.makedirs(os.path.dirname(full), exist_ok=True)
2527
+ os.replace(bpath, full)
2528
+ except OSError:
2529
+ pass
2530
+
2531
+ # Usuń nowe pliki (które nie miały poprzedniej wersji)
2532
+ for fpath in reversed(installed_files):
2533
+ if fpath in backup_map:
2534
+ continue
2535
+ full = os.path.join(root, fpath.lstrip("/"))
2536
+ if os.path.isfile(full) or os.path.islink(full):
2537
+ try:
2538
+ os.remove(full)
2539
+ except OSError:
2540
+ pass
2541
+
2542
+ # Wyczyść puste katalogi
2543
+ dirs_to_check = set()
2544
+ for fpath in installed_files:
2545
+ parent = os.path.dirname(fpath)
2546
+ while parent and parent != "/":
2547
+ dirs_to_check.add(parent)
2548
+ parent = os.path.dirname(parent)
2549
+ for d in sorted(dirs_to_check, key=len, reverse=True):
2550
+ full_d = os.path.join(root, d.lstrip("/"))
2551
+ if os.path.isdir(full_d):
2552
+ try:
2553
+ os.rmdir(full_d)
2554
+ except OSError:
2555
+ pass
2556
+
2557
+ # W trybie immutable: usuń nieudany deployment
2558
+ if is_immutable and deploy_dir:
2559
+ shutil.rmtree(deploy_dir, ignore_errors=True)
2560
+
2561
+ save_json(INSTALLED_DB, snapshot)
2562
+
2563
+
2564
+# =============================================================================
2565
+# USUWANIE
2566
+# =============================================================================
2567
+
2568
+def cmd_remove(package_names):
2569
+ installed_db = load_json(INSTALLED_DB)
2570
+ world = load_world()
2571
+ snapshot = json.loads(json.dumps(installed_db))
2572
+ removed = []
2573
+ removed_files = []
2574
+
2575
+ total = len(package_names)
2576
+ for i, name in enumerate(package_names, 1):
2577
+ if name not in installed_db:
2578
+ print(f" ⚠ {name}: not installed"); continue
2579
+
2580
+ # Pasek postępu
2581
+ pct = (i - 1) / total * 100
2582
+ filled = int(25 * pct / 100)
2583
+ print(f" 🗑 [{'█' * filled + '░' * (25 - filled)}] {i}/{total} ({pct:.0f}%) ", end="\r", file=sys.stderr, flush=True)
2584
+
2585
+ print(f"🗑 {name}-{installed_db[name]['version']} ...", end=" ", flush=True)
2586
+
2587
+ # Pre-remove hook (jeśli dostępny w staging)
2588
+ _run_hook_for_installed(name, "pre-remove")
2589
+
2590
+ count, rm_files = _safe_remove_files(name, installed_db)
2591
+ del installed_db[name]
2592
+ world.discard(name)
2593
+ removed.append(name)
2594
+ removed_files.extend(rm_files)
2595
+ print(f"✅ ({count} files)")
2596
+
2597
+ # Post-remove hook + sprzątanie zapisanych hooków
2598
+ _run_hook_for_installed(name, "post-remove")
2599
+ shutil.rmtree(os.path.join(PAG_DB, "hooks", name), ignore_errors=True)
2600
+
2601
+ save_json(INSTALLED_DB, installed_db)
2602
+ save_world(world)
2603
+ _record_transaction("remove", removed, True, snapshot)
2604
+
2605
+ print(file=sys.stderr) # wyczyść linię paska postępu
2606
+
2607
+ if not removed: return 0
2608
+ print(f"\n✅ Removed {len(removed)}.")
2609
+ _process_triggers(removed_files)
2610
+
2611
+ orphans = _find_orphans(installed_db, world)
2612
+ if orphans:
2613
+ print(f"\n💡 {_('orphans_found', len(orphans), ', '.join(sorted(orphans)[:10]))}")
2614
+ print(" 'pag remove-orphans' to clean up.")
2615
+ return 0
2616
+
2617
+def _run_hook_for_installed(pkg_name, hook_name):
2618
+ """Próbuje uruchomić hook z katalogu pakietu (jeśli został zapisany)."""
2619
+ hook_dir = os.path.join(PAG_DB, "hooks", pkg_name)
2620
+ if os.path.isdir(hook_dir):
2621
+ ver = load_json(INSTALLED_DB).get(pkg_name, {}).get("version", "")
2622
+ _run_hook(hook_dir, hook_name, PackageInfo({"name": pkg_name, "version": ver}))
2623
+
2624
+
2625
+# =============================================================================
2626
+# TRIGGERS – hooki zbiorcze (raz na transakcję, nie per pakiet)
2627
+# =============================================================================
2628
+# Wzorem pacman/dpkg: pakiet/administrator deklaruje zainteresowanie ścieżkami,
2629
+# a pasujący trigger uruchamia się DOKŁADNIE RAZ na końcu transakcji
2630
+# (np. fc-cache, glib-compile-schemas, update-desktop-database) zamiast po
2631
+# każdym pakiecie z osobna.
2632
+
2633
+TRIGGERS_DIR = PAG_CONF + "/triggers"
2634
+
2635
+DEFAULT_TRIGGERS = [
2636
+ {"name": "font-cache", "paths": ["/usr/share/fonts/", "/usr/local/share/fonts/"],
2637
+ "run": "fc-cache -fs"},
2638
+ {"name": "glib-schemas", "paths": ["/usr/share/glib-2.0/schemas/"],
2639
+ "run": "glib-compile-schemas /usr/share/glib-2.0/schemas"},
2640
+ {"name": "desktop-database", "paths": ["/usr/share/applications/"],
2641
+ "run": "update-desktop-database -q /usr/share/applications"},
2642
+ {"name": "mime-database", "paths": ["/usr/share/mime/"],
2643
+ "run": "update-mime-database /usr/share/mime"},
2644
+]
2645
+
2646
+def _load_triggers() -> List[dict]:
2647
+ """Ładuje triggery: domyślne (tylko gdy binarka istnieje) + /etc/pag/triggers/*.json."""
2648
+ out = []
2649
+ for t in DEFAULT_TRIGGERS:
2650
+ bin_name = t["run"].split()[0]
2651
+ if shutil.which(bin_name):
2652
+ out.append(dict(t))
2653
+ if os.path.isdir(TRIGGERS_DIR):
2654
+ for fn in sorted(os.listdir(TRIGGERS_DIR)):
2655
+ if not fn.endswith(".json"):
2656
+ continue
2657
+ try:
2658
+ with open(os.path.join(TRIGGERS_DIR, fn)) as f:
2659
+ data = json.load(f)
2660
+ except (OSError, json.JSONDecodeError):
2661
+ continue
2662
+ if isinstance(data, dict):
2663
+ data = [data]
2664
+ for t in data:
2665
+ if isinstance(t, dict) and t.get("name") and t.get("paths") and t.get("run"):
2666
+ out.append(t)
2667
+ return out
2668
+
2669
+def _process_triggers(touched_paths: List[str]):
2670
+ """Uruchamia pasujące triggery RAZ na końcu transakcji (best-effort)."""
2671
+ if not touched_paths:
2672
+ return
2673
+ if os.environ.get("PAG_NO_HOOKS", "") == "1":
2674
+ return
2675
+ import shlex as _shlex
2676
+ matched = []
2677
+ for trig in _load_triggers():
2678
+ if any(path.startswith(p) for p in trig["paths"] for path in touched_paths):
2679
+ matched.append(trig)
2680
+ for trig in matched:
2681
+ run = trig["run"]
2682
+ print(f" ⚡ Trigger: {trig['name']} ({run})")
2683
+ try:
2684
+ r = subprocess.run(_shlex.split(run), capture_output=True, text=True, timeout=120)
2685
+ _audit(f"TRIGGER {trig['name']}: {run} rc={r.returncode}")
2686
+ if r.returncode != 0:
2687
+ print(f" ⚠ rc={r.returncode}: {(r.stderr or r.stdout or '').strip()[:160]}")
2688
+ except subprocess.TimeoutExpired:
2689
+ print(f" ⚠ trigger {trig['name']} przekroczył limit czasu (120 s)")
2690
+ _audit(f"TRIGGER {trig['name']} TIMEOUT")
2691
+ except Exception as e:
2692
+ print(f" ⚠ trigger {trig['name']}: {e}")
2693
+
2694
+# =============================================================================
2695
+# UPDATE / UPGRADE / LIST / SEARCH / INFO / VERIFY
2696
+# =============================================================================
2697
+
2698
+def _cleanup_tmp_files(*paths):
2699
+ """Usuwa tymczasowe pliki (np. .pag.new) po nieudanej operacji."""
2700
+ for p in paths:
2701
+ try:
2702
+ if os.path.isfile(p):
2703
+ os.remove(p)
2704
+ except OSError:
2705
+ pass
2706
+
2707
+
2708
+def cmd_self_update():
2709
+ """Aktualizuje samego klienta pag z repo (podpisany /stable/pag).
2710
+
2711
+ Kolejność: pobierz → weryfikacja GPG (+ fingerprint repo) → SHA256 →
2712
+ kontrola składni (compile) → backup → atomowe os.replace. Nowa wersja
2713
+ idzie do tego samego katalogu (/usr/local/bin/.pag.new), dzięki czemu
2714
+ podmiana jest atomowa; jeśli system padnie w trakcie, stary pag zostaje.
2715
+ """
2716
+ repos = get_repos()
2717
+ if not repos:
2718
+ print("❌ Brak repozytoriów w konfiguracji.")
2719
+ return 1
2720
+ base = repos[0]
2721
+ dst = "/usr/local/bin/pag"
2722
+ dst_new = dst + ".new"
2723
+ dst_bak = dst + ".bak"
2724
+ print(f"🔄 Sprawdzam aktualizację pag z {base}...")
2725
+ try:
2726
+ with urlopen(Request(f"{base}/pag", headers={"User-Agent": "pag/3.0"}), timeout=20) as r:
2727
+ data = r.read()
2728
+ with urlopen(Request(f"{base}/pag.asc", headers={"User-Agent": "pag/3.0"}), timeout=20) as r:
2729
+ sig = r.read()
2730
+ except Exception as e:
2731
+ print(f" ❌ Nie można pobrać pag: {e}")
2732
+ return 1
2733
+
2734
+ # Zapisz nową wersję w katalogu docelowym (ta sama partycja → atomowy rename)
2735
+ with open(dst_new, "wb") as f:
2736
+ f.write(data)
2737
+ with open(dst_new + ".asc", "wb") as f:
2738
+ f.write(sig)
2739
+
2740
+ # --- 1. Weryfikacja podpisu GPG – bez tego nie instalujemy ---
2741
+ insecure = os.environ.get("PAG_INSECURE", "") == "1"
2742
+ ok, fp = _gpg_verify_fp(dst_new + ".asc", dst_new)
2743
+ if not ok:
2744
+ # Automatyczny import klucza (TOFU) – jak w _verify_repo_sig
2745
+ res = _gpg_run("--verify", dst_new + ".asc", dst_new,
2746
+ capture_output=True, text=True)
2747
+ _stderr = res.stderr.decode(errors="replace") if isinstance(res.stderr, bytes) else (res.stderr or "")
2748
+ if "public key" in _stderr.lower() and "no public key" in _stderr.lower():
2749
+ try:
2750
+ with urlopen(Request(f"{base}/paganos.asc", headers={"User-Agent": "pag/3.0"}), timeout=20) as r:
2751
+ keydata = r.read()
2752
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".asc") as tmp:
2753
+ tmp.write(keydata); tmp.flush()
2754
+ _gpg_run("--import", tmp.name, capture_output=True, timeout=30)
2755
+ os.unlink(tmp.name)
2756
+ print(f" 🔑 Importowano klucz repo z {base}/paganos.asc")
2757
+ ok, fp = _gpg_verify_fp(dst_new + ".asc", dst_new)
2758
+ except Exception:
2759
+ pass
2760
+ if not ok:
2761
+ if insecure:
2762
+ print(" ⚠ Nieprawidłowy podpis aktualizacji (PAG_INSECURE – ignoruję)")
2763
+ else:
2764
+ print(" ❌ Nieprawidłowy podpis aktualizacji – nie aktualizuję.")
2765
+ _cleanup_tmp_files(dst_new, dst_new + ".asc")
2766
+ return 1
2767
+ # Sprawdź fingerprint względem przypiętego klucza repo
2768
+ pinned = _repo_pinned_fp(base)
2769
+ if pinned:
2770
+ if not fp:
2771
+ print(" ❌ Nie można potwierdzić fingerprintu podpisu aktualizacji.")
2772
+ _cleanup_tmp_files(dst_new, dst_new + ".asc")
2773
+ return 1
2774
+ if fp != pinned.upper():
2775
+ if insecure:
2776
+ print(" ⚠ Podpis aktualizacji innym kluczem (PAG_INSECURE – ignoruję)")
2777
+ else:
2778
+ print(" ❌ [SECURITY ERROR] Podpis aktualizacji innym kluczem niż repo!")
2779
+ print(f" Oczekiwany: {pinned}, Otrzymany: {fp}")
2780
+ _cleanup_tmp_files(dst_new, dst_new + ".asc")
2781
+ return 1
2782
+
2783
+ # --- 2. Weryfikacja SHA256 (jeśli repo publikuje pag.sha256) ---
2784
+ try:
2785
+ with urlopen(Request(f"{base}/pag.sha256", headers={"User-Agent": "pag/3.0"}), timeout=15) as r:
2786
+ sha = r.read().decode().strip().split()[0]
2787
+ if sha:
2788
+ actual = hashlib.sha256(data).hexdigest()
2789
+ if actual.lower() != sha.lower():
2790
+ print(f" ❌ SHA256 niezgodny! Oczekiwano {sha}, jest {actual}")
2791
+ _cleanup_tmp_files(dst_new, dst_new + ".asc")
2792
+ return 1
2793
+ print(" ✅ SHA256 zgodny")
2794
+ except Exception:
2795
+ # Brak pag.sha256 w repo – opcjonalne; nie blokuj aktualizacji.
2796
+ pass
2797
+
2798
+ # --- 3. Kontrola składni (nie uruchamiaj uszkodzonego/poddanego edycji pliku) ---
2799
+ try:
2800
+ compile(data, "pag", "exec")
2801
+ except SyntaxError as e:
2802
+ print(f" ❌ Błąd składni w nowym pag: {e}")
2803
+ _cleanup_tmp_files(dst_new, dst_new + ".asc")
2804
+ return 1
2805
+
2806
+ m = (re.search(rb'PAG_VERSION\s*=\s*"(\d+\.\d+\.\d+[a-z]?)"', data[:3000])
2807
+ or re.search(rb"v(\d+\.\d+\.\d+[a-z]?)", data[:3000]))
2808
+ new_ver = m.group(1).decode() if m else "?"
2809
+ print(f" ✅ Pobrano pag {new_ver} (obecny {PAG_VERSION}), podpis zweryfikowany")
2810
+
2811
+ # --- 4. Backup + atomowa podmiana ---
2812
+ if os.path.exists(dst):
2813
+ shutil.copy2(dst, dst_bak)
2814
+ os.chmod(dst_new, 0o755)
2815
+ os.replace(dst_new, dst) # atomowe na tym samym FS
2816
+ try:
2817
+ if os.path.exists(dst_new + ".asc"):
2818
+ os.remove(dst_new + ".asc")
2819
+ except OSError:
2820
+ pass
2821
+ print(f" ✅ Zainstalowano nowy pag. Stary zachowany jako {dst_bak}")
2822
+ print(" Uruchom ponownie pag, aby użyć nowej wersji.")
2823
+ return 0
2824
+
2825
+
2826
+def _candidate_newer(rp, inst):
2827
+ """Czy pakiet z repo jest nowszy od zainstalowanego.
2828
+ Porównuje (version, release): sam bump pkgrel (np. auto-rebuild modułów
2829
+ po aktualizacji jądra: nvidia-kernel-618 610.57.04-1 -> -2) też musi być
2830
+ widziany przez `pag update`. Stare rekordy instalacji (bez pola release)
2831
+ traktujemy jak release=1 – nie generują churnu, dopóki nie wrócą do
2832
+ reinstalacji/zmiany wersji."""
2833
+ rv = getattr(rp, "version", "0")
2834
+ iv = inst.get("version", "0")
2835
+ if _version_newer(rv, iv):
2836
+ return True
2837
+ if rv != iv:
2838
+ return False
2839
+ rr = int(getattr(rp, "release", 1) or 1)
2840
+ ir = int(inst.get("release", 1) or 1)
2841
+ return rr > ir
2842
+
2843
+
2844
+def _pending_updates() -> List[str]:
2845
+ """Zainstalowane pakiety z nowszą wersją/release w repo (bez przypiętych)."""
2846
+ installed = load_json(INSTALLED_DB)
2847
+ pinned = load_json(PINNED_FILE)
2848
+ repo = fetch_all_packages()
2849
+ if not repo:
2850
+ return []
2851
+ return [n for n, i in installed.items()
2852
+ if n not in pinned and (rp := repo.get(n)) and _candidate_newer(rp, i)]
2853
+
2854
+def cmd_update(do_upgrade: bool = False):
2855
+ """`pag sync` / `pag update` – odświeżenie indeksów + raport aktualizacji.
2856
+
2857
+ sync → tylko odświeżenie indeksów + info: „jest X pakietów do
2858
+ zaktualizowania – wpisz: pag update".
2859
+ update → odświeżenie indeksów + AKTUALIZACJA PAKIETÓW (pakiety, nie system).
2860
+ Pomijamy cache TTL (inaczej nowe pakiety/aktualizacje są niewidoczne nawet
2861
+ przez godzinę). Pełne pobranie + weryfikacja GPG przy każdym odświeżeniu.
2862
+ """
2863
+ force = True
2864
+ print("🔄 Refreshing indexes...")
2865
+ for repo_url in get_repos():
2866
+ pkgs = fetch_repo_index(repo_url, force=force)
2867
+ cp = _repo_cache_path(repo_url)
2868
+ has_sig = os.path.exists(cp + ".sig")
2869
+ print(f" {'✅' if pkgs is not None else '❌'} {repo_url}: {len(pkgs or [])} pkgs {'🔐' if has_sig else '⚠'}")
2870
+ print(f"✅ {_('indexes_refreshed')}")
2871
+
2872
+ # Powiadomienie o nowszej wersji pag (repo.json["pag_version"])
2873
+ try:
2874
+ for r in get_repos():
2875
+ cp = _repo_cache_path(r)
2876
+ if os.path.exists(cp):
2877
+ d = json.load(open(cp))
2878
+ rv = d.get("pag_version", "")
2879
+ if rv and rv != PAG_VERSION:
2880
+ print(f" ⚠ Nowa wersja pag {rv} dostępna – uruchom: pag self-update")
2881
+ except Exception:
2882
+ pass
2883
+
2884
+ # Raport: pakiety do aktualizacji
2885
+ pending = _pending_updates()
2886
+ if not pending:
2887
+ print(f"✅ {_('all_up_to_date')}")
2888
+ return 0
2889
+ print(f"{_('updates_available', len(pending))}")
2890
+ installed = load_json(INSTALLED_DB)
2891
+ repo = fetch_all_packages()
2892
+ for n in pending:
2893
+ print(f" {n}: {installed.get(n, {}).get('version', '?')} → {repo[n].version}")
2894
+ if not do_upgrade:
2895
+ return 0 # sync: tylko informacja
2896
+ if not _ask_confirm():
2897
+ return 0
2898
+ return cmd_install(pending, upgrade=True)
2899
+
2900
+def _initramfs_stale() -> bool:
2901
+ """Czy initramfs jest starszy niż najnowsze jądro (wymaga przebudowy)."""
2902
+ try:
2903
+ kernels = [k for k in os.listdir("/boot") if k.startswith("vmlinuz-")] if os.path.isdir("/boot") else []
2904
+ if not kernels:
2905
+ return False
2906
+ newest = max(os.path.getmtime(os.path.join("/boot", k)) for k in kernels)
2907
+ initrd = "/boot/initramfs.img"
2908
+ return (not os.path.exists(initrd)) or os.path.getmtime(initrd) < newest
2909
+ except Exception:
2910
+ return False
2911
+
2912
+def cmd_upgrade():
2913
+ """`pag upgrade` – aktualizacja SYSTEMU: pakiety + kernel/initramfs/GRUB."""
2914
+ rc = cmd_update(do_upgrade=True)
2915
+ if rc != 0:
2916
+ return rc
2917
+ # System: dopilnuj initramfs (gdyby kernel był nowszy) + GRUB (immutable)
2918
+ if _initramfs_stale():
2919
+ print(" 🐧 Przebudowa initramfs (nowsze jądro)...")
2920
+ _rebuild_initramfs()
2921
+ try:
2922
+ if _load_deployments():
2923
+ _update_grub_config()
2924
+ except Exception:
2925
+ pass
2926
+ return 0
2927
+
2928
+def cmd_list(installed_only=False):
2929
+ if installed_only:
2930
+ db = load_json(INSTALLED_DB)
2931
+ pinned = load_json(PINNED_FILE)
2932
+ if not db: print("No packages installed."); return
2933
+ print(f"Installed ({len(db)}):")
2934
+ for n, i in sorted(db.items()):
2935
+ pin = " 📌" if n in pinned else ""
2936
+ print(f" {n}-{i['version']}{pin} – {i.get('description','')}")
2937
+ else:
2938
+ pkgs = fetch_all_packages()
2939
+ installed = load_json(INSTALLED_DB)
2940
+ pinned = load_json(PINNED_FILE)
2941
+ print(f"Available ({len(pkgs)}):")
2942
+ for n, p in sorted(pkgs.items()):
2943
+ m = "✓" if n in installed else " "
2944
+ extra = f" [installed: {installed[n]['version']}]" if n in installed else ""
2945
+ if n in pinned: extra += " 📌"
2946
+ print(f" [{m}] {n}-{p.version} – {p.description}{extra}")
2947
+
2948
+def cmd_search(query):
2949
+ pkgs = fetch_all_packages()
2950
+ results = [(n,p) for n,p in pkgs.items() if query.lower() in n.lower() or query.lower() in p.description.lower()]
2951
+ if not results: print(f"❌ No results for: {query}"); return
2952
+ installed = load_json(INSTALLED_DB)
2953
+ print(f"Results for '{query}' ({len(results)}):")
2954
+ for n,p in sorted(results):
2955
+ print(f" [{'✓' if n in installed else ' '}] {n}-{p.version}")
2956
+ print(f" {p.description}")
2957
+
2958
+
2959
+def _smart_search(query: str) -> int:
2960
+ """
2961
+ Inteligentne wyszukiwanie: repo PaganOS + Flathub.
2962
+ Uruchamiane gdy użytkownik wpisze `pag <nazwa>` zamiast `pag install <nazwa>`.
2963
+ Pokazuje dostępne źródła i sugeruje komendy instalacji.
2964
+ """
2965
+ # 1. Repo PaganOS
2966
+ try:
2967
+ pkgs = fetch_all_packages()
2968
+ except Exception:
2969
+ pkgs = {}
2970
+ repo_lower = [(n, p) for n, p in pkgs.items()
2971
+ if query.lower() in n.lower() or query.lower() in p.description.lower()]
2972
+
2973
+ # 2. Flathub (jeśli dostępny)
2974
+ flat = _flatpak_search_raw(query) if _check_flatpak(quiet=True) else []
2975
+
2976
+ if not repo_lower and not flat:
2977
+ print(f"\n ❌ '{query}' — nie znaleziono.")
2978
+ print(f" Repo PaganOS: pag search {query}")
2979
+ if _check_flatpak(quiet=True):
2980
+ print(f" Flathub: pag flatpak search {query}")
2981
+ print(f" Dodaj repo: pag repo-add <url>")
2982
+ return 1
2983
+
2984
+ installed = load_json(INSTALLED_DB)
2985
+
2986
+ # ── Repo PaganOS ──
2987
+ if repo_lower:
2988
+ exact = [(n, p) for n, p in repo_lower if n.lower() == query.lower()]
2989
+ show = (exact or repo_lower)[:6]
2990
+ print(f"\n 📦 PaganOS — '{query}':")
2991
+ for n, p in sorted(show):
2992
+ mark = "✓" if n in installed else " "
2993
+ desc = p.description[:70] if len(p.description) > 75 else p.description
2994
+ print(f" [{mark}] {n}-{p.version}")
2995
+ if desc:
2996
+ print(f" {desc}")
2997
+ if len(repo_lower) > 6:
2998
+ print(f" ... i {len(repo_lower) - 6} więcej (pag search {query})")
2999
+
3000
+ # ── Flathub ──
3001
+ if flat:
3002
+ print(f"\n 📦 Flathub — '{query}':")
3003
+ for r in flat[:5]:
3004
+ mark = "✓" if r.get("installed") else " "
3005
+ name = r.get("name") or r.get("application", "?")
3006
+ desc = (r.get("description") or "")[:65]
3007
+ print(f" [{mark}] {name}")
3008
+ if desc:
3009
+ print(f" {desc}")
3010
+ if len(flat) > 5:
3011
+ print(f" ... i {len(flat) - 5} więcej (pag flatpak search {query})")
3012
+
3013
+ # ── Sugestie instalacji ──
3014
+ print()
3015
+ if repo_lower:
3016
+ 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]
3017
+ if best in installed:
3018
+ print(f" ✓ {best} jest już zainstalowany ({installed[best]['version']})")
3019
+ else:
3020
+ print(f" 💡 sudo pag install {best}")
3021
+ if flat:
3022
+ best_fp = flat[0].get("application") or flat[0].get("name", query)
3023
+ print(f" 💡 pag flatpak install {best_fp}")
3024
+
3025
+ return 0
3026
+
3027
+def cmd_info(name):
3028
+ pkgs = fetch_all_packages()
3029
+ p = pkgs.get(name)
3030
+ info = load_json(INSTALLED_DB).get(name)
3031
+ if not p and not info: print(f"❌ '{name}' not found."); return 1
3032
+ print(f"📦 {name}")
3033
+ if p:
3034
+ print(f" Version (repo): {p.version}")
3035
+ print(f" Description: {p.description}")
3036
+ print(f" Size: {p.size_bytes/1048576:.1f} MB")
3037
+ print(f" SHA256: {p.sha256[:32]}...")
3038
+ print(f" GPG: {p.gpg_fp or 'none'}")
3039
+ print(f" Dependencies: {', '.join(p.dependencies) if p.dependencies else '(none)'}")
3040
+ if info:
3041
+ print(f" Installed: {info['version']} ({info.get('installed_at','?')})")
3042
+
3043
+def cmd_files(name):
3044
+ if name not in load_json(INSTALLED_DB):
3045
+ print(f"❌ '{name}' not installed."); return 1
3046
+ files = _db_get_package_files(name)
3047
+ print(f"Files in {name} ({len(files)}):")
3048
+ for f in sorted(files): print(f" {f}")
3049
+
3050
+def cmd_verify(deep=False):
3051
+ installed = load_json(INSTALLED_DB)
3052
+ if not installed: print("Nothing to verify."); return
3053
+ errors = []
3054
+
3055
+ for name in installed:
3056
+ for fpath in _db_get_package_files(name):
3057
+ full = os.path.join(PAG_ROOT, fpath.lstrip("/"))
3058
+ if not (os.path.exists(full) or os.path.islink(full)):
3059
+ errors.append(f" ❌ {name}: missing {fpath}")
3060
+ elif deep:
3061
+ checksums = _db_get_all_file_checksums()
3062
+ expected = checksums.get(fpath, "")
3063
+ if expected:
3064
+ actual = _sha256_file(full)
3065
+ if actual != expected:
3066
+ errors.append(f" ❌ {name}: SHA256 mismatch {fpath}")
3067
+
3068
+ if errors:
3069
+ print(f"❌ {_('verify_errors', len(errors))}")
3070
+ for e in errors[:50]: print(e)
3071
+ return 1
3072
+ total = _db_count_files()
3073
+ print(f"✅ {_('verify_ok', total)}")
3074
+
3075
+# =============================================================================
3076
+# PINNING / CLEAN / ORPHANS / REPO / FLATPAK
3077
+# =============================================================================
3078
+
3079
+def cmd_pin(name, version=""):
3080
+ pinned = load_json(PINNED_FILE)
3081
+ if version:
3082
+ pinned[name] = version
3083
+ else:
3084
+ info = load_json(INSTALLED_DB).get(name, {})
3085
+ pinned[name] = info.get("version", "?")
3086
+ save_json(PINNED_FILE, pinned)
3087
+ print(f"📌 {name} {_('pinned_to')} {pinned[name]}")
3088
+
3089
+def cmd_unpin(name):
3090
+ pinned = load_json(PINNED_FILE)
3091
+ if name in pinned:
3092
+ del pinned[name]; save_json(PINNED_FILE, pinned)
3093
+ print(f"🔓 {name} {_('unpinned')}")
3094
+ else:
3095
+ print(f"⚠ {name} {_('not_pinned')}")
3096
+
3097
+def cmd_pinned():
3098
+ pinned = load_json(PINNED_FILE)
3099
+ if not pinned: print(_("no_pinned")); return
3100
+ print(_("pinned_list", len(pinned)))
3101
+ for n,v in sorted(pinned.items()): print(f" 📌 {n} = {v}")
3102
+
3103
+def cmd_clean():
3104
+ if os.path.isdir(PAG_CACHE):
3105
+ count = size = 0
3106
+ for f in os.listdir(PAG_CACHE):
3107
+ fp = os.path.join(PAG_CACHE, f)
3108
+ if os.path.isfile(fp):
3109
+ size += os.path.getsize(fp); os.remove(fp); count += 1
3110
+ print(f"✅ {_('cache_cleared', count, size/1048576)}")
3111
+
3112
+def cmd_remove_orphans():
3113
+ installed = load_json(INSTALLED_DB)
3114
+ world = load_world()
3115
+ orphans = _find_orphans(installed, world)
3116
+ if not orphans: print("✅ No orphans."); return
3117
+ print(f"Orphans ({len(orphans)}):")
3118
+ for n in sorted(orphans): print(f" {n}-{installed[n]['version']}")
3119
+ if not _ask_confirm():
3120
+ return
3121
+ cmd_remove(list(orphans))
3122
+
3123
+
3124
+# =============================================================================
3125
+# PROVIDES – PAKIETY WIRTUALNE
3126
+# =============================================================================
3127
+
3128
+PROVIDES_MAP = {
3129
+ "pkgconfig(glib-2.0)": "glib",
3130
+ "pkgconfig(gobject-introspection-1.0)": "gobject-introspection",
3131
+ "pkgconfig(gtk+-3.0)": "gtk",
3132
+ "pkgconfig(gtk4)": "gtk",
3133
+ "pkgconfig(zlib)": "zlib",
3134
+ "pkgconfig(libffi)": "libffi",
3135
+ "pkgconfig(expat)": "expat",
3136
+ "pkgconfig(libsystemd)": "systemd",
3137
+ "pkgconfig(dbus-1)": "dbus",
3138
+ "pkgconfig(mount)": "util-linux",
3139
+ "pkgconfig(blkid)": "util-linux",
3140
+ "pkgconfig(libcap)": "libcap",
3141
+ "pkgconfig(liblzma)": "xz",
3142
+ "pkgconfig(libzstd)": "zstd",
3143
+ "pkgconfig(bzip2)": "bzip2",
3144
+ "pkgconfig(libcurl)": "curl",
3145
+ "pkgconfig(openssl)": "openssl",
3146
+ "pkgconfig(libpcre2-8)": "pcre2",
3147
+ "pkgconfig(libxml-2.0)": "libxml2",
3148
+ "pkgconfig(libxslt)": "libxslt",
3149
+ "pkgconfig(freetype2)": "freetype",
3150
+ "pkgconfig(fontconfig)": "fontconfig",
3151
+ "pkgconfig(harfbuzz)": "harfbuzz",
3152
+ "pkgconfig(cairo)": "cairo",
3153
+ "pkgconfig(pango)": "pango",
3154
+ "pkgconfig(xt)": "xorg-libxt",
3155
+ "pkgconfig(xmu)": "xorg-libxmu",
3156
+ "pkgconfig(ice)": "xorg-libice",
3157
+ "pkgconfig(sm)": "xorg-libsm",
3158
+ "pkgconfig(x11)": "xorg-libx11",
3159
+ "pkgconfig(xext)": "xorg-libxext",
3160
+ "pkgconfig(xrandr)": "xorg-libxrandr",
3161
+ "pkgconfig(xfixes)": "xorg-libxfixes",
3162
+ "pkgconfig(xcursor)": "xorg-libxcursor",
3163
+ "pkgconfig(xinerama)": "xorg-libxinerama",
3164
+ "pkgconfig(xrender)": "xorg-libxrender",
3165
+ "pkgconfig(xau)": "xorg-libxau",
3166
+ "pkgconfig(xcb)": "xorg-libxcb",
3167
+ "pkgconfig(xdamage)": "xorg-libxdamage",
3168
+ "pkgconfig(xcomposite)": "xorg-libxcomposite",
3169
+ "pkgconfig(xft)": "xorg-libxft",
3170
+ "pkgconfig(xss)": "xorg-libxss",
3171
+ "pkgconfig(libsoup-3.0)": "libsoup3",
3172
+ "pkgconfig(libsoup-2.4)": "libsoup2",
3173
+ "pkgconfig(gdk-pixbuf-2.0)": "gdk-pixbuf2",
3174
+ "pkgconfig(libpng)": "libpng",
3175
+ "pkgconfig(libjpeg)": "libjpeg-turbo",
3176
+ "pkgconfig(libtiff-4)": "libtiff",
3177
+ "pkgconfig(ffi)": "libffi",
3178
+ # ── system / baza ──
3179
+ "pkgconfig(libcrypto)": "openssl",
3180
+ "pkgconfig(libssl)": "openssl",
3181
+ "pkgconfig(libudev)": "systemd",
3182
+ "pkgconfig(libmount)": "util-linux",
3183
+ "pkgconfig(libblkid)": "util-linux",
3184
+ "pkgconfig(uuid)": "util-linux",
3185
+ "pkgconfig(libexpat)": "expat",
3186
+ "pkgconfig(libpcre)": "pcre",
3187
+ "pkgconfig(ncursesw)": "ncurses",
3188
+ "pkgconfig(tinfo)": "ncurses",
3189
+ "pkgconfig(panel)": "ncurses",
3190
+ "pkgconfig(readline)": "readline",
3191
+ "pkgconfig(libseccomp)": "libseccomp",
3192
+ "pkgconfig(pam)": "linux-pam",
3193
+ "pkgconfig(libxcrypt)": "libxcrypt",
3194
+ "pkgconfig(libcrypt)": "libxcrypt",
3195
+ "pkgconfig(libnsl)": "libnsl",
3196
+ "pkgconfig(liblz4)": "lz4",
3197
+ "pkgconfig(libevent)": "libevent",
3198
+ "pkgconfig(libarchive)": "libarchive",
3199
+ "pkgconfig(sqlite3)": "sqlite",
3200
+ "pkgconfig(libpq)": "postgresql",
3201
+ "pkgconfig(mysqlclient)": "mariadb",
3202
+ "pkgconfig(json-c)": "json-c",
3203
+ "pkgconfig(json-glib-1.0)": "json-glib",
3204
+ "pkgconfig(libunistring)": "libunistring",
3205
+ "pkgconfig(libidn2)": "libidn2",
3206
+ "pkgconfig(libpsl)": "libpsl",
3207
+ "pkgconfig(icu-uc)": "icu",
3208
+ "pkgconfig(icu-i18n)": "icu",
3209
+ "pkgconfig(icu-io)": "icu",
3210
+ "pkgconfig(gnutls)": "gnutls",
3211
+ "pkgconfig(nettle)": "nettle",
3212
+ "pkgconfig(hogweed)": "nettle",
3213
+ "pkgconfig(libgcrypt)": "libgcrypt",
3214
+ "pkgconfig(libgpg-error)": "libgpg-error",
3215
+ "pkgconfig(libassuan)": "libassuan",
3216
+ "pkgconfig(libusb-1.0)": "libusb",
3217
+ "pkgconfig(libusb)": "libusb",
3218
+ "pkgconfig(libgudev-1.0)": "libgudev",
3219
+ "pkgconfig(gudev-1.0)": "libgudev",
3220
+ "pkgconfig(polkit-gobject-1)": "polkit",
3221
+ "pkgconfig(polkit-agent-1)": "polkit",
3222
+ "pkgconfig(libpciaccess)": "libpciaccess",
3223
+ "pkgconfig(pixman-1)": "pixman",
3224
+ "pkgconfig(libdrm)": "libdrm",
3225
+ "pkgconfig(libva)": "libva",
3226
+ "pkgconfig(libva-drm)": "libva",
3227
+ "pkgconfig(libva-x11)": "libva",
3228
+ "pkgconfig(libva-wayland)": "libva",
3229
+ "pkgconfig(vdpau)": "libvdpau",
3230
+ "pkgconfig(libvdpau)": "libvdpau",
3231
+ "pkgconfig(libinput)": "libinput",
3232
+ "pkgconfig(libevdev)": "libevdev",
3233
+ "pkgconfig(mtdev)": "mtdev",
3234
+ # ── grafika / GL / multimedia ──
3235
+ "pkgconfig(gbm)": "mesa",
3236
+ "pkgconfig(gl)": "libglvnd",
3237
+ "pkgconfig(egl)": "libglvnd",
3238
+ "pkgconfig(glesv2)": "libglvnd",
3239
+ "pkgconfig(glx)": "libglvnd",
3240
+ "pkgconfig(vulkan)": "vulkan-loader",
3241
+ "pkgconfig(libxkbcommon)": "libxkbcommon",
3242
+ "pkgconfig(xkbcommon)": "libxkbcommon",
3243
+ "pkgconfig(xkbcommon-x11)": "libxkbcommon",
3244
+ "pkgconfig(xcb)": "xorg-libxcb",
3245
+ "pkgconfig(xcb-util)": "xcb-util",
3246
+ "pkgconfig(xcb-keysyms)": "xcb-util-keysyms",
3247
+ "pkgconfig(xcb-icccm)": "xcb-util-wm",
3248
+ "pkgconfig(xcb-cursor)": "xcb-util-cursor",
3249
+ "pkgconfig(xcb-renderutil)": "xcb-util-renderutil",
3250
+ "pkgconfig(xcb-image)": "xcb-util-image",
3251
+ "pkgconfig(xcb-errors)": "xcb-util-errors",
3252
+ "pkgconfig(wayland-client)": "wayland",
3253
+ "pkgconfig(wayland-server)": "wayland",
3254
+ "pkgconfig(wayland-cursor)": "wayland",
3255
+ "pkgconfig(wayland-egl)": "wayland",
3256
+ "pkgconfig(wayland-protocols)": "wayland-protocols",
3257
+ "pkgconfig(gstreamer-1.0)": "gstreamer",
3258
+ "pkgconfig(gstreamer-base-1.0)": "gstreamer",
3259
+ "pkgconfig(gstreamer-check-1.0)": "gstreamer",
3260
+ "pkgconfig(gstreamer-controller-1.0)": "gstreamer",
3261
+ "pkgconfig(gstreamer-app-1.0)": "gst-plugins-base",
3262
+ "pkgconfig(gstreamer-video-1.0)": "gst-plugins-base",
3263
+ "pkgconfig(gstreamer-audio-1.0)": "gst-plugins-base",
3264
+ "pkgconfig(gstreamer-pbutils-1.0)": "gst-plugins-base",
3265
+ "pkgconfig(gstreamer-fft-1.0)": "gst-plugins-base",
3266
+ "pkgconfig(gstreamer-riff-1.0)": "gst-plugins-base",
3267
+ "pkgconfig(gstreamer-rtp-1.0)": "gst-plugins-base",
3268
+ "pkgconfig(gstreamer-rtsp-1.0)": "gst-plugins-base",
3269
+ "pkgconfig(gstreamer-sdp-1.0)": "gst-plugins-base",
3270
+ "pkgconfig(gstreamer-net-1.0)": "gst-plugins-base",
3271
+ "pkgconfig(gstreamer-gl-1.0)": "gst-plugins-base",
3272
+ "pkgconfig(libpulse)": "libpulse",
3273
+ "pkgconfig(libpulse-simple)": "libpulse",
3274
+ "pkgconfig(libpulse-mainloop-glib)": "libpulse",
3275
+ "pkgconfig(alsa)": "alsa-lib",
3276
+ "pkgconfig(jack)": "jack2",
3277
+ "pkgconfig(libsamplerate)": "libsamplerate",
3278
+ "pkgconfig(sndfile)": "libsndfile",
3279
+ "pkgconfig(libavcodec)": "ffmpeg",
3280
+ "pkgconfig(libavformat)": "ffmpeg",
3281
+ "pkgconfig(libavutil)": "ffmpeg",
3282
+ "pkgconfig(libavfilter)": "ffmpeg",
3283
+ "pkgconfig(libswscale)": "ffmpeg",
3284
+ "pkgconfig(libswresample)": "ffmpeg",
3285
+ "pkgconfig(libpostproc)": "ffmpeg",
3286
+ "pkgconfig(SDL2)": "sdl2",
3287
+ "pkgconfig(SDL)": "sdl",
3288
+ "pkgconfig(SDL2_image)": "sdl2-image",
3289
+ "pkgconfig(SDL2_ttf)": "sdl2-ttf",
3290
+ "pkgconfig(SDL2_mixer)": "sdl2-mixer",
3291
+ "pkgconfig(SDL2_net)": "sdl2-net",
3292
+ "pkgconfig(libpng16)": "libpng",
3293
+ "pkgconfig(libwebp)": "libwebp",
3294
+ "pkgconfig(libwebpmux)": "libwebp",
3295
+ "pkgconfig(libwebpdemux)": "libwebp",
3296
+ "pkgconfig(libopenjp2)": "openjpeg2",
3297
+ "pkgconfig(lcms2)": "lcms2",
3298
+ "pkgconfig(libheif)": "libheif",
3299
+ "pkgconfig(libde265)": "libde265",
3300
+ "pkgconfig(x264)": "x264",
3301
+ "pkgconfig(x265)": "x265",
3302
+ # ── glib / gio ──
3303
+ "pkgconfig(gio-unix-2.0)": "glib",
3304
+ "pkgconfig(gmodule-2.0)": "glib",
3305
+ "pkgconfig(gthread-2.0)": "glib",
3306
+ "pkgconfig(girepository-2.0)": "gobject-introspection",
3307
+ "pkgconfig(girepository-1.0)": "gobject-introspection",
3308
+ "pkgconfig(libglib-2.0)": "glib",
3309
+ "pkgconfig(libgobject-2.0)": "glib",
3310
+}
3311
+
3312
+def _resolve_provides(name: str, repo: dict, installed: Optional[dict] = None) -> str:
3313
+ """Rozwija wirtualną nazwę pakietu do rzeczywistej nazwy.
3314
+
3315
+ Kolejność: repo → PROVIDES_MAP → wzorce → provides z repo.json →
3316
+ provides ZAINSTALOWANYCH pakietów (lokalnie zbudowane poza repo też
3317
+ dostarczają wirtualne zależności) → fallback pkgconfig (czyszczenie nazwy).
3318
+ """
3319
+ if name in repo:
3320
+ return name
3321
+ if name in PROVIDES_MAP:
3322
+ real = PROVIDES_MAP[name]
3323
+ if real in repo:
3324
+ return real
3325
+ # Wzorce: moduły Qt (Qt5Core/Qt6Widgets) i GStreamer (gstreamer-video-1.0)
3326
+ if name.startswith("pkgconfig(Qt5"):
3327
+ real = "qt5"
3328
+ if real in repo:
3329
+ return real
3330
+ if name.startswith("pkgconfig(Qt6"):
3331
+ real = "qt6"
3332
+ if real in repo:
3333
+ return real
3334
+ if name.startswith("pkgconfig(gstreamer-") and name.endswith("-1.0)"):
3335
+ real = "gstreamer"
3336
+ if real in repo:
3337
+ return real
3338
+ if name.startswith("pkgconfig(gst-"):
3339
+ real = "gst-plugins-base"
3340
+ if real in repo:
3341
+ return real
3342
+ # Dynamiczne provides z repo.json (sekcja provides: w PAGBUILD.yaml)
3343
+ for _pkg_name, _pkg in repo.items():
3344
+ _provs = getattr(_pkg, "provides", None) or []
3345
+ if name in _provs:
3346
+ return _pkg_name
3347
+ # provides ZAINSTALOWANYCH pakietów – lokalnie zbudowane (pagbuild, poza
3348
+ # repo) też dostarczają wirtualne zależności i muszą być rozpoznawane.
3349
+ if installed:
3350
+ for _pkg_name, _meta in installed.items():
3351
+ _provs = _meta.get("provides") or [] if isinstance(_meta, dict) else []
3352
+ if name in _provs:
3353
+ return _pkg_name
3354
+ clean = name
3355
+ if name.startswith("pkgconfig(") and ")" in name:
3356
+ clean = name.split("(", 1)[1].rstrip(")")
3357
+ elif name.startswith("pkgconfig32(") and ")" in name:
3358
+ clean = name.split("(", 1)[1].rstrip(")")
3359
+ if clean != name and clean in repo:
3360
+ return clean
3361
+ return name
3362
+
3363
+
3364
+def cmd_why(pkg_name: str):
3365
+ """Pokazuje dlaczego pakiet jest zainstalowany."""
3366
+ installed = load_json(INSTALLED_DB)
3367
+ world = load_world()
3368
+ if pkg_name not in installed:
3369
+ print(f" {pkg_name}: {_('why_not_installed')}"); return 1
3370
+ if pkg_name in world:
3371
+ print(f" {pkg_name}-{installed[pkg_name]['version']}: {_('why_explicit')}")
3372
+ return 0
3373
+ parents = set()
3374
+ for w in world:
3375
+ _find_dep_path(w, pkg_name, installed, set(), [], parents)
3376
+ if parents:
3377
+ for pp in sorted(parents):
3378
+ print(f" {pkg_name}: {_('why_dependency')} {' → '.join(pp)}")
3379
+ else:
3380
+ print(f" {pkg_name}: {_('why_dependency')} (unknown/orphan)")
3381
+ return 0
3382
+
3383
+
3384
+def _find_dep_path(cur, target, installed, visited, path, results):
3385
+ if cur in visited: return
3386
+ visited.add(cur); path.append(cur)
3387
+ if cur == target:
3388
+ results.add(tuple(path))
3389
+ else:
3390
+ for dep in installed.get(cur, {}).get("dependencies", []):
3391
+ _find_dep_path(dep, target, installed, visited, path, results)
3392
+ path.pop(); visited.discard(cur)
3393
+
3394
+
3395
+def cmd_autoremove():
3396
+ """Automatycznie usuwa osierocone zależności bez pytania."""
3397
+ installed = load_json(INSTALLED_DB)
3398
+ world = load_world()
3399
+ orphans = _find_orphans(installed, world)
3400
+ if not orphans: print(f"✅ {_('autoremove_none')}"); return 0
3401
+ print(f"🗑 {_('orphans_found', len(orphans), ', '.join(sorted(orphans)[:10]))}")
3402
+ return cmd_remove(list(orphans))
3403
+
3404
+
3405
+def cmd_download(package_names):
3406
+ """Pobiera pakiety do cache bez instalowania."""
3407
+ ensure_dirs()
3408
+ repo = fetch_all_packages()
3409
+ if not repo: print(f"❌ {_('no_index')}"); return 1
3410
+ total_size = 0; downloaded = []
3411
+ for name in package_names:
3412
+ pkg = repo.get(name)
3413
+ if not pkg:
3414
+ print(f" ❌ {name}: {_('not_found')}"); continue
3415
+ print(f" ↓ {name}-{pkg.version} ...", end=" ", flush=True)
3416
+ path = _download_pkg(pkg)
3417
+ if path:
3418
+ total_size += os.path.getsize(path)
3419
+ downloaded.append(name)
3420
+ print(_c("green", "✓"))
3421
+ else:
3422
+ print(_c("red", "✗"))
3423
+ if downloaded:
3424
+ print(f"\n✅ {_('downloaded', len(downloaded), total_size/1048576)}")
3425
+ return 0 if len(downloaded) == len(package_names) else 1
3426
+
3427
+
3428
+def cmd_stats():
3429
+ """Wyświetla statystyki PAG."""
3430
+ installed = load_json(INSTALLED_DB)
3431
+ history = load_json(HISTORY_FILE) if os.path.exists(HISTORY_FILE) else []
3432
+ total_size = sum(i.get("size_bytes", 0) for i in installed.values())
3433
+ total_files = _db_count_files()
3434
+ cache_size = sum(
3435
+ os.path.getsize(os.path.join(PAG_CACHE, f))
3436
+ for f in os.listdir(PAG_CACHE)
3437
+ if os.path.isfile(os.path.join(PAG_CACHE, f))
3438
+ ) if os.path.isdir(PAG_CACHE) else 0
3439
+ last_update = "never"
3440
+ for e in reversed(history):
3441
+ if e.get("action") in ("install", "upgrade") and e.get("success"):
3442
+ last_update = e.get("timestamp", "?")[:19]; break
3443
+ print(f"\n {_c('bold', _('stats_title'))}")
3444
+ print(f" {'─' * 40}")
3445
+ print(f" {_('stats_packages'):<30} {len(installed)}")
3446
+ print(f" {_('stats_files'):<30} {total_files}")
3447
+ print(f" {_('stats_size'):<30} {total_size/1048576:.1f} MB")
3448
+ print(f" {_('stats_cache'):<30} {cache_size/1048576:.1f} MB")
3449
+ print(f" {_('stats_history'):<30} {len(history)}")
3450
+ print(f" {_('stats_last_update'):<30} {last_update}")
3451
+ by_size = sorted(installed.items(), key=lambda x: x[1].get("size_bytes", 0), reverse=True)[:5]
3452
+ if by_size:
3453
+ print(f"\n {_c('dim', 'Top 5:')}")
3454
+ for n, i in by_size:
3455
+ print(f" {n}-{i['version']} {i.get('size_bytes',0)/1048576:.1f} MB")
3456
+ return 0
3457
+
3458
+
3459
+def cmd_repo_add(url, name=None):
3460
+ if not url.startswith("https://") and not os.environ.get("PAG_INSECURE"):
3461
+ print(f" {_('sec_https')}"); return 1
3462
+ ensure_dirs()
3463
+ url = url.rstrip("/")
3464
+ repos = get_repos()
3465
+ if url in repos: print(f"⚠ {_('repo_exists', url)}"); return
3466
+ if name:
3467
+ # Drop-in: /etc/pag/repos/<nazwa>.conf (jak `echo url > .../stable.conf`)
3468
+ os.makedirs(REPOS_DIR, exist_ok=True)
3469
+ target = os.path.join(REPOS_DIR, name.rstrip("/").replace("/", "_") + ".conf")
3470
+ with open(target, "w") as f: f.write(f"{url}\n")
3471
+ print(f"✅ {_('repo_added', url)} → {target}")
3472
+ return
3473
+ with open(REPOS_CONF, "a") as f: f.write(f"{url}\n")
3474
+ print(f"✅ {_('repo_added', url)}")
3475
+
3476
+def cmd_repo_list():
3477
+ for i, url in enumerate(get_repos(), 1): print(f" {i}. {url}")
3478
+
3479
+def _check_flatpak(quiet: bool = False):
3480
+ if not shutil.which("flatpak"):
3481
+ if not quiet:
3482
+ print(f"❌ {_('flatpak_missing')}")
3483
+ return False
3484
+ r = subprocess.run(["flatpak","remotes"], capture_output=True, text=True)
3485
+ if "flathub" not in r.stdout:
3486
+ print(f"⚠ {_('flatpak_adding')}")
3487
+ subprocess.run(["flatpak","remote-add","--if-not-exists","flathub",
3488
+ "https://flathub.org/repo/flathub.flatpakrepo"], check=False)
3489
+ return True
3490
+
3491
+def _spinner(msg: str):
3492
+ """Prosty spinner „myślenia” w osobnym wątku. Zwraca funkcję stop()."""
3493
+ stop = threading.Event()
3494
+ def _spin():
3495
+ for c in itertools.cycle("|/-\\"):
3496
+ if stop.is_set():
3497
+ break
3498
+ sys.stdout.write(f"\r {msg} {c}")
3499
+ sys.stdout.flush()
3500
+ time.sleep(0.1)
3501
+ t = threading.Thread(target=_spin, daemon=True)
3502
+ t.start()
3503
+ def _stop():
3504
+ stop.set()
3505
+ t.join(timeout=0.3)
3506
+ sys.stdout.write("\r" + " " * (len(msg) + 4) + "\r")
3507
+ sys.stdout.flush()
3508
+ return _stop
3509
+
3510
+
3511
+def _flatpak_search_raw(query: str) -> List[dict]:
3512
+ """Szuka we Flathub i zwraca listę wyników jako słowniki."""
3513
+ if not _check_flatpak():
3514
+ return []
3515
+ stop = _spinner("Szukam we Flathub...")
3516
+ try:
3517
+ try:
3518
+ r = subprocess.run(
3519
+ ["flatpak", "search", "--columns=name,description,application,version,branch,remotes", query],
3520
+ capture_output=True, text=True, timeout=120
3521
+ )
3522
+ finally:
3523
+ stop()
3524
+ if r.returncode != 0 and "No matches found" not in r.stdout and not r.stdout.strip():
3525
+ print(f" ⚠ flatpak search: {r.stderr.strip()[:150]}")
3526
+ results = []
3527
+ for line in r.stdout.strip().split("\n"):
3528
+ parts = line.split("\t")
3529
+ if len(parts) >= 3:
3530
+ results.append({
3531
+ "name": parts[0].strip(),
3532
+ "description": parts[1].strip() if len(parts) > 1 else "",
3533
+ "app_id": parts[2].strip() if len(parts) > 2 else "",
3534
+ "version": parts[3].strip() if len(parts) > 3 else "",
3535
+ "branch": parts[4].strip() if len(parts) > 4 else "stable",
3536
+ "origin": parts[5].strip() if len(parts) > 5 else "flathub",
3537
+ })
3538
+ return results
3539
+ except Exception as e:
3540
+ print(f" ⚠ Błąd wyszukiwania: {e}", file=sys.stderr)
3541
+ return []
3542
+
3543
+def _flatpak_find_best(query: str) -> Optional[dict]:
3544
+ """
3545
+ Szuka we Flathub i próbuje znaleźć najlepsze dopasowanie.
3546
+ - Jeśli query dokładnie pasuje do app_id → zwraca od razu
3547
+ - Jeśli query pasuje do nazwy → zwraca pierwsze
3548
+ - Jeśli wiele wyników → wyświetla listę i pyta użytkownika
3549
+ - Jeśli brak → zwraca None
3550
+ """
3551
+ results = _flatpak_search_raw(query)
3552
+ if not results:
3553
+ return None
3554
+
3555
+ # Dokładne dopasowanie app_id
3556
+ exact = [r for r in results if r["app_id"].lower() == query.lower()]
3557
+ if exact:
3558
+ return exact[0]
3559
+
3560
+ # Dokładne dopasowanie nazwy
3561
+ exact_name = [r for r in results if r["name"].lower() == query.lower()]
3562
+ if exact_name:
3563
+ return exact_name[0]
3564
+
3565
+ # Jednoznaczne dopasowanie (tylko 1 wynik)
3566
+ if len(results) == 1:
3567
+ return results[0]
3568
+
3569
+ # Wiele wyników – pokaż użytkownikowi
3570
+ print(f"\n {_('flatpak_found', len(results))}")
3571
+ for i, r in enumerate(results):
3572
+ print(f" {i+1}. {_c('bold', r['name'])} ({r['app_id']})")
3573
+ if r["version"]:
3574
+ print(f" {_('flatpak_info_version')}: {r['version']}")
3575
+ if r["description"]:
3576
+ desc = r["description"][:80] + ("..." if len(r["description"]) > 80 else "")
3577
+ print(f" {desc}")
3578
+
3579
+ try:
3580
+ choice = input(f"\n Wybierz numer (1-{len(results)}) lub Enter aby anulować: ").strip()
3581
+ if not choice:
3582
+ return None
3583
+ idx = int(choice) - 1
3584
+ if 0 <= idx < len(results):
3585
+ return results[idx]
3586
+ except (EOFError, ValueError, IndexError):
3587
+ pass
3588
+ return None
3589
+
3590
+def _flatpak_get_installed_info(app_id: str) -> Optional[dict]:
3591
+ """Zwraca info o zainstalowanym flatpaku lub None."""
3592
+ try:
3593
+ r = subprocess.run(
3594
+ ["flatpak", "info", "--columns=name,version,branch,origin,installed-size,description", app_id],
3595
+ capture_output=True, text=True, timeout=10
3596
+ )
3597
+ if r.returncode != 0:
3598
+ return None
3599
+ parts = r.stdout.strip().split("\t")
3600
+ if len(parts) < 3:
3601
+ return None
3602
+ return {
3603
+ "name": parts[0].strip(),
3604
+ "version": parts[1].strip() if len(parts) > 1 else "",
3605
+ "branch": parts[2].strip() if len(parts) > 2 else "",
3606
+ "origin": parts[3].strip() if len(parts) > 3 else "",
3607
+ "size": parts[4].strip() if len(parts) > 4 else "",
3608
+ "description": parts[5].strip() if len(parts) > 5 else "",
3609
+ }
3610
+ except Exception:
3611
+ return None
3612
+
3613
+def _flatpak_is_installed(app_id: str) -> bool:
3614
+ """Sprawdza czy flatpak o danym ID jest zainstalowany."""
3615
+ try:
3616
+ r = subprocess.run(
3617
+ ["flatpak", "info", app_id],
3618
+ capture_output=True, text=True, timeout=10
3619
+ )
3620
+ return r.returncode == 0
3621
+ except Exception:
3622
+ return False
3623
+
3624
+# =============================================================================
3625
+# FLATPAK – KOMENDY GŁÓWNE (zunifikowany interfejs)
3626
+# =============================================================================
3627
+# pag flatpak <query> → szuka i proponuje instalację (jeśli nie zainstalowany)
3628
+# pag flatpak search <query> → tylko szuka
3629
+# pag flatpak install <query> → instaluje
3630
+# pag flatpak remove <id> → usuwa
3631
+# pag flatpak list → lista zainstalowanych
3632
+# pag flatpak update → aktualizuje wszystkie
3633
+# pag flatpak info <id> → szczegóły flatpaka
3634
+
3635
+def cmd_flatpak(args: list):
3636
+ """
3637
+ Główna komenda flatpak – inteligentnie rozpoznaje intencję:
3638
+ pag flatpak firefox → szuka i instaluje (jeśli nieznaleziony → szuka)
3639
+ pag flatpak search firefox → tylko wyszukiwanie
3640
+ pag flatpak install ... → bezpośrednia instalacja
3641
+ pag flatpak remove ... → odinstalowanie
3642
+ pag flatpak list → lista
3643
+ pag flatpak update → aktualizacja
3644
+ pag flatpak info ... → szczegóły
3645
+ """
3646
+ if not _check_flatpak():
3647
+ return 1
3648
+
3649
+ if not args:
3650
+ # Bez argumentów – domyślnie lista
3651
+ return cmd_flatpak_list()
3652
+
3653
+ subcmd = args[0].lower()
3654
+ rest = args[1:]
3655
+
3656
+ # ── Podkomendy jawne ────────────────────────────────────────────────
3657
+ if subcmd == "search":
3658
+ if not rest:
3659
+ print(_("flatpak_usage")); return 1
3660
+ return cmd_flatpak_search(" ".join(rest))
3661
+
3662
+ elif subcmd == "install":
3663
+ if not rest:
3664
+ print(_("flatpak_usage")); return 1
3665
+ return _flatpak_smart_install(rest)
3666
+
3667
+ elif subcmd == "remove" or subcmd == "uninstall":
3668
+ if not rest:
3669
+ print(_("flatpak_usage")); return 1
3670
+ return _flatpak_smart_remove(rest)
3671
+
3672
+ elif subcmd == "list":
3673
+ return cmd_flatpak_list()
3674
+
3675
+ elif subcmd == "update":
3676
+ return cmd_flatpak_update()
3677
+
3678
+ elif subcmd == "info":
3679
+ if not rest:
3680
+ print(_("flatpak_usage")); return 1
3681
+ return cmd_flatpak_info(rest[0])
3682
+
3683
+ else:
3684
+ # ── Inteligentne wykrywanie: pag flatpak <nazwa> ────────────────
3685
+ # Sprawdź czy to zainstalowany flatpak → pokaż info
3686
+ # Jeśli nie → szukaj i zaproponuj instalację
3687
+ query = " ".join(args)
3688
+
3689
+ # Najpierw sprawdź czy już zainstalowany
3690
+ if _flatpak_is_installed(query):
3691
+ print(f" 📦 {_c('green', query)} – already installed (use 'pag flatpak info {query}' for details)")
3692
+ return cmd_flatpak_info(query)
3693
+
3694
+ # Szukaj we Flathub
3695
+ print(f" {_('flatpak_searching', query)}")
3696
+ best = _flatpak_find_best(query)
3697
+ if not best:
3698
+ print(f" ❌ '{query}' – {_('flatpak_not_found')}")
3699
+ return 1
3700
+
3701
+ print(f"\n {_c('cyan', best['name'])} ({best['app_id']})")
3702
+ if best["version"]:
3703
+ print(f" {_('flatpak_info_version')}: {best['version']}")
3704
+ if best["description"]:
3705
+ print(f" {best['description']}")
3706
+
3707
+ try:
3708
+ ans = input(f"\n {_('flatpak_install_prompt', best['name'])}").strip().lower()
3709
+ except (EOFError, KeyboardInterrupt):
3710
+ print(f"\n ⚠ {_('no_tty')}")
3711
+ return 0
3712
+ if ans and ans not in ("t", "y"):
3713
+ print(_("cancelled"))
3714
+ return 0
3715
+
3716
+ return _flatpak_do_install(best["app_id"])
3717
+
3718
+def _flatpak_smart_install(names: list) -> int:
3719
+ """Instaluje flatpaki – obsługuje nazwy częściowe (wyszukuje przed instalacją)."""
3720
+ failed = 0
3721
+ for name in names:
3722
+ if "." in name and "/" not in name:
3723
+ # Wygląda na pełne app_id (np. org.mozilla.firefox)
3724
+ app_id = name
3725
+ else:
3726
+ # Szukaj najlepszego dopasowania
3727
+ best = _flatpak_find_best(name)
3728
+ if not best:
3729
+ print(f" ❌ '{name}' – {_('flatpak_not_found')}")
3730
+ failed += 1
3731
+ continue
3732
+ app_id = best["app_id"]
3733
+ print(f" → {best['name']} ({app_id})")
3734
+
3735
+ if _flatpak_do_install(app_id) != 0:
3736
+ failed += 1
3737
+ return 1 if failed else 0
3738
+
3739
+def _flatpak_do_install(app_id: str) -> int:
3740
+ """Wykonuje właściwą instalację flatpaka."""
3741
+ print(f" {_('flatpak_installing', app_id)}")
3742
+ result = subprocess.run(
3743
+ ["flatpak", "install", "-y", "flathub", app_id],
3744
+ check=False, timeout=600
3745
+ )
3746
+ if result.returncode == 0:
3747
+ print(f" ✅ {_('flatpak_installed', app_id)}")
3748
+ return 0
3749
+ else:
3750
+ print(f" ❌ {_('download_fail')}: {app_id}")
3751
+ return 1
3752
+
3753
+def _flatpak_smart_remove(names: list) -> int:
3754
+ """Usuwa flatpaki – obsługuje nazwy częściowe."""
3755
+ # Pobierz listę zainstalowanych
3756
+ try:
3757
+ r = subprocess.run(
3758
+ ["flatpak", "list", "--columns=application,name"],
3759
+ capture_output=True, text=True, timeout=10
3760
+ )
3761
+ installed = {}
3762
+ for line in r.stdout.strip().split("\n"):
3763
+ parts = line.split("\t")
3764
+ if len(parts) >= 2:
3765
+ installed[parts[0].strip()] = parts[1].strip()
3766
+ except Exception:
3767
+ installed = {}
3768
+
3769
+ failed = 0
3770
+ for name in names:
3771
+ app_id = name
3772
+
3773
+ # Jeśli nie podano pełnego ID – spróbuj dopasować
3774
+ if name not in installed:
3775
+ matches = {aid: aname for aid, aname in installed.items()
3776
+ if name.lower() in aid.lower() or name.lower() in aname.lower()}
3777
+ if len(matches) == 0:
3778
+ print(f" ❌ '{name}' – {_('flatpak_not_installed', name)}")
3779
+ failed += 1
3780
+ continue
3781
+ elif len(matches) == 1:
3782
+ app_id = list(matches.keys())[0]
3783
+ print(f" → {matches[app_id]} ({app_id})")
3784
+ else:
3785
+ print(f"\n Wiele dopasowań dla '{name}':")
3786
+ for i, (aid, aname) in enumerate(sorted(matches.items()), 1):
3787
+ print(f" {i}. {aname} ({aid})")
3788
+ try:
3789
+ choice = input(f"\n Wybierz numer (1-{len(matches)}) lub Enter: ").strip()
3790
+ if not choice:
3791
+ failed += 1
3792
+ continue
3793
+ aid_list = sorted(matches.keys())
3794
+ app_id = aid_list[int(choice) - 1]
3795
+ except (EOFError, ValueError, IndexError):
3796
+ failed += 1
3797
+ continue
3798
+
3799
+ print(f" 🗑 {app_id} ...", end=" ", flush=True)
3800
+ result = subprocess.run(
3801
+ ["flatpak", "uninstall", "-y", app_id],
3802
+ capture_output=True, text=True, timeout=120
3803
+ )
3804
+ if result.returncode == 0:
3805
+ print("✅")
3806
+ print(f" {_('flatpak_removed', app_id)}")
3807
+ else:
3808
+ print("❌")
3809
+ failed += 1
3810
+ return 1 if failed else 0
3811
+
3812
+def cmd_flatpak_search(q: str):
3813
+ """Wyszukuje we Flathub i wyświetla wyniki (z możliwością wyboru do instalacji)."""
3814
+ if not _check_flatpak():
3815
+ return 1
3816
+ results = _flatpak_search_raw(q)
3817
+ if not results:
3818
+ print(f" ❌ '{q}' – {_('flatpak_not_found')}")
3819
+ return 1
3820
+ print(f"\n {_('flatpak_found', len(results))}")
3821
+ shown = results[:30] # max 30 wyników
3822
+ for i, r in enumerate(shown, 1):
3823
+ installed = "📦 " if _flatpak_is_installed(r["app_id"]) else " "
3824
+ print(f" {i:>2}. {installed}{_c('bold', r['name'])} ({r['app_id']})")
3825
+ if r["version"]:
3826
+ print(f" {_('flatpak_info_version')}: {r['version']} | {_('flatpak_info_branch')}: {r['branch']}")
3827
+ if r["description"]:
3828
+ desc = r["description"][:100] + ("..." if len(r["description"]) > 100 else "")
3829
+ print(f" {_c('dim', desc)}")
3830
+ if len(results) > 30:
3831
+ print(f" ... i {len(results) - 30} więcej. Doprecyzuj zapytanie.")
3832
+
3833
+ # Interaktywny wybór – wpisz numer, aby zainstalować (Enter = anuluj)
3834
+ try:
3835
+ ans = input(f"\n Wybierz numer do zainstalowania (1-{len(shown)}) lub Enter aby anulować: ").strip()
3836
+ except (EOFError, KeyboardInterrupt):
3837
+ return 0
3838
+ if ans:
3839
+ try:
3840
+ idx = int(ans) - 1
3841
+ if 0 <= idx < len(shown):
3842
+ return _flatpak_do_install(shown[idx]["app_id"])
3843
+ print(_("cancelled"))
3844
+ except (ValueError, IndexError):
3845
+ print(_("cancelled"))
3846
+ return 0
3847
+
3848
+def cmd_flatpak_list():
3849
+ """Wyświetla zainstalowane flatpaki."""
3850
+ if not _check_flatpak():
3851
+ return 1
3852
+ r = subprocess.run(
3853
+ ["flatpak", "list", "--columns=application,name,version,origin,installed-size"],
3854
+ capture_output=True, text=True, timeout=10
3855
+ )
3856
+ lines = [l for l in r.stdout.strip().split("\n") if l.strip()]
3857
+ if not lines:
3858
+ print(" (brak zainstalowanych flatpaków)")
3859
+ return 0
3860
+ print(f" Zainstalowane flatpaki ({len(lines)}):")
3861
+ for line in lines:
3862
+ parts = line.split("\t")
3863
+ if len(parts) >= 3:
3864
+ app_id, name, version = parts[0], parts[1], parts[2]
3865
+ size = parts[4] if len(parts) > 4 else ""
3866
+ size_str = f" ({size})" if size else ""
3867
+ print(f" 📦 {_c('bold', name)} {version}{size_str}")
3868
+ print(f" {_c('dim', app_id)}")
3869
+ return 0
3870
+
3871
+def cmd_flatpak_update():
3872
+ """Aktualizuje wszystkie flatpaki."""
3873
+ if not _check_flatpak():
3874
+ return 1
3875
+ print(" 🔄 Aktualizacja flatpaków...")
3876
+ result = subprocess.run(["flatpak", "update", "-y"], check=False, timeout=600)
3877
+ if result.returncode == 0:
3878
+ print(f" ✅ {_('flatpak_updated')}")
3879
+ return result.returncode
3880
+
3881
+def cmd_flatpak_info(app_id: str):
3882
+ """Wyświetla szczegóły flatpaka (zainstalowanego lub z Flathub)."""
3883
+ if not _check_flatpak():
3884
+ return 1
3885
+
3886
+ # Najpierw sprawdź zainstalowany
3887
+ info = _flatpak_get_installed_info(app_id)
3888
+ if info:
3889
+ print(f"\n 📦 {_c('bold', info['name'])} {_c('green', '[zainstalowany]')}")
3890
+ print(f" {'─' * 45}")
3891
+ print(f" {_('flatpak_info_id'):<16} {app_id}")
3892
+ print(f" {_('flatpak_info_version'):<16} {info['version']}")
3893
+ print(f" {_('flatpak_info_branch'):<16} {info['branch']}")
3894
+ print(f" {_('flatpak_info_origin'):<16} {info['origin']}")
3895
+ if info["size"]:
3896
+ print(f" {_('flatpak_info_size'):<16} {info['size']}")
3897
+ if info["description"]:
3898
+ print(f" {_('flatpak_info_desc'):<16} {info['description']}")
3899
+ return 0
3900
+
3901
+ # Szukaj we Flathub
3902
+ results = _flatpak_search_raw(app_id)
3903
+ exact = [r for r in results if r["app_id"].lower() == app_id.lower()]
3904
+ if not exact:
3905
+ # Spróbuj częściowego dopasowania
3906
+ if results:
3907
+ exact = [results[0]]
3908
+ else:
3909
+ print(f" ❌ '{app_id}' – {_('flatpak_not_found')}")
3910
+ return 1
3911
+
3912
+ r = exact[0]
3913
+ print(f"\n 📦 {_c('bold', r['name'])} (Flathub)")
3914
+ print(f" {'─' * 45}")
3915
+ print(f" {_('flatpak_info_id'):<16} {r['app_id']}")
3916
+ print(f" {_('flatpak_info_version'):<16} {r['version']}")
3917
+ if r["description"]:
3918
+ print(f" {_('flatpak_info_desc'):<16} {r['description']}")
3919
+ print(f"\n 💡 Aby zainstalować: pag flatpak install {r['app_id']}")
3920
+ return 0
3921
+
3922
+# =============================================================================
3923
+# IMMUTABLE OS – KOMENDY DEPLOYMENTOWE
3924
+# =============================================================================
3925
+
3926
+# Pakiety jądra – po ich instalacji trzeba przebudować initramfs
3927
+KERNEL_PACKAGE_PATTERNS = ["linux", "kernel", "linux-kernel", "linux-lts"]
3928
+
3929
+def _is_kernel_package(name: str) -> bool:
3930
+ """Sprawdza czy pakiet to jądro (wymaga przebudowy initramfs)."""
3931
+ name_lower = name.lower()
3932
+ return any(pattern in name_lower for pattern in KERNEL_PACKAGE_PATTERNS)
3933
+
3934
+def _rebuild_initramfs(deploy_dir: str = "") -> bool:
3935
+ """
3936
+ Przebudowuje initramfs dla aktywnego (lub podanego) deploymentu.
3937
+ Używa skryptu pag-initramfs lub ręcznego cpio.
3938
+ """
3939
+ if deploy_dir:
3940
+ root = deploy_dir
3941
+ else:
3942
+ root = _get_deployment_root()
3943
+
3944
+ if root == PAG_ROOT:
3945
+ # Zwykły system – użyj dracut jeśli dostępny
3946
+ if shutil.which("dracut"):
3947
+ print(" 🔧 Przebudowa initramfs (dracut)...")
3948
+ result = subprocess.run(
3949
+ ["dracut", "--force", "/boot/initramfs.img"],
3950
+ capture_output=True, text=True, timeout=120
3951
+ )
3952
+ return result.returncode == 0
3953
+ elif shutil.which("mkinitcpio"):
3954
+ print(" 🔧 Przebudowa initramfs (mkinitcpio)...")
3955
+ result = subprocess.run(
3956
+ ["mkinitcpio", "-g", "/boot/initramfs.img"],
3957
+ capture_output=True, text=True, timeout=120
3958
+ )
3959
+ return result.returncode == 0
3960
+ else:
3961
+ print(" ⚠ Brak dracut/mkinitcpio – initramfs nie został przebudowany")
3962
+ return False
3963
+
3964
+ # Tryb immutable – budujemy initramfs dla deploymentu
3965
+ print(" 🔧 Budowanie initramfs dla deploymentu...")
3966
+
3967
+ # Sprawdź czy mamy nasz skrypt init
3968
+ pag_init_script = "/usr/share/pag/initramfs-init"
3969
+ if not os.path.exists(pag_init_script):
3970
+ # Szukaj w źródłach (developerski fallback)
3971
+ alt_paths = [
3972
+ os.path.join(os.path.dirname(os.path.abspath(__file__)), "scripts", "initramfs-init"),
3973
+ "/usr/share/pag/init",
3974
+ ]
3975
+ for p in alt_paths:
3976
+ if os.path.exists(p):
3977
+ pag_init_script = p
3978
+ break
3979
+
3980
+ if not os.path.exists(pag_init_script):
3981
+ print(" ⚠ Nie znaleziono pag-initramfs-init – pomijam budowę initramfs")
3982
+ return False
3983
+
3984
+ boot_dir = os.path.join(root, "boot")
3985
+ os.makedirs(boot_dir, exist_ok=True)
3986
+
3987
+ # Znajdź jądro (vmlinuz-*)
3988
+ kernels = sorted(
3989
+ [f for f in os.listdir(boot_dir) if f.startswith("vmlinuz-")],
3990
+ reverse=True
3991
+ ) if os.path.exists(boot_dir) else []
3992
+ if not kernels:
3993
+ print(" ⚠ Nie znaleziono vmlinuz-* w /boot deploymentu")
3994
+ return False
3995
+
3996
+ kernel_ver = kernels[0].replace("vmlinuz-", "")
3997
+ print(f" 🐧 Jądro: {kernel_ver}")
3998
+
3999
+ # Buduj initramfs ręcznie (cpio)
4000
+ tmpdir = tempfile.mkdtemp(prefix="pag-initramfs-")
4001
+ try:
4002
+ # Podstawowa struktura
4003
+ for d in ["bin", "sbin", "dev", "proc", "sys", "run", "new_root",
4004
+ "usr/bin", "usr/sbin", "lib", "lib64", "etc"]:
4005
+ os.makedirs(os.path.join(tmpdir, d), exist_ok=True)
4006
+
4007
+ # Skopiuj init
4008
+ shutil.copy2(pag_init_script, os.path.join(tmpdir, "init"))
4009
+ os.chmod(os.path.join(tmpdir, "init"), 0o755)
4010
+
4011
+ # Skopiuj niezbędne binaria (busybox lub podstawowe narzędzia)
4012
+ busybox_paths = [
4013
+ os.path.join(root, "usr/bin/busybox"),
4014
+ os.path.join(root, "bin/busybox"),
4015
+ "/usr/bin/busybox",
4016
+ "/bin/busybox",
4017
+ ]
4018
+ busybox = None
4019
+ for bp in busybox_paths:
4020
+ if os.path.exists(bp):
4021
+ busybox = bp
4022
+ break
4023
+
4024
+ if busybox:
4025
+ shutil.copy2(busybox, os.path.join(tmpdir, "bin/busybox"))
4026
+ # Utwórz symlinki dla podstawowych komend
4027
+ for cmd in ["sh", "mount", "umount", "ls", "cat", "echo", "sleep",
4028
+ "readlink", "mkdir", "switch_root", "cp", "rm"]:
4029
+ link = os.path.join(tmpdir, "bin", cmd)
4030
+ if not os.path.exists(link):
4031
+ os.symlink("busybox", link)
4032
+ # /bin/sh → busybox
4033
+ if not os.path.exists(os.path.join(tmpdir, "bin/sh")):
4034
+ os.symlink("busybox", os.path.join(tmpdir, "bin/sh"))
4035
+ else:
4036
+ # Bez busybox – kopiuj podstawowe narzędzia z deploymentu
4037
+ for tool in ["bash", "mount", "umount", "readlink", "mkdir", "cat", "sleep", "cp", "rm"]:
4038
+ src = os.path.join(root, "usr/bin", tool)
4039
+ if not os.path.exists(src):
4040
+ src = os.path.join(root, "bin", tool)
4041
+ if os.path.exists(src):
4042
+ dest = os.path.join(tmpdir, "bin", os.path.basename(tool))
4043
+ shutil.copy2(src, dest)
4044
+ # Kopiuj zależności .so
4045
+ _copy_libs_for_binary(src, tmpdir, root)
4046
+
4047
+ # Dodaj moduły jądra (opcjonalnie – dla sterowników dyskowych)
4048
+ modules_src = os.path.join(root, "lib/modules", kernel_ver)
4049
+ if os.path.isdir(modules_src):
4050
+ modules_dst = os.path.join(tmpdir, "lib/modules", kernel_ver)
4051
+ # Kopiuj tylko niezbędne (fs, block, drivers/ata, drivers/nvme)
4052
+ for sub in ["kernel/fs", "kernel/drivers/ata", "kernel/drivers/nvme",
4053
+ "kernel/drivers/scsi", "kernel/drivers/virtio",
4054
+ "modules.order", "modules.builtin"]:
4055
+ src_sub = os.path.join(modules_src, sub)
4056
+ if os.path.exists(src_sub):
4057
+ dst_sub = os.path.join(modules_dst, sub)
4058
+ os.makedirs(os.path.dirname(dst_sub), exist_ok=True)
4059
+ if os.path.isdir(src_sub):
4060
+ try:
4061
+ shutil.copytree(src_sub, dst_sub, dirs_exist_ok=True, symlinks=True,
4062
+ ignore_dangling_symlinks=True)
4063
+ except (FileNotFoundError, PermissionError):
4064
+ print(f" ⚠ Pomijam niedostępne pliki: {sub}")
4065
+ else:
4066
+ try:
4067
+ shutil.copy2(src_sub, dst_sub)
4068
+ except (FileNotFoundError, PermissionError):
4069
+ print(f" ⚠ Pomijam niedostępny plik: {sub}")
4070
+
4071
+ # Pakuj do initramfs.img
4072
+ initramfs_path = os.path.join(boot_dir, "initramfs.img")
4073
+ old_cwd = os.getcwd()
4074
+ os.chdir(tmpdir)
4075
+ try:
4076
+ with open(initramfs_path + ".tmp", "wb") as out:
4077
+ _run_cpio_pipeline(tmpdir, out)
4078
+ os.rename(initramfs_path + ".tmp", initramfs_path)
4079
+ finally:
4080
+ os.chdir(old_cwd)
4081
+
4082
+ size_mb = os.path.getsize(initramfs_path) / 1048576
4083
+ print(f" ✅ initramfs.img ({size_mb:.1f} MB) → {initramfs_path}")
4084
+ return True
4085
+
4086
+ except Exception as e:
4087
+ print(f" ❌ Błąd budowy initramfs: {e}")
4088
+ return False
4089
+ finally:
4090
+ shutil.rmtree(tmpdir, ignore_errors=True)
4091
+
4092
+
4093
+def _run_cpio_pipeline(tmpdir: str, out):
4094
+ """find . -print0 | cpio --null -oH newc | gzip — bez shell=True.
4095
+
4096
+ Buduje pipeline przez subprocess.Popen, unikając pośrednika powłoki
4097
+ (brak ryzyka injection i niepotrzebnego procesu sh). Wykonuje się w cwd=tmpdir.
4098
+ Separatory NUL (\0): plik/katalog ze znakiem nowej linii w nazwie nie
4099
+ rozjeżdża cpio (inaczej uszkodzone archiwum → kernel panic przy rozruchu).
4100
+ """
4101
+ find = subprocess.Popen(["find", ".", "-print0"], cwd=tmpdir, stdout=subprocess.PIPE)
4102
+ cpio = subprocess.Popen(["cpio", "--null", "-oH", "newc"], cwd=tmpdir,
4103
+ stdin=find.stdout, stdout=subprocess.PIPE)
4104
+ find.stdout.close() # zwolnij uchwyt – cpio dostanie SIGPIPE po zakończeniu find
4105
+ gzip = subprocess.Popen(["gzip"], stdin=cpio.stdout, stdout=out)
4106
+ cpio.stdout.close()
4107
+ try:
4108
+ gzip.wait(timeout=120)
4109
+ if gzip.returncode != 0:
4110
+ raise subprocess.CalledProcessError(gzip.returncode, ["gzip"])
4111
+ cpio.wait(timeout=30)
4112
+ find.wait(timeout=30)
4113
+ except subprocess.TimeoutExpired:
4114
+ for p in (gzip, cpio, find):
4115
+ p.kill()
4116
+ raise
4117
+ finally:
4118
+ for p in (find, cpio, gzip):
4119
+ if p.poll() is None:
4120
+ p.kill()
4121
+ # Skontroluj też kody procesów pośrednich (cpio/find mogą zawieść, a gzip zwrócić 0)
4122
+ if cpio.returncode != 0:
4123
+ raise subprocess.CalledProcessError(cpio.returncode, ["cpio"])
4124
+ if find.returncode != 0:
4125
+ raise subprocess.CalledProcessError(find.returncode, ["find"])
4126
+
4127
+
4128
+def _copy_libs_for_binary(binary: str, dest_dir: str, root: str):
4129
+ """Kopiuje zależności .so dla binarki do initramfs (uproszczone ldd)."""
4130
+ try:
4131
+ result = subprocess.run(
4132
+ ["ldd", binary], capture_output=True, text=True, timeout=10
4133
+ )
4134
+ for line in result.stdout.split("\n"):
4135
+ m = re.search(r'=>\s+(/\S+)', line)
4136
+ if m:
4137
+ lib_path = m.group(1)
4138
+ lib_rel = lib_path.lstrip("/")
4139
+ lib_dest = os.path.join(dest_dir, lib_rel)
4140
+ if not os.path.exists(lib_dest):
4141
+ os.makedirs(os.path.dirname(lib_dest), exist_ok=True)
4142
+ # Szukaj w deployment root lub systemie
4143
+ if os.path.exists(lib_path):
4144
+ shutil.copy2(lib_path, lib_dest)
4145
+ else:
4146
+ alt = os.path.join(root, lib_rel)
4147
+ if os.path.exists(alt):
4148
+ shutil.copy2(alt, lib_dest)
4149
+ except Exception:
4150
+ pass
4151
+
4152
+
4153
+def cmd_initramfs_update():
4154
+ """Ręcznie przebudowuje initramfs dla bieżącego deploymentu."""
4155
+ ensure_dirs()
4156
+ deploy_dir = _get_deployment_root()
4157
+ if deploy_dir != PAG_ROOT:
4158
+ print(f"🏗️ Deployment: {os.path.basename(deploy_dir)}")
4159
+ ok = _rebuild_initramfs(deploy_dir)
4160
+ if ok:
4161
+ print("✅ Initramfs zaktualizowany.")
4162
+ # Po initramfs – zaktualizuj też GRUB
4163
+ _update_grub_config()
4164
+ else:
4165
+ print("❌ Błąd aktualizacji initramfs.")
4166
+ return 0 if ok else 1
4167
+
4168
+
4169
+def _update_grub_config():
4170
+ """
4171
+ Generuje wpisy GRUB dla wszystkich deploymentów.
4172
+ Każdy deployment dostaje własny wpis – rollback możliwy z bootloadera.
4173
+ """
4174
+ grub_cfg = "/boot/grub/grub.cfg"
4175
+ if not os.path.exists(os.path.dirname(grub_cfg)):
4176
+ return # brak GRUB
4177
+
4178
+ deployments = _load_deployments()
4179
+ root_dev = _detect_root_device()
4180
+
4181
+ lines = [
4182
+ "# =====================================================================",
4183
+ "# Pagan Linux – GRUB config (wygenerowane przez pag grub-update)",
4184
+ f"# Data: {datetime.now().isoformat()}",
4185
+ "# =====================================================================",
4186
+ "",
4187
+ ]
4188
+
4189
+ # Domyślny – ostatni (najnowszy) deployment
4190
+ if deployments:
4191
+ latest = deployments[-1]["id"]
4192
+ lines.append(f"set default=0")
4193
+ lines.append(f"set timeout=5")
4194
+ else:
4195
+ lines.append("set default=0")
4196
+ lines.append("set timeout=5")
4197
+ lines.append("")
4198
+
4199
+ # Wpisy dla każdego deploymentu (od najnowszego)
4200
+ entry_num = 0
4201
+ for d in reversed(deployments):
4202
+ deploy_dir = os.path.join(DEPLOYMENTS_DIR, d["id"])
4203
+ boot_dir = os.path.join(deploy_dir, "boot")
4204
+ kernels = sorted(
4205
+ [f for f in os.listdir(boot_dir) if f.startswith("vmlinuz-")],
4206
+ reverse=True
4207
+ ) if os.path.isdir(boot_dir) else []
4208
+
4209
+ kernel_path = f"/.deployments/{d['id']}/boot/{kernels[0]}" if kernels else ""
4210
+ initrd_path = f"/.deployments/{d['id']}/boot/initramfs.img"
4211
+ initrd_line = f"initrd {initrd_path}" if os.path.exists(os.path.join(boot_dir, "initramfs.img")) else ""
4212
+
4213
+ active_mark = " [AKTYWNY]" if d.get("active") else ""
4214
+ pkg_list = ", ".join(d.get("packages", [])[:3])
4215
+ label = f"Pagan Linux – {d['id']}{active_mark}"
4216
+
4217
+ lines.append(f"menuentry '{label}' {{")
4218
+ if kernel_path:
4219
+ lines.append(f" linux {kernel_path} root={root_dev} rw quiet")
4220
+ else:
4221
+ lines.append(f" # Brak jądra w tym deploymencie")
4222
+ if initrd_line:
4223
+ lines.append(f" {initrd_line}")
4224
+ lines.append("}")
4225
+ lines.append("")
4226
+ entry_num += 1
4227
+
4228
+ # Wpis fallback: zwykły root (gdyby wszystko padło)
4229
+ lines.append("menuentry 'Pagan Linux – fallback (zwykły root)' {")
4230
+ lines.append(f" linux /boot/vmlinuz-* root={root_dev} rw quiet")
4231
+ lines.append(f" initrd /boot/initramfs.img")
4232
+ lines.append("}")
4233
+ lines.append("")
4234
+
4235
+ # Zapisz
4236
+ os.makedirs(os.path.dirname(grub_cfg), exist_ok=True)
4237
+ with open(grub_cfg, "w") as f:
4238
+ f.write("\n".join(lines))
4239
+
4240
+ print(" 📋 GRUB config zaktualizowany – wpisy dla każdego deploymentu")
4241
+
4242
+
4243
+def _detect_root_device() -> str:
4244
+ """Wykrywa device partycji root (np. /dev/sda1)."""
4245
+ try:
4246
+ result = subprocess.run(
4247
+ ["findmnt", "-n", "-o", "SOURCE", "/"],
4248
+ capture_output=True, text=True, timeout=5
4249
+ )
4250
+ if result.returncode == 0 and result.stdout.strip():
4251
+ return result.stdout.strip()
4252
+ except Exception:
4253
+ pass
4254
+ return "/dev/sda1" # fallback
4255
+
4256
+
4257
+def cmd_grub_update():
4258
+ """Ręcznie regeneruje konfigurację GRUB (wpisy dla deploymentów)."""
4259
+ ensure_dirs()
4260
+ print("📋 Aktualizacja konfiguracji GRUB...")
4261
+ _update_grub_config()
4262
+ print("✅ GRUB zaktualizowany.")
4263
+ return 0
4264
+
4265
+def cmd_deploy_list():
4266
+ """Wyświetla listę wszystkich deploymentów."""
4267
+ deployments = _load_deployments()
4268
+ if not deployments:
4269
+ print(_("no_deployments")); return
4270
+
4271
+ print(_("deployments_list", len(deployments)))
4272
+ active = os.readlink(ACTIVE_LINK) if os.path.islink(ACTIVE_LINK) else ""
4273
+
4274
+ for d in reversed(deployments):
4275
+ marker = f" ◀ {_('active_deployment')}" if d.get("active") or d["id"] == os.path.basename(active) else ""
4276
+ print(f" {d['id']}{marker}")
4277
+ print(f" {d['action']}: {', '.join(d['packages'][:5])}")
4278
+ if len(d.get('packages', [])) > 5:
4279
+ print(f" +{len(d['packages']) - 5} więcej...")
4280
+ print(f" {d['timestamp']}")
4281
+
4282
+
4283
+def cmd_deploy_rollback():
4284
+ """Przełącza na poprzedni deployment."""
4285
+ deployments = _load_deployments()
4286
+ active_indices = [i for i, d in enumerate(deployments) if d.get("active")]
4287
+
4288
+ if len(deployments) < 2:
4289
+ print(f"❌ {_('deploy_rollback_fail')}"); return 1
4290
+
4291
+ current_idx = active_indices[0] if active_indices else len(deployments) - 1
4292
+ prev_idx = current_idx - 1 if current_idx > 0 else -1
4293
+
4294
+ if prev_idx < 0:
4295
+ print(f"❌ {_('deploy_rollback_fail')}"); return 1
4296
+
4297
+ prev = deployments[prev_idx]
4298
+ prev_dir = os.path.join(DEPLOYMENTS_DIR, prev["id"])
4299
+
4300
+ if not os.path.isdir(prev_dir):
4301
+ print(f"❌ Deployment {prev['id']} nie istnieje na dysku"); return 1
4302
+
4303
+ print(f"⏪ Przywracanie deploymentu: {prev['id']}")
4304
+ print(f" {prev['action']}: {', '.join(prev['packages'][:5])}")
4305
+
4306
+ if not _ask_confirm():
4307
+ return 0
4308
+
4309
+ _switch_deployment(prev_dir)
4310
+
4311
+ for d in deployments:
4312
+ d["active"] = (d["id"] == prev["id"])
4313
+ _save_deployments(deployments)
4314
+
4315
+ _update_grub_config()
4316
+ print(f"✅ {_('deploy_rollback_ok', prev['id'])}")
4317
+ print(" 💡 Restart wymagany do przeładowania systemu.")
4318
+ return 0
4319
+
4320
+
4321
+def cmd_deploy_cleanup(keep: int = 3):
4322
+ """Usuwa stare deploymenty, zachowując ostatnie `keep`."""
4323
+ deployments = _load_deployments()
4324
+
4325
+ if len(deployments) <= keep:
4326
+ print(f"✅ {_('deploy_cleanup_none', keep)}"); return 0
4327
+
4328
+ to_remove = deployments[:-keep]
4329
+ removed = 0
4330
+
4331
+ for d in to_remove:
4332
+ deploy_dir = os.path.join(DEPLOYMENTS_DIR, d["id"])
4333
+ if os.path.isdir(deploy_dir):
4334
+ shutil.rmtree(deploy_dir, ignore_errors=True)
4335
+ removed += 1
4336
+
4337
+ remaining = deployments[-keep:]
4338
+ _save_deployments(remaining)
4339
+
4340
+ print(f"✅ {_('deploy_cleanup_ok', removed)}")
4341
+ return 0
4342
+
4343
+
4344
+# =============================================================================
4345
+# POMOCNICZE
4346
+# =============================================================================
4347
+
4348
+def _resolve_deps(names, repo, installed):
4349
+ resolved, visited = [], set()
4350
+ missing = [] # zależności których nie ma ani w repo ani zainstalowane
4351
+
4352
+ def visit(name):
4353
+ if name in visited: return
4354
+
4355
+ # Rozwijanie wirtualnych zależności przez provides
4356
+ target = _resolve_provides(name, repo, installed)
4357
+
4358
+ if target in visited: return
4359
+ visited.add(target)
4360
+ if target in repo:
4361
+ for dep in repo[target].dependencies:
4362
+ real_dep = _resolve_provides(dep, repo, installed)
4363
+ real_target = real_dep if real_dep in repo else dep
4364
+
4365
+ # Sprawdź czy zależność jest dostępna
4366
+ if real_target not in installed and real_target not in repo:
4367
+ if dep not in missing:
4368
+ missing.append(dep)
4369
+
4370
+ if dep not in installed:
4371
+ visit(real_target)
4372
+ elif target not in installed:
4373
+ # Pakiet nie istnieje ani w repo ani zainstalowany
4374
+ if target not in missing:
4375
+ missing.append(target)
4376
+
4377
+ if target not in installed and target not in resolved:
4378
+ resolved.append(target)
4379
+
4380
+ for name in names:
4381
+ visit(name)
4382
+
4383
+ # Zwróć brakujące (do sprawdzenia przez wywołującego)
4384
+ return resolved, missing
4385
+
4386
+def _verify_dependencies(to_install: list, repo: dict, installed: dict) -> int:
4387
+ """
4388
+ Sprawdza czy wszystkie zależności pakietów do instalacji są spełnione.
4389
+ Zwraca liczbę brakujących zależności.
4390
+ """
4391
+ # Pakiety dostarczane przez bazowy system (zawsze "zainstalowane")
4392
+ SYSTEM_BASE = {
4393
+ "glibc", "libc", "gcc", "g++", "make", "binutils", "coreutils", "bash",
4394
+ "linux-api-headers", "kernel-headers", "zlib", "pkg-config", "pkgconf",
4395
+ "tar", "gzip", "xz", "bzip2", "findutils", "grep", "sed", "gawk", "awk",
4396
+ "diffutils", "patch", "file", "m4", "perl", "python3", "sh",
4397
+ }
4398
+ all_missing = []
4399
+ all_warnings = []
4400
+
4401
+ for pkg_name in to_install:
4402
+ pkg = repo.get(pkg_name)
4403
+ if not pkg:
4404
+ continue
4405
+
4406
+ for dep in pkg.dependencies:
4407
+ if dep in SYSTEM_BASE:
4408
+ continue # bazowy system dostarcza tę zależność
4409
+ real_dep = _resolve_provides(dep, repo, installed)
4410
+ # Sprawdź czy zależność jest dostępna (w repo lub już zainstalowana)
4411
+ in_repo = real_dep in repo
4412
+ in_installed = real_dep in installed
4413
+ will_be_installed = real_dep in to_install
4414
+
4415
+ if not in_repo and not in_installed and not will_be_installed:
4416
+ if dep not in all_missing:
4417
+ all_missing.append((pkg_name, dep))
4418
+ elif in_repo and not in_installed and not will_be_installed:
4419
+ if dep not in [w[1] for w in all_warnings]:
4420
+ all_warnings.append((pkg_name, dep, real_dep))
4421
+
4422
+ if all_missing:
4423
+ print(f"\n❌ {_c('red', 'BRAKUJĄCE ZALEŻNOŚCI')} – nie można zainstalować:")
4424
+ for pkg, dep in all_missing:
4425
+ print(f" {pkg} → potrzebuje {_c('red', dep)} (brak w repozytoriach)")
4426
+ print()
4427
+
4428
+ if all_warnings:
4429
+ print(f"\n⚠ {_c('yellow', 'NIESPEŁNIONE ZALEŻNOŚCI')} – zostaną doinstalowane:")
4430
+ for pkg, dep, real in all_warnings:
4431
+ print(f" {pkg} → {dep} ({_c('green', real)} – będzie pobrane)")
4432
+ print()
4433
+
4434
+ return len(all_missing)
4435
+
4436
+# Biblioteki bazowe (glibc/gcc runtime) – zawsze dostępne, nie wymagają pakietu
4437
+BASE_SO = {
4438
+ "libc.so.6", "libm.so.6", "libpthread.so.0", "libdl.so.2", "librt.so.1",
4439
+ "libutil.so.1", "libresolv.so.2", "libnsl.so.1", "libcrypt.so.1",
4440
+ "ld-linux.so.2", "ld-linux-x86-64.so.2", "ld-linux-aarch64.so.1",
4441
+ "libgcc_s.so.1", "linux-vdso.so.1",
4442
+}
4443
+
4444
+def _verify_so_deps(to_install: list, repo: dict, installed: dict) -> int:
4445
+ """Sprawdza wymagania ABI (provides_so / requires_so z metadata.json).
4446
+
4447
+ Fail-closed TYLKO gdy metadata jawnie deklaruje requires_so, a żaden pakiet
4448
+ (bazowy, zainstalowany lub instalowany w tej transakcji) nie dostarcza
4449
+ wymaganej wersji biblioteki. Stare pakiety bez tych pól są pomijane.
4450
+ """
4451
+ provided = set(BASE_SO)
4452
+ for n in to_install:
4453
+ p = repo.get(n)
4454
+ if p:
4455
+ provided.update(p.provides_so or [])
4456
+ for n, info in installed.items():
4457
+ provided.update(info.get("provides_so", []) or [])
4458
+
4459
+ missing = []
4460
+ for n in sorted(to_install):
4461
+ p = repo.get(n)
4462
+ if not p:
4463
+ continue
4464
+ for so in (p.requires_so or []):
4465
+ if so not in provided:
4466
+ missing.append((n, so))
4467
+
4468
+ if missing:
4469
+ print(f"\n❌ {_c('red', 'BRAK WYMAGANYCH BIBLIOTEK (ABI so-name)')}:")
4470
+ for n, so in missing:
4471
+ print(f" {n} → wymaga {_c('red', so)} – żaden pakiet nie dostarcza tej wersji")
4472
+ print()
4473
+ return len(missing)
4474
+
4475
+def _download_pkg(pkg):
4476
+ url = f"{pkg.repo_url}/{pkg.filename}"
4477
+ dest = os.path.join(PAG_CACHE, pkg.filename)
4478
+ if os.path.exists(dest) and (not pkg.sha256 or _sha256_file(dest) == pkg.sha256):
4479
+ _download_pkg_sig(pkg, dest) # upewnij się, że sygnatura jest w cache
4480
+ return dest
4481
+ try:
4482
+ req = Request(url, headers={"User-Agent":"pag/3.0"})
4483
+ with urlopen(req, timeout=600) as resp:
4484
+ total = int(resp.headers.get("Content-Length", 0))
4485
+ bar = DownloadBar(pkg.filename, total)
4486
+ with open(dest, "wb") as f:
4487
+ while True:
4488
+ chunk = resp.read(65536)
4489
+ if not chunk:
4490
+ break
4491
+ f.write(chunk)
4492
+ bar.update(len(chunk))
4493
+ bar.close()
4494
+ if pkg.sha256 and _sha256_file(dest) != pkg.sha256:
4495
+ os.remove(dest); return None
4496
+ _download_pkg_sig(pkg, dest)
4497
+ return dest
4498
+ except Exception as e:
4499
+ print(f" ⚠ Błąd pobierania {pkg.filename}: {e}", file=sys.stderr)
4500
+ return None
4501
+
4502
+def _download_pkg_sig(pkg, dest):
4503
+ """Pobiera podpis pakietu (.asc, fallback .sig) obok paczki w cache."""
4504
+ for ext in (".asc", ".sig"):
4505
+ sig_dest = dest + ext
4506
+ if os.path.exists(sig_dest):
4507
+ return
4508
+ try:
4509
+ req = Request(f"{pkg.repo_url}/{pkg.filename}{ext}", headers={"User-Agent":"pag/3.0"})
4510
+ with urlopen(req, timeout=30) as resp:
4511
+ with open(sig_dest, "wb") as f:
4512
+ f.write(resp.read())
4513
+ return
4514
+ except Exception:
4515
+ continue
4516
+
4517
+def _download_packages_parallel(pkgs: List[PackageInfo], max_workers: int = 4) -> Dict[str, Optional[str]]:
4518
+ """
4519
+ Równoległe pobieranie wielu pakietów przez ThreadPoolExecutor.
4520
+ Znacząco przyspiesza przy dużych aktualizacjach (50+ pakietów).
4521
+ Zwraca słownik {nazwa_pakietu: ścieżka_lub_None}.
4522
+ """
4523
+ results = {}
4524
+ total = len(pkgs)
4525
+ completed = 0
4526
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
4527
+ future_to_pkg = {executor.submit(_download_pkg, pkg): pkg for pkg in pkgs}
4528
+ for future in as_completed(future_to_pkg):
4529
+ pkg = future_to_pkg[future]
4530
+ try:
4531
+ results[pkg.name] = future.result()
4532
+ except Exception:
4533
+ results[pkg.name] = None
4534
+ completed += 1
4535
+ # Pasek postępu
4536
+ pct = completed / total * 100
4537
+ filled = int(20 * pct / 100)
4538
+ bar = "█" * filled + "░" * (20 - filled)
4539
+ print(f"\r ⏬ [{bar}] {completed}/{total} ({pct:.0f}%)", end="", file=sys.stderr, flush=True)
4540
+ print(file=sys.stderr) # nowa linia po zakończeniu
4541
+ return results
4542
+
4543
+def load_world():
4544
+ if not os.path.exists(WORLD_FILE): return set()
4545
+ return {l.strip() for l in open(WORLD_FILE) if l.strip()}
4546
+
4547
+def save_world(w):
4548
+ with open(WORLD_FILE,"w") as f:
4549
+ for n in sorted(w): f.write(f"{n}\n")
4550
+
4551
+def _find_orphans(installed, world):
4552
+ needed = set(world)
4553
+ changed = True
4554
+ while changed:
4555
+ changed = False
4556
+ for n in list(needed):
4557
+ for dep in installed.get(n,{}).get("dependencies",[]):
4558
+ if dep not in needed and dep in installed:
4559
+ needed.add(dep); changed = True
4560
+ return {n for n in installed if n not in needed}
4561
+
4562
+# =============================================================================
4563
+# MAIN
4564
+# =============================================================================
4565
+
4566
+def cmd_sbom(argv):
4567
+ """pag sbom export [spdx|cyclonedx] – manifest SBOM zainstalowanych pakietów.
4568
+
4569
+ Wypisuje na stdout JSON (SPDX 2.3 lub CycloneDX 1.5) z listą
4570
+ zainstalowanych pakietów, wersji, licencji i sum SHA256.
4571
+ """
4572
+ fmt = (argv[0] if argv else "spdx").lower()
4573
+ if fmt not in ("spdx", "cyclonedx"):
4574
+ print("❌ Format: spdx | cyclonedx")
4575
+ return 1
4576
+ installed = load_json(INSTALLED_DB)
4577
+ if not installed:
4578
+ print("{}") if fmt == "cyclonedx" else print("{\"packages\": []}")
4579
+ return 0
4580
+ # metadata repo (licencje) – best-effort
4581
+ try:
4582
+ repo = fetch_all_packages()
4583
+ except Exception:
4584
+ repo = {}
4585
+ names = sorted(installed)
4586
+ created = datetime.now().astimezone().isoformat(timespec="seconds")
4587
+
4588
+ def _license_of(name):
4589
+ p = repo.get(name)
4590
+ lic = getattr(p, "license", None) or []
4591
+ if isinstance(lic, list):
4592
+ lic = ", ".join(x for x in lic if x)
4593
+ return lic or "NOASSERTION"
4594
+
4595
+ if fmt == "spdx":
4596
+ doc = {
4597
+ "spdxVersion": "SPDX-2.3",
4598
+ "dataLicense": "CC0-1.0",
4599
+ "SPDXID": "SPDXRef-DOCUMENT",
4600
+ "name": "PaganOS-installed",
4601
+ "documentNamespace": f"https://repo.paganlinux.eu/sbom/installed-{int(time.time())}",
4602
+ "creationInfo": {
4603
+ "created": created,
4604
+ "creators": [f"Tool: pag-{PAG_VERSION}"],
4605
+ },
4606
+ "packages": [],
4607
+ }
4608
+ for i, n in enumerate(names):
4609
+ info = installed[n]
4610
+ doc["packages"].append({
4611
+ "SPDXID": f"SPDXRef-Package-{i+1}",
4612
+ "name": n,
4613
+ "versionInfo": info.get("version", ""),
4614
+ "downloadLocation": info.get("repo", "NOASSERTION"),
4615
+ "filesAnalyzed": False,
4616
+ "licenseConcluded": _license_of(n),
4617
+ "checksums": [{"algorithm": "SHA256", "checksumValue": info.get("sha256", "")}],
4618
+ })
4619
+ else: # cyclonedx
4620
+ doc = {
4621
+ "bomFormat": "CycloneDX",
4622
+ "specVersion": "1.5",
4623
+ "serialNumber": f"urn:uuid:{str(uuid.uuid4())}",
4624
+ "version": 1,
4625
+ "metadata": {
4626
+ "timestamp": created,
4627
+ "tools": [{"vendor": "PaganOS", "name": "pag", "version": PAG_VERSION}],
4628
+ },
4629
+ "components": [],
4630
+ }
4631
+ for n in names:
4632
+ info = installed[n]
4633
+ lic = _license_of(n)
4634
+ comp = {
4635
+ "type": "library",
4636
+ "name": n,
4637
+ "version": info.get("version", ""),
4638
+ "hashes": [{"alg": "SHA-256", "content": info.get("sha256", "")}],
4639
+ }
4640
+ if lic != "NOASSERTION":
4641
+ comp["licenses"] = [{"license": {"id": lic}}]
4642
+ doc["components"].append(comp)
4643
+ print(json.dumps(doc, indent=2, ensure_ascii=False))
4644
+ return 0
4645
+
4646
+
4647
+USAGE_EN = """pag v3 – Pagan Linux Package Manager
4648
+
4649
+BASIC:
4650
+ pag install <pkg>... Install packages
4651
+ pag remove <pkg>... Remove packages
4652
+ pag update Update PACKAGES (refreshes indexes first)
4653
+ pag sync Refresh indexes + show pending package updates
4654
+ pag upgrade Update SYSTEM (packages + kernel/initramfs/GRUB)
4655
+ pag list [--installed] List available / installed
4656
+ pag search <query> Search packages
4657
+ pag info <pkg> Package details
4658
+ pag files <pkg> List package files
4659
+ pag verify [--deep] Verify integrity (--deep = SHA256 per file)
4660
+ pag clean Clear download cache
4661
+ pag stats System statistics
4662
+ pag download <pkg>... Download packages to cache (offline prep)
4663
+
4664
+SECURITY:
4665
+ pag key-add <url|file> Import GPG key
4666
+ pag key-list List trusted keys
4667
+ pag key-remove <id> Remove key
4668
+ pag key-trust <repo> Pin repo signing key fingerprint (no TOFU)
4669
+ pag key-untrust <repo> Forget repo fingerprint (back to TOFU)
4670
+ pag key-trusted List pinned repo fingerprints
4671
+
4672
+ADVANCED:
4673
+ pag why <pkg> Show why a package is installed
4674
+ pag autoremove Auto-remove orphaned dependencies
4675
+ pag pin <pkg> [ver] Pin package version
4676
+ pag unpin <pkg> Unpin
4677
+ pag pinned List pinned
4678
+ pag history Transaction history
4679
+ pag rollback Rollback last transaction
4680
+ pag remove-orphans Remove orphaned deps
4681
+ pag repo-add <url> [name] Add repository (drop-in /etc/pag/repos/)
4682
+ pag repo-list List repositories
4683
+ pag sbom export [fmt] SBOM manifest (spdx|cyclonedx)
4684
+
4685
+FLATPAK:
4686
+ pag flatpak [<query>] Search & install (smart)
4687
+ pag flatpak search <q> Search Flathub
4688
+ pag flatpak install <id> Install flatpak
4689
+ pag flatpak remove <id> Remove flatpak
4690
+ pag flatpak list List installed flatpaks
4691
+ pag flatpak update Update all flatpaks
4692
+ pag flatpak info <id> Show flatpak details
4693
+
4694
+IMMUTABLE OS (PAG_IMMUTABLE=1):
4695
+ pag deploy-list List all deployments
4696
+ pag deploy-rollback Switch to previous deployment
4697
+ pag deploy-cleanup [N] Remove old deployments (keep last N, default 3)
4698
+ pag initramfs-update Rebuild initramfs for current kernel/deployment
4699
+ pag grub-update Regenerate GRUB entries for all deployments
4700
+"""
4701
+
4702
+USAGE_PL = """pag v3 – Pagan Linux Package Manager
4703
+
4704
+PODSTAWOWE:
4705
+ pag install <pkg>... Instalacja pakietów
4706
+ pag remove <pkg>... Usuwanie pakietów
4707
+ pag update Aktualizacja PAKIETÓW (odświeża indeksy)
4708
+ pag sync Odśwież indeksy + info o aktualizacjach
4709
+ pag upgrade Aktualizacja SYSTEMU (pakiety + kernel/initramfs/GRUB)
4710
+ pag list [--installed] Lista dostępnych / zainstalowanych
4711
+ pag search <query> Szukaj pakietów
4712
+ pag info <pkg> Szczegóły pakietu
4713
+ pag files <pkg> Lista plików pakietu
4714
+ pag verify [--deep] Weryfikacja integralności
4715
+ pag clean Wyczyść cache pobierania
4716
+ pag stats Statystyki systemu
4717
+ pag download <pkg>... Pobierz do cache (offline)
4718
+
4719
+BEZPIECZEŃSTWO:
4720
+ pag key-add <url|file> Importuj klucz GPG
4721
+ pag key-list Lista zaufanych kluczy
4722
+ pag key-remove <id> Usuń klucz
4723
+ pag key-trust <repo> Przypnij fingerprint klucza repo (bez TOFU)
4724
+ pag key-untrust <repo> Zapomnij fingerprint repo (powrót do TOFU)
4725
+ pag key-trusted Lista przypiętych fingerprintów repo
4726
+
4727
+ZAAWANSOWANE:
4728
+ pag why <pkg> Dlaczego pakiet jest zainstalowany
4729
+ pag autoremove Usuń osierocone zależności
4730
+ pag pin <pkg> [ver] Przypnij wersję pakietu
4731
+ pag unpin <pkg> Odepnij
4732
+ pag pinned Lista przypiętych
4733
+ pag history Historia transakcji
4734
+ pag rollback Cofnij ostatnią transakcję
4735
+ pag remove-orphans Usuń osierocone zależności
4736
+ pag repo-add <url> [nazwa] Dodaj repozytorium (drop-in w /etc/pag/repos/)
4737
+ pag repo-list Lista repozytoriów
4738
+ pag sbom export [fmt] Manifest SBOM (spdx|cyclonedx)
4739
+
4740
+FLATPAK:
4741
+ pag flatpak [<query>] Szukaj i instaluj
4742
+ pag flatpak search <q> Szukaj na Flathub
4743
+ pag flatpak install <id> Zainstaluj flatpak
4744
+ pag flatpak remove <id> Usuń flatpak
4745
+ pag flatpak list Lista zainstalowanych
4746
+ pag flatpak update Aktualizuj wszystkie
4747
+ pag flatpak info <id> Szczegóły flatpaka
4748
+
4749
+IMMUTABLE OS (PAG_IMMUTABLE=1):
4750
+ pag deploy-list Lista wdrożeń
4751
+ pag deploy-rollback Przełącz na poprzednie wdrożenie
4752
+ pag deploy-cleanup [N] Usuń stare wdrożenia (zachowaj N, domyślnie 3)
4753
+ pag initramfs-update Przebuduj initramfs
4754
+ pag grub-update Regeneruj wpisy GRUB"""
4755
+
4756
+def _get_usage():
4757
+ if LANG == "pl":
4758
+ return USAGE_PL
4759
+ return USAGE_EN
4760
+
4761
+
4762
+def main():
4763
+ if len(sys.argv) >= 2 and sys.argv[1] in ("--version", "-V", "version"):
4764
+ print(f"pag {PAG_VERSION}")
4765
+ sys.exit(0)
4766
+ if len(sys.argv) < 2:
4767
+ print(_get_usage()); sys.exit(0)
4768
+
4769
+ cmd = sys.argv[1]
4770
+ args = sys.argv[2:]
4771
+
4772
+ # --- Komendy TYLKO DO ODCZYTU (nie wymagają roota) ---
4773
+ READ_ONLY = {
4774
+ "list": lambda: cmd_list("--installed" in args),
4775
+ "search": lambda: cmd_search(args[0]) if args else print("Usage: pag search <query>"),
4776
+ "info": lambda: cmd_info(args[0]) if args else print("Usage: pag info <pkg>"),
4777
+ "files": lambda: cmd_files(args[0]) if args else print("Usage: pag files <pkg>"),
4778
+ "verify": lambda: cmd_verify("--deep" in args),
4779
+ "why": lambda: cmd_why(args[0]) if args else print("Usage: pag why <pkg>"),
4780
+ "stats": cmd_stats,
4781
+ "pinned": cmd_pinned,
4782
+ "history": cmd_history,
4783
+ "repo-list": cmd_repo_list,
4784
+ "key-list": cmd_key_list,
4785
+ "key-trusted": cmd_key_trusted,
4786
+ "flatpak": lambda: cmd_flatpak(args),
4787
+ "flatpak-search": lambda: cmd_flatpak_search(args[0]) if args else print("Usage: pag flatpak-search <query>"),
4788
+ "flatpak-list": cmd_flatpak_list,
4789
+ "flatpak-info": lambda: cmd_flatpak_info(args[0]) if args else print("Usage: pag flatpak-info <id>"),
4790
+ "deploy-list": cmd_deploy_list,
4791
+ "deploy": cmd_deploy_list,
4792
+ "sbom": lambda: cmd_sbom(args),
4793
+ }
4794
+
4795
+ if cmd in READ_ONLY:
4796
+ sys.exit(READ_ONLY[cmd]() or 0)
4797
+
4798
+ # --- Smart search: `pag <nazwa-pakietu>` → repo + Flathub + sugestie ---
4799
+ WRITE_CMDS = {
4800
+ "install", "remove", "update", "sync", "upgrade", "clean", "download",
4801
+ "autoremove", "remove-orphans", "pin", "unpin", "rollback",
4802
+ "repo-add", "key-add", "key-remove", "key-trust", "key-untrust",
4803
+ "self-update",
4804
+ "flatpak", "flatpak-install", "flatpak-remove", "flatpak-update",
4805
+ "deploy-rollback", "deploy-cleanup", "initramfs-update", "grub-update",
4806
+ }
4807
+ if cmd not in WRITE_CMDS:
4808
+ # Literówka komendy? (np. `pag instal steam` zamiast `pag install`) –
4809
+ # zasugeruj poprawną komendę ZAMIAST wpadać w smart search (który
4810
+ # potrafi wisieć na `flatpak search` aż do Ctrl-C).
4811
+ _known = set(READ_ONLY) | set(WRITE_CMDS)
4812
+ _close = difflib.get_close_matches(cmd, _known, n=1, cutoff=0.75)
4813
+ if _close:
4814
+ print(f"❌ Nieznana komenda: '{cmd}'. Czy chodziło o '{_close[0]}'?")
4815
+ print(f" Uruchom 'pag' bez argumentów, aby zobaczyć listę komend.")
4816
+ sys.exit(1)
4817
+ sys.exit(_smart_search(" ".join([cmd] + args)) or 0)
4818
+
4819
+ # Obsługa flag globalnych (-y/--yes)
4820
+ global_args = []
4821
+ for a in args:
4822
+ if a in ("-y", "--yes"):
4823
+ os.environ["PAG_YES"] = "1"
4824
+ else:
4825
+ global_args.append(a)
4826
+ args = global_args
4827
+
4828
+ # --- Komendy ZAPISU (wymagają roota) ---
4829
+ if os.geteuid() != 0:
4830
+ print(f"❌ {_('root_required')}", file=sys.stderr); sys.exit(1)
4831
+
4832
+ ensure_dirs()
4833
+
4834
+ with DatabaseLock():
4835
+ WRITE_COMMANDS = {
4836
+ "install": lambda: cmd_install(
4837
+ [a for a in args if a not in ("-f", "--force")],
4838
+ upgrade=("-f" in args or "--force" in args)),
4839
+ "remove": lambda: cmd_remove(args),
4840
+ "update": lambda: cmd_update(do_upgrade=True),
4841
+ "sync": lambda: cmd_update(do_upgrade=False),
4842
+ "upgrade": cmd_upgrade,
4843
+ "clean": cmd_clean,
4844
+ "download": lambda: cmd_download(args),
4845
+ "autoremove": cmd_autoremove,
4846
+ "remove-orphans": cmd_remove_orphans,
4847
+ "pin": lambda: cmd_pin(args[0], args[1] if len(args)>1 else ""),
4848
+ "unpin": lambda: cmd_unpin(args[0]) if args else print("Usage: pag unpin <pkg>"),
4849
+ "rollback": cmd_rollback,
4850
+ "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]"),
4851
+ "key-add": lambda: cmd_key_add(args[0]) if args else print("Usage: pag key-add <url|file>"),
4852
+ "key-remove": lambda: cmd_key_remove(args[0]) if args else print("Usage: pag key-remove <id>"),
4853
+ "key-trust": lambda: cmd_key_trust(args[0]) if args else print("Usage: pag key-trust <repo_url>"),
4854
+ "key-untrust": lambda: cmd_key_untrust(args[0]) if args else print("Usage: pag key-untrust <repo_url>"),
4855
+ "self-update": cmd_self_update,
4856
+ "flatpak": lambda: cmd_flatpak(args),
4857
+ "flatpak-install": lambda: _flatpak_smart_install(args) if args else print("Usage: pag flatpak-install <app>"),
4858
+ "flatpak-remove": lambda: _flatpak_smart_remove(args) if args else print("Usage: pag flatpak-remove <app>"),
4859
+ "flatpak-update": cmd_flatpak_update,
4860
+ "deploy-rollback": cmd_deploy_rollback,
4861
+ "deploy-cleanup": lambda: cmd_deploy_cleanup(int(args[0]) if args else 3),
4862
+ "initramfs-update": cmd_initramfs_update,
4863
+ "grub-update": cmd_grub_update,
4864
+ }
4865
+
4866
+ fn = WRITE_COMMANDS.get(cmd)
4867
+ if fn:
4868
+ sys.exit(fn() or 0)
4869
+ # Should never reach here – _smart_search handles unknowns
4870
+ sys.exit(_smart_search(" ".join([cmd] + args)) or 0)
4871
+
4872
+if __name__ == "__main__":
4873
+ try:
4874
+ main()
4875
+ except KeyboardInterrupt:
4876
+ # Ctrl-C (np. podczas flatpak search / pobierania) – bez tracebacka
4877
+ print("\n ⚠ Przerwano (Ctrl-C).")
4779
4878
sys.exit(130)