🔒 Repository is read-only – file editing is disabled.

pagan-web/build-pagan.sh main

2486 linii Raw ← Powrót
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486
#!/bin/bash
# =============================================================================
# build-pagan-complete.sh - Kompletny builder Pagan Linux
# =============================================================================
# Pełna budowa: LFS Ch. 5, 6, 7, 8 + BLFS + Kernel 6.18.43 + systemd + GRUB
# =============================================================================

set -euo pipefail

# ========================= KONFIGURACJA =========================
# Absolutna ścieżka do katalogu skryptów – działa nawet po `cd /` w main()
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

PAGAN_ROOT="${PAGAN_ROOT:-/mnt/pagan}"
PAGAN_VERSION="${PAGAN_VERSION:-0.0.1}"
PAGAN_DE="${PAGAN_DE:-xfce}"                   # gnome (Wayland domyślnie) | xfce | deepin | budgie
PAGAN_RELEASE="2026.07"
LFS_VERSION="13.0"

# Kernel (można zmienić: KERNEL_VERSION=7.1.5 dla latest, KERNEL_VERSION=6.12.98 dla starszego LTS)
KERNEL_VERSION="${KERNEL_VERSION:-6.18.43}"
KERNEL_URL="https://cdn.kernel.org/pub/linux/kernel/v6.x/linux-${KERNEL_VERSION}.tar.xz"

# Hardware
MAKEFLAGS="-j$(nproc)"
LFS_TGT="$(uname -m)-pagan-linux-gnu"

# Ścieżki
SRC_DIR="$PAGAN_ROOT/sources"
TOOLS_DIR="$PAGAN_ROOT/tools"
CROSS_BIN="$TOOLS_DIR/bin"
OUTPUT_DIR="${OUTPUT_DIR:-/var/pagan-build/output}"
mkdir -p "$OUTPUT_DIR"

# Artefakt końcowy: img | iso | both | ask
ARTIFACT_MODE="${ARTIFACT_MODE:-img}"
# Wymuś pełne czyszczenie i budowę od zera: 1|true|yes
REBUILD_FROM_SCRATCH="${REBUILD_FROM_SCRATCH:-0}"

# Rozmiar obrazu IMG (MB)
IMAGE_SIZE="${IMAGE_SIZE:-16384}"  # 16GB

# ========================= SYSTEM LOGÓW =========================
# Poziomy: 0=DEBUG 1=INFO 2=WARN 3=ERROR
: "${PAGAN_LOG_LEVEL:=0}"

LOG_FILE="/var/log/pagan-build.log"
SUMMARY_FILE="/var/log/pagan-build.summary.log"
mkdir -p "$(dirname "$LOG_FILE")"

# Inicjalizuj plik logu
cat > "$LOG_FILE" <<EOF
╔══════════════════════════════════════════════════════════════════╗
║  Pagan Linux Builder v${PAGAN_VERSION} – Log budowy
║  Start: $(date '+%Y-%m-%d %H:%M:%S')  |  DE: ${PAGAN_DE^^}  |  CPU: $(nproc) rdzeni
╚══════════════════════════════════════════════════════════════════╝
EOF
echo "" > "$SUMMARY_FILE"

# ========================= KOLORY (tylko konsola) =========================
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'
BLUE='\033[0;34m'; MAGENTA='\033[0;35m'; CYAN='\033[0;36m'
BOLD='\033[1m'; DIM='\033[2m'; NC='\033[0m'

# ========================= INTERFEJS UŻYTKOWNIKA =========================
source "$SCRIPT_DIR/ui.sh"
ui_init

# ========================= STATYSTYKI =========================
PKG_BUILT=0; PKG_FAILED=0; PKG_SKIPPED=0
RESUME_FILE="${RESUME_FILE:-/var/log/pagan-build.done}"

# ========================= SYSTEM RESUME =========================
# Sprawdza czy pakiet był już zbudowany
_is_built() {
    local pkg="$1"
    # --force-pkg nadpisuje resume
    [[ -n "${FORCE_PKGS:-}" ]] && [[ ",${FORCE_PKGS}," == *",${pkg},"* || ",${FORCE_PKGS}," == *",${pkg%%-*},"* ]] && return 1
    [[ -f "$RESUME_FILE" ]] && grep -qxF "$pkg" "$RESUME_FILE" 2>/dev/null
}
# Oznacza pakiet jako zbudowany
_mark_built() {
    local pkg="$1"
    mkdir -p "$(dirname "$RESUME_FILE")"
    echo "$pkg" >> "$RESUME_FILE"
}

_is_true() {
    case "${1:-}" in
        1|true|TRUE|yes|YES|on|ON|y|Y) return 0 ;;
        *) return 1 ;;
    esac
}

clean_build_state() {
    step "Tryb: zbuduj od nowa"

    if [[ -z "$PAGAN_ROOT" || "$PAGAN_ROOT" == "/" ]]; then
        error "Niebezpieczny PAGAN_ROOT='$PAGAN_ROOT' - odmawiam czyszczenia"
    fi

    if declare -F umount_virtual_fs >/dev/null; then
        umount_virtual_fs >/dev/null 2>&1 || true
    fi

    warn "Czyszczenie katalogu builda: $PAGAN_ROOT"
    rm -rf --one-file-system "$PAGAN_ROOT"
    rm -f "$RESUME_FILE"

    mkdir -p "$PAGAN_ROOT" "$OUTPUT_DIR"
    ok "Wyczyszczono rootfs i stan resume; start od zera"
}

# ========================= FUNKCJE LOGOWANIA =========================
# _log_raw <kolor> <poziom> <msg> – zapisuje do pliku (bez kolorów) i na konsolę
_log_raw() {
    local color="$1" lvl="$2" msg="$3"
    local ts; ts=$(date '+%H:%M:%S')
    echo -e "${color}[${ts}] [${lvl}]${NC} $msg"
    echo "[${ts}] [${lvl}] $msg" >> "$LOG_FILE"
}

dbg() {
    [[ $PAGAN_LOG_LEVEL -le 0 ]] && _log_raw "${DIM}" "DEBUG" "$*" || true
}
info() {
    [[ $PAGAN_LOG_LEVEL -le 1 ]] && _log_raw "${BLUE}" "INFO " "$*" || true
}
warn() {
    [[ $PAGAN_LOG_LEVEL -le 2 ]] && _log_raw "${YELLOW}" "WARN " "$*" >&2 || true
}
error() {
    _log_raw "${RED}" "ERROR" "$*" >&2
    _dump_stack
    _log_raw "${RED}" "FATAL" "Budowa przerwana. Log: $LOG_FILE" >&2
    exit 1
}
ok() {
    _log_raw "${GREEN}" "OK   " "$*"
    ((PKG_BUILT++)) || true
    echo "✓ $*" >> "$SUMMARY_FILE"
}

step() {
    local title="$*"
    echo ""
    echo -e "${MAGENTA}${BOLD}═══ ${title} ═══${NC}"
    echo "━━━ $(date '+%H:%M:%S') ━━━ ${title} ━━━" >> "$LOG_FILE"
    dbg "START: $title"
}

_dump_stack() {
    local frame=0
    echo "  Stack trace:" >> "$LOG_FILE"
    while caller $frame 2>/dev/null; do
        ((frame++))
    done >> "$LOG_FILE"
}

# Trap błędów – łapie SIGERR
_on_error() {
    local lineno="$1" cmd="$2"
    echo -e "${RED}[ERROR]${NC} Linia ${lineno}: \"${cmd}\"" | tee -a "$LOG_FILE" >&2
    echo "[$(date '+%H:%M:%S')] [ERROR] Linia ${lineno}: ${cmd}" >> "$LOG_FILE"
    _dump_stack
}
trap '_on_error "${LINENO}" "${BASH_COMMAND}"' ERR

# Podsumowanie na wyjściu
_show_summary() {
    # Best-effort cleanup: avoid stale mounts after cancel/error.
    if declare -F umount_virtual_fs >/dev/null; then
        umount_virtual_fs >/dev/null 2>&1 || true
    fi

    ui_summary
}
trap _show_summary EXIT

# ========================= KONFIGURACJA =========================

# ========================= BANNER =========================
show_banner() {
    cat << EOF
╔═══════════════════════════════════════════════════════════════════╗
║                                                                   ║
║    ██████   █████   █████   █████  ███    ██                      ║
║    ██   ██ ██   ██ ██      ██   ██ ████   ██                      ║
║    ██████  ███████ ██████  ███████ ██ ██  ██                      ║
║    ██      ██   ██ ██   ██ ██   ██ ██  ██ ██                      ║
║    ██      ██   ██  █████  ██   ██ ██   ████                      ║
║                                                                   ║
║    ╔══════════════════════════════════════════════════════════╗   ║
║    ║  🐉  Pagan Linux Builder v${PAGAN_VERSION}                       ║   ║
║    ║  📦  LFS ${LFS_VERSION} + BLFS + ${PAGAN_DE^^}                 ║   ║
║    ║  🖥️  Architektura: $(uname -m)                               ║   ║
║    ║  📅  Data: $(date +'%Y-%m-%d %H:%M:%S')                    ║   ║
║    ╚══════════════════════════════════════════════════════════╝   ║
║                                                                   ║
╚═══════════════════════════════════════════════════════════════════╝
EOF
}

# ========================= SPRAWDZANIE ZALEŻNOŚCI =========================
check_dependencies() {
    step "Sprawdzanie zależności systemowych"

    local deps=(
        "gcc" "g++" "make" "bison" "flex" "texinfo" "bc"
        "wget" "curl" "tar" "xz" "bzip2" "gzip"
        "patch" "gawk" "sed" "grep" "find"
        "file" "diff" "cmp"
        "python3" "perl" "m4" "cmake"
        "git" "rsync" "cpio" "gpg" "pkg-config"
        "xorriso" "mkfs.fat" "parted" "mksquashfs"
        "ninja" "meson" "glib-mkenums" "g-ir-scanner" "intltool-update" "iceauth"
    )

    local missing=()
    for dep in "${deps[@]}"; do
        if ! command -v "$dep" &>/dev/null; then
            missing+=("$dep")
        fi
    done

    if [[ ${#missing[@]} -gt 0 ]]; then
        warn "Brakujące pakiety: ${missing[*]}"
        info "Instalowanie brakujących pakietów..."

        if command -v apt-get &>/dev/null; then
            apt-get update
            apt-get install -y "${missing[@]}" \
                libncurses-dev libssl-dev libreadline-dev \
                libxml2-dev libxslt1-dev libglib2.0-dev \
                libgtk-3-dev libpango1.0-dev libcairo2-dev \
                libx11-dev libxext-dev libxft-dev \
                libfreetype6-dev libfontconfig1-dev \
                libjpeg-dev libpng-dev libtiff-dev \
                libgdk-pixbuf2.0-dev libnotify-dev \
                libdbus-1-dev libsystemd-dev libudev-dev libmnl-dev libevdev-dev \
                libelf-dev libffi-dev libunistring-dev libacl1-dev libattr1-dev \
                libpam0g-dev libgirepository1.0-dev gobject-introspection \
                libqt5svg5-dev qtbase5-dev qtdeclarative5-dev qttools5-dev \
                shared-mime-info intltool xsltproc gperf valac gcc-multilib \
                libc6-dev-i386 python3-pip python3-venv
        elif command -v dnf &>/dev/null; then
            dnf groupinstall -y "Development Tools" "Development Libraries"
            dnf install -y "${missing[@]}" \
                ncurses-devel openssl-devel readline-devel \
                libxml2-devel libxslt-devel glib2-devel \
                gtk3-devel pango-devel cairo-devel \
                libX11-devel libXext-devel libXft-devel \
                freetype-devel fontconfig-devel \
                libjpeg-devel libpng-devel libtiff-devel \
                gdk-pixbuf2-devel libnotify-devel \
                dbus-devel systemd-devel libudev-devel libmnl-devel libevdev-devel \
                elfutils-libelf-devel libffi-devel libacl-devel libattr-devel \
                pam-devel gobject-introspection-devel qt5-qtbase-devel \
                qt5-qtdeclarative-devel qt5-qtsvg-devel shared-mime-info intltool \
                libxslt-devel gperf vala gcc-c++ multilib-rpm-config \
                python3-devel python3-pip
        elif command -v pacman &>/dev/null; then
            # Mapowanie nazw: Debian/Ubuntu → Arch
            local arch_pkgs=()
            for dep in "${missing[@]}"; do
                case "$dep" in
                    xz) arch_pkgs+=("xz") ;;
                    mkfs.fat) arch_pkgs+=("dosfstools") ;;
                    mksquashfs) arch_pkgs+=("squashfs-tools") ;;
                    find) arch_pkgs+=("findutils") ;;
                    diff|cmp) arch_pkgs+=("diffutils") ;;
                    libjpeg|libjpeg-dev) arch_pkgs+=("libjpeg-turbo") ;;
                    glib-mkenums) arch_pkgs+=("glib2-devel") ;;
                    g-ir-scanner) arch_pkgs+=("gobject-introspection") ;;
                    g++) arch_pkgs+=("gcc") ;;
                    intltool-update) arch_pkgs+=("intltool") ;;
                    *) arch_pkgs+=("$dep") ;;
                esac
            done
            pacman -Sy --noconfirm --needed base-devel "${arch_pkgs[@]}" \
                ncurses openssl readline libxml2 libxslt glib2 glib2-devel \
                gtk3 pango cairo libx11 libxext libxft xtrans xorg-util-macros intltool \
                freetype2 fontconfig libjpeg-turbo libpng libtiff \
                gdk-pixbuf2 libnotify dbus systemd \
                elfutils libffi python python-pip wayland-protocols
        else
            error "Nieznany menedżer pakietów. Zainstaluj ręcznie: ${missing[*]}"
        fi
    fi

    ok "Wszystkie zależności spełnione"
}

# ========================= INICJALIZACJA =========================
init_build() {
    step "Inicjalizacja środowiska budowy"
    cd /

    mkdir -p "$PAGAN_ROOT" "$SRC_DIR" "$TOOLS_DIR" "$OUTPUT_DIR"

    # Katalogi systemowe
    for dir in usr bin sbin lib lib64 etc var boot home root \
                opt tmp run mnt media srv; do
        mkdir -p "$PAGAN_ROOT/$dir"
    done

    # Katalogi PAG
    mkdir -p "$PAGAN_ROOT/var/lib/pag"{,/packages,/snapshots}
    mkdir -p "$PAGAN_ROOT/var/cache/pag"

    # Deploymenty
    mkdir -p "$PAGAN_ROOT/.deployments"

    ok "Środowisko zainicjowane w: $PAGAN_ROOT"
}

# ========================= POBIERANIE PAKIETÓW =========================
_spinner() {
    local pid=$1 delay=0.1 spinstr='⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏' text="${2:-}"
    local i=0
    while kill -0 "$pid" 2>/dev/null; do
        i=$(( (i+1) % ${#spinstr} ))
        printf '\r  %s %s' "${spinstr:$i:1}" "$text"
        sleep "$delay"
    done
    printf '\r  ✓ %s\n' "$text"
}

_archive_is_valid() {
    local file="$1"
    [[ -s "$file" ]] || return 1

    case "$file" in
        *.tar.xz) xz -t "$file" >/dev/null 2>&1 ;;
        *.tar.gz|*.tgz) gzip -t "$file" >/dev/null 2>&1 ;;
        *.tar.bz2|*.tbz2) bzip2 -t "$file" >/dev/null 2>&1 ;;
        *.tar.zst)
            if command -v zstd >/dev/null 2>&1; then
                zstd -t "$file" >/dev/null 2>&1
            else
                unzstd -t "$file" >/dev/null 2>&1
            fi
            ;;
        *.tar) tar -tf "$file" >/dev/null 2>&1 ;;
        *.zip) unzip -tqq "$file" >/dev/null 2>&1 ;;
        *) ! file "$file" 2>/dev/null | grep -qE "HTML document|XML document|ASCII text|empty" ;;
    esac
}

download_pkg() {
    local url="$1" dest="$2" sha="${3:-SKIP}" force="${4:-0}"
    mkdir -p "$(dirname "$dest")"

    if [[ "$force" != "1" && -f "$dest" ]]; then
        if _archive_is_valid "$dest"; then
            info "  ⏭ $(basename "$dest") – już pobrany"
            return 0
        fi
        warn "Uszkodzone archiwum: $(basename "$dest") – pobieram ponownie"
        rm -f "$dest"
    fi

    # Lista adresów do próby (główny + mirror)
    local urls=("$url")
    case "$url" in
        *ftp.gnu.org/gnu/*)
            urls+=("https://mirror.kumi.systems/gnu/${url#https://ftp.gnu.org/gnu/}")
            urls+=("https://mirrors.ocf.berkeley.edu/gnu/${url#https://ftp.gnu.org/gnu/}")
            urls+=("https://ftp.nluug.nl/pub/gnu/${url#https://ftp.gnu.org/gnu/}")
            ;;
        *cdn.kernel.org/*|*www.kernel.org/*)
            urls+=("https://mirrors.edge.kernel.org/${url#https://cdn.kernel.org/}")
            urls+=("https://mirrors.edge.kernel.org/${url#https://www.kernel.org/}")
            ;;
        *download.savannah.gnu.org*)
            urls+=("$(echo "$url" | sed 's|https://download.savannah.gnu.org|https://mirror.rabisu.com/mirrors/savannah|')")
            ;;
        *github.com*releases*download*.tar.xz)
            # GitHub: próbuj .tar.gz zamiast .tar.xz (nie zawsze jest .tar.xz)
            urls+=("${url%.tar.xz}.tar.gz")
            ;;
        *github.com*releases*download*.tar.bz2)
            urls+=("${url%.tar.bz2}.tar.gz")
            ;;
        *prdownloads.sourceforge.net*|*downloads.sourceforge.net*|*download.sourceforge.net*)
            urls+=("${url}?download")
            ;;
        *sourceforge.net/projects/*)
            urls+=("$(echo "$url" | sed 's|https://sourceforge.net/projects/|https://downloads.sourceforge.net/|')?download")
            ;;
    esac

    local ok=0
    for u in "${urls[@]}"; do
        if [[ "$u" != "$url" ]]; then
            info "  ↻ Próbuję mirror: $u"
        fi
        rm -f "$dest"
        if wget -q --show-progress -O "$dest" "$u" 2>/dev/null || \
           curl -f -# -L -o "$dest" "$u" 2>/dev/null; then
            # Sprawdź czy archiwum jest poprawne (nie ucięte/nie HTML)
            if _archive_is_valid "$dest"; then
                ok=1
                break
            fi
            warn "Pobrano uszkodzony/błędny plik z $u – próbuję kolejne źródło"
        fi
    done

    if [[ $ok -eq 0 ]]; then
        rm -f "$dest"
        error "Nie udało się pobrać: $url"
    fi

    info "  ✓ $(basename "$dest")"
}

# ========================= BUDOWA PAKIETU LFS =========================
build_lfs_pkg() {
    local pkg_name="$1"
    local pkg_version="$2"
    local pkg_url="$3"
    local pkg_sha="$4"
    local pkg_config="$5"

    # Prawdziwa nazwa pliku z URL – niezależna od pkg_name
    local archive
    archive=$(basename "$pkg_url" | sed 's/?.*//')

    local archive_path="$SRC_DIR/$archive"
    local pkg_dir="$SRC_DIR/build-${pkg_name}"

    ((UI_PKG_N++)) || true

    # Resume – pomiń jeśli pakiet już zbudowany
    if _is_built "${pkg_name}-${pkg_version}"; then
        ui_skip "${pkg_name}-${pkg_version}"
        ((PKG_SKIPPED++)) || true
        return 0
    fi

    info "  📦 Budowanie: ${pkg_name}-${pkg_version}"

    download_pkg "$pkg_url" "$archive_path" "$pkg_sha"

    rm -rf "$pkg_dir"
    mkdir -p "$pkg_dir"

    # Sprawdź czy archiwum ma katalog nadrzędny (np. gcc-14.2.0/) czy jest płaskie (tzdata)
    local _strip=""
    local _tar_first _tar_second
    tar tf "$archive_path" > /tmp/_tar_first.tmp 2>/dev/null || true
    _tar_first=$(sed -n '1p' /tmp/_tar_first.tmp 2>/dev/null)
    _tar_second=$(sed -n '2p' /tmp/_tar_first.tmp 2>/dev/null)
    rm -f /tmp/_tar_first.tmp
    # Niektóre tarballe (np. openssh) listują katalog nadrzędny BEZ końcowego '/',
    # więc jeśli 1. wpis nie ma '/', ale 2. już ma → to katalog nadrzędny.
    if [[ "$_tar_first" == *"/"* ]]; then
        _strip="--strip-components=1"
    elif [[ -n "$_tar_second" && "$_tar_second" == *"/"* ]]; then
        _strip="--strip-components=1"
    fi

    case "$archive" in
        *.tar.xz) tar -xf "$archive_path" -C "$pkg_dir" $_strip ;;
        *.tar.gz) tar -xf "$archive_path" -C "$pkg_dir" $_strip ;;
        *.tar.zst) unzstd -d "$archive_path" -o "$SRC_DIR/${archive%.zst}" && \
                    tar -xf "$SRC_DIR/${archive%.zst}" -C "$pkg_dir" $_strip ;;
        *.tar.bz2|*.tbz2) tar -xjf "$archive_path" -C "$pkg_dir" $_strip ;;
        *.tgz) tar -xzf "$archive_path" -C "$pkg_dir" $_strip ;;
        *.tar) tar -xf "$archive_path" -C "$pkg_dir" $_strip ;;
        *.zip) unzip -q "$archive_path" -d "$pkg_dir" ;;
        # Pliki bez archiwum (np. .pem, .crt) – kopiuj bezpośrednio
        *) cp "$archive_path" "$pkg_dir/$(basename "$archive")" ;;
    esac || {
        warn "Rozpakowanie $pkg_name nieudane – wymuszam ponowne pobranie i retry"
        rm -f "$archive_path" "$SRC_DIR/${archive%.zst}"
        download_pkg "$pkg_url" "$archive_path" "$pkg_sha" 1
        case "$archive" in
            *.tar.xz) tar -xf "$archive_path" -C "$pkg_dir" $_strip ;;
            *.tar.gz) tar -xf "$archive_path" -C "$pkg_dir" $_strip ;;
            *.tar.zst) unzstd -d "$archive_path" -o "$SRC_DIR/${archive%.zst}" && tar -xf "$SRC_DIR/${archive%.zst}" -C "$pkg_dir" $_strip ;;
            *.tar.bz2|*.tbz2) tar -xjf "$archive_path" -C "$pkg_dir" $_strip ;;
            *.tgz) tar -xzf "$archive_path" -C "$pkg_dir" $_strip ;;
            *.tar) tar -xf "$archive_path" -C "$pkg_dir" $_strip ;;
            *.zip) unzip -q "$archive_path" -d "$pkg_dir" ;;
            *) cp "$archive_path" "$pkg_dir/$(basename "$archive")" ;;
        esac || error "Rozpakowanie $pkg_name nieudane"
    }

    pushd "$pkg_dir" > /dev/null

    local pkg_log="$UI_LOG_DIR/${pkg_name}-${pkg_version}.log"

    if [[ -n "$pkg_config" && "$pkg_config" != "SKIP" ]]; then
        ui_build_eval "${pkg_name}-${pkg_version}" "$pkg_log" "$pkg_config" \
            || error "Configure failed for $pkg_name (log: $pkg_log)"
    fi

    # Pomijaj auto make/install jeśli pkg_config już robi wszystko sam
    local _skip_auto_make=0
    case "$pkg_config" in
        *"cp -"*)                _skip_auto_make=1 ;;
        *"cp "*)                 _skip_auto_make=1 ;;
        *"make install"*)        _skip_auto_make=1 ;;
        *"DESTDIR="*)            _skip_auto_make=1 ;;
        *"ninja"*)              _skip_auto_make=1 ;;
        *"pip3"*)               _skip_auto_make=1 ;;
        *"pip install"*)        _skip_auto_make=1 ;;
        *"cmake --install"*)    _skip_auto_make=1 ;;
        *"./bootstrap"*)        _skip_auto_make=1 ;;
        *"install -m"*)          _skip_auto_make=1 ;;
        *"osinfo-db-import"*)   _skip_auto_make=1 ;;
        *"PREFIX="*)             _skip_auto_make=1 ;;
        *"ZONEINFO="*)           _skip_auto_make=1 ;;
        make*)                   _skip_auto_make=1 ;;
    esac

    if [[ $_skip_auto_make -eq 0 ]]; then
        info "  🔨 Make: $pkg_name"
        ui_build_eval "${pkg_name}-${pkg_version} (make)" "$pkg_log" "make $MAKEFLAGS && make install" \
            || error "Make/Install failed for $pkg_name (log: $pkg_log)"
    fi

    popd > /dev/null
    rm -rf "$pkg_dir"

    # Remove .la files (libtool archives) – they have hardcoded paths, break cross-building
    find "$PAGAN_ROOT/usr/lib" -name "*.la" -delete 2>/dev/null || true

    # Fix .pc files: rewrite prefix paths so pkg-config finds target without SYSROOT
    for pc in "$PAGAN_ROOT/usr/lib/pkgconfig/"*.pc "$PAGAN_ROOT/usr/share/pkgconfig/"*.pc; do
        if [[ -f "$pc" ]]; then
            sed -i 's|^prefix=/usr$|prefix='"$PAGAN_ROOT"'/usr|' "$pc"
            # Remove bare -I${includedir} (without subdir) to avoid exposing target libc headers
            sed -i '/^Cflags:/ { s/ -I\${includedir} / /g; s/^-I\${includedir} //; s/ -I\${includedir}$// }' "$pc"
        fi
    done 2>/dev/null || true

    _mark_built "${pkg_name}-${pkg_version}"
    ok "  ✅ Zbudowano: $pkg_name-$pkg_version"
}

# ========================= ABI SANITY (TARGET ONLY) =========================
_max_ver_from_strings() {
    local file="$1" prefix="$2"
    strings -a "$file" 2>/dev/null \
        | rg -o "${prefix}_[0-9]+\.[0-9]+" 2>/dev/null \
        | sed "s/^${prefix}_//" \
        | sort -V \
        | tail -n 1 || true
}

_ver_gt() {
    # true jeśli $1 > $2
    [[ "$(printf '%s\n%s\n' "$1" "$2" | sort -V | tail -n 1)" == "$1" && "$1" != "$2" ]]
}

check_target_abi() {
    step "ABI sanity check (target LFS libs)"

    local target_libc="$PAGAN_ROOT/usr/lib/libc.so.6"
    if [[ ! -f "$target_libc" ]]; then
        warn "Brak $target_libc - pomijam ABI check"
        return 0
    fi

    local target_glibc
    target_glibc=$(_max_ver_from_strings "$target_libc" "GLIBC")
    if [[ -z "$target_glibc" ]]; then
        warn "Nie udało się odczytać wersji GLIBC z targetu - pomijam ABI check"
        return 0
    fi

    info "Target GLIBC (z $target_libc): $target_glibc"

    local bad=0
    while IFS= read -r so; do
        local req
        req=$(_max_ver_from_strings "$so" "GLIBC")
        [[ -z "$req" ]] && continue

        if _ver_gt "$req" "$target_glibc"; then
            warn "ABI mismatch (target): $(basename "$so") wymaga GLIBC_$req > GLIBC_$target_glibc"
            ((bad++)) || true
        fi
    done < <(find "$PAGAN_ROOT/usr/lib" -maxdepth 1 -type f -name '*.so*' 2>/dev/null)

    if [[ $bad -gt 0 ]]; then
        error "Wykryto $bad bibliotek(i) w targetowym $PAGAN_ROOT/usr/lib wymagających nowszego GLIBC niż LFS target. To nie jest host-check, tylko check targetu. Wyczyść $PAGAN_ROOT i zbuduj od nowa."
    fi

    ok "ABI sanity check targetu: OK"
}

# ========================= LFS PATCH CHECK (BEST-EFFORT) =========================
check_lfs_patches() {
    step "Sprawdzanie dostępnych patchy LFS (best-effort)"

    local patch_index_url="https://www.linuxfromscratch.org/patches/lfs/${LFS_VERSION}/"
    local html
    if ! html=$(curl -fsSL --max-time 20 "$patch_index_url" 2>/dev/null); then
        warn "Nie udało się pobrać indeksu patchy LFS: $patch_index_url"
        warn "Pomijam check patchy (build będzie kontynuowany)."
        return 0
    fi

    local tracked=(
        "bash-5.2.37" "bzip2-1.0.8" "coreutils-9.5" "diffutils-3.10"
        "findutils-4.10.0" "glibc-2.44" "grep-3.11" "gzip-1.13"
        "make-4.4.1" "openssl-3.3.2" "python-3.12.5" "sed-4.9"
        "systemd-256.4" "tar-1.35" "util-linux-2.40.2"
    )

    local found=0
    for pkg in "${tracked[@]}"; do
        if echo "$html" | rg -qi "${pkg}.*\.patch"; then
            warn "LFS patch dostępny dla: $pkg"
            ((found++)) || true
        fi
    done

    if [[ $found -eq 0 ]]; then
        ok "Nie wykryto oczywistych patchy dla śledzonych pakietów LFS ${LFS_VERSION}"
    else
        warn "Wykryto $found potencjalnych patchy LFS. Rozważ integrację przed release build."
    fi
}

report_artifacts() {
    step "LOKALIZACJE ARTEFAKTÓW"

    local img_file="$OUTPUT_DIR/Pagan-Linux-${PAGAN_VERSION}-${PAGAN_DE}.img"
    local iso_file="$OUTPUT_DIR/Pagan-Linux-${PAGAN_VERSION}-${PAGAN_DE}.iso"
    local printed=0

    if [[ -f "$img_file" ]]; then
        info "IMG: $img_file ($(du -h "$img_file" 2>/dev/null | cut -f1))"
        echo "IMG: $img_file" >> "$SUMMARY_FILE"
        printed=1
    fi
    if [[ -f "$iso_file" ]]; then
        info "ISO: $iso_file ($(du -h "$iso_file" 2>/dev/null | cut -f1))"
        echo "ISO: $iso_file" >> "$SUMMARY_FILE"
        printed=1
    fi

    if [[ $printed -eq 0 ]]; then
        warn "Nie znaleziono artefaktów IMG/ISO w $OUTPUT_DIR"
    fi
}

# ========================= BUDOWA TOOLCHAIN (Ch. 5) =========================
build_toolchain() {
    step "ROZDZIAŁ 5: BUDOWA TOOLCHAIN"

    ui_set_total 7

    export LC_ALL=POSIX
    export LFS="$PAGAN_ROOT"
    export LFS_TGT="$LFS_TGT"

    # 5.2 - Linux headers (host make)
    build_lfs_pkg "linux-headers-tc" "$KERNEL_VERSION" \
        "$KERNEL_URL" \
        "SKIP" \
        "make mrproper && make headers && find usr/include -type f ! -name '*.h' -delete && cp -rv usr/include $PAGAN_ROOT/usr"

    # 5.3 - GMP (statycznie – PRZED binutils, czysty host PATH!)
    # GCC 16 (C23) zabija stare testy GMP. -std=gnu89 dla configure (testy),
    # ale build potrzebuje C99 → make CFLAGS='-O2' (nadpisuje Makefile).
    build_lfs_pkg "gmp-tc" "6.3.0" \
        "https://ftp.gnu.org/gnu/gmp/gmp-6.3.0.tar.xz" \
        "SKIP" \
        "CFLAGS='-std=gnu89 -O2' ./configure --prefix=$TOOLS_DIR --enable-cxx --disable-shared --enable-static && make CFLAGS='-O2' $MAKEFLAGS && make install"

    # 5.4 - MPFR (host PATH)
    build_lfs_pkg "mpfr-tc" "4.2.1" \
        "https://ftp.gnu.org/gnu/mpfr/mpfr-4.2.1.tar.xz" \
        "SKIP" \
        "CFLAGS='-std=gnu89 -O2' ./configure --prefix=$TOOLS_DIR --disable-shared --enable-static --with-gmp=$TOOLS_DIR && make CFLAGS='-O2' $MAKEFLAGS && make install"

    # 5.5 - MPC (host PATH)
    build_lfs_pkg "mpc-tc" "1.3.1" \
        "https://ftp.gnu.org/gnu/mpc/mpc-1.3.1.tar.gz" \
        "SKIP" \
        "CFLAGS='-std=gnu89 -O2' ./configure --prefix=$TOOLS_DIR --disable-shared --enable-static --with-gmp=$TOOLS_DIR --with-mpfr=$TOOLS_DIR && make CFLAGS='-O2' $MAKEFLAGS && make install"

    # 5.6 - Binutils pass 1 (cross-tools – od teraz PATH=$TOOLS_DIR/bin:$PATH)
    export PATH="$TOOLS_DIR/bin:$PATH"
    build_lfs_pkg "binutils-pass1" "2.43.1" \
        "https://ftp.gnu.org/gnu/binutils/binutils-2.43.1.tar.xz" \
        "SKIP" \
        "mkdir -v build && cd build && ../configure --prefix=$TOOLS_DIR --with-sysroot=$PAGAN_ROOT --target=$LFS_TGT --disable-nls --enable-gprofng=no --disable-werror --disable-dependency-tracking && make $MAKEFLAGS && make install"

    # 5.7 - GCC pass 1 (cross-compiler)
    # GCC 16.1.1 host kompiluje GCC 14.2.0 źródła jako C++. safe-ctype.h
    # definiuje #define isgraph(c) do_not_use_isgraph..., a GCC16 <cctype>
    # robi using ::isgraph; → makro się rozwija → łamie parser locale_facets.h.
    # Fix: w system.h dodajemy #include <cctype> przed safe-ctype.h i
    #       #undef makr po nim.
    build_lfs_pkg "gcc-pass1" "14.2.0" \
        "https://ftp.gnu.org/gnu/gcc/gcc-14.2.0/gcc-14.2.0.tar.xz" \
        "SKIP" \
        'case $(uname -m) in x86_64) sed -e "/m64=/s/lib64/lib/" -i.orig gcc/config/i386/t-linux64 ;; esac; sed -i "s/__cplusplus != 201103/__cplusplus < 201103/g; s/__cplusplus > 201103/__cplusplus < 201103/g" libcody/configure 2>/dev/null || true; sed -i "/^#include \"safe-ctype.h\"/i #ifdef __cplusplus\n#include <cctype>\n#endif" gcc/system.h 2>/dev/null || true; sed -i "/^#include \"safe-ctype.h\"/a #ifdef __cplusplus\n#undef isalpha\n#undef isalnum\n#undef iscntrl\n#undef isdigit\n#undef isgraph\n#undef islower\n#undef isprint\n#undef ispunct\n#undef isspace\n#undef isupper\n#undef isxdigit\n#undef toupper\n#undef tolower\n#endif" gcc/system.h 2>/dev/null || true; mkdir -v build && cd build && ../configure --target='"$LFS_TGT"' --prefix='"$TOOLS_DIR"' --with-gmp='"$TOOLS_DIR"' --with-mpfr='"$TOOLS_DIR"' --with-mpc='"$TOOLS_DIR"' --with-glibc-version=2.44 --with-sysroot='"$PAGAN_ROOT"' --with-newlib --without-headers --enable-default-pie --enable-default-ssp --disable-nls --disable-shared --disable-multilib --disable-threads --disable-libatomic --disable-libgomp --disable-libquadmath --disable-libssp --disable-libvtv --disable-libstdcxx --enable-languages=c,c++ --enable-werror=no CXXFLAGS="-std=gnu++20 -O2 -Wno-error=return-type -fno-char8_t -Wno-deprecated-enum-enum-conversion" && make '"$MAKEFLAGS"' && make install && cd .. && ln -sf gcc '"$CROSS_BIN"'/cc'

    # 5.8 - Glibc (cross-kompilowana)
    build_lfs_pkg "glibc-tc" "2.44" \
        "https://ftp.gnu.org/gnu/glibc/glibc-2.44.tar.xz" \
        "SKIP" \
        "rm -rf $PAGAN_ROOT/usr/include/gnu $PAGAN_ROOT/usr/include/features.h $PAGAN_ROOT/usr/include/stdc-predef.h 2>/dev/null; mkdir -v build && cd build && ../configure --prefix=/usr --host=$LFS_TGT --build=\$(../scripts/config.guess) --enable-kernel=4.14 --with-headers=$PAGAN_ROOT/usr/include libc_cv_slibdir=/usr/lib --disable-werror CFLAGS=\"-O2 -Wno-error=maybe-uninitialized\" && make $MAKEFLAGS && make DESTDIR=$PAGAN_ROOT install"
    ok "Toolchain zbudowany!"
}

# ========================= BUDOWA SYSTEMU KOŃCOWEGO (Ch. 6) =========================
build_final_system() {
    step "ROZDZIAŁ 6-8: PEŁNY SYSTEM KOŃCOWY LFS 13.0"

    # Używamy NARZĘDZI HOSTA podczas budowy (nie chroot). $PAGAN_ROOT/usr/bin
    # celowo pomijamy: targetowe binarki (groff 1.23.0, msgfmt) nie działają na
    # hoście (szukają fontów/bibliotek w /usr lub nie mają LD_LIBRARY_PATH).
    # /usr/bin/core_perl+/vendor_perl: sudo resetuje PATH i gubi je (pod2man!).
    export PATH="$TOOLS_DIR/bin:/usr/bin/core_perl:/usr/bin/vendor_perl:$PATH"
    export LC_ALL=POSIX

    # Globalna kompatybilność z GCC 16 (Arch) – wycisza nowe warningi,
    # które stają się błędami przez -Werror w wielu projektach.
    # -std=gnu17: stare pakiety (gnulib: m4/coreutils/grep) nie rozumieją C23 ([[nodiscard]])
    export CFLAGS="-std=gnu17 -O2 -Wno-error=implicit-function-declaration -Wno-error=int-conversion -Wno-error=return-type -Wno-error=maybe-uninitialized -Wno-error=discarded-qualifiers -Wno-error=unterminated-string-initialization -Wno-error=incompatible-pointer-types -Wno-error=null-dereference -Wno-error=override-init"
    export CXXFLAGS="-O2 -Wno-error=return-type -Wno-error=maybe-uninitialized"
    # Coreutils (i inne GNU) odmawiają configure jako root bez tej zmiennej
    export FORCE_UNSAFE_CONFIGURE=1
    # Targetowe metadane mają pierwszeństwo podczas budowy systemu PaganOS.
    export PKG_CONFIG_DIR=""
    export PKG_CONFIG_PATH="$PAGAN_ROOT/usr/lib/pkgconfig:$PAGAN_ROOT/usr/lib/x86_64-linux-gnu/pkgconfig:$PAGAN_ROOT/usr/share/pkgconfig"
    export PKG_CONFIG_LIBDIR="$PAGAN_ROOT/usr/lib/pkgconfig:$PAGAN_ROOT/usr/lib/x86_64-linux-gnu/pkgconfig:$PAGAN_ROOT/usr/share/pkgconfig"
    export PKG_CONFIG_SYSROOT_DIR="$PAGAN_ROOT"
    # Linkuj z targetowymi libami (glibc 2.44, zgodne z hostem)
    # UWAGA: brak globalnego CPPFLAGS=-I$PAGAN_ROOT/usr/include — glibc budując sam siebie
    # nie może mieć -I na zainstalowane headery glibc (guard _LIBC w gnu/stubs-64.h)
    export LDFLAGS="-L$PAGAN_ROOT/usr/lib -L$PAGAN_ROOT/lib64 -Wl,-rpath-link,$PAGAN_ROOT/usr/lib -Wl,-rpath-link,$PAGAN_ROOT/lib64"

    local packages=(
        # ======== ADMINISTRACJA I KONFIGURACJA ========
        "man-pages:6.17:https://www.kernel.org/pub/linux/docs/man-pages/man-pages-6.17.tar.xz:SKIP:make -R prefix=/usr install"
        "iana-etc:20260202:https://github.com/Mic92/iana-etc/releases/download/20260202/iana-etc-20260202.tar.gz:SKIP:cp services protocols \$PAGAN_ROOT/etc"
        "tzdata:2025c:https://www.iana.org/time-zones/repository/releases/tzdata2025c.tar.gz:SKIP:ZONEINFO=\$PAGAN_ROOT/usr/share/zoneinfo && mkdir -p \$ZONEINFO && cp -r ./* \$ZONEINFO/"

        # ======== BIBLIOTEKI BAZOWE ========
        "glibc:2.44:https://ftp.gnu.org/gnu/glibc/glibc-2.44.tar.xz:SKIP:mkdir bld && cd bld && ../configure --prefix=/usr --enable-kernel=4.14 --enable-stack-protector=strong libc_cv_slibdir=/usr/lib --disable-werror CFLAGS=\"-O2 -Wno-error=maybe-uninitialized\" && make && make install DESTDIR=\$PAGAN_ROOT"
        "zlib:1.3.2:https://zlib.net/fossils/zlib-1.3.2.tar.gz:SKIP:./configure --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT"
        "bzip2:1.0.8:https://www.sourceware.org/pub/bzip2/bzip2-1.0.8.tar.gz:SKIP:make -f Makefile-libbz2_so && make install PREFIX=\$PAGAN_ROOT/usr"
        "xz:5.8.2:https://github.com/tukaani-project/xz/releases/download/v5.8.2/xz-5.8.2.tar.xz:SKIP:./configure --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT"
        "zstd:1.5.7:https://github.com/facebook/zstd/releases/download/v1.5.7/zstd-1.5.7.tar.gz:SKIP:make prefix=/usr && make prefix=/usr DESTDIR=\$PAGAN_ROOT install"
        "lz4:1.10.0:https://github.com/lz4/lz4/releases/download/v1.10.0/lz4-1.10.0.tar.gz:SKIP:make && make PREFIX=/usr DESTDIR=\$PAGAN_ROOT install"
        "readline:8.3:https://ftp.gnu.org/gnu/readline/readline-8.3.tar.gz:SKIP:./configure --prefix=/usr --disable-static --with-curses && make SHLIB_LIBS=-lncurses && make install DESTDIR=\$PAGAN_ROOT"
        "gmp:6.3.0:https://ftp.gnu.org/gnu/gmp/gmp-6.3.0.tar.xz:SKIP:./configure --prefix=/usr --enable-cxx --disable-static CFLAGS=\"-O2 -std=gnu89\" && make CFLAGS=\"-O2\" && make install DESTDIR=\$PAGAN_ROOT"
        "mpfr:4.2.2:https://ftp.gnu.org/gnu/mpfr/mpfr-4.2.2.tar.xz:SKIP:./configure --prefix=/usr --disable-static --enable-thread-safe && make && make install DESTDIR=\$PAGAN_ROOT"
        "mpc:1.3.1:https://ftp.gnu.org/gnu/mpc/mpc-1.3.1.tar.gz:SKIP:./configure --prefix=/usr --disable-static && make && make install DESTDIR=\$PAGAN_ROOT"
        "isl:0.27:https://libisl.sourceforge.io/isl-0.27.tar.bz2:SKIP:./configure --prefix=/usr --disable-static && make && make install DESTDIR=\$PAGAN_ROOT"
        "attr:2.5.2:https://download.savannah.gnu.org/releases/attr/attr-2.5.2.tar.gz:SKIP:./configure --prefix=/usr --sysconfdir=/etc --disable-static && make && make install DESTDIR=\$PAGAN_ROOT"
        "acl:2.3.2:https://download.savannah.gnu.org/releases/acl/acl-2.3.2.tar.xz:SKIP:./configure --prefix=/usr --sysconfdir=/etc --disable-static && make && make install DESTDIR=\$PAGAN_ROOT"
        "libcap:2.77:https://www.kernel.org/pub/linux/libs/security/linux-privs/libcap2/libcap-2.77.tar.xz:SKIP:make prefix=/usr lib=lib && make prefix=/usr lib=lib DESTDIR=\$PAGAN_ROOT install"
        "libxcrypt:4.5.2:https://github.com/besser82/libxcrypt/releases/download/v4.5.2/libxcrypt-4.5.2.tar.xz:SKIP:./configure --prefix=/usr --enable-hashes=strong,glibc --disable-static CFLAGS=\"-O2 -Wno-error=discarded-qualifiers -Wno-error=unterminated-string-initialization\" && make && make install DESTDIR=\$PAGAN_ROOT"
        "pcre2:10.47:https://github.com/PCRE2Project/pcre2/releases/download/pcre2-10.47/pcre2-10.47.tar.bz2:SKIP:./configure --prefix=/usr --enable-unicode --disable-static && make && make install DESTDIR=\$PAGAN_ROOT"
        "elfutils:0.194:https://sourceware.org/ftp/elfutils/0.194/elfutils-0.194.tar.bz2:SKIP:./configure --prefix=/usr --disable-debuginfod --disable-libdebuginfod --disable-werror && make && make -C libelf install DESTDIR=\$PAGAN_ROOT"
        "libffi:3.4.6:https://github.com/libffi/libffi/releases/download/v3.4.6/libffi-3.4.6.tar.gz:SKIP:./configure --prefix=/usr --disable-static && make && make install DESTDIR=\$PAGAN_ROOT"

        # ======== KOMPILATOR GCC (z C i C++) ========
        "gcc:15.2.0:https://ftp.gnu.org/gnu/gcc/gcc-15.2.0/gcc-15.2.0.tar.xz:SKIP:sed -i 's/__cplusplus != 201103/__cplusplus < 201103/g; s/__cplusplus > 201103/__cplusplus < 201103/g' libcody/configure 2>/dev/null || true; sed -i '/^#include \"safe-ctype.h\"/i #ifdef __cplusplus\n#include <cctype>\n#endif' gcc/system.h 2>/dev/null || true; case \$(uname -m) in x86_64) sed -e '/m64=/s/lib64/lib/' -i.orig gcc/config/i386/t-linux64 ;; esac; mkdir -v build && cd build && ../configure --prefix=/usr --enable-languages=c,c++ --disable-multilib --disable-bootstrap --with-system-zlib --enable-default-pie --enable-default-ssp --disable-libsanitizer --enable-werror=no CXXFLAGS=\"-O2 -Wno-error=return-type -fno-char8_t -Wno-deprecated-enum-enum-conversion\" && make \$MAKEFLAGS && make install DESTDIR=\$PAGAN_ROOT && ln -sf gcc \$PAGAN_ROOT/usr/bin/cc"

        # ======== NARZĘDZIA SYSTEMOWE ========
        "file:5.46:https://astron.com/pub/file/file-5.46.tar.gz:SKIP:./configure --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT"
        "m4:1.4.21:https://ftp.gnu.org/gnu/m4/m4-1.4.21.tar.xz:SKIP:./configure --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT"
        "bc:7.0.3:https://github.com/gavinhoward/bc/releases/download/7.0.3/bc-7.0.3.tar.xz:SKIP:CC=gcc CFLAGS=\"-std=c99 -O2\" ./configure --prefix=/usr -G -O3 && make && make install DESTDIR=\$PAGAN_ROOT"
        "flex:2.6.4:https://github.com/westes/flex/releases/download/v2.6.4/flex-2.6.4.tar.gz:SKIP:./configure --prefix=/usr --disable-static && make && make install DESTDIR=\$PAGAN_ROOT && ln -sf flex \$PAGAN_ROOT/usr/bin/lex"
        "bison:3.8.2:https://ftp.gnu.org/gnu/bison/bison-3.8.2.tar.xz:SKIP:./configure --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT"
        "tcl:8.6.17:https://downloads.sourceforge.net/tcl/tcl8.6.17-src.tar.gz:SKIP:cd unix && ./configure --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT"
        "expect:5.45.4:https://prdownloads.sourceforge.net/expect/expect5.45.4.tar.gz:SKIP:cp -f pty_termios.c pty_.c 2>/dev/null || true; ./configure --prefix=/usr --with-tcl=/usr/lib --enable-shared && sed -e 's/^#undef HAVE_TERMIOS/#define HAVE_TERMIOS 1/' -e 's/^#undef HAVE_UNISTD_H/#define HAVE_UNISTD_H 1/' -e 's/^#undef HAVE_SYS_FCNTL_H/#define HAVE_SYS_FCNTL_H 1/' -e 's/^#undef HAVE_SYS_SELECT_H/#define HAVE_SYS_SELECT_H 1/' -e 's/^#undef HAVE_SYS_TIME_H/#define HAVE_SYS_TIME_H 1/' -e 's/^#undef HAVE_SYS_TYPES_H/#define HAVE_SYS_TYPES_H 1/' -e 's/^#undef HAVE_SYS_STAT_H/#define HAVE_SYS_STAT_H 1/' -e 's/^#undef HAVE_STDLIB_H/#define HAVE_STDLIB_H 1/' -e 's/^#undef HAVE_STRING_H/#define HAVE_STRING_H 1/' -e 's/^#undef HAVE_MEMORY_H/#define HAVE_MEMORY_H 1/' -e 's/^#undef HAVE_INTTYPES_H/#define HAVE_INTTYPES_H 1/' -e 's/^#undef HAVE_LIMITS_H/#define HAVE_LIMITS_H 1/' -e 's/^#undef HAVE_TCGETS_OR_TCGETA_IN_TERMIOS_H/#define HAVE_TCGETS_OR_TCGETA_IN_TERMIOS_H 1/' -e 's/^#undef HAVE_TIOCGWINSZ_IN_TERMIOS_H/#define HAVE_TIOCGWINSZ_IN_TERMIOS_H 1/' -e 's/^#undef HAVE_SYSMACROS_H/#define HAVE_SYSMACROS_H 1/' -e 's/^#undef HAVE_STDARG_H/#define HAVE_STDARG_H 1/' -e 's/^#undef TIME_WITH_SYS_TIME/#define TIME_WITH_SYS_TIME 1/' expect_cf.h.in > expect_cf.h && sed -i '\$a#define NO_UNION_WAIT 1\n#define SETPGRP_VOID 1\n#define POSIX 1\n#define RETSIGTYPE void\n#define HAVE_OPENPTY 1\n#define HAVE_TCSETATTR 1\n#define HAVE_SYS_WAIT_H 1\n#define HAVE_SYSCONF 1\n#define HAVE_STRFTIME 1\n#define HAVE_MEMMOVE 1\n#define HAVE_MEMCPY 1\n#define HAVE_TIMEZONE 1\n#define HAVE_SIGLONGJMP 1\n#define HAVE_STRCHR 1\n#define HAVE_LONG_FILE_NAMES 1\n#define HAVE_TIME_H 1\n#define REARM_SIG 1\n#define WNOHANG_REQUIRES_POSIX_SOURCE 1' expect_cf.h && make && make install DESTDIR=\$PAGAN_ROOT"
        "autoconf:2.72:https://ftp.gnu.org/gnu/autoconf/autoconf-2.72.tar.xz:SKIP:./configure --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT"
        "automake:1.18.1:https://ftp.gnu.org/gnu/automake/automake-1.18.1.tar.xz:SKIP:./configure --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT"
        "libtool:2.5.4:https://ftp.gnu.org/gnu/libtool/libtool-2.5.4.tar.xz:SKIP:./configure --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT"
        "gdbm:1.26:https://ftp.gnu.org/gnu/gdbm/gdbm-1.26.tar.gz:SKIP:./configure --prefix=/usr --disable-static --enable-libgdbm-compat && make && make install DESTDIR=\$PAGAN_ROOT"
        "gperf:3.3:https://ftp.gnu.org/gnu/gperf/gperf-3.3.tar.gz:SKIP:./configure --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT"
        "expat:2.7.4:https://github.com/libexpat/libexpat/releases/download/R_2_7_4/expat-2.7.4.tar.xz:SKIP:./configure --prefix=/usr --disable-static && make && make install DESTDIR=\$PAGAN_ROOT"
        "gettext:0.22.5:https://ftp.gnu.org/gnu/gettext/gettext-0.22.5.tar.xz:SKIP:./configure --prefix=/usr --disable-static --disable-acl && make && make install DESTDIR=\$PAGAN_ROOT"
        "check:0.15.2:https://github.com/libcheck/check/releases/download/0.15.2/check-0.15.2.tar.gz:SKIP:./configure --prefix=/usr --disable-static && make && make install DESTDIR=\$PAGAN_ROOT"
        "groff:1.23.0:https://ftp.gnu.org/gnu/groff/groff-1.23.0.tar.gz:SKIP:./configure --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT"
        "texinfo:7.2:https://ftp.gnu.org/gnu/texinfo/texinfo-7.2.tar.xz:SKIP:./configure --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT"
        "intltool:0.51.0:https://deb.debian.org/debian/pool/main/i/intltool/intltool_0.51.0.orig.tar.gz:SKIP:./configure --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT"

        # ======== NARZĘDZIA GNU CORE ========
        "ncurses:6.6:https://invisible-mirror.net/archives/ncurses/ncurses-6.6.tar.gz:SKIP:./configure --prefix=/usr --with-shared --without-debug --without-normal --enable-widec && make && make install DESTDIR=\$PAGAN_ROOT && for lib in ncurses form panel menu; do ln -sfv lib\${lib}w.so \$PAGAN_ROOT/usr/lib/lib\${lib}.so 2>/dev/null; done && ln -sfv libncursesw.so \$PAGAN_ROOT/usr/lib/libtinfo.so 2>/dev/null"
        "bash:5.3:https://ftp.gnu.org/gnu/bash/bash-5.3.tar.gz:SKIP:./configure --prefix=/usr --without-bash-malloc --with-installed-readline && make && make install DESTDIR=\$PAGAN_ROOT && ln -sf bash \$PAGAN_ROOT/bin/sh"
        "coreutils:9.10:https://ftp.gnu.org/gnu/coreutils/coreutils-9.10.tar.xz:SKIP:./configure --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT"
        "diffutils:3.12:https://ftp.gnu.org/gnu/diffutils/diffutils-3.12.tar.xz:SKIP:./configure --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT"
        "findutils:4.10.0:https://ftp.gnu.org/gnu/findutils/findutils-4.10.0.tar.xz:SKIP:./configure --prefix=/usr --localstatedir=/var/lib/locate && make && make install DESTDIR=\$PAGAN_ROOT"
        "gawk:5.3.2:https://ftp.gnu.org/gnu/gawk/gawk-5.3.2.tar.xz:SKIP:./configure --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT"
        "grep:3.12:https://ftp.gnu.org/gnu/grep/grep-3.12.tar.xz:SKIP:./configure --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT"
        "gzip:1.14:https://ftp.gnu.org/gnu/gzip/gzip-1.14.tar.xz:SKIP:./configure --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT"
        "make:4.4.1:https://ftp.gnu.org/gnu/make/make-4.4.1.tar.gz:SKIP:./configure --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT"
        "patch:2.8:https://ftp.gnu.org/gnu/patch/patch-2.8.tar.xz:SKIP:./configure --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT"
        "sed:4.9:https://ftp.gnu.org/gnu/sed/sed-4.9.tar.xz:SKIP:./configure --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT"
        "tar:1.35:https://ftp.gnu.org/gnu/tar/tar-1.35.tar.xz:SKIP:./configure --prefix=/usr --without-posix-acls && make && make install DESTDIR=\$PAGAN_ROOT"
        "libpipeline:1.5.8:https://download.savannah.gnu.org/releases/libpipeline/libpipeline-1.5.8.tar.gz:SKIP:./configure --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT"
        "man-db:2.13.1:https://download.savannah.gnu.org/releases/man-db/man-db-2.13.1.tar.xz:SKIP:./configure --prefix=/usr --sysconfdir=/etc --disable-setuid && make && make install DESTDIR=\$PAGAN_ROOT"
        "vim:9.2.0078:https://github.com/vim/vim/archive/v9.2.0078/vim-9.2.0078.tar.gz:SKIP:./configure --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT && ln -sf vim \$PAGAN_ROOT/usr/bin/vi"

        # ======== BEZPIECZEŃSTWO ========
        "openssl:3.6.1:https://github.com/openssl/openssl/releases/download/openssl-3.6.1/openssl-3.6.1.tar.gz:SKIP:./Configure --prefix=/usr --openssldir=/etc/ssl --libdir=lib shared zlib-dynamic && make && make install DESTDIR=\$PAGAN_ROOT"
        "libbsd:0.12.2:https://libbsd.freedesktop.org/releases/libbsd-0.12.2.tar.xz:SKIP:./configure --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT"
        "shadow:4.19.3:https://github.com/shadow-maint/shadow/releases/download/4.19.3/shadow-4.19.3.tar.xz:SKIP:./configure --prefix=/usr --sysconfdir=/etc --with-group-name-max-length=32 && make && make install DESTDIR=\$PAGAN_ROOT"
        "linux-pam:1.6.1:https://github.com/linux-pam/linux-pam/releases/download/v1.6.1/Linux-PAM-1.6.1.tar.xz:SKIP:./configure --prefix=/usr --sysconfdir=/etc --disable-static && make && make install DESTDIR=\$PAGAN_ROOT"
        "sudo:1.9.16p2:https://www.sudo.ws/dist/sudo-1.9.16p2.tar.gz:SKIP:./configure --prefix=/usr --sysconfdir=/etc --with-secure-path && make && make install DESTDIR=\$PAGAN_ROOT"
        "polkit:125:https://github.com/polkit-org/polkit/archive/refs/tags/125.tar.gz:SKIP:meson setup build --prefix=/usr && ninja -C build && DESTDIR=\$PAGAN_ROOT ninja -C build install"

        # ======== SIEC ========
        "curl:8.9.1:https://curl.se/download/curl-8.9.1.tar.xz:SKIP:./configure --prefix=/usr --with-openssl --disable-static && make && make install DESTDIR=\$PAGAN_ROOT"
        "inetutils:2.7:https://ftp.gnu.org/gnu/inetutils/inetutils-2.7.tar.gz:SKIP:./configure --prefix=/usr --disable-logger --disable-whois --disable-servers && make && make install DESTDIR=\$PAGAN_ROOT"
        "iproute2:6.18.0:https://www.kernel.org/pub/linux/utils/net/iproute2/iproute2-6.18.0.tar.xz:SKIP:sed -i /ARPD/d Makefile && make && make DESTDIR=\$PAGAN_ROOT SBINDIR=/usr/sbin install"
        "dhcpcd:10.0.8:https://github.com/NetworkConfiguration/dhcpcd/releases/download/v10.0.8/dhcpcd-10.0.8.tar.xz:SKIP:./configure --prefix=/usr --sysconfdir=/etc && make && make install DESTDIR=\$PAGAN_ROOT"
        "wpa_supplicant:2.10:https://w1.fi/releases/wpa_supplicant-2.10.tar.gz:SKIP:cd wpa_supplicant && cp defconfig .config && make && make DESTDIR=\$PAGAN_ROOT install"
        "iptables:1.8.10:https://www.netfilter.org/projects/iptables/files/iptables-1.8.10.tar.xz:SKIP:./configure --prefix=/usr --sysconfdir=/etc && make && make install DESTDIR=\$PAGAN_ROOT"

        # ======== SYSTEM I USŁUGI ========
        "util-linux:2.41.3:https://www.kernel.org/pub/linux/utils/util-linux/v2.41/util-linux-2.41.3.tar.xz:SKIP:./configure --bindir=/usr/bin --libdir=/usr/lib --sbindir=/usr/sbin --disable-chfn-chsh --disable-login --disable-nologin --disable-su --disable-runuser --disable-pylibmount --disable-liblastlog2 --without-python --without-systemd && make && make install DESTDIR=\$PAGAN_ROOT"
        "e2fsprogs:1.47.3:https://downloads.sourceforge.net/project/e2fsprogs/e2fsprogs/v1.47.3/e2fsprogs-1.47.3.tar.gz:SKIP:mkdir bld && cd bld && ../configure --prefix=/usr --sysconfdir=/etc --enable-elf-shlibs --disable-fuse2fs && make && make install DESTDIR=\$PAGAN_ROOT"
        "procps-ng:4.0.6:https://sourceforge.net/projects/procps-ng/files/Production/procps-ng-4.0.6.tar.xz:SKIP:./configure --prefix=/usr --disable-static --disable-kill --without-ncurses && make && make install DESTDIR=\$PAGAN_ROOT"
        "psmisc:23.7:https://sourceforge.net/projects/psmisc/files/psmisc/psmisc-23.7.tar.xz:SKIP:./configure --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT"
        "kmod:34.2:https://www.kernel.org/pub/linux/utils/kernel/kmod/kmod-34.2.tar.xz:SKIP:./configure --prefix=/usr --sysconfdir=/etc --disable-manpages --with-openssl --with-xz --with-zstd --with-zlib && make && make install DESTDIR=\$PAGAN_ROOT"
        "kbd:2.9.0:https://www.kernel.org/pub/linux/utils/kbd/kbd-2.9.0.tar.xz:SKIP:./configure --prefix=/usr --disable-vlock && make && make install DESTDIR=\$PAGAN_ROOT"
        "less:692:https://www.greenwoodsoftware.com/less/less-692.tar.gz:SKIP:./configure --prefix=/usr --sysconfdir=/etc && make && make install DESTDIR=\$PAGAN_ROOT"
        "sysklogd:2.7.2:https://github.com/troglobit/sysklogd/releases/download/v2.7.2/sysklogd-2.7.2.tar.gz:SKIP:./configure --prefix=/usr --sysconfdir=/etc --localstatedir=/var && make && make install DESTDIR=\$PAGAN_ROOT"
        "dbus:1.16.2:https://dbus.freedesktop.org/releases/dbus/dbus-1.16.2.tar.xz:SKIP:CC=gcc CXX=g++ cmake -B build -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_INSTALL_SYSCONFDIR=/etc -DCMAKE_INSTALL_LOCALSTATEDIR=/var -DDBUS_BUILD_TESTS=OFF -DDBUS_SYSTEMD_USER_SERVICE_DIR=/usr/lib/systemd/user && make -C build && make -C build DESTDIR=\$PAGAN_ROOT install"
        "systemd:259.1:https://github.com/systemd/systemd/archive/v259.1.tar.gz:SKIP:CC=gcc CXX=g++ meson setup build --prefix=/usr --sysconfdir=/etc --localstatedir=/var -Dmode=release -Dman=disabled -Ddefault-dnssec=no -Dwerror=false && ninja -C build && DESTDIR=\$PAGAN_ROOT ninja -C build install"
        "grub:2.14:https://ftp.gnu.org/gnu/grub/grub-2.14.tar.xz:SKIP:touch grub-core/extra_deps.lst && ./configure --prefix=/usr --sysconfdir=/etc --disable-werror --with-platform=efi && make && make install DESTDIR=\$PAGAN_ROOT"

        # ======== PERL I PYTHON ========
        "sqlite:3510200:https://sqlite.org/2026/sqlite-autoconf-3510200.tar.gz:SKIP:CC=gcc ./configure --prefix=/usr --disable-static --enable-fts5 && make && make install DESTDIR=\$PAGAN_ROOT"
        "perl:5.42.0:https://www.cpan.org/src/5.0/perl-5.42.0.tar.xz:SKIP:sh Configure -des -Dcc=gcc -Dprefix=/usr -Duseshrplib && make && make install DESTDIR=\$PAGAN_ROOT"
        "python:3.14.3:https://www.python.org/ftp/python/3.14.3/Python-3.14.3.tar.xz:SKIP:sed -i 's|^@MODULE__CRYPT_TRUE@_crypt|#_crypt|' Modules/Setup.stdlib.in && ac_cv_lib_crypt_crypt_r=no ac_cv_func_crypt_r=no ./configure --prefix=/usr --enable-shared && make && make install DESTDIR=\$PAGAN_ROOT"
        "ninja:1.13.2:https://github.com/ninja-build/ninja/archive/v1.13.2/ninja-1.13.2.tar.gz:SKIP:python3 configure.py --bootstrap && install -m755 ninja \$PAGAN_ROOT/usr/bin/"
        "meson:1.10.1:https://github.com/mesonbuild/meson/releases/download/1.10.1/meson-1.10.1.tar.gz:SKIP:pip3 wheel -w dist --no-build-isolation --no-deps \$PWD && pip3 install --no-index --find-links dist --root=\$PAGAN_ROOT meson"
        "pkgconf:2.5.1:https://distfiles.ariadne.space/pkgconf/pkgconf-2.5.1.tar.xz:SKIP:./configure --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT"
        "cmake:3.31.6:https://github.com/Kitware/CMake/releases/download/v3.31.6/cmake-3.31.6.tar.gz:SKIP:cmake -S . -B build -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF && cmake --build build $MAKEFLAGS && DESTDIR=\$PAGAN_ROOT cmake --install build"

        # ======== NARZĘDZIA DEWELOPERSKIE ========
        "git:2.47.2:https://www.kernel.org/pub/software/scm/git/git-2.47.2.tar.xz:SKIP:./configure --prefix=/usr --with-openssl --with-curl --with-expat && make && make install DESTDIR=\$PAGAN_ROOT"
        "gnupg:2.4.7:https://www.gnupg.org/ftp/gcrypt/gnupg/gnupg-2.4.7.tar.bz2:SKIP:./configure --prefix=/usr --sysconfdir=/etc && make && make install DESTDIR=\$PAGAN_ROOT"
        "openssh:9.9p2:https://ftp.openbsd.org/pub/OpenBSD/OpenSSH/portable/openssh-9.9p2.tar.gz:SKIP:./configure --prefix=/usr --sysconfdir=/etc/ssh --with-md5-passwords && make && make install DESTDIR=\$PAGAN_ROOT"
        "rsync:3.3.0:https://www.samba.org/ftp/rsync/src/rsync-3.3.0.tar.gz:SKIP:./configure --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT"
        "htop:3.3.0:https://github.com/htop-dev/htop/releases/download/3.3.0/htop-3.3.0.tar.xz:SKIP:./configure --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT"
        "nano:8.1:https://www.nano-editor.org/dist/v8/nano-8.1.tar.xz:SKIP:./configure --prefix=/usr --enable-utf8 && make && make install DESTDIR=\$PAGAN_ROOT"

        # ======== DODATKOWE NARZĘDZIA ========
        "ca-certificates:2024:https://curl.se/ca/cacert-2024-07-02.pem:SKIP:mkdir -p \$PAGAN_ROOT/etc/ssl/certs && cp cacert-2024-07-02.pem \$PAGAN_ROOT/etc/ssl/certs/ca-certificates.crt"
        "icu:75.1:https://github.com/unicode-org/icu/releases/download/release-75-1/icu4c-75_1-src.tgz:SKIP:( export CFLAGS=\"-fno-stack-protector -std=gnu17 -O2 -Wno-error=override-init\"; export CXXFLAGS=\"-fno-stack-protector -O2\"; S=\$'\72'; cd source && ./configure --prefix=/usr && sed -i \"s#\\\$(LIBRARY_PATH_PREFIX)\\\$(LIBDIR)\${S}\\\$(top_builddir)/stubdata\${S}\\\$(top_builddir)/tools/ctestfw#\$PWD/lib\${S}\$PWD/stubdata\${S}\$PWD/tools/ctestfw#g; s#\\\$(top_builddir)/stubdata\${S}\\\$(top_builddir)/tools/ctestfw\${S}\\\$(LIBRARY_PATH_PREFIX)\\\$(LIBDIR)#\$PWD/stubdata\${S}\$PWD/tools/ctestfw\${S}\$PWD/lib#g\" icudefs.mk && make && ( make install DESTDIR=\$PAGAN_ROOT || true ) && ln -sf libicudata.so.75.1 \$PAGAN_ROOT/usr/lib/libicudata.so.75 && ln -sf libicudata.so.75.1 \$PAGAN_ROOT/usr/lib/libicudata.so )"
        "shared-mime-info:2.4:https://gitlab.freedesktop.org/xdg/shared-mime-info/-/archive/2.4/shared-mime-info-2.4.tar.bz2:SKIP:meson setup build --prefix=/usr && ninja -C build && DESTDIR=\$PAGAN_ROOT ninja -C build install"
    )

    ui_set_total "${#packages[@]}"
    for pkg_info in "${packages[@]}"; do
        name="${pkg_info%%:*}"; rest="${pkg_info#*:}"
        ver="${rest%%:*}"; rest="${rest#*:}"
        config="${rest##*:}"; rest_no_cfg="${rest%:*}"
        sha="${rest_no_cfg##*:}"
        url="${rest_no_cfg%:*}"
        build_lfs_pkg "$name" "$ver" "$url" "$sha" "$config"
    done

    _configure_basic_system
    ok "System końcowy zbudowany!"
}

_configure_basic_system() {
    # /etc/passwd
    cat > "$PAGAN_ROOT/etc/passwd" <<'EOF'
root:x:0:0:root:/root:/bin/bash
nobody:x:65534:65534:nobody:/:/bin/false
EOF

    # /etc/group
    cat > "$PAGAN_ROOT/etc/group" <<'EOF'
root:x:0:
bin:x:1:
sys:x:2:
kmem:x:3:
tty:x:4:
tape:x:5:
daemon:x:6:
floppy:x:7:
disk:x:8:
lp:x:9:
dialout:x:10:
audio:x:11:
video:x:12:
utmp:x:13:
usb:x:14:
cdrom:x:15:
mail:x:34:
nogroup:x:65534:
EOF

    # /etc/fstab
    cat > "$PAGAN_ROOT/etc/fstab" <<'EOF'
# /etc/fstab
/dev/sda1       /               ext4    defaults        0       1
proc            /proc           proc    nosuid,noexec,nodev 0       0
sysfs           /sys            sysfs   nosuid,noexec,nodev 0       0
devtmpfs        /dev            devtmpfs mode=0755,nosuid 0       0
tmpfs           /tmp            tmpfs   defaults        0       0
devpts          /dev/pts        devpts  gid=5,mode=620  0       0
	shm             /dev/shm        tmpfs   defaults        0       0
EOF

    # /etc/systemd/system.conf
    cat > "$PAGAN_ROOT/etc/systemd/system.conf" <<'EOF'
[Manager]
DefaultTimeoutStopSec=10s
DefaultTimeoutStartSec=10s
DefaultStartLimitIntervalSec=10s
DefaultStartLimitBurst=5
EOF

    # /etc/systemd/logind.conf
    cat > "$PAGAN_ROOT/etc/systemd/logind.conf" <<'EOF'
[Login]
HandlePowerKey=poweroff
HandleSuspendKey=suspend
HandleHibernateKey=hibernate
HandleLidSwitch=suspend
HandleLidSwitchExternalPower=suspend
HandleLidSwitchDocked=ignore
PowerKeyIgnoreInhibited=no
SuspendKeyIgnoreInhibited=no
HibernateKeyIgnoreInhibited=no
LidSwitchIgnoreInhibited=yes
HoldoffTimeoutSec=30s
IdleAction=ignore
IdleActionSec=30min
RuntimeDirectorySize=10%
InhibitDelayMaxSec=5
UserTasksMax=infinity
KillUserProcesses=no
KillExcludeUsers=root
RemoveIPC=yes
EOF

    # /etc/hostname
    echo "pagan" > "$PAGAN_ROOT/etc/hostname"

    # /etc/locale.conf
    cat > "$PAGAN_ROOT/etc/locale.conf" <<'EOF'
LANG=en_US.UTF-8
LC_ALL=en_US.UTF-8
EOF

    # /etc/vconsole.conf
    cat > "$PAGAN_ROOT/etc/vconsole.conf" <<'EOF'
KEYMAP=pl
FONT=Lat2-Terminus16
EOF

    # Symlink init systemd
    ln -sf /usr/lib/systemd/systemd "$PAGAN_ROOT/sbin/init" 2>/dev/null || true

    # Enable podstawowych usług (best-effort, może nie działać przy DESTDIR)
    chroot "$PAGAN_ROOT" systemctl enable systemd-logind 2>/dev/null || true
    chroot "$PAGAN_ROOT" systemctl enable systemd-timesyncd 2>/dev/null || true
}

# ========================= BUDOWA BLFS (PEŁNE BIBLIOTEKI) =========================
build_blfs() {
    step "BLFS: BIBLIOTEKI I ZALEŻNOŚCI"

    # Sprawdzamy WYŁĄCZNIE biblioteki targetu LFS w $PAGAN_ROOT/usr/lib
    # zanim zaczniemy BLFS, żeby nie kontynuować z uszkodzonym ABI.
    check_target_abi

    export PATH="$TOOLS_DIR/bin:/usr/bin/core_perl:/usr/bin/vendor_perl:$PATH"
    export PKG_CONFIG_DIR=""
    export PKG_CONFIG_PATH="$PAGAN_ROOT/usr/lib/pkgconfig:$PAGAN_ROOT/usr/lib/x86_64-linux-gnu/pkgconfig:$PAGAN_ROOT/usr/share/pkgconfig"
    export PKG_CONFIG_SYSROOT_DIR="$PAGAN_ROOT"
    export PKG_CONFIG_LIBDIR="$PAGAN_ROOT/usr/lib/pkgconfig:$PAGAN_ROOT/usr/lib/x86_64-linux-gnu/pkgconfig:$PAGAN_ROOT/usr/share/pkgconfig"
    export CPPFLAGS="-I$PAGAN_ROOT/usr/include"
    export LDFLAGS="-L$PAGAN_ROOT/usr/lib -L$PAGAN_ROOT/lib64 -Wl,-rpath-link,$PAGAN_ROOT/usr/lib -Wl,-rpath-link,$PAGAN_ROOT/lib64"

    # Wykryj architekturę dla cross-file (działa na x86_64, aarch64, armv7l...)
    local ARCH
    ARCH=$(uname -m)
    case "$ARCH" in
        x86_64|amd64)  ARCH=x86_64 ;;
        aarch64|arm64) ARCH=aarch64 ;;
        armv7l|armv7*) ARCH=arm ;;
    esac

    # Meson cross-file + stub .pc files
    cat > /tmp/pagan-cross.ini <<CROSS_EOF
[binaries]
c = '$CROSS_BIN/$LFS_TGT-gcc'
ar = '$CROSS_BIN/$LFS_TGT-ar'
strip = '$CROSS_BIN/x86_64-pagan-linux-gnu-strip'
pkg-config = 'pkg-config'
glib_genmarshal = '/usr/bin/glib-genmarshal'
glib_mkenums = '/usr/bin/glib-mkenums'
gdbus_codegen = '/usr/bin/gdbus-codegen'
glib_compile_schemas = '/usr/bin/glib-compile-schemas'

[host_machine]
system = 'linux'
cpu_family = '$ARCH'
cpu = '$ARCH'
endian = 'little'

[properties]
iconv = 'libc'
pkg_config_libdir = '$PAGAN_ROOT/usr/lib/pkgconfig:$PAGAN_ROOT/usr/share/pkgconfig'

[built-in options]
pkg_config_path = '$PAGAN_ROOT/usr/lib/pkgconfig:$PAGAN_ROOT/usr/share/pkgconfig'
CROSS_EOF
    mkdir -p "$PAGAN_ROOT/usr/lib/pkgconfig" "$PAGAN_ROOT/usr/include/sysprof-6"
    cat > "$PAGAN_ROOT/usr/include/sysprof-6/sysprof-capture.h" <<'SYSPROFH'
#ifndef SYSPROF_CAPTURE_H
#define SYSPROF_CAPTURE_H
#include <stdint.h>
typedef struct _SysprofCaptureWriter SysprofCaptureWriter;
typedef struct _SysprofCaptureReader SysprofCaptureReader;
#endif
SYSPROFH
    for stub in iconv sysprof-capture-4; do
        [[ -f "$PAGAN_ROOT/usr/lib/pkgconfig/$stub.pc" ]] || \
            cat > "$PAGAN_ROOT/usr/lib/pkgconfig/$stub.pc" <<EOF
prefix=$PAGAN_ROOT/usr
exec_prefix=\${prefix}
libdir=\${prefix}/lib
includedir=\${prefix}/include
Name: $stub
Description: $stub (stub for cross-build)
Version: 1.0
Libs: -L\${libdir} -lc
Cflags:
EOF
    done
    info "  ✓ Meson cross-file + stubs"

    _pipewire_flag_if_supported() {
        local opt="$1" val="$2"
        local opt_file=""
        if [[ -f meson.options ]]; then
            opt_file="meson.options"
        elif [[ -f meson_options.txt ]]; then
            opt_file="meson_options.txt"
        fi
        [[ -z "$opt_file" ]] && return 0
        if rg -q "option\\(['\"]${opt}['\"]" "$opt_file"; then
            printf ' -D%s=%s' "$opt" "$val"
        fi
    }

    _configure_pipewire() {
        local cross_arg="$1"
        local flags=""

        flags+=$(_pipewire_flag_if_supported "man" "disabled")
        flags+=$(_pipewire_flag_if_supported "session-managers" "[]")
        flags+=$(_pipewire_flag_if_supported "examples" "disabled")
        flags+=$(_pipewire_flag_if_supported "tools" "disabled")
        flags+=$(_pipewire_flag_if_supported "tests" "disabled")

        sed -i '/spa-acp-tool/,+5d; /test-timer/,+5d; /test-hw-params/,+5d' spa/plugins/alsa/meson.build || true
        eval "meson setup build $cross_arg --prefix=/usr${flags}"
    }

    local xc="--cross-file=/tmp/pagan-cross.ini"

    # CFLAGS dla CROSS GCC 14.2 (nie host GCC 16)
    export CFLAGS="-O2 -Wno-error=implicit-function-declaration -Wno-error=int-conversion -Wno-error=return-type -Wno-error=maybe-uninitialized -Wno-error=discarded-qualifiers -Wno-error=incompatible-pointer-types"
    export CXXFLAGS="-O2 -Wno-error=return-type -Wno-error=maybe-uninitialized -Wno-error=deprecated-declarations"
    export FORCE_UNSAFE_CONFIGURE=1

    local libs=(
        # ======== FUNDAMENTY (glib2/libxml2/atk – muszą być pierwsze!) ========
        "glib:2.82.5:https://download.gnome.org/sources/glib/2.82/glib-2.82.5.tar.xz:SKIP:meson setup build $xc --prefix=/usr -Dselinux=disabled -Dman-pages=disabled -Dlibmount=enabled -Dtests=false -Dintrospection=disabled -Dsysprof=disabled && ninja -C build && DESTDIR=\$PAGAN_ROOT ninja -C build install"
        "libxml2:2.13.6:https://download.gnome.org/sources/libxml2/2.13/libxml2-2.13.6.tar.xz:SKIP:./configure --host=$LFS_TGT --prefix=/usr --without-python --disable-static && make \$MAKEFLAGS && make install DESTDIR=\$PAGAN_ROOT"
        "atk:2.54.0:https://download.gnome.org/sources/at-spi2-core/2.54/at-spi2-core-2.54.0.tar.xz:SKIP:meson setup build $xc --prefix=/usr -Dintrospection=disabled -Ddocs=false -Dx11=disabled -Ddbus_broker=disabled && ninja -C build && DESTDIR=\$PAGAN_ROOT ninja -C build install"
        "alsa-lib:1.2.12:https://www.alsa-project.org/files/pub/lib/alsa-lib-1.2.12.tar.bz2:SKIP:./configure --host=$LFS_TGT --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT"
        "libogg:1.3.5:https://downloads.xiph.org/releases/ogg/libogg-1.3.5.tar.xz:SKIP:./configure --host=$LFS_TGT --prefix=/usr --disable-static && make && make install DESTDIR=\$PAGAN_ROOT"
        "libvorbis:1.3.7:https://downloads.xiph.org/releases/vorbis/libvorbis-1.3.7.tar.xz:SKIP:./configure --host=$LFS_TGT --prefix=/usr --disable-static && make && make install DESTDIR=\$PAGAN_ROOT"
        "flac:1.4.3:https://downloads.xiph.org/releases/flac/flac-1.4.3.tar.xz:SKIP:./configure --host=$LFS_TGT --prefix=/usr --disable-static --disable-cpplibs && make && make install DESTDIR=\$PAGAN_ROOT"
        "opus:1.5.2:https://downloads.xiph.org/releases/opus/opus-1.5.2.tar.gz:SKIP:./configure --host=$LFS_TGT --prefix=/usr --disable-static && make && make install DESTDIR=\$PAGAN_ROOT"
        "pipewire:1.2.3:https://gitlab.freedesktop.org/pipewire/pipewire/-/archive/1.2.3/pipewire-1.2.3.tar.gz:SKIP:_configure_pipewire \"$xc\" && ninja -C build && DESTDIR=\$PAGAN_ROOT ninja -C build install"
        "wireplumber:0.5.8:https://gitlab.freedesktop.org/pipewire/wireplumber/-/archive/0.5.8/wireplumber-0.5.8.tar.gz:SKIP:meson setup build $xc --prefix=/usr && ninja -C build && DESTDIR=\$PAGAN_ROOT ninja -C build install"
        "nasm:2.16.03:https://www.nasm.us/pub/nasm/releasebuilds/2.16.03/nasm-2.16.03.tar.xz:SKIP:./configure --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT"
        "sdl2:2.30.7:https://www.libsdl.org/release/SDL2-2.30.7.tar.gz:SKIP:./configure --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT"

        # ======== GRAFIKA 2D/3D ========
        "libpng:1.6.43:https://download.sourceforge.net/libpng/libpng-1.6.43.tar.xz:SKIP:./configure --host=$LFS_TGT --prefix=/usr --disable-static && make && make install DESTDIR=\$PAGAN_ROOT"
        "libjpeg-turbo:3.0.3:https://github.com/libjpeg-turbo/libjpeg-turbo/archive/refs/tags/3.0.3.tar.gz:SKIP:cmake -B build -DCMAKE_INSTALL_PREFIX=/usr -G Ninja && DESTDIR=\$PAGAN_ROOT ninja -C build install"
        "libtiff:4.6.0:https://download.osgeo.org/libtiff/tiff-4.6.0.tar.xz:SKIP:./configure --host=$LFS_TGT --prefix=/usr --disable-static && make && make install DESTDIR=\$PAGAN_ROOT"
        "freetype:2.13.3:https://download.sourceforge.net/freetype/freetype-2.13.3.tar.xz:SKIP:./configure --host=$LFS_TGT --prefix=/usr --disable-static && make && make install DESTDIR=\$PAGAN_ROOT"
        "fontconfig:2.15.0:https://www.freedesktop.org/software/fontconfig/release/fontconfig-2.15.0.tar.xz:SKIP:./configure --host=$LFS_TGT --prefix=/usr --sysconfdir=/etc --disable-static && make && make install DESTDIR=\$PAGAN_ROOT"
        "harfbuzz:9.0.0:https://github.com/harfbuzz/harfbuzz/releases/download/9.0.0/harfbuzz-9.0.0.tar.xz:SKIP:meson setup build --prefix=/usr -Dgraphite2=disabled && ninja -C build && DESTDIR=\$PAGAN_ROOT ninja -C build install"
        "fribidi:1.0.15:https://github.com/fribidi/fribidi/releases/download/v1.0.15/fribidi-1.0.15.tar.xz:SKIP:meson setup build --prefix=/usr && ninja -C build && DESTDIR=\$PAGAN_ROOT ninja -C build install"
        "cairo:1.18.0:https://www.cairographics.org/releases/cairo-1.18.0.tar.xz:SKIP:meson setup build --prefix=/usr -Dxlib=enabled -Dxcb=enabled && ninja -C build && DESTDIR=\$PAGAN_ROOT ninja -C build install"
        "pango:1.54.0:https://download.gnome.org/sources/pango/1.54/pango-1.54.0.tar.xz:SKIP:meson setup build --prefix=/usr -Dgtk_doc=false && ninja -C build && DESTDIR=\$PAGAN_ROOT ninja -C build install"
        "gdk-pixbuf:2.42.12:https://download.gnome.org/sources/gdk-pixbuf/2.42/gdk-pixbuf-2.42.12.tar.xz:SKIP:meson setup build --prefix=/usr -Dman=false && ninja -C build && DESTDIR=\$PAGAN_ROOT ninja -C build install"
        "libepoxy:1.5.10:https://github.com/anholt/libepoxy/archive/refs/tags/1.5.10.tar.gz:SKIP:meson setup build --prefix=/usr && ninja -C build && DESTDIR=\$PAGAN_ROOT ninja -C build install"
        "libdrm:2.4.122:https://dri.freedesktop.org/libdrm/libdrm-2.4.122.tar.xz:SKIP:meson setup build --prefix=/usr -Dudev=true && ninja -C build && DESTDIR=\$PAGAN_ROOT ninja -C build install"
        "mesa:24.3.4:https://archive.mesa3d.org/mesa-24.3.4.tar.xz:SKIP:( export CFLAGS=\"-DHAVE_THRD_CREATE \${CFLAGS}\"; meson setup build --prefix=/usr -Dgallium-drivers=softpipe -Dvulkan-drivers= -Dplatforms=x11,wayland -Dllvm=disabled && sed -i 's/^timespec_sub_saturate/__attribute__((used)) timespec_sub_saturate/' src/util/timespec.h && sed -i 's|#include \"loader_wayland_helper.h\"|#include \"util/timespec.h\"\\n#include \"loader_wayland_helper.h\"|' src/loader/loader_wayland_helper.c && ninja -C build && DESTDIR=\$PAGAN_ROOT ninja -C build install )"

        # ======== GTK I WAYLAND ========
        "gtk:3.24.43:https://download.gnome.org/sources/gtk+/3.24/gtk+-3.24.43.tar.xz:SKIP:meson setup build --prefix=/usr -Dx11_backend=true -Dwayland_backend=false && ninja -C build && DESTDIR=\$PAGAN_ROOT ninja -C build install"
        "libxkbcommon:1.7.0:https://xkbcommon.org/download/libxkbcommon-1.7.0.tar.xz:SKIP:meson setup build --prefix=/usr && ninja -C build && DESTDIR=\$PAGAN_ROOT ninja -C build install"
        "wayland:1.23.1:https://gitlab.freedesktop.org/wayland/wayland/-/releases/1.23.1/downloads/wayland-1.23.1.tar.xz:SKIP:meson setup build --prefix=/usr -Ddocumentation=false && ninja -C build && DESTDIR=\$PAGAN_ROOT ninja -C build install"
        "wayland-protocols:1.36:https://gitlab.freedesktop.org/wayland/wayland-protocols/-/releases/1.36/downloads/wayland-protocols-1.36.tar.xz:SKIP:meson setup build --prefix=/usr && ninja -C build && DESTDIR=\$PAGAN_ROOT ninja -C build install"
        "libinput:1.27.1:https://gitlab.freedesktop.org/libinput/libinput/-/archive/1.27.1/libinput-1.27.1.tar.gz:SKIP:meson setup build --prefix=/usr -Ddocumentation=false -Dtests=false && ninja -C build && DESTDIR=\$PAGAN_ROOT ninja -C build install"

        # ======== SIEC ========
        "networkmanager:1.48.10:https://download.gnome.org/sources/NetworkManager/1.48/NetworkManager-1.48.10.tar.xz:SKIP:meson setup build --prefix=/usr --sysconfdir=/etc --localstatedir=/var -Dnmtui=true -Dppp=false -Ddocs=false -Dtests=no -Dselinux=false && ninja -C build && DESTDIR=\$PAGAN_ROOT ninja -C build install"
        "libarchive:3.7.4:https://github.com/libarchive/libarchive/releases/download/v3.7.4/libarchive-3.7.4.tar.xz:SKIP:./configure --prefix=/usr --disable-static && make && make install DESTDIR=\$PAGAN_ROOT"
        "libnspr:4.35:https://ftp.mozilla.org/pub/nspr/releases/v4.35/src/nspr-4.35.tar.gz:SKIP:cd nspr && ./configure --prefix=/usr --disable-static --enable-64bit && make && make install DESTDIR=$PAGAN_ROOT"
        "xfce4-panel:4.18.6:https://archive.xfce.org/src/xfce/xfce4-panel/4.18/xfce4-panel-4.18.6.tar.bz2:SKIP:./configure --prefix=/usr && make && make install DESTDIR=$PAGAN_ROOT"
        "thunar:4.20.2:https://archive.xfce.org/src/xfce/thunar/4.20/thunar-4.20.2.tar.bz2:SKIP:./configure --prefix=/usr && make && make install DESTDIR=$PAGAN_ROOT"
    )

    ui_set_total "${#libs[@]}"
    for pkg_info in "${libs[@]}"; do
        name="${pkg_info%%:*}"; rest="${pkg_info#*:}"
        ver="${rest%%:*}"; rest="${rest#*:}"
        config="${rest##*:}"; rest_no_cfg="${rest%:*}"
        sha="${rest_no_cfg##*:}"
        url="${rest_no_cfg%:*}"
        build_lfs_pkg "$name" "$ver" "$url" "$sha" "$config"
    done

    ok "BLFS – kompletny zestaw bibliotek!"
}

# ========================= BUDOWA KERNELA =========================
build_kernel() {
    step "BUDOWA KERNELA ${KERNEL_VERSION}"

    export PATH="$TOOLS_DIR/bin:$PATH"
    unset PKG_CONFIG_PATH PKG_CONFIG_SYSROOT_DIR PKG_CONFIG_LIBDIR
    unset CFLAGS CXXFLAGS CPPFLAGS

    local kernel_src="$SRC_DIR/linux-${KERNEL_VERSION}"

    if [[ ! -d "$kernel_src" ]]; then
        download_pkg "$KERNEL_URL" "$SRC_DIR/linux-${KERNEL_VERSION}.tar.xz" "SKIP"
        tar -xf "$SRC_DIR/linux-${KERNEL_VERSION}.tar.xz" -C "$SRC_DIR"
    fi

    pushd "$kernel_src" > /dev/null

    info "  ⚙ Konfiguracja jądra (defconfig + tweaks Pagan)..."

    # Generuj pelna konfiguracje domyslna dla x86_64 (zawsze aktualna dla wersji kernela)
    make defconfig || error "Kernel defconfig failed"

    # === PaganOS overrides ===
    ./scripts/config --set-str CONFIG_LOCALVERSION "-pagan"
    ./scripts/config --disable CONFIG_LOCALVERSION_AUTO
    ./scripts/config --disable CONFIG_WERROR

    # Preemption i scheduling (dla desktop/pulpitu)
    ./scripts/config --enable CONFIG_PREEMPT
    ./scripts/config --disable CONFIG_PREEMPT_VOLUNTARY
    ./scripts/config --set-val CONFIG_HZ 1000
    ./scripts/config --enable CONFIG_SCHED_HRTICK

    # Moduly
    ./scripts/config --enable CONFIG_MODULES
    ./scripts/config --enable CONFIG_MODULE_UNLOAD
    ./scripts/config --enable CONFIG_MODULE_FORCE_UNLOAD
    ./scripts/config --enable CONFIG_MODVERSIONS
    ./scripts/config --disable CONFIG_MODULE_SIG

    # EFI (obowiazkowe dla nowoczesnego sprzetu)
    ./scripts/config --enable CONFIG_EFI
    ./scripts/config --enable CONFIG_EFI_STUB

    # KVM / wirtualizacja
    ./scripts/config --enable CONFIG_VIRTUALIZATION
    ./scripts/config --enable CONFIG_KVM
    ./scripts/config --enable CONFIG_KVM_INTEL
    ./scripts/config --enable CONFIG_KVM_AMD

    # WiFi (jako moduly)
    ./scripts/config --enable CONFIG_WIRELESS
    ./scripts/config --module CONFIG_CFG80211
    ./scripts/config --module CONFIG_MAC80211
    ./scripts/config --module CONFIG_IWLWIFI
    ./scripts/config --module CONFIG_IWLMVM
    ./scripts/config --module CONFIG_ATH9K
    ./scripts/config --module CONFIG_ATH10K
    ./scripts/config --module CONFIG_RTW88
    ./scripts/config --module CONFIG_BRCMFMAC

    # Uzupelnij wszystkie brakujace opcje domyslnymi
    info "  ⚙ olddefconfig (uzupelnianie configu)..."
    make olddefconfig || error "Kernel olddefconfig failed"

    info "  🔨 Kompilacja jądra..."
    make $MAKEFLAGS bzImage || error "Kernel build failed"
    make $MAKEFLAGS modules || error "Kernel modules build failed"

    info "  📥 Instalacja jądra..."
    make INSTALL_MOD_PATH="$PAGAN_ROOT" modules_install || error "Modules install failed"
    cp arch/x86/boot/bzImage "$PAGAN_ROOT/boot/vmlinuz-${KERNEL_VERSION}-pagan"
    cp System.map "$PAGAN_ROOT/boot/System.map-${KERNEL_VERSION}-pagan"
    cp .config "$PAGAN_ROOT/boot/config-${KERNEL_VERSION}-pagan"

    # Symlink
    ln -sf "vmlinuz-${KERNEL_VERSION}-pagan" "$PAGAN_ROOT/boot/vmlinuz-linux"
    ln -sf "System.map-${KERNEL_VERSION}-pagan" "$PAGAN_ROOT/boot/System.map"

    popd > /dev/null

    ok "Kernel ${KERNEL_VERSION} zbudowany!"
}

# ========================= STEROWNIKI NVIDIA (open-gpu-kernel-modules) =========================
# Buduje moduły NVIDIA z oficjalnego open-source repo NVIDIA
# (https://github.com/NVIDIA/open-gpu-kernel-modules) przeciw zbudowanemu kernelowi.
install_nvidia_drivers() {
    step "INSTALACJA STEROWNIKÓW NVIDIA (open-gpu-kernel-modules)"

    local nv_ver="${NVIDIA_VERSION:-main}"
    local nv_url="https://github.com/NVIDIA/open-gpu-kernel-modules/archive/refs/heads/${nv_ver}.tar.gz"
    local nv_arch="$SRC_DIR/nvidia-open-gpu-kernel-modules-${nv_ver}.tar.gz"
    local nv_dir="$SRC_DIR/build-nvidia-open"

    # Kernel źródła muszą być zbudowane (po build_kernel)
    if [[ ! -f "$SRC_DIR/linux-${KERNEL_VERSION}/.config" ]]; then
        warn "Brak zbudowanego kernela – pomijam NVIDIA (zbuduj kernel najpierw)"
        return 0
    fi

    download_pkg "$nv_url" "$nv_arch" "SKIP" || return 0

    rm -rf "$nv_dir"
    mkdir -p "$nv_dir"
    tar -xf "$nv_arch" -C "$nv_dir" --strip-components=1 2>/dev/null || { warn "Rozpakowanie NVIDIA nieudane"; return 0; }

    pushd "$nv_dir" > /dev/null

    info "  🔨 Budowa modułów NVIDIA (to potrwa)..."
    if make -j$(nproc) modules \
            SYSSRC="$SRC_DIR/linux-${KERNEL_VERSION}" \
            SYSOUT="$SRC_DIR/linux-${KERNEL_VERSION}" 2>/tmp/nvidia-build.log; then
        info "  📥 Instalacja modułów NVIDIA do systemu..."
        make modules_install \
            SYSSRC="$SRC_DIR/linux-${KERNEL_VERSION}" \
            SYSOUT="$SRC_DIR/linux-${KERNEL_VERSION}" \
            DESTDIR="$PAGAN_ROOT" 2>/tmp/nvidia-install.log || \
            warn "NVIDIA modules_install nieudane"
        ok "NVIDIA open-gpu-kernel-modules zbudowane i zainstalowane"
    else
        warn "NVIDIA modules build nieudane – pomijam (log: /tmp/nvidia-build.log)"
    fi

    popd > /dev/null
}

# ========================= INSTALACJA XFCE =========================
install_xfce() {
    step "INSTALACJA XFCE"

    export PATH="$TOOLS_DIR/bin:$PATH"
    export PKG_CONFIG_PATH="$PAGAN_ROOT/usr/lib/pkgconfig:$PAGAN_ROOT/usr/share/pkgconfig"
    # Target libs first for rpath-link: host pangoft2 is ABI-newer than target
    # pango, causing symbol mismatch when host pangoft2 resolves against target pango.
    export LDFLAGS="-L$PAGAN_ROOT/usr/lib -L/usr/lib -Wl,-rpath-link,$PAGAN_ROOT/usr/lib -Wl,-rpath-link,/usr/lib"

    # Xorg
    build_lfs_pkg "xorg-server" "21.1.13" \
        "https://www.x.org/releases/individual/xserver/xorg-server-21.1.13.tar.xz" \
        "SKIP" \
        "./configure --prefix=/usr --enable-glamor --enable-dri3 --enable-xcsecurity --disable-systemd-logind"

    # Xorg drivers
    build_lfs_pkg "xf86-input-libinput" "1.4.0" \
        "https://www.x.org/releases/individual/driver/xf86-input-libinput-1.4.0.tar.xz" \
        "SKIP" \
        "./configure --prefix=/usr"

    build_lfs_pkg "xf86-video-fbdev" "0.5.0" \
        "https://gitlab.freedesktop.org/xorg/driver/xf86-video-fbdev/-/archive/xf86-video-fbdev-0.5.0/xf86-video-fbdev-0.5.0.tar.gz" \
        "SKIP" \
        "./autogen.sh && ./configure --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT"

    # Xfce dependencies (not in BLFS)
    # libwnck: test executables fail to link when host pangoft2 is newer than
    # target pango. Patch meson.build to skip test_progs (no --Dtests option).
    build_lfs_pkg "libwnck" "43.0" \
        "https://download.gnome.org/sources/libwnck/43/libwnck-43.0.tar.xz" \
        "SKIP" \
        "sed -i 's/progs + test_progs/[]/' libwnck/meson.build && meson setup build --prefix=/usr -Dgtk_doc=false -Dintrospection=disabled && ninja -C build && DESTDIR=\$PAGAN_ROOT ninja -C build install"

    build_lfs_pkg "startup-notification" "0.12" \
        "https://www.freedesktop.org/software/startup-notification/releases/startup-notification-0.12.tar.gz" \
        "SKIP" \
        "./configure --prefix=/usr && make && make install DESTDIR=\$PAGAN_ROOT"

    # Xfce core
    local xfce_packages=(
        "libxfce4util:4.18.2:https://archive.xfce.org/src/xfce/libxfce4util/4.18/libxfce4util-4.18.2.tar.bz2"
        "xfconf:4.18.3:https://archive.xfce.org/src/xfce/xfconf/4.18/xfconf-4.18.3.tar.bz2"
        "libxfce4ui:4.18.6:https://archive.xfce.org/src/xfce/libxfce4ui/4.18/libxfce4ui-4.18.6.tar.bz2"
        "exo:4.18.0:https://archive.xfce.org/src/xfce/exo/4.18/exo-4.18.0.tar.bz2"
        "garcon:4.18.2:https://archive.xfce.org/src/xfce/garcon/4.18/garcon-4.18.2.tar.bz2"
        "xfce4-panel:4.18.6:https://archive.xfce.org/src/xfce/xfce4-panel/4.18/xfce4-panel-4.18.6.tar.bz2"
        "thunar:4.18.10:https://archive.xfce.org/src/xfce/thunar/4.18/thunar-4.18.10.tar.bz2"
        "xfce4-settings:4.18.6:https://archive.xfce.org/src/xfce/xfce4-settings/4.18/xfce4-settings-4.18.6.tar.bz2"
        "xfce4-session:4.18.4:https://archive.xfce.org/src/xfce/xfce4-session/4.18/xfce4-session-4.18.4.tar.bz2"
        "xfdesktop:4.18.1:https://archive.xfce.org/src/xfce/xfdesktop/4.18/xfdesktop-4.18.1.tar.bz2"
        "xfwm4:4.18.0:https://archive.xfce.org/src/xfce/xfwm4/4.18/xfwm4-4.18.0.tar.bz2"
        "xfce4-appfinder:4.18.1:https://archive.xfce.org/src/xfce/xfce4-appfinder/4.18/xfce4-appfinder-4.18.1.tar.bz2"
        "xfce4-terminal:1.1.3:https://archive.xfce.org/src/apps/xfce4-terminal/1.1/xfce4-terminal-1.1.3.tar.bz2"
        "tumbler:4.18.2:https://archive.xfce.org/src/xfce/tumbler/4.18/tumbler-4.18.2.tar.bz2"
        "mousepad:0.6.2:https://archive.xfce.org/src/apps/mousepad/0.6/mousepad-0.6.2.tar.bz2"
        "ristretto:0.13.2:https://archive.xfce.org/src/apps/ristretto/0.13/ristretto-0.13.2.tar.bz2"
    )

    for pkg_info in "${xfce_packages[@]}"; do
        IFS=':' read -r name ver url <<< "$pkg_info"
        build_lfs_pkg "$name" "$ver" "$url" "SKIP" \
            "./configure --prefix=/usr --sysconfdir=/etc --localstatedir=/var --disable-introspection && make \$MAKEFLAGS && make install DESTDIR=\$PAGAN_ROOT"
    done

    # xfce4-power-manager (potrzebuje upower+libnotify — build best-effort bez nich)
    build_lfs_pkg "xfce4-power-manager" "4.18.4" \
        "https://archive.xfce.org/src/xfce/xfce4-power-manager/4.18/xfce4-power-manager-4.18.4.tar.bz2" \
        "SKIP" \
        "./configure --prefix=/usr --sysconfdir=/etc --disable-introspection --enable-polkit --disable-upower --disable-notifications 2>/dev/null && make \$MAKEFLAGS || true; make install DESTDIR=\$PAGAN_ROOT 2>/dev/null || true"

    # LightDM
    build_lfs_pkg "lightdm" "1.32.0" \
        "https://github.com/canonical/lightdm/releases/download/1.32.0/lightdm-1.32.0.tar.xz" \
        "SKIP" \
        "./configure --prefix=/usr --sysconfdir=/etc --localstatedir=/var --disable-gtk-doc && make \$MAKEFLAGS && make install DESTDIR=\$PAGAN_ROOT"

    build_lfs_pkg "lightdm-gtk-greeter" "2.0.8" \
        "https://github.com/Xfce/lightdm-gtk-greeter/archive/refs/tags/lightdm-gtk-greeter-2.0.8.tar.gz" \
        "SKIP" \
        "./configure --prefix=/usr --sysconfdir=/etc && make \$MAKEFLAGS && make install DESTDIR=\$PAGAN_ROOT"

    # Firefox
    build_lfs_pkg "firefox" "128.0" \
        "https://ftp.mozilla.org/pub/firefox/releases/128.0/linux-$(uname -m)/en-US/firefox-128.0.tar.xz" \
        "SKIP" \
        "tar -xf firefox-*.tar.xz -C $PAGAN_ROOT/usr/lib && ln -sf /usr/lib/firefox/firefox $PAGAN_ROOT/usr/bin/"

    _configure_xfce
    ok "Xfce zainstalowane!"
}

_configure_xfce() {
    # LightDM
    mkdir -p "$PAGAN_ROOT/etc/lightdm"
    cat > "$PAGAN_ROOT/etc/lightdm/lightdm.conf" <<'EOF'
[LightDM]
greeter-session=lightdm-gtk-greeter
user-session=xfce
minimum-vt=7
xserver-command=X -background none -verbose

[Seat:*]
greeter-session=lightdm-gtk-greeter
user-session=xfce
EOF

    # .xinitrc
    mkdir -p "$PAGAN_ROOT/etc/skel"
    cat > "$PAGAN_ROOT/etc/skel/.xinitrc" <<'EOF'
#!/bin/sh
exec startxfce4
EOF
    chmod +x "$PAGAN_ROOT/etc/skel/.xinitrc"

    # Użytkownik
    chroot "$PAGAN_ROOT" useradd -m -G wheel,audio,video,cdrom,plugdev -s /bin/bash pagan 2>/dev/null || true
    echo "pagan:changeme" | chroot "$PAGAN_ROOT" chpasswd 2>/dev/null || true; chroot "$PAGAN_ROOT" passwd -e pagan 2>/dev/null || true
}

# ========================= INSTALACJA DEEPIN =========================
install_deepin() {
    step "INSTALACJA DEEPIN"

    export PATH="$TOOLS_DIR/bin:$PATH"
    export PKG_CONFIG_PATH="$PAGAN_ROOT/usr/lib/pkgconfig:$PAGAN_ROOT/usr/share/pkgconfig"

    # Xorg
    build_lfs_pkg "xorg-server" "21.1.13" \
        "https://www.x.org/releases/individual/xserver/xorg-server-21.1.13.tar.xz" \
        "SKIP" \
        "./configure --prefix=/usr --enable-glamor --enable-dri3 --enable-xcsecurity"

    # Qt6
    build_lfs_pkg "qtbase" "6.7.2" \
        "https://download.qt.io/official_releases/qt/6.7/6.7.2/submodules/qtbase-everywhere-src-6.7.2.tar.xz" \
        "SKIP" \
        "./configure -prefix /usr -opensource -confirm-license -release -shared -nomake tests -nomake examples"

    # Deepin
    local deepin_packages=(
        "dde-qt-dbus-factory:https://github.com/linuxdeepin/dde-qt-dbus-factory/releases/latest/download/dde-qt-dbus-factory.tar.xz"
        "dtkcore:https://github.com/linuxdeepin/dtkcore/releases/latest/download/dtkcore.tar.xz"
        "dtkgui:https://github.com/linuxdeepin/dtkgui/releases/latest/download/dtkgui.tar.xz"
        "dtkwidget:https://github.com/linuxdeepin/dtkwidget/releases/latest/download/dtkwidget.tar.xz"
        "dde-dock:https://github.com/linuxdeepin/dde-dock/releases/latest/download/dde-dock.tar.xz"
        "dde-launcher:https://github.com/linuxdeepin/dde-launcher/releases/latest/download/dde-launcher.tar.xz"
        "dde-control-center:https://github.com/linuxdeepin/dde-control-center/releases/latest/download/dde-control-center.tar.xz"
        "dde-session-shell:https://github.com/linuxdeepin/dde-session-shell/releases/latest/download/dde-session-shell.tar.xz"
        "deepin-terminal:https://github.com/linuxdeepin/deepin-terminal/releases/latest/download/deepin-terminal.tar.xz"
        "deepin-file-manager:https://github.com/linuxdeepin/deepin-file-manager/releases/latest/download/deepin-file-manager.tar.xz"
    )

    for pkg_info in "${deepin_packages[@]}"; do
        IFS=':' read -r name url <<< "$pkg_info"
        build_lfs_pkg "$name" "latest" "$url" "SKIP" \
            "cmake -B build -DCMAKE_INSTALL_PREFIX=/usr && cmake --build build && cmake --install build"
    done

    _configure_deepin
    ok "Deepin zainstalowane!"
}

_configure_deepin() {
    mkdir -p "$PAGAN_ROOT/etc/lightdm"
    cat > "$PAGAN_ROOT/etc/lightdm/lightdm.conf" <<'EOF'
[LightDM]
greeter-session=lightdm-deepin-greeter
user-session=deepin
minimum-vt=7

[Seat:*]
greeter-session=lightdm-deepin-greeter
user-session=deepin
EOF

    chroot "$PAGAN_ROOT" useradd -m -G wheel,audio,video,cdrom,plugdev -s /bin/bash pagan 2>/dev/null || true
    echo "pagan:changeme" | chroot "$PAGAN_ROOT" chpasswd 2>/dev/null || true; chroot "$PAGAN_ROOT" passwd -e pagan 2>/dev/null || true
}

# ========================= INSTALACJA BUDGIE =========================
install_budgie() {
    step "INSTALACJA BUDGIE DESKTOP"

    export PATH="$TOOLS_DIR/bin:$PATH"
    export PKG_CONFIG_PATH="$PAGAN_ROOT/usr/lib/pkgconfig:$PAGAN_ROOT/usr/share/pkgconfig"

    # Xorg base
    build_lfs_pkg "xorg-server" "21.1.13" \
        "https://www.x.org/releases/individual/xserver/xorg-server-21.1.13.tar.xz" \
        "SKIP" \
        "./configure --prefix=/usr --enable-glamor --enable-dri3 --enable-xcsecurity"

    build_lfs_pkg "xf86-input-libinput" "1.4.0" \
        "https://www.x.org/releases/individual/driver/xf86-input-libinput-1.4.0.tar.xz" \
        "SKIP" "./configure --prefix=/usr"

    # GTK+3
    build_lfs_pkg "gtk3" "3.24.43" \
        "https://download.gnome.org/sources/gtk+/3.24/gtk+-3.24.43.tar.xz" \
        "SKIP" \
        "./configure --prefix=/usr --enable-x11-backend --enable-wayland-backend"

    # GNOME stack dependencies for Budgie
    build_lfs_pkg "gnome-menus" "3.36.0" \
        "https://download.gnome.org/sources/gnome-menus/3.36/gnome-menus-3.36.0.tar.xz" \
        "SKIP" "./configure --prefix=/usr"

    build_lfs_pkg "gnome-settings-daemon" "47.2" \
        "https://download.gnome.org/sources/gnome-settings-daemon/47/gnome-settings-daemon-47.2.tar.xz" \
        "SKIP" \
        "meson setup build --prefix=/usr -Dsystemd=false && ninja -C build && DESTDIR=$PAGAN_ROOT ninja -C build install"

    build_lfs_pkg "gnome-control-center" "47.3" \
        "https://download.gnome.org/sources/gnome-control-center/47/gnome-control-center-47.3.tar.xz" \
        "SKIP" \
        "meson setup build --prefix=/usr && ninja -C build && DESTDIR=$PAGAN_ROOT ninja -C build install"

    build_lfs_pkg "gnome-session" "47.1" \
        "https://download.gnome.org/sources/gnome-session/47/gnome-session-47.1.tar.xz" \
        "SKIP" \
        "meson setup build --prefix=/usr -Dsystemd=false && ninja -C build && DESTDIR=$PAGAN_ROOT ninja -C build install"

    build_lfs_pkg "mutter" "47.5" \
        "https://download.gnome.org/sources/mutter/47/mutter-47.5.tar.xz" \
        "SKIP" \
        "meson setup build --prefix=/usr -Dtests=false && ninja -C build && DESTDIR=$PAGAN_ROOT ninja -C build install"

    # Budgie desktop
    build_lfs_pkg "budgie-desktop" "10.9.2" \
        "https://github.com/BuddiesOfBudgie/budgie-desktop/releases/download/v10.9.2/budgie-desktop-10.9.2.tar.xz" \
        "SKIP" \
        "meson setup build --prefix=/usr -Dwith-polkit=disabled && ninja -C build && DESTDIR=$PAGAN_ROOT ninja -C build install"

    # LightDM + slick-greeter
    build_lfs_pkg "lightdm" "1.32.0" \
        "https://github.com/canonical/lightdm/releases/download/1.32.0/lightdm-1.32.0.tar.xz" \
        "SKIP" \
        "./configure --prefix=/usr --sysconfdir=/etc --localstatedir=/var"

    build_lfs_pkg "slick-greeter" "2.0.8" \
        "https://github.com/linuxmint/slick-greeter/archive/refs/tags/2.0.8.tar.gz" \
        "SKIP" \
        "meson setup build --prefix=/usr && ninja -C build && DESTDIR=$PAGAN_ROOT ninja -C build install"

    # Aplikacje
    _install_firefox_binary
    _install_terminal_apps

    _configure_budgie
    ok "Budgie zainstalowane!"
}

_configure_budgie() {
    mkdir -p "$PAGAN_ROOT/etc/lightdm"
    cat > "$PAGAN_ROOT/etc/lightdm/lightdm.conf" <<'EOF'
[LightDM]
greeter-session=slick-greeter
user-session=budgie-desktop
minimum-vt=7

[Seat:*]
greeter-session=slick-greeter
user-session=budgie-desktop
EOF

    mkdir -p "$PAGAN_ROOT/etc/skel"
    cat > "$PAGAN_ROOT/etc/skel/.xinitrc" <<'EOF'
#!/bin/sh
exec budgie-desktop
EOF
    chmod +x "$PAGAN_ROOT/etc/skel/.xinitrc"

    chroot "$PAGAN_ROOT" useradd -m -G wheel,audio,video,cdrom,plugdev -s /bin/bash pagan 2>/dev/null || true
    echo "pagan:changeme" | chroot "$PAGAN_ROOT" chpasswd 2>/dev/null || true; chroot "$PAGAN_ROOT" passwd -e pagan 2>/dev/null || true
}

# ========================= INSTALACJA GNOME =========================
install_gnome() {
    step "INSTALACJA GNOME DESKTOP"

    export PATH="$TOOLS_DIR/bin:$PATH"
    export PKG_CONFIG_PATH="$PAGAN_ROOT/usr/lib/pkgconfig:$PAGAN_ROOT/usr/share/pkgconfig"

    # Xorg base
    build_lfs_pkg "xorg-server" "21.1.13" \
        "https://www.x.org/releases/individual/xserver/xorg-server-21.1.13.tar.xz" \
        "SKIP" \
        "./configure --prefix=/usr --enable-glamor --enable-dri3 --enable-xcsecurity"

    build_lfs_pkg "xf86-input-libinput" "1.4.0" \
        "https://www.x.org/releases/individual/driver/xf86-input-libinput-1.4.0.tar.xz" \
        "SKIP" "./configure --prefix=/usr"

    # GTK stack
    build_lfs_pkg "gtk3" "3.24.43" \
        "https://download.gnome.org/sources/gtk+/3.24/gtk+-3.24.43.tar.xz" \
        "SKIP" \
        "./configure --prefix=/usr --enable-x11-backend --enable-wayland-backend"

    build_lfs_pkg "gtk4" "4.16.7" \
        "https://download.gnome.org/sources/gtk/4.16/gtk-4.16.7.tar.xz" \
        "SKIP" \
        "meson setup build --prefix=/usr -Dx11-backend=true -Dwayland-backend=true && ninja -C build && DESTDIR=$PAGAN_ROOT ninja -C build install"

    # GNOME core
    build_lfs_pkg "gnome-menus" "3.36.0" \
        "https://download.gnome.org/sources/gnome-menus/3.36/gnome-menus-3.36.0.tar.xz" \
        "SKIP" "./configure --prefix=/usr"

    build_lfs_pkg "gnome-settings-daemon" "47.2" \
        "https://download.gnome.org/sources/gnome-settings-daemon/47/gnome-settings-daemon-47.2.tar.xz" \
        "SKIP" \
        "meson setup build --prefix=/usr && ninja -C build && DESTDIR=$PAGAN_ROOT ninja -C build install"

    build_lfs_pkg "gnome-control-center" "47.3" \
        "https://download.gnome.org/sources/gnome-control-center/47/gnome-control-center-47.3.tar.xz" \
        "SKIP" \
        "meson setup build --prefix=/usr && ninja -C build && DESTDIR=$PAGAN_ROOT ninja -C build install"

    build_lfs_pkg "gnome-session" "47.1" \
        "https://download.gnome.org/sources/gnome-session/47/gnome-session-47.1.tar.xz" \
        "SKIP" \
        "meson setup build --prefix=/usr -Dsystemd=false && ninja -C build && DESTDIR=$PAGAN_ROOT ninja -C build install"

    build_lfs_pkg "mutter" "47.5" \
        "https://download.gnome.org/sources/mutter/47/mutter-47.5.tar.xz" \
        "SKIP" \
        "meson setup build --prefix=/usr -Dtests=false && ninja -C build && DESTDIR=$PAGAN_ROOT ninja -C build install"

    build_lfs_pkg "gnome-shell" "47.4" \
        "https://download.gnome.org/sources/gnome-shell/47/gnome-shell-47.4.tar.xz" \
        "SKIP" \
        "meson setup build --prefix=/usr -Dtests=false && ninja -C build && DESTDIR=$PAGAN_ROOT ninja -C build install"

    build_lfs_pkg "nautilus" "47.2" \
        "https://download.gnome.org/sources/nautilus/47/nautilus-47.2.tar.xz" \
        "SKIP" \
        "meson setup build --prefix=/usr && ninja -C build && DESTDIR=$PAGAN_ROOT ninja -C build install"

    build_lfs_pkg "gnome-terminal" "3.54.2" \
        "https://download.gnome.org/sources/gnome-terminal/3.54/gnome-terminal-3.54.2.tar.xz" \
        "SKIP" \
        "meson setup build --prefix=/usr && ninja -C build && DESTDIR=$PAGAN_ROOT ninja -C build install"

    build_lfs_pkg "gnome-tweaks" "46.1" \
        "https://download.gnome.org/sources/gnome-tweaks/46/gnome-tweaks-46.1.tar.xz" \
        "SKIP" \
        "meson setup build --prefix=/usr && ninja -C build && DESTDIR=$PAGAN_ROOT ninja -C build install"

    build_lfs_pkg "adwaita-icon-theme" "47.0" \
        "https://download.gnome.org/sources/adwaita-icon-theme/47/adwaita-icon-theme-47.0.tar.xz" \
        "SKIP" "./configure --prefix=/usr"

    # GDM
    build_lfs_pkg "gdm" "47.0" \
        "https://download.gnome.org/sources/gdm/47/gdm-47.0.tar.xz" \
        "SKIP" \
        "meson setup build --prefix=/usr -Dinitial-vt=7 && ninja -C build && DESTDIR=$PAGAN_ROOT ninja -C build install"

    _install_firefox_binary
    _install_terminal_apps

    _configure_gnome
    ok "GNOME zainstalowane!"
}

_configure_gnome() {
    mkdir -p "$PAGAN_ROOT/etc/gdm"
    cat > "$PAGAN_ROOT/etc/gdm/custom.conf" <<'EOF'
[daemon]
AutomaticLoginEnable=false
TimedLoginEnable=false
WaylandEnable=true

[security]
DisallowTCP=true

[xdmcp]
Enable=false
EOF

    mkdir -p "$PAGAN_ROOT/etc/skel"
    cat > "$PAGAN_ROOT/etc/skel/.xinitrc" <<'EOF'
#!/bin/sh
exec gnome-session
EOF
    chmod +x "$PAGAN_ROOT/etc/skel/.xinitrc"

    chroot "$PAGAN_ROOT" useradd -m -G wheel,audio,video,cdrom,plugdev -s /bin/bash pagan 2>/dev/null || true
    echo "pagan:changeme" | chroot "$PAGAN_ROOT" chpasswd 2>/dev/null || true; chroot "$PAGAN_ROOT" passwd -e pagan 2>/dev/null || true
}

# ========================= WSPÓLNE APLIKACJE =========================
_install_firefox_binary() {
    local ff_ver="128.0.3"
    local ff_url="https://ftp.mozilla.org/pub/firefox/releases/${ff_ver}/linux-$(uname -m)/en-US/firefox-${ff_ver}.tar.xz"
    local ff_arch="$SRC_DIR/firefox-${ff_ver}.tar.xz"
    info "  Instalowanie Firefox ${ff_ver}..."
    wget -q --timeout=60 -O "$ff_arch" "$ff_url" 2>/dev/null || return 0
    mkdir -p "$PAGAN_ROOT/usr/lib/firefox"
    tar -xf "$ff_arch" -C "$PAGAN_ROOT/usr/lib/firefox" --strip-components=1 2>/dev/null
    ln -sf /usr/lib/firefox/firefox "$PAGAN_ROOT/usr/bin/firefox" 2>/dev/null || true
}

_install_terminal_apps() {
    build_lfs_pkg "xfce4-terminal" "1.1.3" \
        "https://archive.xfce.org/src/apps/xfce4-terminal/1.1/xfce4-terminal-1.1.3.tar.bz2" \
        "SKIP" "./configure --prefix=/usr" 2>/dev/null || true
    build_lfs_pkg "nano" "8.1" \
        "https://www.nano-editor.org/dist/v8/nano-8.1.tar.xz" \
        "SKIP" "./configure --prefix=/usr --enable-utf8" 2>/dev/null || true
}

# ========================= OSINFO-DB (PAGAN ROLLING) =========================
install_osinfo() {
    step "INSTALACJA OSINFO-DB (Pagan Linux OS database)"

    build_lfs_pkg "osinfo-db-tools" "1.12.0" \
        "https://releases.pagure.org/libosinfo/osinfo-db-tools-1.12.0.tar.xz" \
        "SKIP" \
        "meson setup build --prefix=/usr && DESTDIR=$PAGAN_ROOT ninja -C build install"

    build_lfs_pkg "osinfo-db" "20250606" \
        "https://releases.pagure.org/libosinfo/osinfo-db-20250606.tar.xz" \
        "SKIP" \
        "osinfo-db-import --root $PAGAN_ROOT --system $SRC_DIR/osinfo-db-20250606.tar.xz 2>/dev/null || true"

    # Pagan Linux Rolling XML
    mkdir -p "$PAGAN_ROOT/usr/share/osinfo/os/pagan"
    cat > "$PAGAN_ROOT/usr/share/osinfo/os/pagan/pagan-rolling.xml" <<'OSINFO'
<?xml version="1.0" encoding="UTF-8"?>
<libosinfo version="0.0.1">
  <os id="http://paganlinux.eu/pagan/rolling">
    <short-id>pagan-rolling</short-id>
    <name>Pagan Linux</name>
    <version>Rolling</version>
    <vendor>Pagan Linux Community</vendor>
    <family>linux</family>
    <distributor>paganlinux.eu</distributor>
    <release-status>rolling</release-status>
    <resources arch="x86_64">
      <minimum>
        <cpu>200000000</cpu>
        <ram>1073741824</ram>
        <storage>8589934592</storage>
      </minimum>
      <recommended>
        <cpu>1000000000</cpu>
        <ram>2147483648</ram>
        <storage>21474836480</storage>
      </recommended>
    </resources>
    <media arch="x86_64">
      <iso>
        <volume-id>PaganLinux</volume-id>
        <kernel>boot/vmlinuz-linux</kernel>
        <initrd>boot/initramfs.img</initrd>
      </iso>
    </media>
  </os>
</libosinfo>
OSINFO

    ok "osinfo-db + Pagan Rolling XML ✓"
}

# ========================= CALAMARES INSTALLER =========================
install_calamares() {
    step "INSTALACJA CALAMARES (Instalator systemu)"

    export PATH="$TOOLS_DIR/bin:$PATH"
    export PKG_CONFIG_PATH="$PAGAN_ROOT/usr/lib/pkgconfig:$PAGAN_ROOT/usr/share/pkgconfig"

    # KPMcore – biblioteka partycjonowania
    build_lfs_pkg "kpmcore" "24.12.3" \
        "https://download.kde.org/stable/release-service/24.12.3/src/kpmcore-24.12.3.tar.xz" \
        "SKIP" \
        "cmake -B build -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_BUILD_TYPE=Release -G Ninja && DESTDIR=\$PAGAN_ROOT ninja -C build install"

    # Calamares
    build_lfs_pkg "calamares" "3.3.14" \
        "https://github.com/calamares/calamares/releases/download/v3.3.14/calamares-3.3.14.tar.gz" \
        "SKIP" \
        "cmake -B build -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_BUILD_TYPE=Release -DWITH_PYTHONQT=OFF -DWITH_KF5KIO=OFF -G Ninja && DESTDIR=\$PAGAN_ROOT ninja -C build install"

    # Konfiguracja
    mkdir -p "$PAGAN_ROOT/etc/calamares"
    mkdir -p "$PAGAN_ROOT/usr/share/calamares/branding/paganlinux"

    # settings.conf
    cat > "$PAGAN_ROOT/etc/calamares/settings.conf" <<'CALEOF'
---
sequence:
  - show: [welcome, locale, keyboard, partition, users, summary]
  - exec: [partition, mount, unpackfs, machineid, fstab, locale, keyboard, localecfg, users, displaymanager, networkcfg, hwclock, services, grubcfg, bootloader, packages, umount]
  - show: [finished]

branding: paganlinux

partition:
    defaultFileSystemType: "ext4"
    availableFileSystemTypes: ["ext4","xfs","btrfs","f2fs"]
    enableLuks: true
    requiredPartitionTableType: "gpt"
    requiredStorage: 8.0

users:
    defaultGroups: [lp, video, audio, optical, storage, scanner, power, wheel]
    setRootPassword: true

networkcfg:
    writeNetworkManager: true

grubcfg:
    preferGrubEfi: true

bootloader:
    installEFIFallback: true

services:
    enabled: [NetworkManager, lightdm, pipewire]
    disabled: [sshd]

welcome:
    showDonateUrl: false

finished:
    restartNowEnabled: true
    restartNowCommand: "systemctl reboot"
CALEOF

    # branding.desc
    cat > "$PAGAN_ROOT/usr/share/calamares/branding/paganlinux/branding.desc" <<'CALEOF'
---
componentName:  paganlinux
version:        1.0
welcomeStyleCalamares:  true
strings:
    productName:         "Pagan Linux"
    shortProductName:    "Pagan"
    version:             "1.0 Loki"
    shortVersion:        "1.0"
    versionedName:       "Pagan Linux 1.0 Loki"
    bootloaderEntryName: "Pagan Linux"
    productUrl:          "https://paganlinux.eu"
    supportUrl:          "https://paganlinux.eu/support"
images:
    productLogo:         "logo.png"
    productIcon:         "icon.png"
    productWelcome:      "welcome.png"

slideshow:               "show.qml"
slideshowAPI:            2

style:
    sidebarBackground:    "#1a1a2e"
    sidebarText:          "#e0e0e0"
    sidebarTextSelect:    "#58a6ff"
CALEOF

    ok "Calamares Installer + Pagan branding ✓"
}

# ========================= KONFIGURACJA GRUB =========================
install_pag() {
    step "INSTALACJA PAG + PAGBUILD (MENEDŻER PAKIETÓW + BUDOWANIE)"

    # Python dependencies for pag/pagbuild
    chroot "$PAGAN_ROOT" pip3 install flit-core packaging markupsafe jinja2 setuptools wheel pyyaml --break-system-packages 2>/dev/null || true

    # ---- pag - natywny menedżer pakietów (pełna wersja) ----
    cp "$SCRIPT_DIR/pag" "$PAGAN_ROOT/usr/bin/pag"
    chmod +x "$PAGAN_ROOT/usr/bin/pag"

    # ---- pagbuild - builder receptur w chroot ----
    cat > "$PAGAN_ROOT/usr/bin/pagbuild" <<'PAGBUILDEOF'
#!/bin/bash
# PAGBUILD – buduje pakiety z PAGBUILD.yaml w izolacji chroot
set -euo pipefail
RECIPE="${1:-PAGBUILD.yaml}"
OUT="${OUT_DIR:-/var/cache/pagbuild/output}"
SRC="${SRC_CACHE:-/var/cache/pagbuild/sources}"
WORK="/tmp/pagbuild-$$"
ROOTFS="${ROOTFS:-/}"

[[ -f "$RECIPE" ]] || { echo "❌ $RECIPE nie istnieje."; exit 1; }

eval $(python3 -c "
import yaml
with open('$RECIPE') as f: d=yaml.safe_load(f)
print(f'NAME=\"{d[\"pkgname\"]}\" VER=\"{d[\"pkgver\"]}\" URL=\"{d[\"source\"][0]}\"')
")

ARCH=$(basename "$URL")
FULL="${NAME}-${VER}"
echo "🚀 $FULL"

mkdir -p "$SRC" "$OUT" "$WORK/src" "$WORK/dest"
[[ -f "$SRC/$ARCH" ]] || curl -sSL "$URL" -o "$SRC/$ARCH"
tar -xf "$SRC/$ARCH" -C "$WORK/src" --strip-components=1 2>/dev/null || tar -xf "$SRC/$ARCH" -C "$WORK/src"

# Generuj skrypt build+package z receptury
python3 -c "
import yaml
with open('$RECIPE') as f: d=yaml.safe_load(f)
script = f'''#!/bin/bash
set -eo pipefail
export PKGDIR=/tmp/dest
cd /tmp/src
{d['build']}
{d['package']}
'''
open('/tmp/pagbuild-script.sh','w').write(script)
"
chmod +x /tmp/pagbuild-script.sh

cp -r "$WORK/src/"* "$ROOTFS/tmp/src/" 2>/dev/null || true
cp /tmp/pagbuild-script.sh "$ROOTFS/tmp/build.sh"

mount -t proc proc "$ROOTFS/proc" 2>/dev/null || true
mount -t sysfs sys "$ROOTFS/sys" 2>/dev/null || true
mount --bind /dev "$ROOTFS/dev" 2>/dev/null || true

chroot "$ROOTFS" /usr/bin/env -i PATH=/usr/bin:/usr/sbin:/bin:/sbin HOME=/root /tmp/build.sh

umount -l "$ROOTFS/dev" "$ROOTFS/sys" "$ROOTFS/proc" 2>/dev/null || true

cp -r "$ROOTFS/tmp/dest/"* "$WORK/dest/" 2>/dev/null || true
echo "{\"name\":\"$NAME\",\"version\":\"$VER\"}" > "$WORK/dest/metadata.json"
PKG="$OUT/${FULL}-1.pkg.tar.xz"
tar -cJf "$PKG" -C "$WORK/dest" .
echo "✅ $PKG"
rm -rf "$WORK" /tmp/pagbuild-script.sh
PAGBUILDEOF
    chmod +x "$PAGAN_ROOT/usr/bin/pagbuild"

    mkdir -p "$PAGAN_ROOT/var/cache/pagbuild/"{sources,output}
    ok "PAG + PAGBUILD zainstalowane!"
}

# ========================= MENEDŻER STEROWNIKÓW =========================
install_driver_manager() {
    step "INSTALACJA MENEDŻERA STEROWNIKÓW"

    cat > "$PAGAN_ROOT/usr/bin/pagan-drivers" <<'EOF'
#!/bin/bash
# pagan-drivers - Menedżer sterowników Pagan Linux

GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

detect() {
    echo "🔍 Wykrywanie sprzętu..."
    echo -e "\n${YELLOW}GPU:${NC}"
    lspci | grep -E "VGA|3D|Display" || echo "  Brak"
    echo -e "\n${YELLOW}Sieć:${NC}"
    lspci | grep -E "Ethernet|Network|Wi-Fi" || echo "  Brak"
    echo -e "\n${YELLOW}Audio:${NC}"
    lspci | grep -E "Audio|Sound" || echo "  Brak"
}

install_nvidia() {
    echo "⬇ Pobieranie NVIDIA..."
    wget -O /tmp/nvidia.run "https://us.download.nvidia.com/XFree86/Linux-x86_64/550.120/NVIDIA-Linux-x86_64-550.120.run"
    chmod +x /tmp/nvidia.run && /tmp/nvidia.run --silent
    echo "✅ NVIDIA zainstalowane"
}

install_amd() {
    echo "⬇ AMDGPU..."
    echo "  Zainstaluj: xf86-video-amdgpu"
    echo "✅ AMD gotowe"
}

install_intel() {
    echo "⬇ Intel..."
    echo "  Zainstaluj: xf86-video-intel"
    echo "✅ Intel gotowe"
}

case "${1:-help}" in
    detect) detect ;;
    nvidia) install_nvidia ;;
    amd) install_amd ;;
    intel) install_intel ;;
    auto) detect && echo -e "\n${GREEN}Automatyczne dopasowanie...${NC}" ;;
    *) echo "Użycie: pagan-drivers {detect|nvidia|amd|intel|auto}" ;;
esac
EOF

    chmod +x "$PAGAN_ROOT/usr/bin/pagan-drivers"
    ok "Menedżer sterowników zainstalowany!"
}

# ========================= KONFIGURACJA GRUB =========================
configure_grub() {
    step "KONFIGURACJA GRUB"

    mkdir -p "$PAGAN_ROOT/boot/grub"

    cat > "$PAGAN_ROOT/boot/grub/grub.cfg" <<'EOF'
# GRUB dla Pagan Linux
set default=0
set timeout=5
set root=(hd0,gpt1)

menuentry "Pagan Linux" {
    linux /boot/vmlinuz-linux root=/dev/sda1 rw quiet splash
    initrd /boot/initramfs.img
}

menuentry "Pagan Linux (single)" {
    linux /boot/vmlinuz-linux root=/dev/sda1 rw single
    initrd /boot/initramfs.img
}

menuentry "Pagan Linux (fallback)" {
    linux /boot/vmlinuz-linux root=/dev/sda1 rw noacpi
    initrd /boot/initramfs.img
}
EOF

    ok "GRUB skonfigurowany"
}

# ========================= BUDOWA INITRAMFS =========================
build_initramfs() {
    step "BUDOWA INITRAMFS"

    local initramfs_dir="$PAGAN_ROOT/tmp/initramfs"
    rm -rf "$initramfs_dir"
    mkdir -p "$initramfs_dir"/{bin,dev,proc,sys,run,new_root,etc,lib,lib64,usr,sbin}

    # Skrypt init
    cat > "$initramfs_dir/init" <<'EOF'
#!/bin/sh

mount -t proc proc /proc
mount -t sysfs sys /sys
mount -t devtmpfs dev /dev

if [ -f /etc/pagan-release ]; then
    cat /etc/pagan-release
fi

ACTIVE_LINK="/.deployments/active"
DEPLOYMENT=""

if [ -L "$ACTIVE_LINK" ]; then
    DEPLOYMENT=$(readlink "$ACTIVE_LINK")
elif [ -d "/.deployments" ]; then
    DEPLOYMENT=$(ls -1 /.deployments/ | grep -v active | sort -r | head -1)
    [ -n "$DEPLOYMENT" ] && DEPLOYMENT="/.deployments/$DEPLOYMENT"
fi

if [ -n "$DEPLOYMENT" ] && [ -d "$DEPLOYMENT" ]; then
    echo "Booting from deployment: $DEPLOYMENT"
    mount --move /proc "$DEPLOYMENT/proc" 2>/dev/null
    mount --move /sys "$DEPLOYMENT/sys" 2>/dev/null
    mount --move /dev "$DEPLOYMENT/dev" 2>/dev/null
    exec switch_root "$DEPLOYMENT" /sbin/init
else
    echo "No deployment found, booting from /"
    exec switch_root /new_root /sbin/init
fi
EOF

    chmod +x "$initramfs_dir/init"

    # Busybox lub bash
    local busybox=""
    for p in "$PAGAN_ROOT/usr/bin/busybox" "$PAGAN_ROOT/bin/busybox" "/usr/bin/busybox"; do
        [ -f "$p" ] && busybox="$p" && break
    done

    if [ -n "$busybox" ]; then
        cp "$busybox" "$initramfs_dir/bin/busybox"
        chmod 755 "$initramfs_dir/bin/busybox"
        for cmd in sh mount umount ls cat echo sleep readlink mkdir switch_root cp rm ln; do
            ln -sf busybox "$initramfs_dir/bin/$cmd"
        done
    else
        # Kopiuj bash i ldd
        for tool in bash mount umount ls cat echo sleep readlink mkdir switch_root cp rm ln; do
            src=$(which "$tool" 2>/dev/null)
            [ -n "$src" ] && cp "$src" "$initramfs_dir/bin/"
        done
    fi

    # Kopiuj /etc/pagan-release
    [ -f "$PAGAN_ROOT/etc/pagan-release" ] && cp "$PAGAN_ROOT/etc/pagan-release" "$initramfs_dir/etc/"

    # Pakowanie
    pushd "$initramfs_dir" > /dev/null
    find . | cpio -oH newc | gzip > "$PAGAN_ROOT/boot/initramfs.img"
    popd > /dev/null

    rm -rf "$initramfs_dir"
    ok "Initramfs zbudowany!"
}

# ========================= TWORZENIE IMG =========================
create_image() {
    step "TWORZENIE OBRAZU IMG"

    mkdir -p "$OUTPUT_DIR"
    local img_file="$OUTPUT_DIR/Pagan-Linux-${PAGAN_VERSION}-${PAGAN_DE}.img"

    info "Tworzenie IMG (${IMAGE_SIZE}MB)..."

    dd if=/dev/zero of="$img_file" bs=1M count="$IMAGE_SIZE" status=progress 2>/dev/null
    parted -s "$img_file" mklabel gpt
    parted -s "$img_file" mkpart primary ext4 2048s 100%
    parted -s "$img_file" set 1 boot on

    local loopdev=$(losetup -f)
    losetup -P "$loopdev" "$img_file"
    mkfs.ext4 -F -L "PAGAN_ROOT" "${loopdev}p1" >/dev/null 2>&1

    local mount_point="/mnt/pagan-img"
    mkdir -p "$mount_point"
    mount "${loopdev}p1" "$mount_point"

    info "Kopiowanie systemu..."
    rsync -aAX --delete \
        --exclude={"/dev/*","/proc/*","/sys/*","/tmp/*","/run/*","/mnt/*","/media/*","/lost+found","*.img","*.iso"} \
        "$PAGAN_ROOT/" "$mount_point/" 2>/dev/null

    # Instalacja GRUB
    mount --bind /dev "$mount_point/dev"
    mount --bind /proc "$mount_point/proc"
    mount --bind /sys "$mount_point/sys"

    chroot "$mount_point" grub-install --target=i386-pc "$loopdev" 2>/dev/null || true

    umount "$mount_point/dev" "$mount_point/proc" "$mount_point/sys" 2>/dev/null
    umount "$mount_point" 2>/dev/null
    losetup -d "$loopdev" 2>/dev/null

    ok "IMG: $img_file ($(du -h "$img_file" 2>/dev/null | cut -f1))"
}

# ========================= TWORZENIE ISO =========================
create_iso() {
    step "TWORZENIE OBRAZU ISO"

    mkdir -p "$OUTPUT_DIR"
    local iso_file="$OUTPUT_DIR/Pagan-Linux-${PAGAN_VERSION}-${PAGAN_DE}.iso"
    local iso_root="/tmp/pagan-iso-$$"

    rm -rf "$iso_root"
    mkdir -p "$iso_root"/{boot,isolinux,live}

    # Kopiuj binaria ISOLINUX z hosta (wymagane do bootowania BIOS)
    for isolinux_bin in \
        /usr/lib/syslinux/bios/isolinux.bin \
        /usr/share/syslinux/isolinux.bin \
        /usr/lib/ISOLINUX/isolinux.bin; do
        [[ -f "$isolinux_bin" ]] && { cp "$isolinux_bin" "$iso_root/isolinux/"; break; }
    done
    for ldlinux in \
        /usr/lib/syslinux/bios/ldlinux.c32 \
        /usr/share/syslinux/ldlinux.c32; do
        [[ -f "$ldlinux" ]] && { cp "$ldlinux" "$iso_root/isolinux/"; break; }
    done
    if [[ ! -f "$iso_root/isolinux/isolinux.bin" ]]; then
        warn "isolinux.bin nie znaleziony – ISO bez obsługi BIOS (tylko EFI)"
    fi

    cp "$PAGAN_ROOT/boot/vmlinuz-linux" "$iso_root/boot/" 2>/dev/null || true
    cp "$PAGAN_ROOT/boot/initramfs.img" "$iso_root/boot/" 2>/dev/null || true

    info "Tworzenie squashfs..."
    mksquashfs "$PAGAN_ROOT" "$iso_root/live/filesystem.squashfs" \
        -comp xz -b 1M -noappend \
        -wildcards -e "*.img" "*.iso" "/dev/*" "/proc/*" "/sys/*" "/tmp/*" "/run/*" \
        -no-progress 2>/dev/null

    cat > "$iso_root/isolinux/isolinux.cfg" <<'EOF'
DEFAULT pagan
TIMEOUT 50

LABEL pagan
    MENU LABEL ^Pagan Linux Live
    KERNEL /boot/vmlinuz-linux
    APPEND initrd=/boot/initramfs.img root=/dev/ram0 rw quiet splash

LABEL pagan-fallback
    MENU LABEL Pagan Linux (fallback)
    KERNEL /boot/vmlinuz-linux
    APPEND initrd=/boot/initramfs.img root=/dev/ram0 rw noacpi
EOF

    # Instalator
    cat > "$iso_root/install-pagan.sh" <<'EOF'
#!/bin/bash
echo "╔═══════════════════════════════════════════════╗"
echo "║     PAGAN LINUX INSTALLER                    ║"
echo "╚═══════════════════════════════════════════════╝"
lsblk
read -p "Dysk docelowy (np. /dev/sda): " DISK
[ -z "$DISK" ] && exit 1

echo "Instalacja na $DISK..."
dd if=/dev/zero of="$DISK" bs=1M count=1
parted -s "$DISK" mklabel gpt
parted -s "$DISK" mkpart primary ext4 2048s 100%
parted -s "$DISK" set 1 boot on
mkfs.ext4 -F -L "PAGAN" "${DISK}1"

MOUNT="/mnt/pagan-install"
mkdir -p "$MOUNT"
mount "${DISK}1" "$MOUNT"

rsync -aAX /live/ "$MOUNT/" --exclude={"/dev/*","/proc/*","/sys/*","/tmp/*","/run/*"}

mkdir -p "$MOUNT/dev" "$MOUNT/proc" "$MOUNT/sys"
mount --bind /dev "$MOUNT/dev"
mount --bind /proc "$MOUNT/proc"
mount --bind /sys "$MOUNT/sys"

chroot "$MOUNT" grub-install "$DISK"
chroot "$MOUNT" update-grub 2>/dev/null || true

umount "$MOUNT/dev" "$MOUNT/proc" "$MOUNT/sys"
umount "$MOUNT"

echo "✅ Instalacja zakończona!"
EOF
    chmod +x "$iso_root/install-pagan.sh"

    # Generuj ISO
    if command -v xorriso &>/dev/null; then
        xorriso -as mkisofs -o "$iso_file" \
            -b isolinux/isolinux.bin -c isolinux/boot.cat \
            -no-emul-boot -boot-load-size 4 -boot-info-table \
            -V "Pagan Linux ${PAGAN_VERSION}" \
            "$iso_root" 2>/dev/null
    else
        error "Brak xorriso"
    fi

    rm -rf "$iso_root"
    ok "ISO: $iso_file ($(du -h "$iso_file" 2>/dev/null | cut -f1))"
}

# ========================= FINALIZACJA =========================
finalize_build() {
    step "FINALIZACJA BUDOWY"

    # /etc/pagan-release
    cat > "$PAGAN_ROOT/etc/pagan-release" <<EOF
Pagan Linux ${PAGAN_VERSION}
Środowisko: ${PAGAN_DE^^}
Kernel: ${KERNEL_VERSION}
Data: $(date)
Architektura: $(uname -m)
LFS: ${LFS_VERSION}
EOF

    # /etc/issue
    cat > "$PAGAN_ROOT/etc/issue" <<EOF
Pagan Linux ${PAGAN_VERSION} \n \l

EOF

    # /etc/os-release
    cat > "$PAGAN_ROOT/etc/os-release" <<EOF
NAME="Pagan Linux"
VERSION="${PAGAN_VERSION}"
ID=pagan
PRETTY_NAME="Pagan Linux ${PAGAN_VERSION}"
ANSI_COLOR="1;32"
HOME_URL="https://github.com/pagan-linux"
EOF

    ok "Finalizacja zakończona!"
}

# ========================= WERYFIKACJA SYSTEMU =========================
verify_rootfs() {
    step "🧪 WERYFIKACJA SYSTEMU – sanity check po buildzie"
    local fails=0

    # Podstawowe binarki
    local check
    for check in bash sh ls cat grep sed awk make gcc python3 perl; do
        if [[ ! -x "$PAGAN_ROOT/usr/bin/$check" ]] && [[ ! -x "$PAGAN_ROOT/bin/$check" ]]; then
            warn "Brak binarki: $check"
            ((fails++)) || true
        fi
    done

    # Python + sqlite3 (wymagane przez pag)
    if [[ -x "$PAGAN_ROOT/usr/bin/python3" ]]; then
        if chroot "$PAGAN_ROOT" /usr/bin/python3 -c "import sqlite3; import zlib; import tarfile" >/dev/null 2>&1; then
            ok "python3 + sqlite3 działa"
        else
            warn "python3 nie ma sqlite3/zlib/tarfile – pag nie będzie działać!"
            ((fails++)) || true
        fi
    else
        warn "Brak python3 – pag nie będzie działać!"
        ((fails++)) || true
    fi

    # pag – pełna wersja v3 (nie stub)
    if [[ -f "$PAGAN_ROOT/usr/bin/pag" ]]; then
        if grep -q "PAG - Pagan Linux Package Manager v3" "$PAGAN_ROOT/usr/bin/pag" 2>/dev/null; then
            ok "pag – pełna wersja v3"
        else
            warn "pag to stub (niepełna wersja) – sprawdź install_pag"
            ((fails++)) || true
        fi
    else
        warn "Brak /usr/bin/pag"
        ((fails++)) || true
    fi

    # glibc
    if [[ -f "$PAGAN_ROOT/usr/lib/libc.so.6" ]]; then
        local glibc_ver
        glibc_ver=$(chroot "$PAGAN_ROOT" /usr/bin/ldd --version 2>/dev/null | head -1 | grep -o '[0-9.]*' || true)
        ok "glibc: ${glibc_ver:-?}"
    else
        warn "Brak libc.so.6!"
        ((fails++)) || true
    fi

    # Chroot test
    if chroot "$PAGAN_ROOT" /bin/bash -c "echo OK" >/dev/null 2>&1; then
        ok "chroot + bash działa"
    else
        warn "chroot /bin/bash NIE działa!"
        ((fails++)) || true
    fi

    if [[ $fails -gt 0 ]]; then
        warn "Weryfikacja: $fails problemów znalezionych (patrz wyżej)"
    else
        ok "Weryfikacja: wszystkie sanity checki przeszły ✅"
    fi
    return $fails
}

# ========================= WIRTUALNE SYSTEMY PLIKÓW =========================
mount_virtual_fs() {
    info "Montowanie wirtualnych systemów plików w $PAGAN_ROOT..."
    mount --bind /dev "$PAGAN_ROOT/dev" 2>/dev/null || true
    mount --bind /dev/pts "$PAGAN_ROOT/dev/pts" 2>/dev/null || true
    mount -t proc proc "$PAGAN_ROOT/proc" 2>/dev/null || true
    mount -t sysfs sysfs "$PAGAN_ROOT/sys" 2>/dev/null || true
    mount -t tmpfs tmpfs "$PAGAN_ROOT/run" 2>/dev/null || true
}

umount_virtual_fs() {
    info "Odmontowywanie wirtualnych systemów plików..."
    umount -l "$PAGAN_ROOT/dev/pts" 2>/dev/null || true
    umount -l "$PAGAN_ROOT/dev" 2>/dev/null || true
    umount -l "$PAGAN_ROOT/proc" 2>/dev/null || true
    umount -l "$PAGAN_ROOT/sys" 2>/dev/null || true
    umount -l "$PAGAN_ROOT/run" 2>/dev/null || true
}

# ========================= GŁÓWNY PROCES =========================
main() {
    cd /
    show_banner

    local arg
    FORCE_PKGS=""
    for arg in "$@"; do
        case "$arg" in
            --rebuild|--from-scratch|--clean)
                REBUILD_FROM_SCRATCH=1
                ;;
            --force-pkg=*)
                FORCE_PKGS="${arg#*=},${FORCE_PKGS}"
                ;;
        esac
    done

    # Clean environment from any previous SYSROOT leakage
    unset PKG_CONFIG_SYSROOT_DIR

    if [[ $EUID -ne 0 ]]; then
        error "Wymagane uprawnienia root (sudo)"
    fi

    if _is_true "${REBUILD_FROM_SCRATCH:-0}"; then
        clean_build_state
    fi

    # Wybór środowiska
    if [[ -z "${PAGAN_DE:-}" ]]; then
        echo ""
        echo "Wybierz środowisko graficzne:"
        echo "  1) GNOME  (Wayland, pełne, nowoczesne – domyślne)"
        echo "  2) Deepin (nowoczesne, eleganckie)"
        echo "  3) Budgie (minimalne, eleganckie)"
        echo "  4) Xfce   (lekkie, stabilne)"
        echo ""
        read -p "Wybierz [1-4]: " de_choice
        case "$de_choice" in
            1|"") PAGAN_DE="gnome" ;;
            2) PAGAN_DE="deepin" ;;
            3) PAGAN_DE="budgie" ;;
            4) PAGAN_DE="xfce" ;;
            *) error "Nieprawidłowy wybór" ;;
        esac
    fi

    # Wybór formatu obrazu
    BUILD_IMG="${BUILD_IMG:-}"
    BUILD_ISO="${BUILD_ISO:-}"
    if [[ -z "$BUILD_IMG" ]] && [[ -z "$BUILD_ISO" ]]; then
        case "${ARTIFACT_MODE,,}" in
            img|"") BUILD_IMG=1; BUILD_ISO=0 ;;
            iso)      BUILD_IMG=0; BUILD_ISO=1 ;;
            both)     BUILD_IMG=1; BUILD_ISO=1 ;;
            ask)
                echo ""
                echo "Wybierz format obrazu:"
                echo "  1) IMG (obraz dysku – gotowy system)"
                echo "  2) ISO (obraz live/instalacyjny)"
                echo "  3) Oba (IMG + ISO)"
                echo ""
                read -p "Wybierz [1-3]: " img_choice
                case "$img_choice" in
                    1|"") BUILD_IMG=1; BUILD_ISO=0 ;;
                    2) BUILD_IMG=0; BUILD_ISO=1 ;;
                    3) BUILD_IMG=1; BUILD_ISO=1 ;;
                    *) error "Nieprawidłowy wybór" ;;
                esac
                ;;
            *) error "Nieprawidłowe ARTIFACT_MODE: ${ARTIFACT_MODE}. Użyj: img|iso|both|ask" ;;
        esac
    fi

    check_dependencies
    check_lfs_patches
    init_build
    build_toolchain          # Ch. 5

    mount_virtual_fs        # Montuj /dev /proc /sys przed budową systemu

    build_final_system       # Ch. 6-8 (LFS + systemd + GRUB)
    build_blfs               # BLFS
    build_kernel             # Kernel (w tym moduły WiFi)
    install_nvidia_drivers   # NVIDIA open-gpu-kernel-modules (best-effort)
    install_pag
    install_driver_manager

    case "${PAGAN_DE,,}" in
        xfce)   install_xfce ;;
        deepin) install_deepin ;;
        budgie) install_budgie ;;
        gnome)  install_gnome ;;
        *)      warn "Nieznane DE: $PAGAN_DE – używam GNOME (Wayland)"; install_gnome ;;
    esac

    install_calamares
    install_osinfo
    configure_grub
    build_initramfs
    finalize_build
    verify_rootfs

    umount_virtual_fs       # Odmontuj przed tworzeniem obrazów

    if [[ "${BUILD_IMG:-1}" -eq 1 ]]; then
        create_image
    fi

    if [[ "${BUILD_ISO:-0}" -eq 1 ]]; then
        create_iso
    fi

    report_artifacts

    # Podsumowanie
    step "✅ BUDOWA ZAKOŃCZONA!"

    echo -e "\n${GREEN}${BOLD}╔═══════════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${GREEN}${BOLD}║                                                                   ║${NC}"
    echo -e "${GREEN}${BOLD}║   ✅  PAGAN LINUX ${PAGAN_VERSION} z ${PAGAN_DE^^} ZBUDOWANY!        ║${NC}"
    echo -e "${GREEN}${BOLD}║                                                                   ║${NC}"
    echo -e "${GREEN}${BOLD}║   📁  System:      ${PAGAN_ROOT}${NC}"
    echo -e "${GREEN}${BOLD}║   🖥️  Środowisko:  ${PAGAN_DE^^}${NC}"
    echo -e "${GREEN}${BOLD}║   🐧  Kernel:      ${KERNEL_VERSION}${NC}"
    echo -e "${GREEN}${BOLD}║   📦  Menedżer:    PAG + pagan-drivers                             ║${NC}"
    echo -e "${GREEN}${BOLD}║                                                                   ║${NC}"

    if [[ -f "$OUTPUT_DIR/Pagan-Linux-${PAGAN_VERSION}-${PAGAN_DE}.img" ]]; then
        echo -e "${GREEN}${BOLD}║   💾  IMG:        $OUTPUT_DIR/Pagan-Linux-${PAGAN_VERSION}-${PAGAN_DE}.img    ║${NC}"
    fi
    if [[ -f "$OUTPUT_DIR/Pagan-Linux-${PAGAN_VERSION}-${PAGAN_DE}.iso" ]]; then
        echo -e "${GREEN}${BOLD}║   💿  ISO:        $OUTPUT_DIR/Pagan-Linux-${PAGAN_VERSION}-${PAGAN_DE}.iso    ║${NC}"
    fi

    echo -e "${GREEN}${BOLD}║                                                                   ║${NC}"
    echo -e "${GREEN}${BOLD}║   📋  Log:        ${LOG_FILE}${NC}"
    echo -e "${GREEN}${BOLD}║                                                                   ║${NC}"
    echo -e "${GREEN}${BOLD}║   💡  Następne kroki:                                              ║${NC}"
    echo -e "${GREEN}${BOLD}║       - Wypal obraz: dd if=... of=/dev/sdX bs=4M status=progress  ║${NC}"
    echo -e "${GREEN}${BOLD}║       - Uruchom system: logowanie pagan / changeme (wymusi zmianę)║${NC}"
    echo -e "${GREEN}${BOLD}║       - Sterowniki:   pagan-drivers auto                           ║${NC}"
    echo -e "${GREEN}${BOLD}║                                                                   ║${NC}"
    echo -e "${GREEN}${BOLD}╚═══════════════════════════════════════════════════════════════════╝${NC}"
    echo ""
}

# ========================= URUCHOMIENIE =========================
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi