Compare commits
13
Commits
1ff26b0e9d
...
a6699866bd
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a6699866bd | ||
|
|
e78f716d05 | ||
|
|
44c5feda48 | ||
|
|
0fc6adf354 | ||
|
|
1fe38d0b61 | ||
|
|
6eae9e357c | ||
|
|
d5d5beff04 | ||
|
|
070b110b75 | ||
|
|
be84a20f7a | ||
|
|
b22cd7b49b | ||
|
|
141de3e0e2 | ||
|
|
376db9495a | ||
|
|
9b35975f19 |
+4
-1
@@ -1,6 +1,9 @@
|
||||
sources/
|
||||
output/
|
||||
build/
|
||||
logs/
|
||||
wlasnyos-repo/
|
||||
KhOS-packages/
|
||||
installer/
|
||||
.git/
|
||||
*.iso
|
||||
*.iso
|
||||
|
||||
+5
-1
@@ -3,5 +3,9 @@ sources/
|
||||
logs/
|
||||
build/output/
|
||||
output/
|
||||
scratch/
|
||||
*.iso
|
||||
*.iso.sha256
|
||||
*.iso.sha256
|
||||
.vscode/
|
||||
__pycache__/
|
||||
*.pyc
|
||||
@@ -1,4 +1,3 @@
|
||||
[submodule "KhOS-packages"]
|
||||
path = KhOS-packages
|
||||
url = https://git.kpgpmc.org/KhOS/KhOS-packages.git
|
||||
|
||||
|
||||
+7
-2
@@ -3,8 +3,9 @@ FROM debian:bookworm-slim
|
||||
# Prevent interactive prompts during apt
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
# Install all required build dependencies
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
# Configure non-free-firmware repository and install all build dependencies & physical drivers/firmware
|
||||
RUN sed -i 's/Components: main/Components: main non-free-firmware/' /etc/apt/sources.list.d/debian.sources 2>/dev/null || echo 'deb http://deb.debian.org/debian bookworm main non-free-firmware' > /etc/apt/sources.list && \
|
||||
apt-get update && apt-get install -y --no-install-recommends \
|
||||
build-essential \
|
||||
gcc \
|
||||
g++ \
|
||||
@@ -43,6 +44,10 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
texinfo \
|
||||
gawk \
|
||||
patch \
|
||||
firmware-amd-graphics \
|
||||
firmware-realtek \
|
||||
firmware-atheros \
|
||||
firmware-misc-nonfree \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /build
|
||||
|
||||
+1
-1
Submodule KhOS-packages updated: 0db335a1a9...96c7164bf1
+3
-2
@@ -38,12 +38,13 @@ if (Test-Path $ScratchDir) {
|
||||
}
|
||||
|
||||
$PackagesDir = (Join-Path $PWD.Path "KhOS-packages").Replace('\', '/')
|
||||
$InstallerDir = (Join-Path $PWD.Path "installer").Replace('\', '/')
|
||||
|
||||
Write-Host "Running build container (with --privileged)..." -ForegroundColor Cyan
|
||||
if ($ExtraMount -ne "") {
|
||||
docker run --rm --privileged -v "${OutDir}:/build/build/output" -v "${SourcesDir}:/build/build/sources" -v "${LogsDir}:/build/build/logs" -v "${ScriptsDir}:/build/scripts" -v "${OverlayDir}:/build/overlay" -v "${PackagesDir}:/build/KhOS-packages:ro" -v "${ScratchDir}:/scratch:ro" $ImageName
|
||||
docker run --rm --privileged -v "${OutDir}:/build/build/output" -v "${SourcesDir}:/build/build/sources" -v "${LogsDir}:/build/build/logs" -v "${ScriptsDir}:/build/scripts" -v "${OverlayDir}:/build/overlay" -v "${PackagesDir}:/build/KhOS-packages:ro" -v "${InstallerDir}:/build/installer:ro" -v "${ScratchDir}:/scratch:ro" $ImageName
|
||||
} else {
|
||||
docker run --rm --privileged -v "${OutDir}:/build/build/output" -v "${SourcesDir}:/build/build/sources" -v "${LogsDir}:/build/build/logs" -v "${ScriptsDir}:/build/scripts" -v "${OverlayDir}:/build/overlay" -v "${PackagesDir}:/build/KhOS-packages:ro" $ImageName
|
||||
docker run --rm --privileged -v "${OutDir}:/build/build/output" -v "${SourcesDir}:/build/build/sources" -v "${LogsDir}:/build/build/logs" -v "${ScriptsDir}:/build/scripts" -v "${OverlayDir}:/build/overlay" -v "${PackagesDir}:/build/KhOS-packages:ro" -v "${InstallerDir}:/build/installer:ro" $ImageName
|
||||
}
|
||||
$DockerExitCode = $LASTEXITCODE
|
||||
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
$extensions = @("*.sh", "*.conf", "*.db", "wpkg", "inittab", "pomoc", "help", "start-hyprland", "start-plasma", "khos-installer", "setup", "install-os", "rcS", "rcK", "network", "dropbear", "WPKGBUILD")
|
||||
$extensions = @("*.sh", "*.conf", "*.db", "*.c", "*.h", "wpkg", "inittab", "pomoc", "help", "start-hyprland", "start-plasma", "autologin-plasma", "khos-installer", "khos-installer-gui", "setup", "install-os", "rcS", "rcK", "network", "dropbear", "WPKGBUILD", "sudoers", "passwd", "shadow", "group", "mdev.conf", "profile", ".profile", "*.desktop", "*.py")
|
||||
|
||||
Get-ChildItem -Recurse -File | Where-Object {
|
||||
$name = $_.Name
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
cmake_minimum_required(VERSION 3.15)
|
||||
|
||||
project(khos-installer
|
||||
VERSION 1.1.0
|
||||
DESCRIPTION "Nowoczesny instalator systemu operacyjnego KhOS w C++"
|
||||
LANGUAGES CXX
|
||||
)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
# Opcja statycznej kompilacji (dla musl-gcc / g++ -static)
|
||||
option(STATIC_BUILD "Wlacz kompilacje statyczna (-static)" OFF)
|
||||
if(STATIC_BUILD)
|
||||
message(STATUS "[KhOS] Wlaczono w pelni statyczne linkowanie (-static)")
|
||||
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static")
|
||||
endif()
|
||||
|
||||
# Flagi kompilatora
|
||||
if(MSVC)
|
||||
add_compile_options(/W4 /EHsc /O2)
|
||||
else()
|
||||
add_compile_options(
|
||||
-Wall
|
||||
-Wextra
|
||||
-Wpedantic
|
||||
-Wshadow
|
||||
-Wnon-virtual-dtor
|
||||
-O2
|
||||
)
|
||||
endif()
|
||||
|
||||
# Zrodla programu
|
||||
set(SOURCES
|
||||
src/main.cpp
|
||||
src/disk.cpp
|
||||
src/bootloader.cpp
|
||||
src/installer.cpp
|
||||
src/utils.cpp
|
||||
)
|
||||
|
||||
set(HEADERS
|
||||
include/installer.hpp
|
||||
include/disk.hpp
|
||||
include/bootloader.hpp
|
||||
include/utils.hpp
|
||||
)
|
||||
|
||||
add_executable(khos-installer ${SOURCES} ${HEADERS})
|
||||
|
||||
target_include_directories(khos-installer PRIVATE
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/include
|
||||
)
|
||||
|
||||
# Biblioteki systemowe (wielowatkowosc i obsluga std::filesystem)
|
||||
find_package(Threads REQUIRED)
|
||||
target_link_libraries(khos-installer PRIVATE Threads::Threads)
|
||||
|
||||
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS 9.1)
|
||||
target_link_libraries(khos-installer PRIVATE stdc++fs)
|
||||
endif()
|
||||
|
||||
# Instalacja
|
||||
include(GNUInstallDirs)
|
||||
install(TARGETS khos-installer
|
||||
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
|
||||
)
|
||||
|
||||
# Alias dowiazania instalatora
|
||||
install(CODE "
|
||||
execute_process(
|
||||
COMMAND \${CMAKE_COMMAND} -E create_symlink
|
||||
khos-installer
|
||||
\$ENV{DESTDIR}\${CMAKE_INSTALL_FULL_BINDIR}/install-os
|
||||
)
|
||||
")
|
||||
@@ -0,0 +1,40 @@
|
||||
# =========================================================================
|
||||
# KhOS Installer C++ - Natywny Makefile
|
||||
# =========================================================================
|
||||
|
||||
CXX ?= g++
|
||||
CXXFLAGS ?= -std=c++17 -Wall -Wextra -Wpedantic -O2 -Iinclude
|
||||
LDFLAGS ?= -pthread
|
||||
DESTDIR ?=
|
||||
PREFIX ?= /usr
|
||||
|
||||
SRCS = src/main.cpp src/disk.cpp src/bootloader.cpp src/installer.cpp src/utils.cpp
|
||||
OBJS = $(SRCS:src/%.cpp=build/%.o)
|
||||
TARGET = khos-installer
|
||||
|
||||
.PHONY: all static clean install test
|
||||
|
||||
all: $(TARGET)
|
||||
|
||||
# Kompilacja w pelni statyczna (np. musl-gcc lub g++ -static)
|
||||
static: LDFLAGS += -static
|
||||
static: $(TARGET)
|
||||
|
||||
$(TARGET): $(OBJS)
|
||||
$(CXX) $(OBJS) -o $@ $(LDFLAGS)
|
||||
|
||||
build/%.o: src/%.cpp
|
||||
@mkdir -p build
|
||||
$(CXX) $(CXXFLAGS) -c $< -o $@
|
||||
|
||||
clean:
|
||||
rm -rf build $(TARGET)
|
||||
|
||||
install: $(TARGET)
|
||||
install -d $(DESTDIR)$(PREFIX)/bin
|
||||
install -m 755 $(TARGET) $(DESTDIR)$(PREFIX)/bin/khos-installer
|
||||
ln -sf khos-installer $(DESTDIR)$(PREFIX)/bin/install-os
|
||||
|
||||
uninstall:
|
||||
rm -f $(DESTDIR)$(PREFIX)/bin/khos-installer
|
||||
rm -f $(DESTDIR)$(PREFIX)/bin/install-os
|
||||
@@ -0,0 +1,239 @@
|
||||
# KhOS C++ Installer (Genesis Edition)
|
||||
|
||||
Pełny, nowoczesny i zoptymalizowany port oficjalnego instalatora systemu operacyjnego **KhOS** napisany w języku **C++17 / C++20**.
|
||||
|
||||
Zaprojektowany z myślą o maksymalnej niezawodności, bezpieczeństwie zasobów (**RAII**), zerowych zewnętrznych zależnościach bibliotecznych oraz możliwości w pełni statycznej kompilacji (z użyciem `musl-gcc` lub `g++ -static`), co czyni go idealnym narzędziem dla środowiska Live CD/USB oraz instalacji w minimalnych obrazach ratunkowych.
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Główne cechy
|
||||
|
||||
- **Architektura obiektowa i bezpieczeństwo RAII**:
|
||||
- `ScopedMount` oraz `MountStack`: automatyczne, bezpieczne odmontowywanie partycji w odwrotnej kolejności (LIFO) w przypadku błędów, wyjątków lub przerwania sygnałem (SIGINT/SIGTERM).
|
||||
- `ScopedFd`: bezpieczne zarządzanie deskryptorami plików i potokami IPC.
|
||||
- **Wieloplatformowy rozruch (UEFI & BIOS)**:
|
||||
- **UEFI**: Automatyczne tworzenie tablicy GPT, partycji EFI System Partition (512 MB, FAT32) i instalacja `GRUB 2` (`x86_64-efi`) z awaryjną kopią `BOOTX64.EFI`.
|
||||
- **BIOS / MBR**: Tworzenie tablicy partycji DOS/MBR, flaga bootable, instalacja `GRUB 2` (`i386-pc`) z automatycznym fallbackiem do `Syslinux / EXTLINUX` w razie braku GRUB-a.
|
||||
- **Elastyczne partycjonowanie i formatowanie**:
|
||||
- Bezpośrednia obsługa dysków NVMe (`/dev/nvme0n1pX`), SATA/SCSI (`/dev/sdX`), VirtIO (`/dev/vdX`) oraz kart MMC (`/dev/mmcblk0pX`).
|
||||
- Priorytetyzacja nowoczesnego `sfdisk` z automatycznym fallbackiem do `parted` i `fdisk`.
|
||||
- Czyszczenie nagłówków dysku: zerowanie początkowych 10 MB (MBR/GPT) oraz końcowych 2 MB (zapasowy GPT).
|
||||
- Formatowanie `mkfs.ext4` z optymalizacjami dla SSD (`noatime`, opcjonalny fallback do `ext2`).
|
||||
- **Zerowe zależności zewnętrzne**:
|
||||
- Samodzielny, bezpieczny parser argumentów wiersza poleceń.
|
||||
- Wbudowany lekki generator formatu JSON do integracji z zewnętrznymi skryptami i interfejsami graficznymi.
|
||||
- **Interfejsy pracy**:
|
||||
- **Interaktywny**: Z kolorowym interfejsem ANSI, wykrywaniem dysków i ostrzeżeniami o usunięciu danych.
|
||||
- **Automatyczny (`--auto`)**: Cicha instalacja nienadzorowana dla instalacji sieciowych, provisioning i testów.
|
||||
- **Symulacja (`--dry-run`)**: Bezpieczny audyt kroków bez dotykania struktury dysku fizycznego.
|
||||
- **Integracja (`--json`)**: Eksport stanu dysków i wyników w formacie JSON.
|
||||
|
||||
---
|
||||
|
||||
## 📁 Struktura katalogów
|
||||
|
||||
```text
|
||||
installer/cpp/
|
||||
├── CMakeLists.txt # Nowoczesna konfiguracja CMake 3.15+ (standard C++17, opcja STATIC_BUILD)
|
||||
├── Makefile # Prosty, natywny Makefile bez zbędnych zależności
|
||||
├── README.md # Dokumentacja techniczna i instrukcja obsługi
|
||||
├── include/
|
||||
│ ├── installer.hpp # Główna klasa Installer, RAII ScopedMount, MountStack, InstallResult
|
||||
│ ├── disk.hpp # Reprezentacja dysków, partycji, detekcja /sys/block, UUID, formatowanie
|
||||
│ ├── bootloader.hpp # Interfejs IBootloader, implementacje GrubBootloader i SyslinuxBootloader
|
||||
│ └── utils.hpp # Kolory ANSI, uruchamianie procesów IPC, pomocnicze operacje na plikach i CLI
|
||||
└── src/
|
||||
├── main.cpp # Parsowanie flag CLI, interaktywne menu oraz obsługa sygnałów
|
||||
├── disk.cpp # Wykrywanie dysków, partycjonowanie (GPT/MBR), czyszczenie sygnatur, mkfs
|
||||
├── bootloader.cpp # Generowanie grub.cfg, instalacja GRUB i rezerwowy EXTLINUX
|
||||
├── installer.cpp # Montowanie, kopiowanie payloadu, /etc/fstab, hostname, hosts, hasło root
|
||||
└── utils.cpp # Implementacja funkcji pomocniczych i parsera CLI
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ Kompilacja i budowanie
|
||||
|
||||
Wymagania: Kompilator wspierający standard C++17 (np. GCC 8+, Clang 7+) oraz CMake 3.15+ lub GNU Make.
|
||||
|
||||
### 1. Budowanie przy użyciu CMake (Zalecane)
|
||||
|
||||
```bash
|
||||
# Wejdź do katalogu instalatora
|
||||
cd installer/cpp
|
||||
|
||||
# Utwórz katalog roboczy i skonfiguruj projekt
|
||||
mkdir -p build && cd build
|
||||
cmake ..
|
||||
|
||||
# Skompiluj binarkę
|
||||
make -j$(nproc)
|
||||
```
|
||||
|
||||
#### Kompilacja w pełni statyczna (np. do obrazu Live CD z musl / glibc):
|
||||
```bash
|
||||
cmake -DSTATIC_BUILD=ON ..
|
||||
make -j$(nproc)
|
||||
```
|
||||
|
||||
#### Kompilacja krzyżowa z musl toolchain:
|
||||
```bash
|
||||
CC=musl-gcc CXX=x86_64-linux-musl-g++ cmake -DSTATIC_BUILD=ON ..
|
||||
make -j$(nproc)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. Budowanie przy użyciu natywnego Makefile
|
||||
|
||||
Dla szybkiego środowiska budowania bez instalowania CMake:
|
||||
|
||||
```bash
|
||||
cd installer/cpp
|
||||
|
||||
# Standardowa kompilacja dynamiczna:
|
||||
make
|
||||
|
||||
# Kompilacja w pełni statyczna (flaga -static):
|
||||
make static
|
||||
|
||||
# Czyszczenie:
|
||||
make clean
|
||||
|
||||
# Instalacja w systemie (do /usr/bin/):
|
||||
sudo make install
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 💻 Przykłady uruchomienia
|
||||
|
||||
### 1. Tryb interaktywny (Domyślny)
|
||||
|
||||
Wystarczy uruchomić program z uprawnieniami administratora (root):
|
||||
|
||||
```bash
|
||||
sudo ./khos-installer
|
||||
```
|
||||
|
||||
Program powita użytkownika banerem ASCII, wykryje tryb rozruchu (BIOS vs UEFI), przeszuka system pod kątem dysków twardych i SSD, a następnie poprowadzi przez proces instalacji lub aktualizacji.
|
||||
|
||||
---
|
||||
|
||||
### 2. Tryb automatyczny (Nienadzorowany)
|
||||
|
||||
Idealny do skryptów masowej instalacji:
|
||||
|
||||
```bash
|
||||
sudo ./khos-installer --auto \
|
||||
--disk /dev/sda \
|
||||
--hostname moj-khos \
|
||||
--password supertajne \
|
||||
--mode uefi
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3. Bezpieczna symulacja (`--dry-run`)
|
||||
|
||||
Pozwala sprawdzić wszystkie etapy instalacji bez zapisywania jakichkolwiek zmian na dysku:
|
||||
|
||||
```bash
|
||||
./khos-installer --dry-run \
|
||||
--disk /dev/nvme0n1 \
|
||||
--mode uefi \
|
||||
--auto
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 4. Wyświetlenie listy dysków w formacie JSON
|
||||
|
||||
Może posłużyć jako backend dla instalatora webowego lub GUI w GTK / Qt:
|
||||
|
||||
```bash
|
||||
./khos-installer --list-disks --json
|
||||
```
|
||||
|
||||
Przykładowa odpowiedź:
|
||||
```json
|
||||
{
|
||||
"disks": [
|
||||
{
|
||||
"device": "/dev/sda",
|
||||
"name": "sda",
|
||||
"model": "Samsung SSD 870 EVO 500GB",
|
||||
"size_bytes": 500107862016,
|
||||
"size_sectors": 976773168,
|
||||
"size_human": "465.8 GB",
|
||||
"is_rotational": false,
|
||||
"is_removable": false,
|
||||
"partitions": [
|
||||
{
|
||||
"device": "/dev/sda1",
|
||||
"number": 1,
|
||||
"size_bytes": 536870912,
|
||||
"fstype": "vfat",
|
||||
"uuid": "A1B2-C3D4",
|
||||
"label": "ESP",
|
||||
"is_bootable": false,
|
||||
"is_efi": true
|
||||
},
|
||||
{
|
||||
"device": "/dev/sda2",
|
||||
"number": 2,
|
||||
"size_bytes": 499570991104,
|
||||
"fstype": "ext4",
|
||||
"uuid": "4f9d2a6b-1c3e-4f8a-9a0d-7b2c5e8f1a3d",
|
||||
"label": "KHOS",
|
||||
"is_bootable": false,
|
||||
"is_efi": false
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 5. Wszystkie dostępne opcje wiersza poleceń
|
||||
|
||||
| Flaga | Krótka flaga | Opis | Domyślna wartość |
|
||||
|---|---|---|---|
|
||||
| `--auto` | `-a` | Tryb nienadzorowany (bez pytań interaktywnych) | `false` |
|
||||
| `--disk <ścieżka>` | `-d` | Ścieżka do docelowego dysku blokowego (np. `/dev/sda`) | brak |
|
||||
| `--hostname <nazwa>` | `-n` | Nazwa komputera w sieci lokalnej | `khos` |
|
||||
| `--password <hasło>` | `-p` | Nowe hasło dla konta administratora `root` | `khos` |
|
||||
| `--mode <tryb>` | `-m` | Wymuszenie trybu rozruchu: `uefi`, `bios` lub `auto` | `auto` |
|
||||
| `--source <katalog>` | `-s` | Własny katalog źródłowy systemu (rootfs) | autodetekcja Live |
|
||||
| `--dry-run` | - | Symulacja operacji (bezpieczny podgląd bez zmian na dysku) | `false` |
|
||||
| `--json` | - | Wyjście w formacie JSON | `false` |
|
||||
| `--list-disks` | `-l` | Wyświetla listę podłączonych dysków i kończy pracę | `false` |
|
||||
| `--help` | `-h` | Wyświetla ekran pomocy | `false` |
|
||||
| `--version` | `-v` | Wyświetla wersję instalatora | `false` |
|
||||
|
||||
---
|
||||
|
||||
## ⚙️ Krok po kroku: Przebieg instalacji
|
||||
|
||||
1. **Weryfikacja uprawnień i środowiska**: Sprawdzenie uprawnień `root` (`getuid() == 0`) oraz weryfikacja istnienia wybranego urządzenia blokowego.
|
||||
2. **Czyszczenie dysku**: Odmontowanie aktywnych partycji na urządzeniu, wyzerowanie pierwszych 10 MB (MBR, główny GPT) oraz ostatnich 2 MB dysku (zapasowy GPT).
|
||||
3. **Tworzenie partycji**:
|
||||
- Dla **UEFI**: Utworzenie partycji 1 (ESP, 512 MB, type `U`) oraz partycji 2 (Root, reszta dysku, type `L`).
|
||||
- Dla **BIOS**: Utworzenie partycji 1 (Root, 100% pojemności, type `83`, flaga rozruchowa `bootable`).
|
||||
4. **Formatowanie**:
|
||||
- ESP: `mkfs.vfat -F32`
|
||||
- Root: `mkfs.ext4 -F -L "KHOS"` (z fallbackiem do `ext2` w skrajnych przypadkach)
|
||||
5. **Montowanie RAII (`MountStack`)**: Montowanie partycji głównej w `/mnt/install_target` oraz opcjonalnej partycji ESP w `/mnt/install_target/boot/efi`.
|
||||
6. **Kopiowanie systemu**: Odnalezienie obrazu `filesystem.squashfs` (lub zamontowanego `/mnt/squashfs` z nośnika Live) i szybki streaming plików z zachowaniem atrybutów, symlinków i uprawnień.
|
||||
7. **Kopiowanie jądra i initramfs**: Przeniesienie plików `vmlinuz` oraz `initramfs.img` do docelowego `/boot`.
|
||||
8. **Konfiguracja systemu**:
|
||||
- Generowanie `/etc/fstab` (odczyt UUID partycji przez `blkid` lub `/dev/disk/by-uuid`).
|
||||
- Zapis `/etc/hostname` oraz `/etc/hosts`.
|
||||
- Zmiana hasła użytkownika `root` za pomocą `chpasswd -R` lub środowiska `chroot`.
|
||||
9. **Instalacja Bootloadera**:
|
||||
- Utworzenie konfiguracji `/boot/grub/grub.cfg` (z opcjami uruchomienia dla XFCE 4, KDE Plasma, trybu awaryjnego z logami jądra, restartu i wyłączenia zasilania).
|
||||
- Wywołanie `grub-install` (UEFI / BIOS). W przypadku braku GRUB na BIOS, instalator automatycznie wgrywa sektor MBR (`mbr.bin`) oraz konfiguruje `Syslinux/EXTLINUX`.
|
||||
10. **Nadanie uprawnień**: Ustawienie uprawnień wykonywania dla skryptów graficznych (`start-xfce`, `start-plasma`, `start-hyprland`, `start-openbox`) oraz bitu SUID (`chmod 4755`) dla krytycznych binariów (`Xorg`, `seatd-launch`, `busybox`).
|
||||
11. **Finalizacja**: Wykonanie polecenia `sync`, bezpieczne rozwinięcie stosu montowania (`MountStack::unmount_all()`) i usunięcie punktu montowania.
|
||||
@@ -0,0 +1,95 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
#include "disk.hpp"
|
||||
|
||||
namespace khos {
|
||||
|
||||
struct BootEntry {
|
||||
std::string title;
|
||||
std::string linux_cmd;
|
||||
std::string initrd_cmd;
|
||||
std::string extra_args;
|
||||
};
|
||||
|
||||
class IBootloader {
|
||||
public:
|
||||
virtual ~IBootloader() = default;
|
||||
|
||||
virtual std::string name() const = 0;
|
||||
virtual bool install(const std::string& target_disk,
|
||||
const std::string& mount_dir,
|
||||
const std::string& efi_mount_dir,
|
||||
BootMode mode,
|
||||
bool dry_run = false) = 0;
|
||||
|
||||
virtual bool configure(const std::string& mount_dir,
|
||||
const std::string& root_param,
|
||||
BootMode mode,
|
||||
bool dry_run = false) = 0;
|
||||
};
|
||||
|
||||
class GrubBootloader : public IBootloader {
|
||||
public:
|
||||
std::string name() const override { return "GRUB 2 (UEFI / BIOS)"; }
|
||||
|
||||
bool install(const std::string& target_disk,
|
||||
const std::string& mount_dir,
|
||||
const std::string& efi_mount_dir,
|
||||
BootMode mode,
|
||||
bool dry_run = false) override;
|
||||
|
||||
bool configure(const std::string& mount_dir,
|
||||
const std::string& root_param,
|
||||
BootMode mode,
|
||||
bool dry_run = false) override;
|
||||
|
||||
static std::string generate_grub_cfg(const std::string& root_param);
|
||||
|
||||
private:
|
||||
bool install_uefi(const std::string& mount_dir,
|
||||
const std::string& efi_mount_dir,
|
||||
bool dry_run);
|
||||
|
||||
bool install_bios(const std::string& target_disk,
|
||||
const std::string& mount_dir,
|
||||
bool dry_run);
|
||||
};
|
||||
|
||||
class SyslinuxBootloader : public IBootloader {
|
||||
public:
|
||||
std::string name() const override { return "Syslinux / EXTLINUX (BIOS Fallback)"; }
|
||||
|
||||
bool install(const std::string& target_disk,
|
||||
const std::string& mount_dir,
|
||||
const std::string& efi_mount_dir,
|
||||
BootMode mode,
|
||||
bool dry_run = false) override;
|
||||
|
||||
bool configure(const std::string& mount_dir,
|
||||
const std::string& root_param,
|
||||
BootMode mode,
|
||||
bool dry_run = false) override;
|
||||
|
||||
static std::string generate_extlinux_conf(const std::string& root_param);
|
||||
};
|
||||
|
||||
class BootloaderManager {
|
||||
public:
|
||||
BootloaderManager();
|
||||
|
||||
bool setup_bootloader(const std::string& target_disk,
|
||||
const std::string& mount_dir,
|
||||
const std::string& efi_mount_dir,
|
||||
const std::string& root_param,
|
||||
BootMode mode,
|
||||
bool dry_run = false);
|
||||
|
||||
private:
|
||||
std::unique_ptr<IBootloader> grub_;
|
||||
std::unique_ptr<IBootloader> syslinux_;
|
||||
};
|
||||
|
||||
} // namespace khos
|
||||
@@ -0,0 +1,92 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <optional>
|
||||
#include <cstdint>
|
||||
|
||||
namespace khos {
|
||||
|
||||
enum class BootMode {
|
||||
BIOS,
|
||||
UEFI,
|
||||
Auto
|
||||
};
|
||||
|
||||
enum class PartitionTableType {
|
||||
MBR,
|
||||
GPT,
|
||||
Unknown
|
||||
};
|
||||
|
||||
enum class FileSystemType {
|
||||
Ext4,
|
||||
Ext2,
|
||||
Fat32,
|
||||
Swap,
|
||||
Unknown
|
||||
};
|
||||
|
||||
struct PartitionInfo {
|
||||
std::string device; // np. /dev/sda1 lub /dev/nvme0n1p1
|
||||
int number = 0;
|
||||
std::uint64_t size_bytes = 0;
|
||||
std::string fstype;
|
||||
std::string uuid;
|
||||
std::string label;
|
||||
bool is_bootable = false;
|
||||
bool is_efi = false;
|
||||
|
||||
std::string to_json() const;
|
||||
};
|
||||
|
||||
struct DiskInfo {
|
||||
std::string device; // np. /dev/sda lub /dev/nvme0n1
|
||||
std::string name; // np. sda
|
||||
std::string model; // np. QEMU HARDDISK, WDC WD10EZEX
|
||||
std::uint64_t size_bytes = 0;
|
||||
std::uint64_t size_sectors = 0;
|
||||
bool is_rotational = false; // true dla HDD, false dla SSD/NVMe
|
||||
bool is_removable = false;
|
||||
std::vector<PartitionInfo> partitions;
|
||||
|
||||
std::string size_human() const;
|
||||
std::string to_json() const;
|
||||
};
|
||||
|
||||
class DiskManager {
|
||||
public:
|
||||
// Skanowanie i detekcja urzadzen blokowych z /sys/block
|
||||
static std::vector<DiskInfo> scan_disks();
|
||||
static std::optional<DiskInfo> get_disk(const std::string& device_node);
|
||||
static std::string make_partition_name(const std::string& disk_device, int part_number);
|
||||
|
||||
// Operacje przygotowania i modyfikacji dysku
|
||||
static bool unmount_partitions(const std::string& disk_device, bool dry_run = false);
|
||||
static bool wipe_disk_signatures(const std::string& disk_device, bool dry_run = false);
|
||||
static bool partition_disk(const std::string& disk_device,
|
||||
BootMode mode,
|
||||
std::string& out_root_part,
|
||||
std::string& out_efi_part,
|
||||
bool dry_run = false);
|
||||
static bool format_partition(const std::string& part_device,
|
||||
FileSystemType fs,
|
||||
const std::string& label = "",
|
||||
bool dry_run = false);
|
||||
|
||||
// Odczyt UUID partycji
|
||||
static std::string get_uuid(const std::string& part_device);
|
||||
|
||||
// Detekcja i konwersja trybu bootowania
|
||||
static BootMode detect_system_boot_mode();
|
||||
static std::string boot_mode_to_string(BootMode mode);
|
||||
static BootMode string_to_boot_mode(const std::string& str);
|
||||
static std::string fstype_to_string(FileSystemType fs);
|
||||
static FileSystemType string_to_fstype(const std::string& str);
|
||||
|
||||
// Odswiezenie tablicy partycji w jadrze
|
||||
static bool reread_partition_table(const std::string& disk_device);
|
||||
static bool wait_for_device_node(const std::string& part_device, int timeout_seconds = 5);
|
||||
};
|
||||
|
||||
} // namespace khos
|
||||
@@ -0,0 +1,132 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <functional>
|
||||
#include <cstdint>
|
||||
#include "disk.hpp"
|
||||
#include "bootloader.hpp"
|
||||
|
||||
namespace khos {
|
||||
|
||||
// RAII Mount Point Manager
|
||||
class ScopedMount {
|
||||
public:
|
||||
ScopedMount(std::string source,
|
||||
std::string target,
|
||||
std::string fstype = "",
|
||||
unsigned long flags = 0,
|
||||
std::string data = "") noexcept;
|
||||
|
||||
~ScopedMount();
|
||||
|
||||
ScopedMount(const ScopedMount&) = delete;
|
||||
ScopedMount& operator=(const ScopedMount&) = delete;
|
||||
|
||||
ScopedMount(ScopedMount&& other) noexcept;
|
||||
ScopedMount& operator=(ScopedMount&& other) noexcept;
|
||||
|
||||
bool mount(bool dry_run = false);
|
||||
bool unmount(bool force = false, bool dry_run = false);
|
||||
bool is_mounted() const noexcept { return is_mounted_; }
|
||||
|
||||
const std::string& source() const noexcept { return source_; }
|
||||
const std::string& target() const noexcept { return target_; }
|
||||
const std::string& fstype() const noexcept { return fstype_; }
|
||||
|
||||
private:
|
||||
std::string source_;
|
||||
std::string target_;
|
||||
std::string fstype_;
|
||||
unsigned long flags_ = 0;
|
||||
std::string data_;
|
||||
bool is_mounted_ = false;
|
||||
};
|
||||
|
||||
// RAII Mount Stack (LIFO unmount order)
|
||||
class MountStack {
|
||||
public:
|
||||
MountStack() = default;
|
||||
~MountStack();
|
||||
|
||||
MountStack(const MountStack&) = delete;
|
||||
MountStack& operator=(const MountStack&) = delete;
|
||||
|
||||
MountStack(MountStack&&) noexcept = default;
|
||||
MountStack& operator=(MountStack&&) noexcept = default;
|
||||
|
||||
bool push_and_mount(std::string source,
|
||||
std::string target,
|
||||
std::string fstype = "",
|
||||
unsigned long flags = 0,
|
||||
std::string data = "",
|
||||
bool dry_run = false);
|
||||
|
||||
void unmount_all(bool dry_run = false);
|
||||
size_t size() const noexcept { return mounts_.size(); }
|
||||
bool empty() const noexcept { return mounts_.empty(); }
|
||||
|
||||
private:
|
||||
std::vector<std::unique_ptr<ScopedMount>> mounts_;
|
||||
};
|
||||
|
||||
struct InstallerConfig {
|
||||
std::string target_disk;
|
||||
BootMode boot_mode = BootMode::Auto;
|
||||
std::string hostname = "khos";
|
||||
std::string root_password = "khos";
|
||||
std::string source_dir;
|
||||
std::string mount_dir = "/mnt/install_target";
|
||||
bool auto_mode = false;
|
||||
bool dry_run = false;
|
||||
bool json_output = false;
|
||||
};
|
||||
|
||||
struct InstallResult {
|
||||
bool success = false;
|
||||
std::string message;
|
||||
std::string target_disk;
|
||||
std::string root_partition;
|
||||
std::string efi_partition;
|
||||
BootMode boot_mode = BootMode::BIOS;
|
||||
std::string hostname;
|
||||
std::string duration_str;
|
||||
|
||||
std::string to_json() const;
|
||||
};
|
||||
|
||||
class Installer {
|
||||
public:
|
||||
explicit Installer(InstallerConfig config);
|
||||
~Installer();
|
||||
|
||||
InstallResult run();
|
||||
|
||||
const InstallerConfig& config() const noexcept { return config_; }
|
||||
const InstallResult& result() const noexcept { return result_; }
|
||||
|
||||
private:
|
||||
bool validate_environment();
|
||||
bool prepare_disk();
|
||||
bool partition_and_format();
|
||||
bool mount_target_partitions(MountStack& mounts);
|
||||
bool copy_system_payload();
|
||||
bool copy_kernel_and_initramfs();
|
||||
bool generate_system_configs();
|
||||
bool install_bootloader();
|
||||
bool apply_file_permissions();
|
||||
bool finalize_installation(MountStack& mounts);
|
||||
|
||||
std::string locate_source_payload();
|
||||
std::string get_root_kernel_param();
|
||||
|
||||
InstallerConfig config_;
|
||||
InstallResult result_;
|
||||
std::string resolved_root_part_;
|
||||
std::string resolved_efi_part_;
|
||||
std::string root_uuid_;
|
||||
std::unique_ptr<BootloaderManager> boot_mgr_;
|
||||
};
|
||||
|
||||
} // namespace khos
|
||||
@@ -0,0 +1,127 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <string_view>
|
||||
#include <optional>
|
||||
#include <cstdint>
|
||||
#include <sys/types.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
namespace khos {
|
||||
namespace utils {
|
||||
|
||||
// ANSI Terminal Colors
|
||||
namespace colors {
|
||||
inline constexpr std::string_view RESET = "\033[0m";
|
||||
inline constexpr std::string_view BOLD = "\033[1m";
|
||||
inline constexpr std::string_view RED = "\033[1;31m";
|
||||
inline constexpr std::string_view GREEN = "\033[1;32m";
|
||||
inline constexpr std::string_view YELLOW = "\033[1;33m";
|
||||
inline constexpr std::string_view BLUE = "\033[1;34m";
|
||||
inline constexpr std::string_view MAGENTA = "\033[1;35m";
|
||||
inline constexpr std::string_view CYAN = "\033[1;36m";
|
||||
inline constexpr std::string_view WHITE = "\033[1;37m";
|
||||
}
|
||||
|
||||
void set_colors_enabled(bool enabled);
|
||||
bool are_colors_enabled();
|
||||
|
||||
// Message formatting
|
||||
void msg(std::string_view text);
|
||||
void info(std::string_view text);
|
||||
void ok(std::string_view text);
|
||||
void warn(std::string_view text);
|
||||
void err(std::string_view text);
|
||||
[[noreturn]] void die(std::string_view text, int exit_code = 1);
|
||||
|
||||
// RAII File Descriptor Holder
|
||||
class ScopedFd {
|
||||
public:
|
||||
explicit ScopedFd(int fd = -1) noexcept : fd_(fd) {}
|
||||
~ScopedFd();
|
||||
|
||||
ScopedFd(const ScopedFd&) = delete;
|
||||
ScopedFd& operator=(const ScopedFd&) = delete;
|
||||
|
||||
ScopedFd(ScopedFd&& other) noexcept : fd_(other.fd_) {
|
||||
other.fd_ = -1;
|
||||
}
|
||||
|
||||
ScopedFd& operator=(ScopedFd&& other) noexcept {
|
||||
if (this != &other) {
|
||||
reset(other.fd_);
|
||||
other.fd_ = -1;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
int get() const noexcept { return fd_; }
|
||||
bool valid() const noexcept { return fd_ >= 0; }
|
||||
void reset(int new_fd = -1) noexcept;
|
||||
int release() noexcept {
|
||||
int temp = fd_;
|
||||
fd_ = -1;
|
||||
return temp;
|
||||
}
|
||||
|
||||
private:
|
||||
int fd_;
|
||||
};
|
||||
|
||||
// Process execution result
|
||||
struct CommandResult {
|
||||
int exit_code = -1;
|
||||
std::string stdout_output;
|
||||
std::string stderr_output;
|
||||
|
||||
bool success() const noexcept { return exit_code == 0; }
|
||||
};
|
||||
|
||||
// Command execution functions
|
||||
CommandResult run_command(const std::string& cmd, bool log = true, bool dry_run = false);
|
||||
CommandResult run_command_with_stdin(const std::string& cmd, const std::string& input, bool log = true, bool dry_run = false);
|
||||
CommandResult run_args(const std::vector<std::string>& args, const std::string& input = "", bool log = true, bool dry_run = false);
|
||||
bool command_exists(const std::string& cmd);
|
||||
|
||||
// File and directory utilities
|
||||
bool file_exists(const std::string& path);
|
||||
bool directory_exists(const std::string& path);
|
||||
std::string read_file_string(const std::string& path);
|
||||
bool write_file_string(const std::string& path, const std::string& content);
|
||||
bool append_file_string(const std::string& path, const std::string& content);
|
||||
bool copy_file_safe(const std::string& src, const std::string& dst, bool dry_run = false);
|
||||
bool make_directories(const std::string& path);
|
||||
bool set_permissions(const std::string& path, mode_t mode, bool dry_run = false);
|
||||
std::uintmax_t copy_recursive_tar(const std::string& src_dir, const std::string& dst_dir, bool dry_run = false);
|
||||
|
||||
// String helpers
|
||||
std::string trim(const std::string& str);
|
||||
bool starts_with(const std::string& str, const std::string& prefix);
|
||||
bool ends_with(const std::string& str, const std::string& suffix);
|
||||
std::vector<std::string> split(const std::string& str, char delimiter);
|
||||
std::string join(const std::vector<std::string>& elements, const std::string& delimiter);
|
||||
std::string escape_json(const std::string& s);
|
||||
std::string format_size(std::uint64_t bytes);
|
||||
|
||||
// CLI Options Structure
|
||||
struct CliOptions {
|
||||
bool auto_mode = false;
|
||||
std::string disk;
|
||||
std::string hostname = "khos";
|
||||
std::string password = "khos";
|
||||
std::string mode_str = "auto"; // "uefi", "bios", "auto"
|
||||
bool dry_run = false;
|
||||
bool json_output = false;
|
||||
std::string source_dir;
|
||||
bool list_disks = false;
|
||||
bool help = false;
|
||||
bool version = false;
|
||||
};
|
||||
|
||||
CliOptions parse_cli_args(int argc, char* argv[]);
|
||||
void print_banner();
|
||||
void print_help(const char* prog_name);
|
||||
|
||||
} // namespace utils
|
||||
} // namespace khos
|
||||
@@ -0,0 +1,335 @@
|
||||
#include "bootloader.hpp"
|
||||
#include "utils.hpp"
|
||||
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <filesystem>
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
namespace khos {
|
||||
|
||||
// =========================================================================
|
||||
// GRUB Bootloader Implementation
|
||||
// =========================================================================
|
||||
|
||||
std::string GrubBootloader::generate_grub_cfg(const std::string& root_param) {
|
||||
std::ostringstream ss;
|
||||
ss << "set timeout=5\n"
|
||||
<< "set default=0\n\n"
|
||||
<< "terminal_input console\n"
|
||||
<< "terminal_output console\n\n"
|
||||
<< "menuentry \"KhOS 1.1 (Pulpit XFCE 4 - domyslny)\" {\n"
|
||||
<< " linux /boot/vmlinuz " << root_param << " rw quiet\n"
|
||||
<< " initrd /boot/initramfs.img\n"
|
||||
<< "}\n\n"
|
||||
<< "menuentry \"KhOS 1.1 (Pulpit KDE Plasma)\" {\n"
|
||||
<< " linux /boot/vmlinuz " << root_param << " desktop=plasma rw quiet\n"
|
||||
<< " initrd /boot/initramfs.img\n"
|
||||
<< "}\n\n"
|
||||
<< "menuentry \"KhOS 1.1 (Tryb awaryjny - verbose)\" {\n"
|
||||
<< " linux /boot/vmlinuz " << root_param << " rw textmode debug loglevel=7\n"
|
||||
<< " initrd /boot/initramfs.img\n"
|
||||
<< "}\n\n"
|
||||
<< "menuentry \"Uruchom ponownie\" {\n"
|
||||
<< " reboot\n"
|
||||
<< "}\n\n"
|
||||
<< "menuentry \"Wylacz komputer\" {\n"
|
||||
<< " halt\n"
|
||||
<< "}\n";
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
bool GrubBootloader::configure(const std::string& mount_dir,
|
||||
const std::string& root_param,
|
||||
BootMode mode,
|
||||
bool dry_run) {
|
||||
utils::info("Generowanie konfiguracji bootloadera GRUB (grub.cfg)...");
|
||||
std::string cfg_content = generate_grub_cfg(root_param);
|
||||
|
||||
std::string grub_dir = mount_dir + "/boot/grub";
|
||||
std::string grub_cfg = grub_dir + "/grub.cfg";
|
||||
|
||||
if (dry_run) {
|
||||
utils::info("[DRY-RUN] Zapis konfiguracji do " + grub_cfg);
|
||||
return true;
|
||||
}
|
||||
|
||||
utils::make_directories(grub_dir);
|
||||
if (!utils::write_file_string(grub_cfg, cfg_content)) {
|
||||
utils::err("Nie udalo sie zapisac pliku " + grub_cfg);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Dodatkowa kopia dla rozruchu UEFI
|
||||
if (mode == BootMode::UEFI) {
|
||||
std::string efi_grub_dir = mount_dir + "/boot/efi/boot/grub";
|
||||
utils::make_directories(efi_grub_dir);
|
||||
utils::write_file_string(efi_grub_dir + "/grub.cfg", cfg_content);
|
||||
|
||||
std::string khos_grub_dir = mount_dir + "/boot/efi/EFI/khos";
|
||||
utils::make_directories(khos_grub_dir);
|
||||
utils::write_file_string(khos_grub_dir + "/grub.cfg", cfg_content);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool GrubBootloader::install(const std::string& target_disk,
|
||||
const std::string& mount_dir,
|
||||
const std::string& efi_mount_dir,
|
||||
BootMode mode,
|
||||
bool dry_run) {
|
||||
if (mode == BootMode::UEFI) {
|
||||
return install_uefi(mount_dir, efi_mount_dir, dry_run);
|
||||
} else {
|
||||
return install_bios(target_disk, mount_dir, dry_run);
|
||||
}
|
||||
}
|
||||
|
||||
bool GrubBootloader::install_uefi(const std::string& mount_dir,
|
||||
const std::string& efi_mount_dir,
|
||||
bool dry_run) {
|
||||
utils::info("Instalacja GRUB (UEFI x86_64) na partycji EFI (" + efi_mount_dir + ")...");
|
||||
if (dry_run) {
|
||||
utils::info("[DRY-RUN] grub-install --target=x86_64-efi --boot-directory=" + mount_dir + "/boot --efi-directory=" + efi_mount_dir);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool success = false;
|
||||
if (utils::command_exists("grub-install")) {
|
||||
std::string cmd = "grub-install --target=x86_64-efi "
|
||||
"--boot-directory=\"" + mount_dir + "/boot\" "
|
||||
"--efi-directory=\"" + efi_mount_dir + "\" "
|
||||
"--removable --recheck 2>/dev/null";
|
||||
auto res = utils::run_command(cmd, true, false);
|
||||
if (res.success()) {
|
||||
success = true;
|
||||
utils::ok("GRUB (UEFI) zainstalowany pomyslnie przez grub-install.");
|
||||
}
|
||||
}
|
||||
|
||||
// Rezerwowe wdrozenie prekompilowanego pliku BOOTX64.EFI z nosnika Live/CDROM
|
||||
std::string boot_dir = efi_mount_dir + "/EFI/BOOT";
|
||||
std::string khos_dir = efi_mount_dir + "/EFI/khos";
|
||||
utils::make_directories(boot_dir);
|
||||
utils::make_directories(khos_dir);
|
||||
|
||||
std::vector<std::string> efi_sources = {
|
||||
"/mnt/cdrom/EFI/BOOT/BOOTX64.EFI",
|
||||
"/EFI/BOOT/BOOTX64.EFI",
|
||||
"/boot/efi/EFI/BOOT/BOOTX64.EFI",
|
||||
"/usr/lib/grub/x86_64-efi/monolithic/grubx64.efi",
|
||||
"/usr/share/syslinux/efi64/syslinux.efi"
|
||||
};
|
||||
|
||||
for (const auto& src : efi_sources) {
|
||||
if (utils::file_exists(src)) {
|
||||
utils::info("Kopiowanie zapasowego pliku binarnego UEFI z: " + src);
|
||||
utils::copy_file_safe(src, boot_dir + "/BOOTX64.EFI", false);
|
||||
utils::copy_file_safe(src, khos_dir + "/grubx64.efi", false);
|
||||
success = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
bool GrubBootloader::install_bios(const std::string& target_disk,
|
||||
const std::string& mount_dir,
|
||||
bool dry_run) {
|
||||
utils::info("Instalacja GRUB (BIOS i386-pc) na dysku " + target_disk + "...");
|
||||
if (dry_run) {
|
||||
utils::info("[DRY-RUN] grub-install --target=i386-pc --boot-directory=" + mount_dir + "/boot " + target_disk);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!utils::command_exists("grub-install")) {
|
||||
utils::warn("Polecenie grub-install nie jest zainstalowane w biezacym systemie.");
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string cmd = "grub-install --target=i386-pc "
|
||||
"--boot-directory=\"" + mount_dir + "/boot\" "
|
||||
"--modules=\"part_msdos ext2 biosdisk\" "
|
||||
"--recheck \"" + target_disk + "\" 2>/dev/null";
|
||||
|
||||
auto res = utils::run_command(cmd, true, false);
|
||||
if (res.success()) {
|
||||
utils::ok("GRUB (BIOS) zainstalowany pomyslnie na " + target_disk);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Proba z flaga --force
|
||||
utils::info("Ponowna proba instalacji GRUB z flaga --force...");
|
||||
std::string cmd_force = "grub-install --target=i386-pc "
|
||||
"--boot-directory=\"" + mount_dir + "/boot\" "
|
||||
"--modules=\"part_msdos ext2 biosdisk\" "
|
||||
"--force --recheck \"" + target_disk + "\" 2>/dev/null";
|
||||
auto res_force = utils::run_command(cmd_force, true, false);
|
||||
if (res_force.success()) {
|
||||
utils::ok("GRUB (BIOS) zainstalowany z wymuszeniem (--force) na " + target_disk);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Syslinux / EXTLINUX Bootloader Implementation
|
||||
// =========================================================================
|
||||
|
||||
std::string SyslinuxBootloader::generate_extlinux_conf(const std::string& root_param) {
|
||||
std::ostringstream ss;
|
||||
ss << "DEFAULT xfce\n"
|
||||
<< "PROMPT 1\n"
|
||||
<< "TIMEOUT 50\n\n"
|
||||
<< "LABEL xfce\n"
|
||||
<< " MENU LABEL KhOS 1.1 (XFCE 4 - domyslny)\n"
|
||||
<< " LINUX /boot/vmlinuz\n"
|
||||
<< " INITRD /boot/initramfs.img\n"
|
||||
<< " APPEND " << root_param << " rw quiet\n\n"
|
||||
<< "LABEL plasma\n"
|
||||
<< " MENU LABEL KhOS 1.1 (KDE Plasma)\n"
|
||||
<< " LINUX /boot/vmlinuz\n"
|
||||
<< " INITRD /boot/initramfs.img\n"
|
||||
<< " APPEND " << root_param << " desktop=plasma rw quiet\n\n"
|
||||
<< "LABEL textmode\n"
|
||||
<< " MENU LABEL KhOS 1.1 (Tryb tekstowy)\n"
|
||||
<< " LINUX /boot/vmlinuz\n"
|
||||
<< " INITRD /boot/initramfs.img\n"
|
||||
<< " APPEND " << root_param << " rw textmode\n";
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
bool SyslinuxBootloader::configure(const std::string& mount_dir,
|
||||
const std::string& root_param,
|
||||
BootMode /*mode*/,
|
||||
bool dry_run) {
|
||||
utils::info("Generowanie konfiguracji awaryjnego bootloadera EXTLINUX (extlinux.conf)...");
|
||||
std::string extlinux_dir = mount_dir + "/boot/extlinux";
|
||||
std::string cfg_path = extlinux_dir + "/extlinux.conf";
|
||||
std::string cfg_content = generate_extlinux_conf(root_param);
|
||||
|
||||
if (dry_run) {
|
||||
utils::info("[DRY-RUN] Zapis konfiguracji do " + cfg_path);
|
||||
return true;
|
||||
}
|
||||
|
||||
utils::make_directories(extlinux_dir);
|
||||
return utils::write_file_string(cfg_path, cfg_content);
|
||||
}
|
||||
|
||||
bool SyslinuxBootloader::install(const std::string& target_disk,
|
||||
const std::string& mount_dir,
|
||||
const std::string& /*efi_mount_dir*/,
|
||||
BootMode /*mode*/,
|
||||
bool dry_run) {
|
||||
utils::info("Instalacja zapasowego programu rozruchowego Syslinux / EXTLINUX na " + target_disk + "...");
|
||||
if (dry_run) {
|
||||
utils::info("[DRY-RUN] Zapis MBR oraz extlinux -i " + mount_dir + "/boot/extlinux");
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string extlinux_dir = mount_dir + "/boot/extlinux";
|
||||
utils::make_directories(extlinux_dir);
|
||||
|
||||
// 1. Zapis kodu MBR (440 bajtow) do sektora rozruchowego dysku
|
||||
std::vector<std::string> mbr_candidates = {
|
||||
"/usr/share/syslinux/mbr.bin",
|
||||
"/usr/lib/syslinux/mbr.bin",
|
||||
"/usr/lib/syslinux/bios/mbr.bin",
|
||||
"/usr/share/syslinux/bios/mbr.bin"
|
||||
};
|
||||
|
||||
std::string found_mbr;
|
||||
for (const auto& cand : mbr_candidates) {
|
||||
if (utils::file_exists(cand)) {
|
||||
found_mbr = cand;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!found_mbr.empty()) {
|
||||
utils::info("Zapis sektora MBR z pliku " + found_mbr + " na dysk " + target_disk + "...");
|
||||
std::string dd_cmd = "dd bs=440 count=1 conv=notrunc if=\"" + found_mbr + "\" of=\"" + target_disk + "\" 2>/dev/null";
|
||||
utils::run_command(dd_cmd, false, false);
|
||||
} else {
|
||||
utils::warn("Nie znaleziono pliku mbr.bin dla Syslinux.");
|
||||
}
|
||||
|
||||
// 2. Kopiowanie modulow COM32 (*.c32)
|
||||
std::vector<std::string> c32_dirs = {
|
||||
"/usr/share/syslinux",
|
||||
"/usr/lib/syslinux/modules/bios",
|
||||
"/usr/lib/syslinux"
|
||||
};
|
||||
for (const auto& dir : c32_dirs) {
|
||||
if (utils::directory_exists(dir)) {
|
||||
std::string cp_cmd = "cp -f \"" + dir + "\"/*.c32 \"" + extlinux_dir + "/\" 2>/dev/null";
|
||||
utils::run_command(cp_cmd, false, false);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Uruchomienie extlinux -i na partycji
|
||||
bool extlinux_ok = false;
|
||||
std::vector<std::string> extlinux_binaries = {"extlinux", "/sbin/extlinux", "/usr/bin/extlinux"};
|
||||
for (const auto& bin : extlinux_binaries) {
|
||||
if (utils::command_exists(bin)) {
|
||||
std::string run_cmd = bin + " -i \"" + extlinux_dir + "\" 2>/dev/null";
|
||||
auto res = utils::run_command(run_cmd, false, false);
|
||||
if (res.success()) {
|
||||
extlinux_ok = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return extlinux_ok;
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// BootloaderManager Implementation
|
||||
// =========================================================================
|
||||
|
||||
BootloaderManager::BootloaderManager()
|
||||
: grub_(std::make_unique<GrubBootloader>()),
|
||||
syslinux_(std::make_unique<SyslinuxBootloader>()) {}
|
||||
|
||||
bool BootloaderManager::setup_bootloader(const std::string& target_disk,
|
||||
const std::string& mount_dir,
|
||||
const std::string& efi_mount_dir,
|
||||
const std::string& root_param,
|
||||
BootMode mode,
|
||||
bool dry_run) {
|
||||
utils::msg("Instalacja i konfiguracja programu rozruchowego...");
|
||||
|
||||
// Najpierw konfiguracja GRUB (grub.cfg)
|
||||
bool grub_cfg_ok = grub_->configure(mount_dir, root_param, mode, dry_run);
|
||||
|
||||
// Proba instalacji GRUB
|
||||
bool grub_installed = grub_->install(target_disk, mount_dir, efi_mount_dir, mode, dry_run);
|
||||
|
||||
if (grub_installed && grub_cfg_ok) {
|
||||
utils::ok("Program rozruchowy GRUB zainstalowany i skonfigurowany pomyslnie.");
|
||||
return true;
|
||||
}
|
||||
|
||||
// Jesli GRUB zawiodl, a system jest w trybie BIOS: sprobuj zapasowego Syslinux/EXTLINUX
|
||||
if (mode == BootMode::BIOS) {
|
||||
utils::warn("Instalacja GRUB nie powiodla sie, aktywacja rezerwowego programu rozruchowego Syslinux/EXTLINUX...");
|
||||
syslinux_->configure(mount_dir, root_param, mode, dry_run);
|
||||
bool syslinux_installed = syslinux_->install(target_disk, mount_dir, efi_mount_dir, mode, dry_run);
|
||||
if (syslinux_installed) {
|
||||
utils::ok("Zapasowy program rozruchowy EXTLINUX zainstalowany pomyslnie.");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
utils::warn("Uwaga: instalator nie mogl w pelni zweryfikowac bootloadera. Sprawdz konfiguracje recznie przed restartem.");
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace khos
|
||||
@@ -0,0 +1,566 @@
|
||||
#include "disk.hpp"
|
||||
#include "utils.hpp"
|
||||
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <filesystem>
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <cctype>
|
||||
|
||||
#if defined(__unix__) || defined(__linux__) || defined(__APPLE__)
|
||||
#include <unistd.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <fcntl.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/types.h>
|
||||
#if defined(__linux__)
|
||||
#include <linux/fs.h>
|
||||
#endif
|
||||
#endif
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
namespace khos {
|
||||
|
||||
std::string PartitionInfo::to_json() const {
|
||||
std::ostringstream ss;
|
||||
ss << "{"
|
||||
<< "\"device\":\"" << utils::escape_json(device) << "\","
|
||||
<< "\"number\":" << number << ","
|
||||
<< "\"size_bytes\":" << size_bytes << ","
|
||||
<< "\"fstype\":\"" << utils::escape_json(fstype) << "\","
|
||||
<< "\"uuid\":\"" << utils::escape_json(uuid) << "\","
|
||||
<< "\"label\":\"" << utils::escape_json(label) << "\","
|
||||
<< "\"is_bootable\":" << (is_bootable ? "true" : "false") << ","
|
||||
<< "\"is_efi\":" << (is_efi ? "true" : "false")
|
||||
<< "}";
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
std::string DiskInfo::size_human() const {
|
||||
return utils::format_size(size_bytes);
|
||||
}
|
||||
|
||||
std::string DiskInfo::to_json() const {
|
||||
std::ostringstream ss;
|
||||
ss << "{"
|
||||
<< "\"device\":\"" << utils::escape_json(device) << "\","
|
||||
<< "\"name\":\"" << utils::escape_json(name) << "\","
|
||||
<< "\"model\":\"" << utils::escape_json(model) << "\","
|
||||
<< "\"size_bytes\":" << size_bytes << ","
|
||||
<< "\"size_sectors\":" << size_sectors << ","
|
||||
<< "\"size_human\":\"" << utils::escape_json(size_human()) << "\","
|
||||
<< "\"is_rotational\":" << (is_rotational ? "true" : "false") << ","
|
||||
<< "\"is_removable\":" << (is_removable ? "true" : "false") << ","
|
||||
<< "\"partitions\":[";
|
||||
|
||||
for (size_t i = 0; i < partitions.size(); ++i) {
|
||||
if (i > 0) ss << ",";
|
||||
ss << partitions[i].to_json();
|
||||
}
|
||||
ss << "]}";
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
std::vector<DiskInfo> DiskManager::scan_disks() {
|
||||
std::vector<DiskInfo> disks;
|
||||
const std::string sys_block = "/sys/block";
|
||||
|
||||
if (!utils::directory_exists(sys_block)) {
|
||||
// Fallback for simulation / test environments without /sys/block
|
||||
return disks;
|
||||
}
|
||||
|
||||
std::error_code ec;
|
||||
for (const auto& entry : fs::directory_iterator(sys_block, ec)) {
|
||||
if (!entry.is_directory()) continue;
|
||||
|
||||
std::string bname = entry.path().filename().string();
|
||||
|
||||
// Ignoruj urzadzenia wirtualne, petlowe, optyczne i ramdiski
|
||||
if (utils::starts_with(bname, "loop") ||
|
||||
utils::starts_with(bname, "ram") ||
|
||||
utils::starts_with(bname, "sr") ||
|
||||
utils::starts_with(bname, "dm-") ||
|
||||
utils::starts_with(bname, "zram") ||
|
||||
utils::starts_with(bname, "fd")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
std::string dev_path = "/dev/" + bname;
|
||||
|
||||
DiskInfo d;
|
||||
d.device = dev_path;
|
||||
d.name = bname;
|
||||
|
||||
// Odczyt liczby sektorow (512 bajtow kazdy)
|
||||
std::string size_file = entry.path().string() + "/size";
|
||||
std::string size_str = utils::trim(utils::read_file_string(size_file));
|
||||
try {
|
||||
d.size_sectors = size_str.empty() ? 0 : std::stoull(size_str);
|
||||
} catch (...) {
|
||||
d.size_sectors = 0;
|
||||
}
|
||||
d.size_bytes = d.size_sectors * 512ULL;
|
||||
|
||||
if (d.size_bytes == 0) {
|
||||
// Puste urzadzenie lub brak nosnika
|
||||
continue;
|
||||
}
|
||||
|
||||
// Odczyt modelu dysku
|
||||
std::string model_file = entry.path().string() + "/device/model";
|
||||
d.model = utils::trim(utils::read_file_string(model_file));
|
||||
if (d.model.empty()) {
|
||||
std::string name_file = entry.path().string() + "/device/name";
|
||||
d.model = utils::trim(utils::read_file_string(name_file));
|
||||
}
|
||||
if (d.model.empty()) {
|
||||
d.model = "Dysk twardy / SSD (" + bname + ")";
|
||||
}
|
||||
|
||||
// Rotational (0 = SSD/NVMe, 1 = HDD)
|
||||
std::string rot_file = entry.path().string() + "/queue/rotational";
|
||||
std::string rot_str = utils::trim(utils::read_file_string(rot_file));
|
||||
d.is_rotational = (rot_str == "1");
|
||||
|
||||
// Removable
|
||||
std::string rem_file = entry.path().string() + "/removable";
|
||||
std::string rem_str = utils::trim(utils::read_file_string(rem_file));
|
||||
d.is_removable = (rem_str == "1");
|
||||
|
||||
// Skanowanie istniejacych partycji w /sys/block/<bname>/
|
||||
for (const auto& sub : fs::directory_iterator(entry.path(), ec)) {
|
||||
if (!sub.is_directory()) continue;
|
||||
std::string part_name = sub.path().filename().string();
|
||||
if (!utils::starts_with(part_name, bname) || part_name == bname) {
|
||||
continue;
|
||||
}
|
||||
|
||||
PartitionInfo p;
|
||||
p.device = "/dev/" + part_name;
|
||||
std::string part_size_file = sub.path().string() + "/size";
|
||||
std::string psize_str = utils::trim(utils::read_file_string(part_size_file));
|
||||
try {
|
||||
p.size_bytes = (psize_str.empty() ? 0 : std::stoull(psize_str)) * 512ULL;
|
||||
} catch (...) {
|
||||
p.size_bytes = 0;
|
||||
}
|
||||
|
||||
p.uuid = get_uuid(p.device);
|
||||
|
||||
// Odczyt typu systemu plikow przez blkid
|
||||
utils::CommandResult bres = utils::run_command("blkid -s TYPE -o value " + p.device, false, false);
|
||||
if (bres.success()) {
|
||||
p.fstype = utils::trim(bres.stdout_output);
|
||||
}
|
||||
|
||||
if (p.fstype == "vfat" || p.fstype == "fat") {
|
||||
p.is_efi = true;
|
||||
}
|
||||
|
||||
d.partitions.push_back(p);
|
||||
}
|
||||
|
||||
disks.push_back(d);
|
||||
}
|
||||
|
||||
return disks;
|
||||
}
|
||||
|
||||
std::optional<DiskInfo> DiskManager::get_disk(const std::string& device_node) {
|
||||
auto all_disks = scan_disks();
|
||||
for (const auto& d : all_disks) {
|
||||
if (d.device == device_node) {
|
||||
return d;
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
std::string DiskManager::make_partition_name(const std::string& disk_device, int part_number) {
|
||||
if (disk_device.empty()) return "";
|
||||
char last_char = disk_device.back();
|
||||
if (std::isdigit(static_cast<unsigned char>(last_char))) {
|
||||
return disk_device + "p" + std::to_string(part_number);
|
||||
}
|
||||
return disk_device + std::to_string(part_number);
|
||||
}
|
||||
|
||||
bool DiskManager::unmount_partitions(const std::string& disk_device, bool dry_run) {
|
||||
if (dry_run) {
|
||||
utils::info("[DRY-RUN] Odmontowywanie partycji na " + disk_device);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Odczyt /proc/mounts i odmontowanie wszystkich powiazanych punktow
|
||||
std::string mounts = utils::read_file_string("/proc/mounts");
|
||||
std::vector<std::string> lines = utils::split(mounts, '\n');
|
||||
|
||||
for (const auto& line : lines) {
|
||||
std::vector<std::string> fields = utils::split(line, ' ');
|
||||
if (fields.size() >= 2) {
|
||||
std::string mnt_dev = fields[0];
|
||||
std::string mnt_point = fields[1];
|
||||
if (utils::starts_with(mnt_dev, disk_device)) {
|
||||
utils::info("Odmontowywanie " + mnt_dev + " zamontowanego w " + mnt_point + "...");
|
||||
utils::run_command("umount -f \"" + mnt_point + "\" 2>/dev/null", false, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Proba wymuszenia odmontowania potencjalnych wezlow partycji
|
||||
for (int i = 1; i <= 8; ++i) {
|
||||
std::string pdev = make_partition_name(disk_device, i);
|
||||
utils::run_command("umount -f \"" + pdev + "\" 2>/dev/null", false, false);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool DiskManager::wipe_disk_signatures(const std::string& disk_device, bool dry_run) {
|
||||
utils::msg("Czyszczenie naglowkow i sygnatur tablic partycji na " + disk_device + "...");
|
||||
if (dry_run) {
|
||||
utils::info("[DRY-RUN] Wyzerowanie poczatku i konca dysku: " + disk_device);
|
||||
return true;
|
||||
}
|
||||
|
||||
// 1. Wyzerowanie poczatkowych 10 MB (MBR, glowny GPT, superbloki)
|
||||
std::string wipe_head = "dd if=/dev/zero of=\"" + disk_device + "\" bs=1M count=10 conv=notrunc 2>/dev/null";
|
||||
utils::run_command(wipe_head, false, false);
|
||||
|
||||
// 2. Wyzerowanie zapasowej tablicy GPT na koncu dysku
|
||||
std::string size_cmd = "blockdev --getsize64 \"" + disk_device + "\" 2>/dev/null";
|
||||
utils::CommandResult s_res = utils::run_command(size_cmd, false, false);
|
||||
std::uint64_t total_bytes = 0;
|
||||
try {
|
||||
total_bytes = std::stoull(utils::trim(s_res.stdout_output));
|
||||
} catch (...) {
|
||||
total_bytes = 0;
|
||||
}
|
||||
|
||||
if (total_bytes > 20971520ULL) { // wiecej niz 20 MB
|
||||
std::uint64_t total_sectors = total_bytes / 512ULL;
|
||||
std::uint64_t seek_sectors = (total_sectors > 4096) ? (total_sectors - 4096) : 0;
|
||||
std::string wipe_tail = "dd if=/dev/zero of=\"" + disk_device + "\" seek=" +
|
||||
std::to_string(seek_sectors) + " count=4096 bs=512 conv=notrunc 2>/dev/null";
|
||||
utils::run_command(wipe_tail, false, false);
|
||||
}
|
||||
|
||||
// 3. Wipefs jesli dostepne
|
||||
if (utils::command_exists("wipefs")) {
|
||||
utils::run_command("wipefs -a -f \"" + disk_device + "\" 2>/dev/null", false, false);
|
||||
}
|
||||
|
||||
utils::run_command("sync", false, false);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool DiskManager::partition_disk(const std::string& disk_device,
|
||||
BootMode mode,
|
||||
std::string& out_root_part,
|
||||
std::string& out_efi_part,
|
||||
bool dry_run) {
|
||||
if (mode == BootMode::Auto) {
|
||||
mode = detect_system_boot_mode();
|
||||
}
|
||||
|
||||
std::string mode_str = boot_mode_to_string(mode);
|
||||
utils::msg("Tworzenie tablicy partycji na " + disk_device + " (Tryb: " + mode_str + ")...");
|
||||
|
||||
if (dry_run) {
|
||||
if (mode == BootMode::UEFI) {
|
||||
out_efi_part = make_partition_name(disk_device, 1);
|
||||
out_root_part = make_partition_name(disk_device, 2);
|
||||
utils::info("[DRY-RUN] Utworzono partycje GPT: EFI=" + out_efi_part + ", ROOT=" + out_root_part);
|
||||
} else {
|
||||
out_efi_part.clear();
|
||||
out_root_part = make_partition_name(disk_device, 1);
|
||||
utils::info("[DRY-RUN] Utworzono partycje MBR: ROOT=" + out_root_part + " (bootable)");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool success = false;
|
||||
|
||||
if (mode == BootMode::UEFI) {
|
||||
out_efi_part = make_partition_name(disk_device, 1);
|
||||
out_root_part = make_partition_name(disk_device, 2);
|
||||
|
||||
// Metoda 1: sfdisk (nowoczesny i stabilny standard w Linux)
|
||||
if (utils::command_exists("sfdisk")) {
|
||||
utils::info("Partycjonowanie GPT za pomoca sfdisk...");
|
||||
std::string sfdisk_input =
|
||||
"label: gpt\n"
|
||||
",512M,U\n" // 512MB EFI System Partition (U lub C12A7328-F81F-11D2-BA4B-00A0C93EC93B)
|
||||
",,L\n"; // Cala reszta: Linux Root (L lub 0FC63DAF-8483-4772-8E79-3D69D8477DE4)
|
||||
|
||||
auto res = utils::run_command_with_stdin("sfdisk --force \"" + disk_device + "\"", sfdisk_input, true, false);
|
||||
if (res.success()) success = true;
|
||||
}
|
||||
|
||||
// Metoda 2: parted fallback
|
||||
if (!success && utils::command_exists("parted")) {
|
||||
utils::info("Fallback partycjonowania GPT za pomoca parted...");
|
||||
std::string parted_cmd = "parted -s \"" + disk_device + "\" mklabel gpt "
|
||||
"mkpart ESP fat32 1MiB 513MiB set 1 esp on "
|
||||
"mkpart primary ext4 513MiB 100%";
|
||||
auto res = utils::run_command(parted_cmd, true, false);
|
||||
if (res.success()) success = true;
|
||||
}
|
||||
|
||||
// Metoda 3: fdisk pipe fallback
|
||||
if (!success && utils::command_exists("fdisk")) {
|
||||
utils::info("Fallback partycjonowania GPT za pomoca fdisk...");
|
||||
std::string fdisk_input = "g\nn\n1\n\n+512M\nt\n1\nn\n2\n\n\nw\n";
|
||||
auto res = utils::run_command_with_stdin("fdisk \"" + disk_device + "\"", fdisk_input, true, false);
|
||||
if (res.success()) success = true;
|
||||
}
|
||||
} else {
|
||||
// BIOS (MBR / DOS)
|
||||
out_efi_part.clear();
|
||||
out_root_part = make_partition_name(disk_device, 1);
|
||||
|
||||
// Metoda 1: sfdisk
|
||||
if (utils::command_exists("sfdisk")) {
|
||||
utils::info("Partycjonowanie MBR za pomoca sfdisk...");
|
||||
std::string sfdisk_input =
|
||||
"label: dos\n"
|
||||
",,83,*\n"; // Cala przestrzen, typ 83 (Linux), flaga bootable (*)
|
||||
|
||||
auto res = utils::run_command_with_stdin("sfdisk --force \"" + disk_device + "\"", sfdisk_input, true, false);
|
||||
if (res.success()) success = true;
|
||||
}
|
||||
|
||||
// Metoda 2: parted fallback
|
||||
if (!success && utils::command_exists("parted")) {
|
||||
utils::info("Fallback partycjonowania MBR za pomoca parted...");
|
||||
std::string parted_cmd = "parted -s \"" + disk_device + "\" mklabel msdos "
|
||||
"mkpart primary ext4 1MiB 100% set 1 boot on";
|
||||
auto res = utils::run_command(parted_cmd, true, false);
|
||||
if (res.success()) success = true;
|
||||
}
|
||||
|
||||
// Metoda 3: fdisk pipe fallback (jak w oryginalnym skrypcie KhOS)
|
||||
if (!success && utils::command_exists("fdisk")) {
|
||||
utils::info("Fallback partycjonowania MBR za pomoca fdisk...");
|
||||
std::string fdisk_input = "o\nn\np\n1\n\n\na\n1\nw\n";
|
||||
auto res = utils::run_command_with_stdin("fdisk \"" + disk_device + "\"", fdisk_input, true, false);
|
||||
if (res.success()) success = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!success) {
|
||||
utils::err("Nie udalo sie wykonac partycjonowania dysku " + disk_device);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Przeladuj tablice partycji w jadrze
|
||||
reread_partition_table(disk_device);
|
||||
|
||||
// Poczekaj na wezly urzadzen w /dev
|
||||
if (!wait_for_device_node(out_root_part, 5)) {
|
||||
utils::err("Partycja glowna " + out_root_part + " nie jest dostepna w /dev!");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!out_efi_part.empty()) {
|
||||
if (!wait_for_device_node(out_efi_part, 5)) {
|
||||
utils::warn("Partycja EFI " + out_efi_part + " wymaga recznej weryfikacji!");
|
||||
}
|
||||
}
|
||||
|
||||
utils::ok("Utworzono partycje systemowa: " + out_root_part);
|
||||
if (!out_efi_part.empty()) {
|
||||
utils::ok("Utworzono partycje rozruchowa EFI: " + out_efi_part);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool DiskManager::format_partition(const std::string& part_device,
|
||||
FileSystemType fs,
|
||||
const std::string& label,
|
||||
bool dry_run) {
|
||||
std::string fs_name = fstype_to_string(fs);
|
||||
utils::info("Formatowanie partycji " + part_device + " jako " + fs_name + "...");
|
||||
|
||||
if (dry_run) {
|
||||
utils::info("[DRY-RUN] Formatowanie " + part_device + " (" + fs_name + ") z etykieta '" + label + "'");
|
||||
return true;
|
||||
}
|
||||
|
||||
utils::CommandResult res;
|
||||
|
||||
switch (fs) {
|
||||
case FileSystemType::Fat32: {
|
||||
std::string cmd = "mkfs.vfat -F32 ";
|
||||
if (!label.empty()) cmd += "-n \"" + label + "\" ";
|
||||
cmd += "\"" + part_device + "\" 2>/dev/null";
|
||||
|
||||
res = utils::run_command(cmd, false, false);
|
||||
if (!res.success()) {
|
||||
cmd = "mkfs.fat -F32 \"" + part_device + "\" 2>/dev/null";
|
||||
res = utils::run_command(cmd, false, false);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case FileSystemType::Ext4:
|
||||
case FileSystemType::Ext2: {
|
||||
std::string cmd = "mkfs.ext4 -F ";
|
||||
if (!label.empty()) cmd += "-L \"" + label + "\" ";
|
||||
cmd += "\"" + part_device + "\" 2>/dev/null";
|
||||
|
||||
res = utils::run_command(cmd, false, false);
|
||||
if (!res.success()) {
|
||||
cmd = "mke2fs -t ext4 -F ";
|
||||
if (!label.empty()) cmd += "-L \"" + label + "\" ";
|
||||
cmd += "\"" + part_device + "\" 2>/dev/null";
|
||||
res = utils::run_command(cmd, false, false);
|
||||
}
|
||||
if (!res.success()) {
|
||||
// Fallback do ext2
|
||||
utils::warn("mkfs.ext4 zawiodl, proba zapasowego formatowania jako ext2...");
|
||||
cmd = "mkfs.ext2 -F \"" + part_device + "\" 2>/dev/null";
|
||||
res = utils::run_command(cmd, false, false);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
utils::err("Nieobslugiwany typ systemu plikow do formatowania!");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!res.success()) {
|
||||
utils::err("Formatowanie partycji " + part_device + " nie powiodlo sie!");
|
||||
return false;
|
||||
}
|
||||
|
||||
utils::ok("Partycja " + part_device + " zostala pomyslnie sformatowana.");
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string DiskManager::get_uuid(const std::string& part_device) {
|
||||
if (part_device.empty()) return "";
|
||||
|
||||
// Metoda 1: blkid -s UUID -o value
|
||||
utils::CommandResult res = utils::run_command("blkid -s UUID -o value \"" + part_device + "\" 2>/dev/null", false, false);
|
||||
std::string uuid = utils::trim(res.stdout_output);
|
||||
if (!uuid.empty()) return uuid;
|
||||
|
||||
// Metoda 2: przeszukanie dowiazan /dev/disk/by-uuid
|
||||
const std::string by_uuid_dir = "/dev/disk/by-uuid";
|
||||
if (utils::directory_exists(by_uuid_dir)) {
|
||||
std::error_code ec;
|
||||
for (const auto& entry : fs::directory_iterator(by_uuid_dir, ec)) {
|
||||
if (entry.is_symlink()) {
|
||||
fs::path target = fs::canonical(entry.path(), ec);
|
||||
if (!ec && target.string() == part_device) {
|
||||
return entry.path().filename().string();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
BootMode DiskManager::detect_system_boot_mode() {
|
||||
if (utils::directory_exists("/sys/firmware/efi")) {
|
||||
return BootMode::UEFI;
|
||||
}
|
||||
return BootMode::BIOS;
|
||||
}
|
||||
|
||||
std::string DiskManager::boot_mode_to_string(BootMode mode) {
|
||||
switch (mode) {
|
||||
case BootMode::UEFI: return "UEFI";
|
||||
case BootMode::BIOS: return "BIOS";
|
||||
case BootMode::Auto: return "Auto";
|
||||
}
|
||||
return "Nieznany";
|
||||
}
|
||||
|
||||
BootMode DiskManager::string_to_boot_mode(const std::string& str) {
|
||||
std::string s = str;
|
||||
std::transform(s.begin(), s.end(), s.begin(), ::tolower);
|
||||
if (s == "uefi") return BootMode::UEFI;
|
||||
if (s == "bios" || s == "mbr") return BootMode::BIOS;
|
||||
return BootMode::Auto;
|
||||
}
|
||||
|
||||
std::string DiskManager::fstype_to_string(FileSystemType fs) {
|
||||
switch (fs) {
|
||||
case FileSystemType::Ext4: return "ext4";
|
||||
case FileSystemType::Ext2: return "ext2";
|
||||
case FileSystemType::Fat32: return "vfat";
|
||||
case FileSystemType::Swap: return "swap";
|
||||
case FileSystemType::Unknown: return "unknown";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
FileSystemType DiskManager::string_to_fstype(const std::string& str) {
|
||||
std::string s = str;
|
||||
std::transform(s.begin(), s.end(), s.begin(), ::tolower);
|
||||
if (s == "ext4") return FileSystemType::Ext4;
|
||||
if (s == "ext2") return FileSystemType::Ext2;
|
||||
if (s == "vfat" || s == "fat32" || s == "fat") return FileSystemType::Fat32;
|
||||
if (s == "swap") return FileSystemType::Swap;
|
||||
return FileSystemType::Unknown;
|
||||
}
|
||||
|
||||
bool DiskManager::reread_partition_table(const std::string& disk_device) {
|
||||
utils::run_command("sync", false, false);
|
||||
|
||||
#if defined(__linux__) && defined(BLKRRPART)
|
||||
int fd = open(disk_device.c_str(), O_RDONLY);
|
||||
if (fd >= 0) {
|
||||
ioctl(fd, BLKRRPART, 0);
|
||||
close(fd);
|
||||
}
|
||||
#endif
|
||||
|
||||
utils::run_command("blockdev --rereadpt \"" + disk_device + "\" 2>/dev/null", false, false);
|
||||
utils::run_command("partprobe \"" + disk_device + "\" 2>/dev/null", false, false);
|
||||
utils::run_command("mdev -s 2>/dev/null", false, false);
|
||||
utils::run_command("udevadm settle 2>/dev/null", false, false);
|
||||
|
||||
std::this_thread::sleep_for(std::chrono::seconds(2));
|
||||
return true;
|
||||
}
|
||||
|
||||
bool DiskManager::wait_for_device_node(const std::string& part_device, int timeout_seconds) {
|
||||
for (int i = 0; i < timeout_seconds * 2; ++i) {
|
||||
if (utils::file_exists(part_device)) {
|
||||
return true;
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
||||
}
|
||||
|
||||
// Jesli wezel nie powstal, sprobuj mknod w oparciu o /proc/partitions
|
||||
std::string bname = fs::path(part_device).filename().string();
|
||||
std::string partitions_file = utils::read_file_string("/proc/partitions");
|
||||
std::vector<std::string> lines = utils::split(partitions_file, '\n');
|
||||
|
||||
for (const auto& line : lines) {
|
||||
std::vector<std::string> parts = utils::split(line, ' ');
|
||||
if (parts.size() >= 4 && parts[3] == bname) {
|
||||
std::string major = parts[0];
|
||||
std::string minor = parts[1];
|
||||
utils::info("Tworzenie wezla blokowego mknod " + part_device + " b " + major + " " + minor);
|
||||
utils::run_command("mknod \"" + part_device + "\" b " + major + " " + minor + " 2>/dev/null", false, false);
|
||||
return utils::file_exists(part_device);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace khos
|
||||
@@ -0,0 +1,723 @@
|
||||
#include "installer.hpp"
|
||||
#include "utils.hpp"
|
||||
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
#include <filesystem>
|
||||
#include <vector>
|
||||
#include <utility>
|
||||
|
||||
#if defined(__unix__) || defined(__linux__) || defined(__APPLE__)
|
||||
#include <unistd.h>
|
||||
#include <sys/mount.h>
|
||||
#include <sys/stat.h>
|
||||
#endif
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
namespace khos {
|
||||
|
||||
// =========================================================================
|
||||
// ScopedMount Implementation (RAII Mount Manager)
|
||||
// =========================================================================
|
||||
|
||||
ScopedMount::ScopedMount(std::string source,
|
||||
std::string target,
|
||||
std::string fstype,
|
||||
unsigned long flags,
|
||||
std::string data) noexcept
|
||||
: source_(std::move(source)),
|
||||
target_(std::move(target)),
|
||||
fstype_(std::move(fstype)),
|
||||
flags_(flags),
|
||||
data_(std::move(data)),
|
||||
is_mounted_(false) {}
|
||||
|
||||
ScopedMount::~ScopedMount() {
|
||||
if (is_mounted_) {
|
||||
unmount(true, false);
|
||||
}
|
||||
}
|
||||
|
||||
ScopedMount::ScopedMount(ScopedMount&& other) noexcept
|
||||
: source_(std::move(other.source_)),
|
||||
target_(std::move(other.target_)),
|
||||
fstype_(std::move(other.fstype_)),
|
||||
flags_(other.flags_),
|
||||
data_(std::move(other.data_)),
|
||||
is_mounted_(other.is_mounted_) {
|
||||
other.is_mounted_ = false;
|
||||
}
|
||||
|
||||
ScopedMount& ScopedMount::operator=(ScopedMount&& other) noexcept {
|
||||
if (this != &other) {
|
||||
if (is_mounted_) {
|
||||
unmount(true, false);
|
||||
}
|
||||
source_ = std::move(other.source_);
|
||||
target_ = std::move(other.target_);
|
||||
fstype_ = std::move(other.fstype_);
|
||||
flags_ = other.flags_;
|
||||
data_ = std::move(other.data_);
|
||||
is_mounted_ = other.is_mounted_;
|
||||
other.is_mounted_ = false;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
bool ScopedMount::mount(bool dry_run) {
|
||||
if (is_mounted_) return true;
|
||||
|
||||
if (dry_run) {
|
||||
utils::info("[DRY-RUN] Montowanie " + source_ + " w " + target_ + " (" + fstype_ + ")");
|
||||
is_mounted_ = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
utils::make_directories(target_);
|
||||
|
||||
#if defined(__linux__)
|
||||
const char* fs_ptr = fstype_.empty() ? nullptr : fstype_.c_str();
|
||||
const void* data_ptr = data_.empty() ? nullptr : data_.c_str();
|
||||
if (::mount(source_.c_str(), target_.c_str(), fs_ptr, flags_, data_ptr) == 0) {
|
||||
is_mounted_ = true;
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
|
||||
// Fallback: uruchomienie polecenia mount
|
||||
std::string cmd = "mount ";
|
||||
if (!fstype_.empty()) cmd += "-t " + fstype_ + " ";
|
||||
if (!data_.empty()) cmd += "-o \"" + data_ + "\" ";
|
||||
cmd += "\"" + source_ + "\" \"" + target_ + "\" 2>/dev/null";
|
||||
|
||||
auto res = utils::run_command(cmd, false, false);
|
||||
if (res.success()) {
|
||||
is_mounted_ = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool ScopedMount::unmount(bool force, bool dry_run) {
|
||||
if (!is_mounted_) return true;
|
||||
|
||||
if (dry_run) {
|
||||
utils::info("[DRY-RUN] Odmontowywanie: " + target_);
|
||||
is_mounted_ = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
utils::run_command("sync", false, false);
|
||||
|
||||
#if defined(__linux__)
|
||||
int flags = 0;
|
||||
if (force) {
|
||||
#ifdef MNT_FORCE
|
||||
flags |= MNT_FORCE;
|
||||
#endif
|
||||
#ifdef MNT_DETACH
|
||||
flags |= MNT_DETACH;
|
||||
#endif
|
||||
}
|
||||
if (::umount2(target_.c_str(), flags) == 0) {
|
||||
is_mounted_ = false;
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
|
||||
// Fallback: polecenie umount
|
||||
std::string cmd = "umount ";
|
||||
if (force) cmd += "-f -l ";
|
||||
cmd += "\"" + target_ + "\" 2>/dev/null";
|
||||
|
||||
auto res = utils::run_command(cmd, false, false);
|
||||
if (res.success()) {
|
||||
is_mounted_ = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// MountStack Implementation (LIFO RAII)
|
||||
// =========================================================================
|
||||
|
||||
MountStack::~MountStack() {
|
||||
unmount_all(false);
|
||||
}
|
||||
|
||||
bool MountStack::push_and_mount(std::string source,
|
||||
std::string target,
|
||||
std::string fstype,
|
||||
unsigned long flags,
|
||||
std::string data,
|
||||
bool dry_run) {
|
||||
auto mnt = std::make_unique<ScopedMount>(std::move(source),
|
||||
std::move(target),
|
||||
std::move(fstype),
|
||||
flags,
|
||||
std::move(data));
|
||||
if (!mnt->mount(dry_run)) {
|
||||
utils::err("Nie udalo sie zamontowac " + mnt->source() + " w " + mnt->target());
|
||||
return false;
|
||||
}
|
||||
mounts_.push_back(std::move(mnt));
|
||||
return true;
|
||||
}
|
||||
|
||||
void MountStack::unmount_all(bool dry_run) {
|
||||
// Odmontowuj w odwrotnej kolejnosci (LIFO)
|
||||
while (!mounts_.empty()) {
|
||||
auto& top = mounts_.back();
|
||||
if (top && top->is_mounted()) {
|
||||
top->unmount(true, dry_run);
|
||||
}
|
||||
mounts_.pop_back();
|
||||
}
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// InstallResult Implementation
|
||||
// =========================================================================
|
||||
|
||||
std::string InstallResult::to_json() const {
|
||||
std::ostringstream ss;
|
||||
ss << "{"
|
||||
<< "\"success\":" << (success ? "true" : "false") << ","
|
||||
<< "\"message\":\"" << utils::escape_json(message) << "\","
|
||||
<< "\"target_disk\":\"" << utils::escape_json(target_disk) << "\","
|
||||
<< "\"root_partition\":\"" << utils::escape_json(root_partition) << "\","
|
||||
<< "\"efi_partition\":\"" << utils::escape_json(efi_partition) << "\","
|
||||
<< "\"boot_mode\":\"" << utils::escape_json(DiskManager::boot_mode_to_string(boot_mode)) << "\","
|
||||
<< "\"hostname\":\"" << utils::escape_json(hostname) << "\","
|
||||
<< "\"duration\":\"" << utils::escape_json(duration_str) << "\""
|
||||
<< "}";
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Installer Implementation
|
||||
// =========================================================================
|
||||
|
||||
Installer::Installer(InstallerConfig config)
|
||||
: config_(std::move(config)),
|
||||
boot_mgr_(std::make_unique<BootloaderManager>()) {}
|
||||
|
||||
Installer::~Installer() = default;
|
||||
|
||||
InstallResult Installer::run() {
|
||||
auto start_time = std::chrono::steady_clock::now();
|
||||
result_.target_disk = config_.target_disk;
|
||||
result_.hostname = config_.hostname;
|
||||
|
||||
if (!config_.json_output) {
|
||||
utils::print_banner();
|
||||
}
|
||||
|
||||
// Krok 1: Weryfikacja srodowiska
|
||||
if (!validate_environment()) {
|
||||
result_.success = false;
|
||||
result_.message = "Weryfikacja srodowiska instalacji nie powiodla sie.";
|
||||
return result_;
|
||||
}
|
||||
|
||||
// Krok 2: Przygotowanie dysku (odmontowanie, czyszczenie sygnatur)
|
||||
if (!prepare_disk()) {
|
||||
result_.success = false;
|
||||
result_.message = "Przygotowanie dysku docelowego nie powiodlo sie.";
|
||||
return result_;
|
||||
}
|
||||
|
||||
// Krok 3: Partycjonowanie i formatowanie
|
||||
if (!partition_and_format()) {
|
||||
result_.success = false;
|
||||
result_.message = "Partycjonowanie lub formatowanie dysku nie powiodlo sie.";
|
||||
return result_;
|
||||
}
|
||||
|
||||
result_.root_partition = resolved_root_part_;
|
||||
result_.efi_partition = resolved_efi_part_;
|
||||
|
||||
// Krok 4: Montowanie partycji docelowych (zarzadzane przez RAII MountStack)
|
||||
MountStack mounts;
|
||||
if (!mount_target_partitions(mounts)) {
|
||||
result_.success = false;
|
||||
result_.message = "Montowanie partycji docelowych nie powiodlo sie.";
|
||||
return result_;
|
||||
}
|
||||
|
||||
// Krok 5: Kopiowanie plikow systemu
|
||||
if (!copy_system_payload()) {
|
||||
result_.success = false;
|
||||
result_.message = "Kopiowanie plikow systemu nie powiodlo sie.";
|
||||
return result_;
|
||||
}
|
||||
|
||||
// Krok 6: Kopiowanie jadra i obrazu initramfs
|
||||
if (!copy_kernel_and_initramfs()) {
|
||||
result_.success = false;
|
||||
result_.message = "Kopiowanie plikow rozruchowych (vmlinuz/initramfs) nie powiodlo sie.";
|
||||
return result_;
|
||||
}
|
||||
|
||||
// Krok 7: Generowanie plikow konfiguracyjnych (/etc/fstab, hostname, hosts, haslo root)
|
||||
if (!generate_system_configs()) {
|
||||
result_.success = false;
|
||||
result_.message = "Generowanie plikow konfiguracyjnych nie powiodlo sie.";
|
||||
return result_;
|
||||
}
|
||||
|
||||
// Krok 8: Instalacja bootloadera (GRUB UEFI/BIOS, Syslinux fallback)
|
||||
if (!install_bootloader()) {
|
||||
utils::warn("Instalacja bootloadera zakonczyla sie z uwagami.");
|
||||
}
|
||||
|
||||
// Krok 9: Prawa dostepu do plikow (SUID dla Xorg, busybox, prawa wykonywania skryptow)
|
||||
if (!apply_file_permissions()) {
|
||||
utils::warn("Ustawianie uprawnien plikow zakonczylo sie z uwagami.");
|
||||
}
|
||||
|
||||
// Krok 10: Finalizacja i bezpieczne odmontowanie
|
||||
if (!finalize_installation(mounts)) {
|
||||
result_.success = false;
|
||||
result_.message = "Finalizacja i odmontowanie partycji zakonczylo sie bledem.";
|
||||
return result_;
|
||||
}
|
||||
|
||||
auto end_time = std::chrono::steady_clock::now();
|
||||
auto elapsed_sec = std::chrono::duration_cast<std::chrono::seconds>(end_time - start_time).count();
|
||||
result_.duration_str = std::to_string(elapsed_sec) + "s";
|
||||
result_.success = true;
|
||||
result_.message = "System KhOS zostal pomyslnie zainstalowany!";
|
||||
|
||||
if (!config_.json_output) {
|
||||
std::cout << "\n"
|
||||
<< "╔══════════════════════════════════════════════════════════════╗\n"
|
||||
<< "║ ║\n"
|
||||
<< "║ SUKCES! KhOS 1.1 zostal pomyslnie zainstalowany! ║\n"
|
||||
<< "║ ║\n"
|
||||
<< "║ Dysk docelowy: " << result_.target_disk << "\n"
|
||||
<< "║ Partycja systemowa: " << result_.root_partition << "\n"
|
||||
<< "║ Tryb rozruchu: " << DiskManager::boot_mode_to_string(result_.boot_mode) << "\n"
|
||||
<< "║ Program rozruchowy: GRUB 2.14 ║\n"
|
||||
<< "║ Uzytkownik: root / Haslo: " << config_.root_password << "\n"
|
||||
<< "║ Czas instalacji: " << result_.duration_str << "\n"
|
||||
<< "║ ║\n"
|
||||
<< "║ Pulpity graficzne: ║\n"
|
||||
<< "║ - Openbox (X11): wpisz 'start-openbox' ║\n"
|
||||
<< "║ - Hyprland (Wayland): wpisz 'start-hyprland' ║\n"
|
||||
<< "║ - XFCE 4 / KDE: automatycznie po uruchomieniu ║\n"
|
||||
<< "║ ║\n"
|
||||
<< "║ Mozesz teraz wyciagnac nosnik instalacyjny (ISO / USB) ║\n"
|
||||
<< "║ i zrestartowac komputer wpisujac polecenie: reboot ║\n"
|
||||
<< "║ ║\n"
|
||||
<< "╚══════════════════════════════════════════════════════════════╝\n\n";
|
||||
}
|
||||
|
||||
return result_;
|
||||
}
|
||||
|
||||
bool Installer::validate_environment() {
|
||||
utils::msg("Sprawdzanie wymagan systemowych...");
|
||||
|
||||
// Uprawnienia root
|
||||
#if defined(__unix__) || defined(__linux__) || defined(__APPLE__)
|
||||
if (getuid() != 0 && !config_.dry_run) {
|
||||
utils::die("Ten program musi byc uruchomiony z uprawnieniami roota (uzyj: sudo lub su).");
|
||||
}
|
||||
#endif
|
||||
|
||||
// Weryfikacja dysku docelowego
|
||||
if (config_.target_disk.empty()) {
|
||||
utils::die("Nie okreslono dysku docelowego! Uzyj opcji --disk <sciezka>.");
|
||||
}
|
||||
|
||||
if (!config_.dry_run && !utils::file_exists(config_.target_disk)) {
|
||||
utils::die("Podany dysk docelowy '" + config_.target_disk + "' nie istnieje!");
|
||||
}
|
||||
|
||||
// Detekcja trybu rozruchu
|
||||
if (config_.boot_mode == BootMode::Auto) {
|
||||
config_.boot_mode = DiskManager::detect_system_boot_mode();
|
||||
}
|
||||
result_.boot_mode = config_.boot_mode;
|
||||
|
||||
utils::ok("Dysk docelowy: " + config_.target_disk);
|
||||
utils::ok("Tryb rozruchu komputera: " + DiskManager::boot_mode_to_string(config_.boot_mode));
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Installer::prepare_disk() {
|
||||
utils::msg("Przygotowanie dysku " + config_.target_disk + "...");
|
||||
|
||||
// Odmontowanie istniejacych partycji
|
||||
DiskManager::unmount_partitions(config_.target_disk, config_.dry_run);
|
||||
|
||||
// Czyszczenie sygnatur tablic partycji
|
||||
return DiskManager::wipe_disk_signatures(config_.target_disk, config_.dry_run);
|
||||
}
|
||||
|
||||
bool Installer::partition_and_format() {
|
||||
// Tworzenie tablicy partycji
|
||||
if (!DiskManager::partition_disk(config_.target_disk,
|
||||
config_.boot_mode,
|
||||
resolved_root_part_,
|
||||
resolved_efi_part_,
|
||||
config_.dry_run)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Formatowanie EFI (jesli UEFI)
|
||||
if (config_.boot_mode == BootMode::UEFI && !resolved_efi_part_.empty()) {
|
||||
if (!DiskManager::format_partition(resolved_efi_part_, FileSystemType::Fat32, "EFI", config_.dry_run)) {
|
||||
utils::warn("Formatowanie partycji EFI zglosilo uwagi.");
|
||||
}
|
||||
}
|
||||
|
||||
// Formatowanie partycji glownej (EXT4)
|
||||
if (!DiskManager::format_partition(resolved_root_part_, FileSystemType::Ext4, "KHOS", config_.dry_run)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Installer::mount_target_partitions(MountStack& mounts) {
|
||||
utils::msg("Montowanie partycji docelowych...");
|
||||
|
||||
// Montowanie glownej partycji w katalogu docelowym
|
||||
if (!mounts.push_and_mount(resolved_root_part_, config_.mount_dir, "ext4", 0, "noatime", config_.dry_run)) {
|
||||
utils::err("Nie udalo sie zamontowac partycji glownej: " + resolved_root_part_);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Montowanie partycji EFI
|
||||
if (config_.boot_mode == BootMode::UEFI && !resolved_efi_part_.empty()) {
|
||||
std::string efi_mnt = config_.mount_dir + "/boot/efi";
|
||||
utils::make_directories(efi_mnt);
|
||||
if (!mounts.push_and_mount(resolved_efi_part_, efi_mnt, "vfat", 0, "", config_.dry_run)) {
|
||||
utils::warn("Montowanie partycji EFI w " + efi_mnt + " zakonczylo sie ostrzezeniem.");
|
||||
}
|
||||
}
|
||||
|
||||
utils::ok("Partycje zamontowane w punkcie docelowym: " + config_.mount_dir);
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string Installer::locate_source_payload() {
|
||||
if (!config_.source_dir.empty() && utils::directory_exists(config_.source_dir)) {
|
||||
return config_.source_dir;
|
||||
}
|
||||
|
||||
// 1. Sprawdz /mnt/squashfs
|
||||
if (utils::directory_exists("/mnt/squashfs") && utils::file_exists("/mnt/squashfs/bin/busybox")) {
|
||||
return "/mnt/squashfs";
|
||||
}
|
||||
|
||||
// 2. Sprawdz /mnt/cdrom/live/filesystem.squashfs
|
||||
if (utils::file_exists("/mnt/cdrom/live/filesystem.squashfs")) {
|
||||
std::string sq_mount = "/mnt/squashfs_inst";
|
||||
utils::make_directories(sq_mount);
|
||||
utils::run_command("mount -t squashfs -o ro,loop /mnt/cdrom/live/filesystem.squashfs \"" + sq_mount + "\" 2>/dev/null", false, false);
|
||||
if (utils::file_exists(sq_mount + "/bin/busybox")) {
|
||||
return sq_mount;
|
||||
}
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
bool Installer::copy_system_payload() {
|
||||
utils::msg("Kopiowanie plikow systemu KhOS na dysk...");
|
||||
|
||||
std::string source_dir = locate_source_payload();
|
||||
|
||||
if (!source_dir.empty()) {
|
||||
utils::info("Kopiowanie z obrazu Live (" + source_dir + ")...");
|
||||
utils::copy_recursive_tar(source_dir, config_.mount_dir, config_.dry_run);
|
||||
} else {
|
||||
utils::info("Kopiowanie biezacego srodowiska systemu...");
|
||||
std::vector<std::string> base_dirs = {
|
||||
"bin", "sbin", "lib", "lib64", "usr", "etc", "var", "root", "home", "opt", "srv"
|
||||
};
|
||||
for (const auto& dir : base_dirs) {
|
||||
std::string src_path = "/" + dir;
|
||||
if (utils::directory_exists(src_path)) {
|
||||
std::string dst_path = config_.mount_dir + "/" + dir;
|
||||
utils::copy_recursive_tar(src_path, dst_path, config_.dry_run);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Utworz niezbedne katalogi wirtualnych systemow plikow i punktow montowania
|
||||
std::vector<std::string> required_dirs = {
|
||||
config_.mount_dir + "/proc",
|
||||
config_.mount_dir + "/sys",
|
||||
config_.mount_dir + "/dev",
|
||||
config_.mount_dir + "/tmp",
|
||||
config_.mount_dir + "/run",
|
||||
config_.mount_dir + "/mnt",
|
||||
config_.mount_dir + "/mnt/cdrom",
|
||||
config_.mount_dir + "/boot"
|
||||
};
|
||||
|
||||
for (const auto& d : required_dirs) {
|
||||
utils::make_directories(d);
|
||||
}
|
||||
|
||||
utils::set_permissions(config_.mount_dir + "/tmp", 01777, config_.dry_run);
|
||||
utils::ok("Pliki systemu KhOS skopiowane.");
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Installer::copy_kernel_and_initramfs() {
|
||||
utils::info("Weryfikacja i kopiowanie jadra (vmlinuz) oraz initramfs...");
|
||||
|
||||
std::string target_boot = config_.mount_dir + "/boot";
|
||||
utils::make_directories(target_boot);
|
||||
|
||||
std::string kernel_src;
|
||||
std::string initrd_src;
|
||||
|
||||
std::vector<std::string> kernel_candidates = {
|
||||
"/mnt/cdrom/boot/vmlinuz",
|
||||
"/boot/vmlinuz",
|
||||
"/vmlinuz"
|
||||
};
|
||||
|
||||
std::vector<std::string> initrd_candidates = {
|
||||
"/mnt/cdrom/boot/initramfs.img",
|
||||
"/boot/initramfs.img",
|
||||
"/initramfs.img"
|
||||
};
|
||||
|
||||
for (const auto& k : kernel_candidates) {
|
||||
if (utils::file_exists(k)) {
|
||||
kernel_src = k;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for (const auto& i : initrd_candidates) {
|
||||
if (utils::file_exists(i)) {
|
||||
initrd_src = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Jesli nosnik CDROM nie byl zamontowany, sprobuj odnalezc go w /dev/sr* lub /dev/cdrom
|
||||
if (kernel_src.empty() || initrd_src.empty()) {
|
||||
std::vector<std::string> cd_devs = {"/dev/sr0", "/dev/sr1", "/dev/cdrom"};
|
||||
for (const auto& cd : cd_devs) {
|
||||
if (utils::file_exists(cd)) {
|
||||
utils::run_command("mount -o ro \"" + cd + "\" /mnt/cdrom 2>/dev/null", false, false);
|
||||
if (utils::file_exists("/mnt/cdrom/boot/vmlinuz")) {
|
||||
kernel_src = "/mnt/cdrom/boot/vmlinuz";
|
||||
}
|
||||
if (utils::file_exists("/mnt/cdrom/boot/initramfs.img")) {
|
||||
initrd_src = "/mnt/cdrom/boot/initramfs.img";
|
||||
}
|
||||
if (!kernel_src.empty() && !initrd_src.empty()) break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!kernel_src.empty()) {
|
||||
utils::copy_file_safe(kernel_src, target_boot + "/vmlinuz", config_.dry_run);
|
||||
utils::ok("Skopiowano jadro: " + kernel_src + " -> " + target_boot + "/vmlinuz");
|
||||
} else {
|
||||
utils::warn("Nie znaleziono pliku jadra vmlinuz!");
|
||||
}
|
||||
|
||||
if (!initrd_src.empty()) {
|
||||
utils::copy_file_safe(initrd_src, target_boot + "/initramfs.img", config_.dry_run);
|
||||
utils::ok("Skopiowano obraz initramfs: " + initrd_src + " -> " + target_boot + "/initramfs.img");
|
||||
} else {
|
||||
utils::warn("Nie znaleziono pliku obrazu initramfs.img!");
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string Installer::get_root_kernel_param() {
|
||||
root_uuid_ = DiskManager::get_uuid(resolved_root_part_);
|
||||
if (!root_uuid_.empty()) {
|
||||
return "root=UUID=" + root_uuid_;
|
||||
}
|
||||
return "root=" + resolved_root_part_;
|
||||
}
|
||||
|
||||
bool Installer::generate_system_configs() {
|
||||
utils::msg("Generowanie konfiguracji systemowych (/etc/fstab, hostname, hosts)...");
|
||||
|
||||
// 1. /etc/fstab
|
||||
std::string fstab_path = config_.mount_dir + "/etc/fstab";
|
||||
std::ostringstream fstab;
|
||||
fstab << "# /etc/fstab - KhOS Linux\n"
|
||||
<< "# <file system> <mount point> <type> <options> <dump> <pass>\n";
|
||||
|
||||
if (!root_uuid_.empty()) {
|
||||
fstab << "UUID=" << root_uuid_ << " / ext4 defaults,noatime 0 1\n";
|
||||
} else {
|
||||
fstab << resolved_root_part_ << " / ext4 defaults,noatime 0 1\n";
|
||||
}
|
||||
|
||||
if (config_.boot_mode == BootMode::UEFI && !resolved_efi_part_.empty()) {
|
||||
std::string efi_uuid = DiskManager::get_uuid(resolved_efi_part_);
|
||||
if (!efi_uuid.empty()) {
|
||||
fstab << "UUID=" << efi_uuid << " /boot/efi vfat defaults 0 2\n";
|
||||
} else {
|
||||
fstab << resolved_efi_part_ << " /boot/efi vfat defaults 0 2\n";
|
||||
}
|
||||
}
|
||||
|
||||
fstab << "proc /proc proc defaults 0 0\n"
|
||||
<< "sysfs /sys sysfs defaults 0 0\n"
|
||||
<< "devtmpfs /dev devtmpfs defaults 0 0\n"
|
||||
<< "devpts /dev/pts devpts defaults,gid=5,mode=620,nosuid,noexec 0 0\n"
|
||||
<< "tmpfs /dev/shm tmpfs defaults,nosuid,nodev,noexec 0 0\n"
|
||||
<< "tmpfs /tmp tmpfs defaults,nosuid,nodev 0 0\n"
|
||||
<< "tmpfs /run tmpfs defaults,nosuid,nodev,mode=0755 0 0\n";
|
||||
|
||||
if (!config_.dry_run) {
|
||||
utils::write_file_string(fstab_path, fstab.str());
|
||||
} else {
|
||||
utils::info("[DRY-RUN] Zapis " + fstab_path);
|
||||
}
|
||||
|
||||
// 2. /etc/hostname
|
||||
std::string hostname_path = config_.mount_dir + "/etc/hostname";
|
||||
if (!config_.dry_run) {
|
||||
utils::write_file_string(hostname_path, config_.hostname + "\n");
|
||||
} else {
|
||||
utils::info("[DRY-RUN] Zapis " + hostname_path + " (" + config_.hostname + ")");
|
||||
}
|
||||
|
||||
// 3. /etc/hosts
|
||||
std::string hosts_path = config_.mount_dir + "/etc/hosts";
|
||||
std::ostringstream hosts;
|
||||
hosts << "127.0.0.1 localhost " << config_.hostname << "\n"
|
||||
<< "::1 localhost ip6-localhost ip6-loopback\n";
|
||||
|
||||
if (!config_.dry_run) {
|
||||
utils::write_file_string(hosts_path, hosts.str());
|
||||
} else {
|
||||
utils::info("[DRY-RUN] Zapis " + hosts_path);
|
||||
}
|
||||
|
||||
// 4. Zmiana hasla root
|
||||
if (!config_.dry_run) {
|
||||
std::string shadow_path = config_.mount_dir + "/etc/shadow";
|
||||
if (utils::file_exists(shadow_path)) {
|
||||
std::string chpasswd_in = "root:" + config_.root_password + "\n";
|
||||
auto res = utils::run_command_with_stdin("chpasswd -R \"" + config_.mount_dir + "\" 2>/dev/null", chpasswd_in, false, false);
|
||||
if (!res.success()) {
|
||||
utils::run_command_with_stdin("chroot \"" + config_.mount_dir + "\" chpasswd 2>/dev/null", chpasswd_in, false, false);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
utils::info("[DRY-RUN] Aktualizacja hasla konta root");
|
||||
}
|
||||
|
||||
utils::ok("Konfiguracja systemowa wygenerowana.");
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Installer::install_bootloader() {
|
||||
std::string root_param = get_root_kernel_param();
|
||||
std::string efi_mnt = config_.mount_dir + "/boot/efi";
|
||||
|
||||
return boot_mgr_->setup_bootloader(config_.target_disk,
|
||||
config_.mount_dir,
|
||||
efi_mnt,
|
||||
root_param,
|
||||
config_.boot_mode,
|
||||
config_.dry_run);
|
||||
}
|
||||
|
||||
bool Installer::apply_file_permissions() {
|
||||
utils::info("Ustawianie uprawnien binariow systemowych oraz skryptow sesji...");
|
||||
if (config_.dry_run) return true;
|
||||
|
||||
std::vector<std::string> executable_scripts = {
|
||||
config_.mount_dir + "/usr/bin/start-xfce",
|
||||
config_.mount_dir + "/usr/bin/startxfce4",
|
||||
config_.mount_dir + "/usr/bin/xfce",
|
||||
config_.mount_dir + "/usr/bin/xfce4",
|
||||
config_.mount_dir + "/usr/bin/start-plasma",
|
||||
config_.mount_dir + "/usr/bin/plasma",
|
||||
config_.mount_dir + "/usr/bin/kde",
|
||||
config_.mount_dir + "/usr/bin/autologin-plasma",
|
||||
config_.mount_dir + "/usr/bin/start-hyprland",
|
||||
config_.mount_dir + "/usr/bin/start-openbox",
|
||||
config_.mount_dir + "/usr/bin/Hyprland",
|
||||
config_.mount_dir + "/usr/bin/foot",
|
||||
config_.mount_dir + "/usr/bin/wofi",
|
||||
config_.mount_dir + "/usr/bin/openbox",
|
||||
config_.mount_dir + "/usr/bin/tint2",
|
||||
config_.mount_dir + "/usr/bin/xterm",
|
||||
config_.mount_dir + "/usr/bin/feh",
|
||||
config_.mount_dir + "/usr/bin/khos-installer",
|
||||
config_.mount_dir + "/usr/bin/install-os",
|
||||
config_.mount_dir + "/usr/bin/wpkg"
|
||||
};
|
||||
|
||||
for (const auto& path : executable_scripts) {
|
||||
if (utils::file_exists(path)) {
|
||||
utils::set_permissions(path, 0755, false);
|
||||
}
|
||||
}
|
||||
|
||||
// Binarne z bitem SUID (sudo, doas)
|
||||
std::vector<std::string> suid_binaries = {
|
||||
config_.mount_dir + "/usr/bin/sudo",
|
||||
config_.mount_dir + "/usr/bin/doas"
|
||||
};
|
||||
|
||||
for (const auto& path : suid_binaries) {
|
||||
if (utils::file_exists(path)) {
|
||||
utils::set_permissions(path, 04755, false);
|
||||
}
|
||||
}
|
||||
|
||||
// Bezpieczne uprawnienia standardowe (0755)
|
||||
std::vector<std::string> standard_binaries = {
|
||||
config_.mount_dir + "/usr/bin/seatd-launch",
|
||||
config_.mount_dir + "/usr/bin/Xorg",
|
||||
config_.mount_dir + "/bin/busybox"
|
||||
};
|
||||
|
||||
for (const auto& path : standard_binaries) {
|
||||
if (utils::file_exists(path)) {
|
||||
utils::set_permissions(path, 0755, false);
|
||||
}
|
||||
}
|
||||
|
||||
if (utils::file_exists(config_.mount_dir + "/etc/shadow")) {
|
||||
utils::set_permissions(config_.mount_dir + "/etc/shadow", 0600, false);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Installer::finalize_installation(MountStack& mounts) {
|
||||
utils::msg("Synchronizacja buforow i bezpieczne odmontowanie dysku...");
|
||||
utils::run_command("sync", false, config_.dry_run);
|
||||
|
||||
mounts.unmount_all(config_.dry_run);
|
||||
|
||||
if (!config_.dry_run) {
|
||||
std::error_code ec;
|
||||
fs::remove(config_.mount_dir, ec);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace khos
|
||||
@@ -0,0 +1,186 @@
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <csignal>
|
||||
#include <cstdlib>
|
||||
|
||||
#if defined(__unix__) || defined(__linux__) || defined(__APPLE__)
|
||||
#include <sys/wait.h>
|
||||
#endif
|
||||
|
||||
#include "utils.hpp"
|
||||
#include "disk.hpp"
|
||||
#include "installer.hpp"
|
||||
|
||||
namespace {
|
||||
void signal_handler(int sig) {
|
||||
khos::utils::err("\nOtrzymano sygnal przerwania (" + std::to_string(sig) + "). Przerywanie instalacji...");
|
||||
std::exit(128 + sig);
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char* argv[]) {
|
||||
std::signal(SIGINT, signal_handler);
|
||||
std::signal(SIGTERM, signal_handler);
|
||||
|
||||
khos::utils::CliOptions options = khos::utils::parse_cli_args(argc, argv);
|
||||
|
||||
if (options.help) {
|
||||
khos::utils::print_help(argv[0]);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (options.version) {
|
||||
std::cout << "khos-installer v1.1.0 (Genesis C++ Edition)\n"
|
||||
<< "Kompilacja: C++17 / C++20 dla dystrybucji KhOS Linux\n";
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Obsluga listowania dyskow (--list-disks)
|
||||
if (options.list_disks) {
|
||||
auto disks = khos::DiskManager::scan_disks();
|
||||
if (options.json_output) {
|
||||
std::cout << "{\"disks\":[";
|
||||
for (size_t i = 0; i < disks.size(); ++i) {
|
||||
if (i > 0) std::cout << ",";
|
||||
std::cout << disks[i].to_json();
|
||||
}
|
||||
std::cout << "]}\n";
|
||||
} else {
|
||||
khos::utils::msg("Dostepne dyski twarde i SSD:");
|
||||
if (disks.empty()) {
|
||||
khos::utils::warn("Nie znaleziono zadnych dyskow blokowych w /sys/block.");
|
||||
} else {
|
||||
for (const auto& d : disks) {
|
||||
std::cout << " - " << khos::utils::colors::BOLD << d.device << khos::utils::colors::RESET
|
||||
<< " (" << d.size_human() << ") - " << d.model
|
||||
<< (d.is_rotational ? " [HDD]" : " [SSD/NVMe]") << "\n";
|
||||
for (const auto& p : d.partitions) {
|
||||
std::cout << " └─ " << p.device << " (" << khos::utils::format_size(p.size_bytes)
|
||||
<< ", " << (p.fstype.empty() ? "brak fs" : p.fstype)
|
||||
<< (p.uuid.empty() ? "" : ", UUID=" + p.uuid) << ")\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
khos::InstallerConfig config;
|
||||
config.target_disk = options.disk;
|
||||
config.hostname = options.hostname;
|
||||
config.root_password = options.password;
|
||||
config.source_dir = options.source_dir;
|
||||
config.auto_mode = options.auto_mode;
|
||||
config.dry_run = options.dry_run;
|
||||
config.json_output = options.json_output;
|
||||
config.boot_mode = khos::DiskManager::string_to_boot_mode(options.mode_str);
|
||||
|
||||
// Tryb interaktywny (jesli nie podano --auto)
|
||||
if (!config.auto_mode) {
|
||||
khos::utils::print_banner();
|
||||
|
||||
khos::BootMode detected_mode = khos::DiskManager::detect_system_boot_mode();
|
||||
khos::utils::info("Wykryty tryb rozruchu komputera: " +
|
||||
std::string(khos::utils::colors::BOLD) +
|
||||
khos::DiskManager::boot_mode_to_string(detected_mode) +
|
||||
std::string(khos::utils::colors::RESET));
|
||||
|
||||
std::cout << "\n";
|
||||
khos::utils::msg("Wybierz operacje:");
|
||||
std::cout << " 1) Czysta instalacja (formatowanie wybranego dysku i instalacja od zera)\n"
|
||||
<< " 2) Aktualizacja istniejacego systemu KhOS z tego ISO (bez utraty danych w /home)\n";
|
||||
std::cout << khos::utils::colors::BOLD << "Wybor [1]: " << khos::utils::colors::RESET;
|
||||
|
||||
std::string op_mode_str;
|
||||
std::getline(std::cin, op_mode_str);
|
||||
op_mode_str = khos::utils::trim(op_mode_str);
|
||||
|
||||
if (op_mode_str == "2") {
|
||||
khos::utils::info("Uruchamianie asystenta aktualizacji systemu KhOS (/usr/bin/khos-update)...");
|
||||
int res = std::system("/usr/bin/khos-update");
|
||||
#if defined(WEXITSTATUS)
|
||||
return WEXITSTATUS(res);
|
||||
#else
|
||||
return res;
|
||||
#endif
|
||||
}
|
||||
|
||||
// Skanowanie i wyswietlanie dostepnych dyskow
|
||||
std::cout << "\n";
|
||||
khos::utils::msg("Wyszukiwanie dyskow twardych i SSD...");
|
||||
auto disks = khos::DiskManager::scan_disks();
|
||||
|
||||
if (disks.empty()) {
|
||||
khos::utils::die("Nie znaleziono zadnych dyskow twardych w systemie!");
|
||||
}
|
||||
|
||||
for (const auto& d : disks) {
|
||||
std::cout << " - " << khos::utils::colors::BOLD << d.device << khos::utils::colors::RESET
|
||||
<< " (" << d.size_human() << ") - " << d.model
|
||||
<< (d.is_rotational ? " [HDD]" : " [SSD/NVMe]") << "\n";
|
||||
}
|
||||
|
||||
std::cout << "\n";
|
||||
if (config.target_disk.empty()) {
|
||||
std::cout << khos::utils::colors::BOLD << "Wybierz dysk docelowy (np. /dev/sda): " << khos::utils::colors::RESET;
|
||||
std::string user_disk;
|
||||
std::getline(std::cin, user_disk);
|
||||
config.target_disk = khos::utils::trim(user_disk);
|
||||
}
|
||||
|
||||
if (config.target_disk.empty()) {
|
||||
khos::utils::die("Nie wybrano dysku docelowego!");
|
||||
}
|
||||
|
||||
std::cout << "\n";
|
||||
khos::utils::warn("UWAGA: Wszystkie dane na dysku " +
|
||||
std::string(khos::utils::colors::BOLD) +
|
||||
config.target_disk +
|
||||
std::string(khos::utils::colors::RESET) +
|
||||
" zostana BEZPOWROTNIE USUNIETE!");
|
||||
std::cout << "Czy na pewno chcesz kontynuowac? Wpisz "
|
||||
<< khos::utils::colors::BOLD << "TAK" << khos::utils::colors::RESET
|
||||
<< " (wielkimi literami): ";
|
||||
|
||||
std::string confirm;
|
||||
std::getline(std::cin, confirm);
|
||||
confirm = khos::utils::trim(confirm);
|
||||
|
||||
if (confirm != "TAK") {
|
||||
khos::utils::die("Instalacja zostala anulowana przez uzytkownika.");
|
||||
}
|
||||
|
||||
std::cout << "\n";
|
||||
std::cout << "Podaj nazwe komputera (hostname) [domyslnie: " << config.hostname << "]: ";
|
||||
std::string user_host;
|
||||
std::getline(std::cin, user_host);
|
||||
user_host = khos::utils::trim(user_host);
|
||||
if (!user_host.empty()) config.hostname = user_host;
|
||||
|
||||
std::cout << "Ustaw nowe haslo dla konta root [domyslnie: " << config.root_password << "]: ";
|
||||
std::string user_pass;
|
||||
std::getline(std::cin, user_pass);
|
||||
user_pass = khos::utils::trim(user_pass);
|
||||
if (!user_pass.empty()) config.root_password = user_pass;
|
||||
} else {
|
||||
// W trybie auto dysk docelowy jest bezwzglednie wymagany
|
||||
if (config.target_disk.empty()) {
|
||||
if (config.json_output) {
|
||||
std::cout << "{\"success\":false,\"error\":\"Brak flagi --disk w trybie --auto\"}\n";
|
||||
} else {
|
||||
khos::utils::err("W trybie automatycznym nalezy podac dysk: --disk <sciezka>");
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
khos::Installer installer(config);
|
||||
khos::InstallResult result = installer.run();
|
||||
|
||||
if (config.json_output) {
|
||||
std::cout << result.to_json() << "\n";
|
||||
}
|
||||
|
||||
return result.success ? 0 : 1;
|
||||
}
|
||||
@@ -0,0 +1,546 @@
|
||||
#include "utils.hpp"
|
||||
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <iomanip>
|
||||
#include <cstring>
|
||||
#include <cstdlib>
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <filesystem>
|
||||
#include <vector>
|
||||
|
||||
#if defined(__unix__) || defined(__linux__) || defined(__APPLE__)
|
||||
#include <unistd.h>
|
||||
#include <sys/wait.h>
|
||||
#include <sys/stat.h>
|
||||
#include <fcntl.h>
|
||||
#else
|
||||
#include <io.h>
|
||||
#endif
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
namespace khos {
|
||||
namespace utils {
|
||||
|
||||
namespace {
|
||||
bool g_colors_enabled = true;
|
||||
}
|
||||
|
||||
void set_colors_enabled(bool enabled) {
|
||||
g_colors_enabled = enabled;
|
||||
}
|
||||
|
||||
bool are_colors_enabled() {
|
||||
return g_colors_enabled;
|
||||
}
|
||||
|
||||
void msg(std::string_view text) {
|
||||
if (g_colors_enabled) {
|
||||
std::cout << colors::BOLD << colors::BLUE << "==>" << colors::RESET
|
||||
<< " " << colors::BOLD << text << colors::RESET << "\n";
|
||||
} else {
|
||||
std::cout << "==> " << text << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
void info(std::string_view text) {
|
||||
if (g_colors_enabled) {
|
||||
std::cout << colors::CYAN << " ->" << colors::RESET << " " << text << "\n";
|
||||
} else {
|
||||
std::cout << " -> " << text << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
void ok(std::string_view text) {
|
||||
if (g_colors_enabled) {
|
||||
std::cout << colors::GREEN << " [OK]" << colors::RESET << " " << text << "\n";
|
||||
} else {
|
||||
std::cout << " [OK] " << text << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
void warn(std::string_view text) {
|
||||
if (g_colors_enabled) {
|
||||
std::cout << colors::YELLOW << "[OSTRZEŻENIE]" << colors::RESET << " " << text << "\n";
|
||||
} else {
|
||||
std::cout << "[OSTRZEŻENIE] " << text << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
void err(std::string_view text) {
|
||||
if (g_colors_enabled) {
|
||||
std::cerr << colors::RED << "[BŁĄD]" << colors::RESET << " " << text << "\n";
|
||||
} else {
|
||||
std::cerr << "[BŁĄD] " << text << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
[[noreturn]] void die(std::string_view text, int exit_code) {
|
||||
err(text);
|
||||
std::exit(exit_code);
|
||||
}
|
||||
|
||||
// ScopedFd implementation
|
||||
ScopedFd::~ScopedFd() {
|
||||
reset();
|
||||
}
|
||||
|
||||
void ScopedFd::reset(int new_fd) noexcept {
|
||||
if (fd_ >= 0) {
|
||||
#if defined(__unix__) || defined(__linux__) || defined(__APPLE__)
|
||||
::close(fd_);
|
||||
#else
|
||||
_close(fd_);
|
||||
#endif
|
||||
}
|
||||
fd_ = new_fd;
|
||||
}
|
||||
|
||||
// Command execution implementation
|
||||
CommandResult run_command(const std::string& cmd, bool log, bool dry_run) {
|
||||
return run_command_with_stdin(cmd, "", log, dry_run);
|
||||
}
|
||||
|
||||
CommandResult run_command_with_stdin(const std::string& cmd, const std::string& input, bool log, bool dry_run) {
|
||||
CommandResult result;
|
||||
|
||||
if (dry_run) {
|
||||
if (log) {
|
||||
info("[DRY-RUN] Wykonanie polecenia: " + cmd);
|
||||
if (!input.empty()) {
|
||||
info("[DRY-RUN] Stdin: " + input);
|
||||
}
|
||||
}
|
||||
result.exit_code = 0;
|
||||
result.stdout_output = "[DRY-RUN simulated output]";
|
||||
return result;
|
||||
}
|
||||
|
||||
#if defined(__unix__) || defined(__linux__) || defined(__APPLE__)
|
||||
int pipe_stdin[2];
|
||||
int pipe_stdout[2];
|
||||
int pipe_stderr[2];
|
||||
|
||||
if (pipe(pipe_stdin) != 0 || pipe(pipe_stdout) != 0 || pipe(pipe_stderr) != 0) {
|
||||
result.exit_code = -1;
|
||||
result.stderr_output = "Nie udalo sie utworzyc potokow IPC";
|
||||
return result;
|
||||
}
|
||||
|
||||
pid_t pid = fork();
|
||||
if (pid < 0) {
|
||||
result.exit_code = -1;
|
||||
result.stderr_output = "fork() nie powiodl sie";
|
||||
close(pipe_stdin[0]); close(pipe_stdin[1]);
|
||||
close(pipe_stdout[0]); close(pipe_stdout[1]);
|
||||
close(pipe_stderr[0]); close(pipe_stderr[1]);
|
||||
return result;
|
||||
}
|
||||
|
||||
if (pid == 0) {
|
||||
// Child process
|
||||
close(pipe_stdin[1]);
|
||||
close(pipe_stdout[0]);
|
||||
close(pipe_stderr[0]);
|
||||
|
||||
dup2(pipe_stdin[0], STDIN_FILENO);
|
||||
dup2(pipe_stdout[1], STDOUT_FILENO);
|
||||
dup2(pipe_stderr[1], STDERR_FILENO);
|
||||
|
||||
close(pipe_stdin[0]);
|
||||
close(pipe_stdout[1]);
|
||||
close(pipe_stderr[1]);
|
||||
|
||||
execl("/bin/sh", "sh", "-c", cmd.c_str(), static_cast<char*>(nullptr));
|
||||
_exit(127);
|
||||
}
|
||||
|
||||
// Parent process
|
||||
close(pipe_stdin[0]);
|
||||
close(pipe_stdout[1]);
|
||||
close(pipe_stderr[1]);
|
||||
|
||||
if (!input.empty()) {
|
||||
size_t written = 0;
|
||||
while (written < input.size()) {
|
||||
ssize_t res = write(pipe_stdin[1], input.data() + written, input.size() - written);
|
||||
if (res <= 0) break;
|
||||
written += static_cast<size_t>(res);
|
||||
}
|
||||
}
|
||||
close(pipe_stdin[1]);
|
||||
|
||||
// Read stdout
|
||||
char buffer[4096];
|
||||
ssize_t bytes_read;
|
||||
while ((bytes_read = read(pipe_stdout[0], buffer, sizeof(buffer))) > 0) {
|
||||
result.stdout_output.append(buffer, static_cast<size_t>(bytes_read));
|
||||
}
|
||||
close(pipe_stdout[0]);
|
||||
|
||||
// Read stderr
|
||||
while ((bytes_read = read(pipe_stderr[0], buffer, sizeof(buffer))) > 0) {
|
||||
result.stderr_output.append(buffer, static_cast<size_t>(bytes_read));
|
||||
}
|
||||
close(pipe_stderr[0]);
|
||||
|
||||
int status = 0;
|
||||
waitpid(pid, &status, 0);
|
||||
|
||||
if (WIFEXITED(status)) {
|
||||
result.exit_code = WEXITSTATUS(status);
|
||||
} else if (WIFSIGNALED(status)) {
|
||||
result.exit_code = 128 + WTERMSIG(status);
|
||||
} else {
|
||||
result.exit_code = -1;
|
||||
}
|
||||
|
||||
#else
|
||||
// Fallback for non-POSIX platforms
|
||||
std::string full_cmd = cmd;
|
||||
FILE* pipe = _popen(full_cmd.c_str(), "r");
|
||||
if (!pipe) {
|
||||
result.exit_code = -1;
|
||||
result.stderr_output = "Popen failed";
|
||||
return result;
|
||||
}
|
||||
char buf[512];
|
||||
while (fgets(buf, sizeof(buf), pipe) != nullptr) {
|
||||
result.stdout_output += buf;
|
||||
}
|
||||
result.exit_code = _pclose(pipe);
|
||||
#endif
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
CommandResult run_args(const std::vector<std::string>& args, const std::string& input, bool log, bool dry_run) {
|
||||
if (args.empty()) {
|
||||
return CommandResult{-1, "", "Brak argumentow polecenia"};
|
||||
}
|
||||
std::string full_cmd;
|
||||
for (size_t i = 0; i < args.size(); ++i) {
|
||||
if (i > 0) full_cmd += " ";
|
||||
// Simple shell escape
|
||||
if (args[i].find(' ') != std::string::npos || args[i].find('"') != std::string::npos) {
|
||||
full_cmd += "\"";
|
||||
for (char c : args[i]) {
|
||||
if (c == '"' || c == '\\' || c == '$' || c == '`') full_cmd += '\\';
|
||||
full_cmd += c;
|
||||
}
|
||||
full_cmd += "\"";
|
||||
} else {
|
||||
full_cmd += args[i];
|
||||
}
|
||||
}
|
||||
return run_command_with_stdin(full_cmd, input, log, dry_run);
|
||||
}
|
||||
|
||||
bool command_exists(const std::string& cmd) {
|
||||
if (cmd.find('/') != std::string::npos) {
|
||||
return file_exists(cmd);
|
||||
}
|
||||
const char* path_env = std::getenv("PATH");
|
||||
std::string path_str = path_env ? path_env : "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
|
||||
std::vector<std::string> dirs = split(path_str, ':');
|
||||
for (const auto& d : dirs) {
|
||||
std::string cand = d + "/" + cmd;
|
||||
if (file_exists(cand)) {
|
||||
#if defined(__unix__) || defined(__linux__) || defined(__APPLE__)
|
||||
if (access(cand.c_str(), X_OK) == 0) return true;
|
||||
#else
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// File and directory utilities
|
||||
bool file_exists(const std::string& path) {
|
||||
std::error_code ec;
|
||||
return fs::exists(path, ec) && !fs::is_directory(path, ec);
|
||||
}
|
||||
|
||||
bool directory_exists(const std::string& path) {
|
||||
std::error_code ec;
|
||||
return fs::is_directory(path, ec);
|
||||
}
|
||||
|
||||
std::string read_file_string(const std::string& path) {
|
||||
std::ifstream file(path, std::ios::in | std::ios::binary);
|
||||
if (!file.is_open()) return "";
|
||||
std::ostringstream ss;
|
||||
ss << file.rdbuf();
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
bool write_file_string(const std::string& path, const std::string& content) {
|
||||
std::error_code ec;
|
||||
fs::path p(path);
|
||||
if (p.has_parent_path()) {
|
||||
fs::create_directories(p.parent_path(), ec);
|
||||
}
|
||||
std::ofstream file(path, std::ios::out | std::ios::binary | std::ios::trunc);
|
||||
if (!file.is_open()) return false;
|
||||
file.write(content.data(), static_cast<std::streamsize>(content.size()));
|
||||
return file.good();
|
||||
}
|
||||
|
||||
bool append_file_string(const std::string& path, const std::string& content) {
|
||||
std::ofstream file(path, std::ios::out | std::ios::binary | std::ios::app);
|
||||
if (!file.is_open()) return false;
|
||||
file.write(content.data(), static_cast<std::streamsize>(content.size()));
|
||||
return file.good();
|
||||
}
|
||||
|
||||
bool copy_file_safe(const std::string& src, const std::string& dst, bool dry_run) {
|
||||
if (dry_run) {
|
||||
info("[DRY-RUN] Kopiowanie pliku: " + src + " -> " + dst);
|
||||
return true;
|
||||
}
|
||||
std::error_code ec;
|
||||
fs::path p(dst);
|
||||
if (p.has_parent_path()) {
|
||||
fs::create_directories(p.parent_path(), ec);
|
||||
}
|
||||
return fs::copy_file(src, dst, fs::copy_options::overwrite_existing, ec);
|
||||
}
|
||||
|
||||
bool make_directories(const std::string& path) {
|
||||
std::error_code ec;
|
||||
return fs::create_directories(path, ec);
|
||||
}
|
||||
|
||||
bool set_permissions(const std::string& path, mode_t mode, bool dry_run) {
|
||||
if (dry_run) {
|
||||
info("[DRY-RUN] chmod " + std::to_string(mode) + " " + path);
|
||||
return true;
|
||||
}
|
||||
#if defined(__unix__) || defined(__linux__) || defined(__APPLE__)
|
||||
return chmod(path.c_str(), mode) == 0;
|
||||
#else
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
|
||||
std::uintmax_t copy_recursive_tar(const std::string& src_dir, const std::string& dst_dir, bool dry_run) {
|
||||
if (dry_run) {
|
||||
info("[DRY-RUN] Kopiowanie zawartosci: " + src_dir + " -> " + dst_dir);
|
||||
return 1;
|
||||
}
|
||||
make_directories(dst_dir);
|
||||
|
||||
// Prefer fast streaming tar pipeline if tar is available
|
||||
if (command_exists("tar")) {
|
||||
std::string tar_cmd = "(cd \"" + src_dir + "\" && tar -cf - .) | (cd \"" + dst_dir + "\" && tar -xf -) 2>/dev/null";
|
||||
CommandResult res = run_command(tar_cmd, false, false);
|
||||
if (res.success()) return 1;
|
||||
}
|
||||
|
||||
// Fallback: cp -af
|
||||
std::string cp_cmd = "cp -af \"" + src_dir + "/.\" \"" + dst_dir + "/\" 2>/dev/null";
|
||||
CommandResult cp_res = run_command(cp_cmd, false, false);
|
||||
if (cp_res.success()) return 1;
|
||||
|
||||
// Fallback: C++17 filesystem copy
|
||||
std::error_code ec;
|
||||
fs::copy(src_dir, dst_dir, fs::copy_options::recursive | fs::copy_options::overwrite_existing, ec);
|
||||
return ec ? 0 : 1;
|
||||
}
|
||||
|
||||
// String helpers
|
||||
std::string trim(const std::string& str) {
|
||||
size_t first = str.find_first_not_of(" \t\n\r");
|
||||
if (first == std::string::npos) return "";
|
||||
size_t last = str.find_last_not_of(" \t\n\r");
|
||||
return str.substr(first, (last - first + 1));
|
||||
}
|
||||
|
||||
bool starts_with(const std::string& str, const std::string& prefix) {
|
||||
return str.size() >= prefix.size() && str.compare(0, prefix.size(), prefix) == 0;
|
||||
}
|
||||
|
||||
bool ends_with(const std::string& str, const std::string& suffix) {
|
||||
return str.size() >= suffix.size() && str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
|
||||
}
|
||||
|
||||
std::vector<std::string> split(const std::string& str, char delimiter) {
|
||||
std::vector<std::string> tokens;
|
||||
std::stringstream ss(str);
|
||||
std::string token;
|
||||
while (std::getline(ss, token, delimiter)) {
|
||||
if (!token.empty()) {
|
||||
tokens.push_back(token);
|
||||
}
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
std::string join(const std::vector<std::string>& elements, const std::string& delimiter) {
|
||||
std::string res;
|
||||
for (size_t i = 0; i < elements.size(); ++i) {
|
||||
if (i > 0) res += delimiter;
|
||||
res += elements[i];
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
std::string escape_json(const std::string& s) {
|
||||
std::ostringstream o;
|
||||
for (char c : s) {
|
||||
switch (c) {
|
||||
case '"': o << "\\\""; break;
|
||||
case '\\': o << "\\\\"; break;
|
||||
case '\b': o << "\\b"; break;
|
||||
case '\f': o << "\\f"; break;
|
||||
case '\n': o << "\\n"; break;
|
||||
case '\r': o << "\\r"; break;
|
||||
case '\t': o << "\\t"; break;
|
||||
default:
|
||||
if (static_cast<unsigned char>(c) <= 0x1f) {
|
||||
o << "\\u" << std::hex << std::setw(4) << std::setfill('0') << static_cast<int>(c);
|
||||
} else {
|
||||
o << c;
|
||||
}
|
||||
}
|
||||
}
|
||||
return o.str();
|
||||
}
|
||||
|
||||
std::string format_size(std::uint64_t bytes) {
|
||||
constexpr double KB = 1024.0;
|
||||
constexpr double MB = KB * 1024.0;
|
||||
constexpr double GB = MB * 1024.0;
|
||||
constexpr double TB = GB * 1024.0;
|
||||
|
||||
std::ostringstream ss;
|
||||
ss << std::fixed << std::setprecision(1);
|
||||
|
||||
if (bytes >= TB) {
|
||||
ss << (bytes / TB) << " TB";
|
||||
} else if (bytes >= GB) {
|
||||
ss << (bytes / GB) << " GB";
|
||||
} else if (bytes >= MB) {
|
||||
ss << (bytes / MB) << " MB";
|
||||
} else if (bytes >= KB) {
|
||||
ss << (bytes / KB) << " KB";
|
||||
} else {
|
||||
ss << bytes << " B";
|
||||
}
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
// CLI Parsing
|
||||
CliOptions parse_cli_args(int argc, char* argv[]) {
|
||||
CliOptions opt;
|
||||
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
std::string arg = argv[i];
|
||||
|
||||
if (arg == "--auto" || arg == "-a") {
|
||||
opt.auto_mode = true;
|
||||
} else if (arg == "--disk" || arg == "-d") {
|
||||
if (i + 1 < argc) {
|
||||
opt.disk = argv[++i];
|
||||
} else {
|
||||
die("Brak sciezki dysku po fladze --disk");
|
||||
}
|
||||
} else if (arg == "--hostname" || arg == "-n") {
|
||||
if (i + 1 < argc) {
|
||||
opt.hostname = argv[++i];
|
||||
} else {
|
||||
die("Brak nazwy hosta po fladze --hostname");
|
||||
}
|
||||
} else if (arg == "--password" || arg == "-p") {
|
||||
if (i + 1 < argc) {
|
||||
opt.password = argv[++i];
|
||||
} else {
|
||||
die("Brak hasla po fladze --password");
|
||||
}
|
||||
} else if (arg == "--mode" || arg == "-m") {
|
||||
if (i + 1 < argc) {
|
||||
opt.mode_str = argv[++i];
|
||||
std::transform(opt.mode_str.begin(), opt.mode_str.end(), opt.mode_str.begin(), ::tolower);
|
||||
} else {
|
||||
die("Brak trybu rozruchu po fladze --mode (dozwolone: uefi, bios, auto)");
|
||||
}
|
||||
} else if (arg == "--dry-run") {
|
||||
opt.dry_run = true;
|
||||
} else if (arg == "--json") {
|
||||
opt.json_output = true;
|
||||
set_colors_enabled(false);
|
||||
} else if (arg == "--source" || arg == "-s") {
|
||||
if (i + 1 < argc) {
|
||||
opt.source_dir = argv[++i];
|
||||
} else {
|
||||
die("Brak sciezki zrodlowej po fladze --source");
|
||||
}
|
||||
} else if (arg == "--list-disks" || arg == "-l") {
|
||||
opt.list_disks = true;
|
||||
} else if (arg == "--help" || arg == "-h") {
|
||||
opt.help = true;
|
||||
} else if (arg == "--version" || arg == "-v") {
|
||||
opt.version = true;
|
||||
} else {
|
||||
warn("Nieznana opcja: " + arg);
|
||||
}
|
||||
}
|
||||
|
||||
return opt;
|
||||
}
|
||||
|
||||
void print_banner() {
|
||||
if (!g_colors_enabled) {
|
||||
std::cout <<
|
||||
R"( ╔══════════════════════════════════════════════════════════════╗
|
||||
║ ║
|
||||
║ ╦ ╦╦ ╔═╗╔═╗╔╗╔╦ ╦╔═╗╔═╗ INSTALATOR SYSTEMU ║
|
||||
║ ║║║║ ╠═╣╚═╗║║║╚╦╝║ ║╚═╗ KhOS ║
|
||||
║ ╚╩╝╩═╝╩ ╩╚═╝╝╚╝ ╩ ╚═╝╚═╝ v1.1 (Genesis C++ Edition) ║
|
||||
║ ║
|
||||
║ Witaj w nowoczesnym instalatorze systemu KhOS! ║
|
||||
║ Ten program zainstaluje system na dysku Twojego komputera. ║
|
||||
╚══════════════════════════════════════════════════════════════╝
|
||||
)";
|
||||
return;
|
||||
}
|
||||
|
||||
std::cout << colors::CYAN <<
|
||||
R"( ╔══════════════════════════════════════════════════════════════╗
|
||||
║ ║
|
||||
║ ╦ ╦╦ ╔═╗╔═╗╔╗╔╦ ╦╔═╗╔═╗ INSTALATOR SYSTEMU ║
|
||||
║ ║║║║ ╠═╣╚═╗║║║╚╦╝║ ║╚═╗ )" << colors::BOLD << colors::WHITE << "KhOS" << colors::RESET << colors::CYAN << R"( ║
|
||||
║ ╚╩╝╩═╝╩ ╩╚═╝╝╚╝ ╩ ╚═╝╚═╝ )" << colors::YELLOW << "v1.1 (Genesis C++ Edition)" << colors::CYAN << R"( ║
|
||||
║ ║
|
||||
║ )" << colors::GREEN << "Witaj w nowoczesnym instalatorze systemu KhOS!" << colors::CYAN << R"( ║
|
||||
║ Ten program zainstaluje system na dysku Twojego komputera. ║
|
||||
╚══════════════════════════════════════════════════════════════╝)"
|
||||
<< colors::RESET << "\n\n";
|
||||
}
|
||||
|
||||
void print_help(const char* prog_name) {
|
||||
std::cout << "Uzycie: " << prog_name << " [OPCJE]\n\n"
|
||||
<< "Opcje instalatora KhOS:\n"
|
||||
<< " --auto, -a Tryb automatyczny (bez interaktywnych pytan)\n"
|
||||
<< " --disk <sciezka>, -d Docelowy dysk instalacji (np. /dev/sda, /dev/nvme0n1)\n"
|
||||
<< " --hostname <nazwa>, -n Nazwa komputera w sieci (domyslnie: khos)\n"
|
||||
<< " --password <haslo>, -p Haslo dla uzytkownika root (domyslnie: khos)\n"
|
||||
<< " --mode <tryb>, -m Wymuszenie trybu rozruchu: uefi, bios lub auto\n"
|
||||
<< " --source <katalog>, -s Wlasny katalog zrodlowy rootfs systemu\n"
|
||||
<< " --dry-run Symulacja instalacji bez fizycznych zmian na dysku\n"
|
||||
<< " --json Formatowanie wynikow i listowania w formacie JSON\n"
|
||||
<< " --list-disks, -l Wypisz liste dostepnych dyskow i zakoncz\n"
|
||||
<< " --help, -h Wyswietl te pomoc\n"
|
||||
<< " --version, -v Wyswietl informacje o wersji instalatora\n\n"
|
||||
<< "Przyklady:\n"
|
||||
<< " " << prog_name << " --auto --disk /dev/sda --hostname khos-pc --password tajne\n"
|
||||
<< " " << prog_name << " --list-disks --json\n"
|
||||
<< " " << prog_name << " --dry-run --disk /dev/vda --mode uefi\n";
|
||||
}
|
||||
|
||||
} // namespace utils
|
||||
} // namespace khos
|
||||
@@ -0,0 +1,181 @@
|
||||
# KhOS System Installer (Python 3)
|
||||
|
||||
Kompletny, profesjonalny pakiet instalatora systemu operacyjnego **KhOS Linux 1.1 (Genesis)** napisany w języku Python 3.
|
||||
|
||||
Instalator umożliwia instalację systemu KhOS na dyskach twardych (HDD), dyskach półprzewodnikowych (SATA/VirtIO SSD) oraz pamięciach NVMe, oferując zarówno interaktywny kreator terminalowy (CLI), zautomatyzowany tryb nienadzorowany (`--auto`), strumieniowanie zdarzeń JSON dla API/skryptów, jak i nowoczesny interfejs graficzny (GUI) w oparciu o `tkinter` z ciemnym motywem graficznym.
|
||||
|
||||
---
|
||||
|
||||
## 📁 Struktura pakietu
|
||||
|
||||
```text
|
||||
installer/python/
|
||||
├── setup.py # Klasyczny instalator pakietu setuptools
|
||||
├── pyproject.toml # Standard PEP 517 / 621 dla nowoczesnego Pythona
|
||||
├── run-installer.py # Główny punkt wejściowy instalatora CLI
|
||||
├── run-gui.py # Punkt wejściowy instalatora graficznego (GUI)
|
||||
├── khos_installer/
|
||||
│ ├── __init__.py # Eksporty klas, wersji i publicznego API
|
||||
│ ├── types.py # Modele danych, konfiguracje (InstallConfig), enumy (BootMode, DesktopEnvironment)
|
||||
│ ├── disk.py # Wykrywanie dysków, odczyt /sys/block, obsługa blkid, UUID i punktów montowania
|
||||
│ ├── partitioner.py # Tworzenie partycji GPT/MBR (sfdisk, parted, fdisk), formatowanie ext4, vfat, swap
|
||||
│ ├── core.py # Silnik instalacji (walidacja, montowanie, kopiowanie squashfs/live, callbacks)
|
||||
│ ├── config.py # Generowanie /etc/fstab, hostname, hosts, haszowanie haseł SHA-512, tworzenie użytkowników
|
||||
│ ├── bootloader.py # Instalacja GRUB 2.14 (UEFI x86_64, BIOS i386-pc), grub.cfg, rezerwowy EXTLINUX
|
||||
│ ├── cli.py # Interaktywny kreator krok po kroku oraz tryb cichy/automatyczny z paskiem postępu
|
||||
│ ├── gui.py # Nowoczesny interfejs graficzny Tkinter (ciemny motyw Catppuccin, wątek roboczy)
|
||||
│ └── utils.py # Bezpieczny subprocess runner, formatowanie ANSI, structured logger JSON
|
||||
├── tests/
|
||||
│ └── test_installer.py # Kompletny zestaw 22 testów jednostkowych z mockowaniem operacji dyskowych
|
||||
└── README.md # Niniejsza dokumentacja
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Możliwości i architektura
|
||||
|
||||
### 1. Wykrywanie i zarządzanie dyskami (`disk.py`)
|
||||
- Automatyczne wykrywanie trybu oprogramowania układowego: **UEFI** (`/sys/firmware/efi`) vs **BIOS (Legacy)**.
|
||||
- Inteligentne skanowanie `/sys/block` z odfiltrowaniem urządzeń wirtualnych i optycznych (`sr*`, `loop*`, `ram*`, `dm-*`, `zram*`).
|
||||
- Odczyt rozmiarów sektorowych (512B), modeli dysków (`/sys/block/<dev>/device/model`) oraz typu nośnika (SSD/NVMe vs HDD).
|
||||
- Bezpieczne pobieranie UUID partycji poprzez narzędzie `blkid` oraz symlinki `/dev/disk/by-uuid/`.
|
||||
- Dynamiczne rozwiązywanie ścieżek partycji (np. `/dev/sda` -> `/dev/sda1`, `/dev/nvme0n1` -> `/dev/nvme0n1p1`).
|
||||
- Bezpieczne odmontowywanie partycji dysku przed operacjami zapisu (zabezpieczenie przed omyłkowym odmontowaniem aktywnego `/`).
|
||||
|
||||
### 2. Partycjonowanie i formatowanie (`partitioner.py`)
|
||||
- Skryptowe tworzenie tablic partycji przy użyciu `sfdisk`:
|
||||
- **Tryb UEFI (GPT)**: Partycja ESP (FAT32, domyślnie 512MB, GUID `c12a7328-f81f-11d2-ba4b-00a0c93ec93b`), opcjonalna partycja wymiany Swap, partycja główna Root (EXT4, GUID `4f68bce3-e8cd-4db1-96e7-fbcaf984b709`).
|
||||
- **Tryb BIOS (MBR / DOS)**: Główna partycja rozruchowa (typ 83, flaga bootable), opcjonalny Swap.
|
||||
- Kaskadowe mechanizmy rezerwowe: w przypadku braku `sfdisk`, instalator automatycznie używa `parted`, a następnie skryptów `fdisk`.
|
||||
- Bezpieczne czyszczenie sygnatur: zerowanie pierwszych 10MB oraz sektorów rezerwowego nagłówka GPT na końcu nośnika.
|
||||
- Formatowanie: `mkfs.ext4 -F -L KHOS` dla partycji systemowej oraz `mkfs.vfat -F32` dla partycji EFI.
|
||||
|
||||
### 3. Silnik instalacyjny (`core.py`)
|
||||
- Pipeline podzielony na 8 logicznych etapów:
|
||||
1. **Walidacja** (uprawnienia root, poprawność parametrów, rozmiar dysku).
|
||||
2. **Partycjonowanie** (odmontowanie, wyczyszczenie, utworzenie partycji).
|
||||
3. **Formatowanie** (przygotowanie systemów plików).
|
||||
4. **Montowanie** (`/mnt/install_target` oraz `/boot/efi`).
|
||||
5. **Kopiowanie** (automatyczna detekcja obrazu SquashFS `/mnt/cdrom/live/filesystem.squashfs`, rozpakowanego `/mnt/squashfs` lub bieżącego środowiska na żywo, kopiowanie jądra `vmlinuz` i `initramfs.img`).
|
||||
6. **Konfiguracja** (generowanie plików systemowych, haszowanie haseł, konta użytkowników, uprawnienia).
|
||||
7. **Bootloader** (instalacja GRUB/EXTLINUX i generowanie menu).
|
||||
8. **Finalizacja** (`sync`, bezpieczne odmontowanie rekursywne `umount -R`).
|
||||
- Wzorzec subskrypcji zdarzeń (`ProgressCallback`) umożliwiający raportowanie w czasie rzeczywistym do CLI i GUI.
|
||||
- Pełna obsługa trybu symulacji (`dry_run=True`), pozwalająca na bezpieczne testy bez ryzyka uszkodzenia danych.
|
||||
|
||||
### 4. Konfiguracja systemu (`config.py`)
|
||||
- Generowanie `/etc/fstab` w oparciu o trwałe identyfikatory `UUID=...` dla partycji Root i EFI oraz standardowych systemów wirtualnych (`proc`, `sysfs`, `devtmpfs`, `devpts`, `tmpfs`).
|
||||
- Konfiguracja `/etc/hostname` i `/etc/hosts` (w tym obsługa IPv4 i IPv6 localhost).
|
||||
- Bezpieczne haszowanie haseł zgodnie ze standardem Unix SHA-512 crypt (`$6$<salt>$<hash>`) z implementacją fallbacku.
|
||||
- Obsługa tworzenia zwykłego użytkownika wraz z przydziałem grup (`wheel`, `sudo`, `audio`, `video`, `input`).
|
||||
- Automatyczne nadawanie uprawnień wykonywalnych (`chmod +x`) dla launcherów pulpitów (`start-xfce`, `start-plasma`, `start-hyprland`, `start-openbox`) oraz bitów SUID (`chmod 4755`) dla `seatd-launch`, `Xorg` i `busybox`.
|
||||
|
||||
### 5. Program rozruchowy (`bootloader.py`)
|
||||
- **GRUB UEFI (x86_64-efi)**: Instalacja z flagami `--removable --recheck` na partycji EFI, a także automatyczne kopiowanie zapasowego `BOOTX64.EFI` z nośnika Live.
|
||||
- **GRUB BIOS (i386-pc)**: Instalacja w sektorze MBR z modułami `part_msdos ext2 biosdisk`.
|
||||
- **Rezerwowy EXTLINUX**: W przypadku braku instalatora GRUB, system automatycznie zapisuje kod `mbr.bin` syslinuxa i konfiguruje `extlinux.conf`.
|
||||
- Menu rozruchowe `grub.cfg`:
|
||||
- Wpis dla wybranego środowiska graficznego (XFCE 4, KDE Plasma, Hyprland, Openbox).
|
||||
- Wpisy dla pozostałych zainstalowanych środowisk.
|
||||
- Wpis trybu awaryjnego (debug, verbose, loglevel 7).
|
||||
- Wpisy szybkiego restartu i wyłączenia zasilania komputera.
|
||||
|
||||
### 6. Interfejsy użytkownika:
|
||||
- **CLI (`cli.py`)**:
|
||||
- Kolorowy baner ASCII KhOS.
|
||||
- Interaktywny asystent krok po kroku z walidacją wejścia.
|
||||
- Dynamiczny pasek postępu renderowany w terminalu.
|
||||
- Pełny tryb nienadzorowany: `khos-installer --auto --disk /dev/sda --root-password haslo --hostname khos-pc`.
|
||||
- Strumień zdarzeń maszynowych JSON: flaga `--json` generuje linie JSON na standardowe wyjście.
|
||||
- **GUI (`gui.py`)**:
|
||||
- Nowoczesna paleta kolorystyczna Catppuccin Mocha (`#1e1e2e`, `#89b4fa`, `#cdd6f4`).
|
||||
- Asystent wieloetapowy (Wybór dysku -> Konfiguracja kont -> Ostrzeżenie -> Postęp -> Sukces).
|
||||
- Wykonywanie instalacji w osobnym wątku (`threading.Thread`) - brak zawieszania się okna podczas kopiowania.
|
||||
- Podgląd logów w czasie rzeczywistym w oknie konsoli.
|
||||
- Bezpieczne wyjście w przypadku braku środowiska X11/Wayland z sugestią użycia CLI.
|
||||
|
||||
---
|
||||
|
||||
## 💻 Instrukcja uruchamiania
|
||||
|
||||
### Wymagania
|
||||
- Python 3.8 lub nowszy (testowany na Python 3.8 - 3.14).
|
||||
- Uprawnienia administratora (`root` / `sudo`) w celu modyfikacji dysków blokowych (chyba że używana jest flaga `--dry-run`).
|
||||
- Standardowe narzędzia jądra Linux w środowisku docelowym: `sfdisk`/`parted`/`fdisk`, `mkfs.ext4`, `mkfs.vfat`, `blkid`.
|
||||
|
||||
### 1. Interaktywny kreator CLI
|
||||
```bash
|
||||
# Bezpośrednie uruchomienie
|
||||
sudo python3 run-installer.py
|
||||
|
||||
# Lub w trybie testowym (bezpieczna symulacja)
|
||||
python3 run-installer.py --dry-run
|
||||
```
|
||||
|
||||
### 2. Tryb automatyczny (nienadzorowany / unattended)
|
||||
```bash
|
||||
# Czysta instalacja na dysku /dev/sda
|
||||
sudo python3 run-installer.py --auto \
|
||||
--disk /dev/sda \
|
||||
--hostname moj-komputer \
|
||||
--root-password tajnehaslo \
|
||||
--desktop plasma
|
||||
|
||||
# Z opcjonalnym kontem użytkownika i partycją swap
|
||||
sudo python3 run-installer.py --auto \
|
||||
--disk /dev/nvme0n1 \
|
||||
--hostname stacja-khos \
|
||||
--root-password rootsecret \
|
||||
--user bartosz \
|
||||
--user-password usersecret \
|
||||
--desktop hyprland \
|
||||
--swap-size 4096
|
||||
```
|
||||
|
||||
### 3. Strumieniowanie JSON (do integracji z API / skryptami zewnętrznymi)
|
||||
```bash
|
||||
sudo python3 run-installer.py --auto --disk /dev/sda --json
|
||||
```
|
||||
Przykładowy strumień wyjściowy:
|
||||
```json
|
||||
{"event_type": "stage", "percent": 10, "stage": "Partycjonowanie", "message": "Przygotowanie dysku /dev/sda...", "details": {}}
|
||||
{"event_type": "stage", "percent": 25, "stage": "Formatowanie", "message": "Formatowanie partycji systemowych...", "details": {}}
|
||||
{"event_type": "stage", "percent": 45, "stage": "Kopiowanie", "message": "Kopiowanie plików systemu...", "details": {}}
|
||||
{"event_type": "completed", "percent": 100, "stage": "Zakończono", "message": "Sukces!", "details": {"target_disk": "/dev/sda"}}
|
||||
```
|
||||
|
||||
### 4. Interfejs graficzny (GUI)
|
||||
W środowisku z uruchomionym serwerem X11 lub Wayland (np. po starcie pulpitu Openbox lub XFCE):
|
||||
```bash
|
||||
sudo python3 run-gui.py
|
||||
|
||||
# Symulacja GUI:
|
||||
python3 run-gui.py --dry-run
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🧪 Uruchamianie testów jednostkowych
|
||||
|
||||
Wszystkie moduły objęte są testami jednostkowymi weryfikującymi parsowanie dysków, wyliczanie partycji, generowanie `grub.cfg`, `fstab`, haszowanie haseł i przejście całego potoku w trybie dry-run.
|
||||
|
||||
Uruchomienie testów:
|
||||
```bash
|
||||
python3 -m unittest discover -s tests -p "test_*.py"
|
||||
```
|
||||
Lub za pomocą menedżera `uv`:
|
||||
```bash
|
||||
uv run python -m unittest discover -s tests -p "test_*.py"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📦 Instalacja w systemie KhOS
|
||||
|
||||
Instalator może zostać zainstalowany jako globalny pakiet w systemie:
|
||||
```bash
|
||||
pip install .
|
||||
```
|
||||
Po instalacji w systemie dostępne są bezpośrednie polecenia:
|
||||
- `khos-installer`
|
||||
- `khos-installer-gui`
|
||||
@@ -0,0 +1,30 @@
|
||||
"""KhOS System Installer package.
|
||||
|
||||
A modern, robust installation engine and user interface for KhOS.
|
||||
Supports both UEFI and BIOS, multiple desktop environments (XFCE, KDE Plasma, Hyprland, Openbox),
|
||||
GPT and MBR partitioning, CLI interactive/automated modes, and Tkinter GUI.
|
||||
"""
|
||||
|
||||
from .core import InstallerCore, ProgressCallback, ProgressEvent
|
||||
from .disk import BootMode, DiskInfo, DiskManager, PartitionInfo, detect_boot_mode
|
||||
from .partitioner import Partitioner, TargetPartitions
|
||||
from .types import DesktopEnvironment, InstallConfig
|
||||
|
||||
__version__ = "1.1.0"
|
||||
__author__ = "KhOS Team"
|
||||
|
||||
__all__ = [
|
||||
"InstallerCore",
|
||||
"InstallConfig",
|
||||
"BootMode",
|
||||
"DesktopEnvironment",
|
||||
"DiskInfo",
|
||||
"PartitionInfo",
|
||||
"TargetPartitions",
|
||||
"DiskManager",
|
||||
"Partitioner",
|
||||
"ProgressCallback",
|
||||
"ProgressEvent",
|
||||
"detect_boot_mode",
|
||||
"__version__",
|
||||
]
|
||||
@@ -0,0 +1,305 @@
|
||||
"""Bootloader installation and configuration for GRUB (UEFI & BIOS) and EXTLINUX."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import glob
|
||||
import os
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
from typing import Callable, Optional
|
||||
|
||||
from .types import BootMode, DesktopEnvironment, TargetPartitions
|
||||
from .utils import err, info, ok, run_cmd, warn, which
|
||||
|
||||
|
||||
def generate_grub_config(
|
||||
targets: TargetPartitions,
|
||||
default_desktop: DesktopEnvironment = DesktopEnvironment.XFCE,
|
||||
) -> str:
|
||||
"""Generate grub.cfg bootloader menu."""
|
||||
if targets.root_uuid:
|
||||
root_param = f"root=UUID={targets.root_uuid}"
|
||||
else:
|
||||
root_param = f"root={targets.root_part}"
|
||||
|
||||
lines = [
|
||||
"# grub.cfg - Generated by KhOS System Installer",
|
||||
"set timeout=5",
|
||||
"set default=0",
|
||||
"",
|
||||
"terminal_input console",
|
||||
"terminal_output console",
|
||||
"",
|
||||
]
|
||||
|
||||
# Menu entries
|
||||
# 1. Default desktop entry
|
||||
lines.extend([
|
||||
f'menuentry "KhOS 1.1 ({default_desktop.display_name})" {{',
|
||||
f" linux /boot/vmlinuz {root_param} desktop={default_desktop.value} rw quiet",
|
||||
" initrd /boot/initramfs.img",
|
||||
"}",
|
||||
"",
|
||||
])
|
||||
|
||||
# 2. XFCE (if not default)
|
||||
if default_desktop != DesktopEnvironment.XFCE:
|
||||
lines.extend([
|
||||
'menuentry "KhOS 1.1 (Pulpit XFCE 4)" {',
|
||||
f" linux /boot/vmlinuz {root_param} desktop=xfce rw quiet",
|
||||
" initrd /boot/initramfs.img",
|
||||
"}",
|
||||
"",
|
||||
])
|
||||
|
||||
# 3. KDE Plasma (if not default)
|
||||
if default_desktop != DesktopEnvironment.PLASMA:
|
||||
lines.extend([
|
||||
'menuentry "KhOS 1.1 (Pulpit KDE Plasma)" {',
|
||||
f" linux /boot/vmlinuz {root_param} desktop=plasma rw quiet",
|
||||
" initrd /boot/initramfs.img",
|
||||
"}",
|
||||
"",
|
||||
])
|
||||
|
||||
# 4. Hyprland Wayland (if not default)
|
||||
if default_desktop != DesktopEnvironment.HYPRLAND:
|
||||
lines.extend([
|
||||
'menuentry "KhOS 1.1 (Hyprland Wayland)" {',
|
||||
f" linux /boot/vmlinuz {root_param} desktop=hyprland rw quiet",
|
||||
" initrd /boot/initramfs.img",
|
||||
"}",
|
||||
"",
|
||||
])
|
||||
|
||||
# 5. Openbox (if not default)
|
||||
if default_desktop != DesktopEnvironment.OPENBOX:
|
||||
lines.extend([
|
||||
'menuentry "KhOS 1.1 (Openbox Minimal X11)" {',
|
||||
f" linux /boot/vmlinuz {root_param} desktop=openbox rw quiet",
|
||||
" initrd /boot/initramfs.img",
|
||||
"}",
|
||||
"",
|
||||
])
|
||||
|
||||
# 6. Safe mode / verbose
|
||||
lines.extend([
|
||||
'menuentry "KhOS 1.1 (Tryb awaryjny - Verbose & Debug)" {',
|
||||
f" linux /boot/vmlinuz {root_param} rw textmode debug loglevel=7",
|
||||
" initrd /boot/initramfs.img",
|
||||
"}",
|
||||
"",
|
||||
'menuentry "Uruchom ponownie (Reboot)" {',
|
||||
" reboot",
|
||||
"}",
|
||||
"",
|
||||
'menuentry "Wylacz komputer (Poweroff)" {',
|
||||
" halt",
|
||||
"}",
|
||||
"",
|
||||
])
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def generate_extlinux_config(
|
||||
targets: TargetPartitions,
|
||||
default_desktop: DesktopEnvironment = DesktopEnvironment.XFCE,
|
||||
) -> str:
|
||||
"""Generate extlinux.conf for syslinux/extlinux fallback bootloader."""
|
||||
if targets.root_uuid:
|
||||
root_param = f"root=UUID={targets.root_uuid}"
|
||||
else:
|
||||
root_param = f"root={targets.root_part}"
|
||||
|
||||
lines = [
|
||||
"# extlinux.conf - Generated by KhOS System Installer",
|
||||
"DEFAULT default_os",
|
||||
"PROMPT 1",
|
||||
"TIMEOUT 50",
|
||||
"",
|
||||
"LABEL default_os",
|
||||
f" MENU LABEL KhOS 1.1 ({default_desktop.value})",
|
||||
" LINUX /boot/vmlinuz",
|
||||
" INITRD /boot/initramfs.img",
|
||||
f" APPEND {root_param} desktop={default_desktop.value} rw quiet",
|
||||
"",
|
||||
"LABEL textmode",
|
||||
" MENU LABEL KhOS 1.1 (Tryb tekstowy / Debug)",
|
||||
" LINUX /boot/vmlinuz",
|
||||
" INITRD /boot/initramfs.img",
|
||||
f" APPEND {root_param} rw textmode debug",
|
||||
"",
|
||||
]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
class BootloaderInstaller:
|
||||
"""Handles installation of GRUB UEFI / BIOS bootloader and fallback syslinux/extlinux."""
|
||||
|
||||
def __init__(self, target_root: str, dry_run: bool = False, log_func: Optional[Callable[[str], None]] = None):
|
||||
self.target_root = Path(target_root)
|
||||
self.dry_run = dry_run
|
||||
self.log_func = log_func
|
||||
|
||||
def _log(self, text: str) -> None:
|
||||
if self.log_func:
|
||||
self.log_func(text)
|
||||
|
||||
def install(
|
||||
self,
|
||||
targets: TargetPartitions,
|
||||
boot_mode: BootMode,
|
||||
default_desktop: DesktopEnvironment = DesktopEnvironment.XFCE,
|
||||
) -> bool:
|
||||
"""Install bootloader onto target disk and generate configuration menus."""
|
||||
grub_cfg = generate_grub_config(targets, default_desktop)
|
||||
grub_dir = self.target_root / "boot" / "grub"
|
||||
|
||||
if not self.dry_run:
|
||||
grub_dir.mkdir(parents=True, exist_ok=True)
|
||||
(grub_dir / "grub.cfg").write_text(grub_cfg, encoding="utf-8")
|
||||
self._log(f"Wrote GRUB configuration: {grub_dir / 'grub.cfg'}")
|
||||
|
||||
bootloader_installed = False
|
||||
|
||||
if boot_mode == BootMode.UEFI:
|
||||
bootloader_installed = self._install_grub_uefi(targets, grub_cfg)
|
||||
else:
|
||||
bootloader_installed = self._install_grub_bios(targets, grub_cfg, default_desktop)
|
||||
|
||||
return bootloader_installed
|
||||
|
||||
def _install_grub_uefi(self, targets: TargetPartitions, grub_cfg: str) -> bool:
|
||||
"""Install GRUB x86_64-efi."""
|
||||
self._log("Installing GRUB (UEFI x86_64)...")
|
||||
boot_dir = str(self.target_root / "boot")
|
||||
efi_dir = str(self.target_root / "boot" / "efi")
|
||||
|
||||
success = False
|
||||
if which("grub-install"):
|
||||
cmd = [
|
||||
"grub-install",
|
||||
"--target=x86_64-efi",
|
||||
f"--boot-directory={boot_dir}",
|
||||
f"--efi-directory={efi_dir}",
|
||||
"--removable",
|
||||
"--recheck",
|
||||
]
|
||||
res = run_cmd(cmd, check=False, dry_run=self.dry_run, log_func=self.log_func)
|
||||
if res.success:
|
||||
success = True
|
||||
|
||||
# Fallback: Copy pre-built BOOTX64.EFI from live medium or system files
|
||||
efi_boot_dir = self.target_root / "boot" / "efi" / "EFI" / "BOOT"
|
||||
efi_khos_dir = self.target_root / "boot" / "efi" / "EFI" / "khos"
|
||||
if not self.dry_run:
|
||||
efi_boot_dir.mkdir(parents=True, exist_ok=True)
|
||||
efi_khos_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
live_efi_sources = [
|
||||
Path("/mnt/cdrom/EFI/BOOT/BOOTX64.EFI"),
|
||||
Path("/boot/efi/EFI/BOOT/BOOTX64.EFI"),
|
||||
Path("/usr/lib/grub/x86_64-efi/monolithic/grubx64.efi"),
|
||||
]
|
||||
for src in live_efi_sources:
|
||||
if src.exists() and not self.dry_run:
|
||||
try:
|
||||
shutil.copy2(src, efi_boot_dir / "BOOTX64.EFI")
|
||||
shutil.copy2(src, efi_khos_dir / "grubx64.efi")
|
||||
self._log(f"Copied standalone UEFI binary from {src}")
|
||||
success = True
|
||||
break
|
||||
except OSError as e:
|
||||
self._log(f"Failed to copy EFI binary: {e}")
|
||||
|
||||
# Also copy grub.cfg to EFI partition directory
|
||||
efi_grub_cfg = self.target_root / "boot" / "efi" / "boot" / "grub" / "grub.cfg"
|
||||
if not self.dry_run:
|
||||
efi_grub_cfg.parent.mkdir(parents=True, exist_ok=True)
|
||||
efi_grub_cfg.write_text(grub_cfg, encoding="utf-8")
|
||||
|
||||
return success or self.dry_run
|
||||
|
||||
def _install_grub_bios(
|
||||
self,
|
||||
targets: TargetPartitions,
|
||||
grub_cfg: str,
|
||||
default_desktop: DesktopEnvironment,
|
||||
) -> bool:
|
||||
"""Install GRUB i386-pc or fallback EXTLINUX."""
|
||||
self._log(f"Installing GRUB (BIOS i386-pc) onto {targets.disk_path}...")
|
||||
boot_dir = str(self.target_root / "boot")
|
||||
|
||||
success = False
|
||||
if which("grub-install"):
|
||||
cmd = [
|
||||
"grub-install",
|
||||
"--target=i386-pc",
|
||||
f"--boot-directory={boot_dir}",
|
||||
"--modules=part_msdos ext2 biosdisk",
|
||||
"--recheck",
|
||||
targets.disk_path,
|
||||
]
|
||||
res = run_cmd(cmd, check=False, dry_run=self.dry_run, log_func=self.log_func)
|
||||
if res.success:
|
||||
success = True
|
||||
else:
|
||||
# Try with --force
|
||||
cmd.append("--force")
|
||||
res = run_cmd(cmd, check=False, dry_run=self.dry_run, log_func=self.log_func)
|
||||
if res.success:
|
||||
success = True
|
||||
|
||||
if not success:
|
||||
self._log("GRUB BIOS install failed or unavailable. Falling back to EXTLINUX / syslinux...")
|
||||
success = self._install_extlinux(targets, default_desktop)
|
||||
|
||||
return success or self.dry_run
|
||||
|
||||
def _install_extlinux(self, targets: TargetPartitions, default_desktop: DesktopEnvironment) -> bool:
|
||||
"""Fallback bootloader using syslinux / EXTLINUX."""
|
||||
mbr_candidates = [
|
||||
Path("/usr/share/syslinux/mbr.bin"),
|
||||
Path("/usr/lib/syslinux/mbr.bin"),
|
||||
Path("/usr/lib/syslinux/bios/mbr.bin"),
|
||||
]
|
||||
for mbr in mbr_candidates:
|
||||
if mbr.exists():
|
||||
self._log(f"Writing MBR code from {mbr} to {targets.disk_path}...")
|
||||
run_cmd(
|
||||
["dd", "bs=440", "count=1", "conv=notrunc", f"if={mbr}", f"of={targets.disk_path}"],
|
||||
check=False,
|
||||
dry_run=self.dry_run,
|
||||
log_func=self.log_func,
|
||||
)
|
||||
break
|
||||
|
||||
extlinux_dir = self.target_root / "boot" / "extlinux"
|
||||
if not self.dry_run:
|
||||
extlinux_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Run extlinux installer
|
||||
extlinux_bin = which("extlinux") or "/sbin/extlinux"
|
||||
res = run_cmd([extlinux_bin, "-i", str(extlinux_dir)], check=False, dry_run=self.dry_run, log_func=self.log_func)
|
||||
|
||||
# Copy *.c32 support modules
|
||||
module_dirs = [
|
||||
Path("/usr/share/syslinux"),
|
||||
Path("/usr/lib/syslinux"),
|
||||
Path("/usr/lib/syslinux/modules/bios"),
|
||||
]
|
||||
for mdir in module_dirs:
|
||||
if mdir.exists() and not self.dry_run:
|
||||
for c32_file in mdir.glob("*.c32"):
|
||||
try:
|
||||
shutil.copy2(c32_file, extlinux_dir / c32_file.name)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# Write extlinux.conf
|
||||
conf_content = generate_extlinux_config(targets, default_desktop)
|
||||
if not self.dry_run:
|
||||
(extlinux_dir / "extlinux.conf").write_text(conf_content, encoding="utf-8")
|
||||
|
||||
return res.success or self.dry_run
|
||||
@@ -0,0 +1,315 @@
|
||||
"""Command Line Interface (CLI) for KhOS System Installer.
|
||||
|
||||
Supports interactive step-by-step wizard and fully automated unattended mode (--auto).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import getpass
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from typing import List, Optional
|
||||
|
||||
from .core import InstallerCore
|
||||
from .disk import DiskManager, detect_boot_mode
|
||||
from .types import BootMode, DesktopEnvironment, DiskInfo, InstallConfig, ProgressEvent
|
||||
from .utils import (
|
||||
C_BLUE,
|
||||
C_BOLD,
|
||||
C_CYAN,
|
||||
C_GREEN,
|
||||
C_RED,
|
||||
C_RESET,
|
||||
C_YELLOW,
|
||||
check_root,
|
||||
colorize,
|
||||
err,
|
||||
info,
|
||||
msg,
|
||||
ok,
|
||||
set_color_enabled,
|
||||
warn,
|
||||
)
|
||||
|
||||
BANNER = r"""
|
||||
╔══════════════════════════════════════════════════════════════╗
|
||||
║ ╦ ╦╦ ╔═╗╔═╗╔╗╔╦ ╦╔═╗╔═╗ INSTALATOR SYSTEMU ║
|
||||
║ ║║║║ ╠═╣╚═╗║║║╚╦╝║ ║╚═╗ KhOS ║
|
||||
║ ╚╩╝╩═╝╩ ╩╚═╝╝╚╝ ╩ ╚═╝╚═╝ v1.1 (Genesis) ║
|
||||
║ ║
|
||||
║ Witaj w oficjalnym instalatorze systemu KhOS Linux! ║
|
||||
╚══════════════════════════════════════════════════════════════╝
|
||||
"""
|
||||
|
||||
|
||||
def draw_progress_bar(percent: int, stage: str, width: int = 40) -> None:
|
||||
"""Render an in-terminal animated progress bar."""
|
||||
percent = max(0, min(100, percent))
|
||||
filled = int(width * (percent / 100.0))
|
||||
bar = "█" * filled + "░" * (width - filled)
|
||||
sys.stdout.write(f"\r [{colorize(bar, C_GREEN)}] {percent:3d}% | {stage[:25]:<25}")
|
||||
sys.stdout.flush()
|
||||
if percent >= 100:
|
||||
sys.stdout.write("\n")
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
class CliInstaller:
|
||||
"""CLI orchestrator supporting both interactive and automated modes."""
|
||||
|
||||
def __init__(self, config: InstallConfig):
|
||||
self.config = config
|
||||
self.disk_manager = DiskManager(dry_run=config.dry_run)
|
||||
self.verbose = False
|
||||
|
||||
def handle_event(self, event: ProgressEvent) -> None:
|
||||
"""Receive and display progress events from the core engine."""
|
||||
if self.config.json_output:
|
||||
print(event.to_json(), flush=True)
|
||||
return
|
||||
|
||||
if event.event_type == "stage":
|
||||
draw_progress_bar(event.percent, event.stage)
|
||||
if self.verbose:
|
||||
info(f"Krok: {event.stage} - {event.message}")
|
||||
elif event.event_type == "progress":
|
||||
draw_progress_bar(event.percent, event.stage or "Instalacja")
|
||||
elif event.event_type == "log":
|
||||
if self.verbose:
|
||||
print(f" {event.message}")
|
||||
elif event.event_type == "completed":
|
||||
draw_progress_bar(100, "Zakończono")
|
||||
print("")
|
||||
self._print_success_summary(event)
|
||||
elif event.event_type == "error":
|
||||
print("")
|
||||
err(f"BŁĄD KRYTYCZNY: {event.message}")
|
||||
|
||||
def _print_success_summary(self, event: ProgressEvent) -> None:
|
||||
"""Display installation completion summary."""
|
||||
target_disk = event.details.get("target_disk", self.config.target_disk)
|
||||
root_part = event.details.get("root_partition", "")
|
||||
boot_mode = event.details.get("boot_mode", self.config.boot_mode.value).upper()
|
||||
elapsed = event.details.get("elapsed_seconds", 0)
|
||||
|
||||
summary_box = f"""
|
||||
╔══════════════════════════════════════════════════════════════╗
|
||||
║ INSTALACJA ZAKOŃCZONA ║
|
||||
╠══════════════════════════════════════════════════════════════╣
|
||||
║ Dysk docelowy: {target_disk:<41} ║
|
||||
║ Partycja główna: {root_part:<41} ║
|
||||
║ Tryb rozruchu: {boot_mode:<41} ║
|
||||
║ Środowisko: {self.config.desktop.value.upper():<41} ║
|
||||
║ Nazwa hosta: {self.config.hostname:<41} ║
|
||||
║ Czas trwania: {f'{elapsed} sekund':<41} ║
|
||||
╚══════════════════════════════════════════════════════════════╝
|
||||
|
||||
Możesz teraz bezpiecznie wyciągnąć nośnik instalacyjny (USB/CD)
|
||||
i uruchomić komputer ponownie poleceniem: reboot
|
||||
"""
|
||||
print(colorize(summary_box, C_GREEN))
|
||||
|
||||
def run_interactive(self) -> int:
|
||||
"""Run the interactive step-by-step CLI wizard."""
|
||||
print(colorize(BANNER, C_CYAN))
|
||||
|
||||
# Check root
|
||||
if not self.config.dry_run and not check_root():
|
||||
err("Ten program musi być uruchomiony z uprawnieniami roota (np. sudo python run-installer.py).")
|
||||
return 1
|
||||
|
||||
# 1. Boot mode detection
|
||||
detected_mode = detect_boot_mode()
|
||||
self.config.boot_mode = detected_mode
|
||||
info(f"Wykryty tryb rozruchu komputera: {colorize(detected_mode.label, C_BOLD)}")
|
||||
|
||||
# 2. Discover available storage devices
|
||||
msg("Wyszukiwanie dysków twardych i SSD...")
|
||||
disks = self.disk_manager.list_disks()
|
||||
if not disks:
|
||||
err("Nie wykryto żadnych dostępnych dysków twardych w systemie!")
|
||||
return 1
|
||||
|
||||
print("\nDostępne urządzenia pamięci masowej:")
|
||||
for idx, d in enumerate(disks, start=1):
|
||||
print(f" {colorize(str(idx), C_BOLD)}) {colorize(d.path, C_BOLD)} - {d.size_gb:.1f} GB ({d.disk_type}) [{d.model}]")
|
||||
for p in d.partitions:
|
||||
print(f" └─ {p.path} ({p.size_human}, {p.fs_type or 'brak fs'})")
|
||||
|
||||
print("")
|
||||
# Select target disk
|
||||
while True:
|
||||
choice = input(colorize("Wybierz numer lub ścieżkę dysku docelowego [1]: ", C_BOLD)).strip()
|
||||
if not choice:
|
||||
selected_disk = disks[0].path
|
||||
break
|
||||
if choice.isdigit():
|
||||
val = int(choice)
|
||||
if 1 <= val <= len(disks):
|
||||
selected_disk = disks[val - 1].path
|
||||
break
|
||||
elif any(d.path == choice for d in disks) or os.path.exists(choice):
|
||||
selected_disk = choice
|
||||
break
|
||||
warn("Nieprawidłowy wybór. Spróbuj ponownie.")
|
||||
|
||||
self.config.target_disk = selected_disk
|
||||
ok(f"Wybrano dysk docelowy: {colorize(selected_disk, C_BOLD)}")
|
||||
|
||||
# 3. Confirmation warning
|
||||
print("")
|
||||
warn(f"UWAGA: Wszystkie dotychczasowe dane na dysku {selected_disk} zostaną BEZPOWROTNIE USUNIĘTE!")
|
||||
confirm = input(f"Czy na pewno chcesz kontynuować? Wpisz {colorize('TAK', C_BOLD)}: ").strip()
|
||||
if confirm != "TAK":
|
||||
info("Instalacja została anulowana przez użytkownika.")
|
||||
return 0
|
||||
|
||||
# 4. Hostname
|
||||
print("")
|
||||
new_host = input(f"Podaj nazwę komputera (hostname) [{self.config.hostname}]: ").strip()
|
||||
if new_host:
|
||||
self.config.hostname = new_host
|
||||
|
||||
# 5. Root password
|
||||
new_pass = getpass.getpass(f"Ustaw hasło dla konta root [domyślnie: {self.config.root_password}]: ").strip()
|
||||
if new_pass:
|
||||
self.config.root_password = new_pass
|
||||
|
||||
# 6. Optional standard user
|
||||
print("")
|
||||
add_user = input("Czy chcesz utworzyć standardowe konto użytkownika? (t/N): ").strip().lower()
|
||||
if add_user in ("t", "tak", "y", "yes"):
|
||||
username = input("Nazwa użytkownika: ").strip()
|
||||
if username:
|
||||
user_pass = getpass.getpass(f"Hasło dla użytkownika {username}: ").strip()
|
||||
self.config.username = username
|
||||
self.config.user_password = user_pass
|
||||
|
||||
# 7. Desktop environment selection
|
||||
print("\nWybierz domyślne środowisko graficzne:")
|
||||
desktops = [
|
||||
DesktopEnvironment.XFCE,
|
||||
DesktopEnvironment.PLASMA,
|
||||
DesktopEnvironment.HYPRLAND,
|
||||
DesktopEnvironment.OPENBOX,
|
||||
]
|
||||
for idx, de in enumerate(desktops, start=1):
|
||||
marker = "*" if de == DesktopEnvironment.XFCE else " "
|
||||
print(f" {idx}) [{marker}] {de.display_name}")
|
||||
|
||||
de_choice = input("\nWybór [1]: ").strip()
|
||||
if de_choice.isdigit() and 1 <= int(de_choice) <= len(desktops):
|
||||
self.config.desktop = desktops[int(de_choice) - 1]
|
||||
else:
|
||||
self.config.desktop = DesktopEnvironment.XFCE
|
||||
|
||||
ok(f"Wybrane środowisko: {self.config.desktop.value.upper()}")
|
||||
|
||||
# 8. Start installation
|
||||
print("\n" + "=" * 60)
|
||||
msg(f"Rozpoczynanie instalacji KhOS na dysku {self.config.target_disk}...")
|
||||
print("=" * 60 + "\n")
|
||||
|
||||
core = InstallerCore(self.config, callback=self.handle_event)
|
||||
try:
|
||||
success = core.run()
|
||||
return 0 if success else 1
|
||||
except Exception as e:
|
||||
err(f"Instalacja przerwana z powodu błędu: {e}")
|
||||
return 1
|
||||
|
||||
def run_auto(self) -> int:
|
||||
"""Run non-interactive automated mode using provided configuration."""
|
||||
if not self.config.target_disk:
|
||||
err("W trybie automatycznym (--auto) wymagane jest podanie dysku (--disk /dev/sdX).")
|
||||
return 1
|
||||
|
||||
if not self.config.json_output:
|
||||
msg(f"Uruchamianie nienadzorowanej instalacji KhOS na {self.config.target_disk}...")
|
||||
|
||||
core = InstallerCore(self.config, callback=self.handle_event)
|
||||
try:
|
||||
success = core.run()
|
||||
return 0 if success else 1
|
||||
except Exception as e:
|
||||
if self.config.json_output:
|
||||
print(json.dumps({"type": "error", "message": str(e)}), flush=True)
|
||||
else:
|
||||
err(f"Błąd instalacji automatycznej: {e}")
|
||||
return 1
|
||||
|
||||
|
||||
def build_argument_parser() -> argparse.ArgumentParser:
|
||||
"""Build the command-line argument parser."""
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="khos-installer",
|
||||
description="Oficjalny Instalator Systemu KhOS Linux 1.1 (Genesis)",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
)
|
||||
parser.add_argument("-d", "--disk", help="Ścieżka urządzenia docelowego (np. /dev/sda, /dev/nvme0n1)")
|
||||
parser.add_argument("-m", "--boot-mode", choices=["uefi", "bios", "auto"], default="auto", help="Wymuszenie trybu rozruchu")
|
||||
parser.add_argument("-n", "--hostname", default="khos", help="Nazwa sieciowa komputera")
|
||||
parser.add_argument("-p", "--root-password", default="khos", help="Hasło dla konta root")
|
||||
parser.add_argument("-u", "--user", dest="username", help="Nazwa zwykłego użytkownika do utworzenia")
|
||||
parser.add_argument("--user-password", help="Hasło zwykłego użytkownika")
|
||||
parser.add_argument(
|
||||
"--desktop",
|
||||
choices=["xfce", "plasma", "hyprland", "openbox"],
|
||||
default="xfce",
|
||||
help="Domyślne środowisko graficzne",
|
||||
)
|
||||
parser.add_argument("--efi-size", type=int, default=512, help="Rozmiar partycji EFI w megabajtach (MB)")
|
||||
parser.add_argument("--swap-size", type=int, default=0, help="Rozmiar partycji wymiany (Swap) w MB (0 = wyłączona)")
|
||||
parser.add_argument("--source", dest="source_path", help="Własna ścieżka do obrazu squashfs lub katalogu źródłowego")
|
||||
parser.add_argument("--mount-point", default="/mnt/install_target", help="Katalog montowania instalacji")
|
||||
parser.add_argument("--dry-run", action="store_true", help="Tryb symulacji: testuje proces bez zapisu na dysku")
|
||||
parser.add_argument("--auto", action="store_true", help="Tryb nienadzorowany (bez pytań interaktywnych)")
|
||||
parser.add_argument("--json", action="store_true", help="Formatuj komunikaty i postęp w formacie JSON na stdout")
|
||||
parser.add_argument("--no-color", action="store_true", help="Wyłącz kolory ANSI w terminalu")
|
||||
parser.add_argument("-v", "--verbose", action="store_true", help="Szczegółowe logowanie komunikatów kroków")
|
||||
parser.add_argument("--version", action="version", version="KhOS Installer 1.1.0")
|
||||
|
||||
return parser
|
||||
|
||||
|
||||
def main(argv: Optional[List[str]] = None) -> int:
|
||||
"""CLI Entry point."""
|
||||
parser = build_argument_parser()
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
if args.no_color:
|
||||
set_color_enabled(False)
|
||||
|
||||
boot_mode = detect_boot_mode() if args.boot_mode == "auto" else BootMode(args.boot_mode)
|
||||
desktop = DesktopEnvironment(args.desktop)
|
||||
|
||||
config = InstallConfig(
|
||||
target_disk=args.disk or "",
|
||||
boot_mode=boot_mode,
|
||||
hostname=args.hostname,
|
||||
root_password=args.root_password,
|
||||
username=args.username,
|
||||
user_password=args.user_password,
|
||||
desktop=desktop,
|
||||
efi_size_mb=args.efi_size,
|
||||
swap_size_mb=args.swap_size,
|
||||
source_path=args.source_path,
|
||||
mount_point=args.mount_point,
|
||||
dry_run=args.dry_run,
|
||||
json_output=args.json,
|
||||
auto_mode=args.auto,
|
||||
)
|
||||
|
||||
cli = CliInstaller(config)
|
||||
cli.verbose = args.verbose
|
||||
|
||||
if args.auto:
|
||||
return cli.run_auto()
|
||||
return cli.run_interactive()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,416 @@
|
||||
"""System configuration generator: fstab, hostname, hosts, user management, and permissions."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import os
|
||||
import secrets
|
||||
import string
|
||||
from pathlib import Path
|
||||
from typing import Callable, Optional
|
||||
|
||||
from .types import DesktopEnvironment, InstallConfig, TargetPartitions
|
||||
from .utils import run_cmd, which
|
||||
|
||||
|
||||
def generate_fstab(targets: TargetPartitions) -> str:
|
||||
"""Generate /etc/fstab content using UUIDs when available, falling back to device paths."""
|
||||
lines = [
|
||||
"# /etc/fstab - KhOS Linux",
|
||||
"# Created by KhOS System Installer",
|
||||
"# <device/UUID> <mount point> <type> <options> <dump> <pass>",
|
||||
]
|
||||
|
||||
# Root mount
|
||||
if targets.root_uuid:
|
||||
root_spec = f"UUID={targets.root_uuid}"
|
||||
else:
|
||||
root_spec = targets.root_part
|
||||
lines.append(f"{root_spec:<38} / ext4 defaults,noatime 0 1")
|
||||
|
||||
# EFI mount
|
||||
if targets.efi_part:
|
||||
if targets.efi_uuid:
|
||||
efi_spec = f"UUID={targets.efi_uuid}"
|
||||
else:
|
||||
efi_spec = targets.efi_part
|
||||
lines.append(f"{efi_spec:<38} /boot/efi vfat defaults,umask=0077 0 2")
|
||||
|
||||
# Swap mount
|
||||
if targets.swap_part:
|
||||
swap_spec = targets.swap_part
|
||||
lines.append(f"{swap_spec:<38} none swap sw 0 0")
|
||||
|
||||
# Virtual filesystems
|
||||
lines.extend([
|
||||
f"{'proc':<38} /proc proc defaults 0 0",
|
||||
f"{'sysfs':<38} /sys sysfs defaults 0 0",
|
||||
f"{'devtmpfs':<38} /dev devtmpfs defaults 0 0",
|
||||
f"{'devpts':<38} /dev/pts devpts defaults,gid=5,mode=620,nosuid,noexec 0 0",
|
||||
f"{'tmpfs':<38} /dev/shm tmpfs defaults,nosuid,nodev,noexec 0 0",
|
||||
f"{'tmpfs':<38} /tmp tmpfs defaults,nosuid,nodev 0 0",
|
||||
f"{'tmpfs':<38} /run tmpfs defaults,nosuid,nodev,mode=0755 0 0",
|
||||
])
|
||||
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def generate_hostname(hostname: str) -> str:
|
||||
"""Generate /etc/hostname file content."""
|
||||
clean_host = hostname.strip() or "khos"
|
||||
return f"{clean_host}\n"
|
||||
|
||||
|
||||
def generate_hosts(hostname: str) -> str:
|
||||
"""Generate /etc/hosts file content."""
|
||||
clean_host = hostname.strip() or "khos"
|
||||
return (
|
||||
"# /etc/hosts - KhOS Linux\n"
|
||||
f"127.0.0.1 localhost {clean_host}\n"
|
||||
"::1 localhost ip6-localhost ip6-loopback\n"
|
||||
)
|
||||
|
||||
|
||||
def hash_password_sha512(password: str) -> str:
|
||||
"""Generate standard Unix SHA-512 shadow password hash ($6$...)."""
|
||||
# 1. Try openssl passwd -6 if available
|
||||
if which("openssl"):
|
||||
res = run_cmd(["openssl", "passwd", "-6", "-salt", secrets.token_hex(8), password], check=False)
|
||||
if res.success and res.stdout.strip().startswith("$6$"):
|
||||
return res.stdout.strip()
|
||||
|
||||
# 2. Try crypt module if available
|
||||
try:
|
||||
import crypt # type: ignore
|
||||
salt = crypt.mksalt(crypt.METHOD_SHA512)
|
||||
return crypt.crypt(password, salt)
|
||||
except (ImportError, AttributeError):
|
||||
pass
|
||||
|
||||
# 3. Fallback: Unix sha512_crypt algorithm implementation
|
||||
salt = "".join(secrets.choice(string.ascii_letters + string.digits) for _ in range(16))
|
||||
return _sha512_crypt(password, salt)
|
||||
|
||||
|
||||
def _sha512_crypt(password: str, salt: str, rounds: int = 5000) -> str:
|
||||
"""Pure-Python implementation of Unix crypt SHA-512 ($6$) standard."""
|
||||
b_pass = password.encode("utf-8")
|
||||
b_salt = salt[:16].encode("utf-8")
|
||||
|
||||
ctx_b = hashlib.sha512()
|
||||
ctx_b.update(b_pass)
|
||||
ctx_b.update(b_salt)
|
||||
ctx_b.update(b_pass)
|
||||
digest_b = ctx_b.digest()
|
||||
|
||||
ctx_a = hashlib.sha512()
|
||||
ctx_a.update(b_pass)
|
||||
ctx_a.update(b_salt)
|
||||
|
||||
cnt = len(b_pass)
|
||||
while cnt > 64:
|
||||
ctx_a.update(digest_b)
|
||||
cnt -= 64
|
||||
ctx_a.update(digest_b[:cnt])
|
||||
|
||||
cnt = len(b_pass)
|
||||
while cnt > 0:
|
||||
if cnt & 1:
|
||||
ctx_a.update(digest_b)
|
||||
else:
|
||||
ctx_a.update(b_pass)
|
||||
cnt >>= 1
|
||||
digest_a = ctx_a.digest()
|
||||
|
||||
ctx_dp = hashlib.sha512()
|
||||
for _ in range(len(b_pass)):
|
||||
ctx_dp.update(b_pass)
|
||||
digest_dp = ctx_dp.digest()
|
||||
|
||||
p_seq = bytearray()
|
||||
cnt = len(b_pass)
|
||||
while cnt > 64:
|
||||
p_seq.extend(digest_dp)
|
||||
cnt -= 64
|
||||
p_seq.extend(digest_dp[:cnt])
|
||||
|
||||
ctx_ds = hashlib.sha512()
|
||||
for _ in range(16 + digest_a[0]):
|
||||
ctx_ds.update(b_salt)
|
||||
digest_ds = ctx_ds.digest()
|
||||
|
||||
s_seq = bytearray()
|
||||
cnt = len(b_salt)
|
||||
while cnt > 64:
|
||||
s_seq.extend(digest_ds)
|
||||
cnt -= 64
|
||||
s_seq.extend(digest_ds[:cnt])
|
||||
|
||||
cur = digest_a
|
||||
for i in range(rounds):
|
||||
ctx = hashlib.sha512()
|
||||
if i & 1:
|
||||
ctx.update(p_seq)
|
||||
else:
|
||||
ctx.update(cur)
|
||||
if i % 3:
|
||||
ctx.update(s_seq)
|
||||
if i % 7:
|
||||
ctx.update(p_seq)
|
||||
if i & 1:
|
||||
ctx.update(cur)
|
||||
else:
|
||||
ctx.update(p_seq)
|
||||
cur = ctx.digest()
|
||||
|
||||
# B64 encoding with crypt custom alphabet
|
||||
b64_chars = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
|
||||
|
||||
def b64_from_24bit(b2: int, b1: int, b0: int, n: int) -> str:
|
||||
w = (b2 << 16) | (b1 << 8) | b0
|
||||
res_str = ""
|
||||
while n > 0:
|
||||
res_str += b64_chars[w & 0x3F]
|
||||
w >>= 6
|
||||
n -= 1
|
||||
return res_str
|
||||
|
||||
result = "$6$" + salt + "$"
|
||||
result += b64_from_24bit(cur[0], cur[21], cur[42], 4)
|
||||
result += b64_from_24bit(cur[22], cur[43], cur[1], 4)
|
||||
result += b64_from_24bit(cur[44], cur[2], cur[23], 4)
|
||||
result += b64_from_24bit(cur[3], cur[24], cur[45], 4)
|
||||
result += b64_from_24bit(cur[25], cur[46], cur[4], 4)
|
||||
result += b64_from_24bit(cur[47], cur[5], cur[26], 4)
|
||||
result += b64_from_24bit(cur[6], cur[27], cur[48], 4)
|
||||
result += b64_from_24bit(cur[28], cur[49], cur[7], 4)
|
||||
result += b64_from_24bit(cur[50], cur[8], cur[29], 4)
|
||||
result += b64_from_24bit(cur[9], cur[30], cur[51], 4)
|
||||
result += b64_from_24bit(cur[31], cur[52], cur[10], 4)
|
||||
result += b64_from_24bit(cur[53], cur[11], cur[32], 4)
|
||||
result += b64_from_24bit(cur[12], cur[33], cur[54], 4)
|
||||
result += b64_from_24bit(cur[34], cur[55], cur[13], 4)
|
||||
result += b64_from_24bit(cur[56], cur[14], cur[35], 4)
|
||||
result += b64_from_24bit(cur[15], cur[36], cur[57], 4)
|
||||
result += b64_from_24bit(cur[37], cur[58], cur[16], 4)
|
||||
result += b64_from_24bit(cur[59], cur[17], cur[38], 4)
|
||||
result += b64_from_24bit(cur[18], cur[39], cur[60], 4)
|
||||
result += b64_from_24bit(cur[40], cur[61], cur[19], 4)
|
||||
result += b64_from_24bit(cur[62], cur[20], cur[41], 4)
|
||||
result += b64_from_24bit(0, 0, cur[63], 2)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
class SystemConfigurator:
|
||||
"""Manages application of configuration to the installed KhOS target rootfs."""
|
||||
|
||||
def __init__(self, target_root: str, dry_run: bool = False, log_func: Optional[Callable[[str], None]] = None):
|
||||
self.target_root = Path(target_root)
|
||||
self.dry_run = dry_run
|
||||
self.log_func = log_func
|
||||
|
||||
def _log(self, text: str) -> None:
|
||||
if self.log_func:
|
||||
self.log_func(text)
|
||||
|
||||
def write_file(self, rel_path: str, content: str, mode: int = 0o644) -> None:
|
||||
"""Safely write configuration file into target directory."""
|
||||
full_path = self.target_root / rel_path.lstrip("/")
|
||||
self._log(f"Writing config: {rel_path}")
|
||||
if self.dry_run:
|
||||
return
|
||||
|
||||
full_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
full_path.write_text(content, encoding="utf-8")
|
||||
try:
|
||||
full_path.chmod(mode)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def apply_basic_configs(self, config: InstallConfig, targets: TargetPartitions) -> None:
|
||||
"""Apply /etc/fstab, /etc/hostname, and /etc/hosts."""
|
||||
# /etc/fstab
|
||||
fstab_content = generate_fstab(targets)
|
||||
self.write_file("etc/fstab", fstab_content)
|
||||
|
||||
# /etc/hostname
|
||||
self.write_file("etc/hostname", generate_hostname(config.hostname))
|
||||
|
||||
# /etc/hosts
|
||||
self.write_file("etc/hosts", generate_hosts(config.hostname))
|
||||
|
||||
def set_root_password(self, password: str) -> None:
|
||||
"""Set root user password in the target system."""
|
||||
self._log("Setting root password...")
|
||||
if self.dry_run:
|
||||
return
|
||||
|
||||
# Method 1: chpasswd with -R flag if supported
|
||||
res = run_cmd(["chpasswd", "-R", str(self.target_root)], stdin_input=f"root:{password}\n", check=False)
|
||||
if res.success:
|
||||
return
|
||||
|
||||
# Method 2: chroot chpasswd
|
||||
res = run_cmd(["chroot", str(self.target_root), "chpasswd"], stdin_input=f"root:{password}\n", check=False)
|
||||
if res.success:
|
||||
return
|
||||
|
||||
# Method 3: Direct update of /etc/shadow
|
||||
shadow_path = self.target_root / "etc" / "shadow"
|
||||
shadow_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
pass_hash = hash_password_sha512(password)
|
||||
if shadow_path.exists():
|
||||
lines = shadow_path.read_text(encoding="utf-8").splitlines()
|
||||
new_lines = []
|
||||
updated = False
|
||||
for line in lines:
|
||||
parts = line.split(":")
|
||||
if len(parts) >= 2 and parts[0] == "root":
|
||||
parts[1] = pass_hash
|
||||
new_lines.append(":".join(parts))
|
||||
updated = True
|
||||
else:
|
||||
new_lines.append(line)
|
||||
if not updated:
|
||||
new_lines.append(f"root:{pass_hash}:19000:0:99999:7:::")
|
||||
shadow_path.write_text("\n".join(new_lines) + "\n", encoding="utf-8")
|
||||
else:
|
||||
shadow_path.write_text(f"root:{pass_hash}:19000:0:99999:7:::\n", encoding="utf-8")
|
||||
|
||||
def create_user_account(self, username: str, password: str) -> None:
|
||||
"""Create a regular user account with home directory and sudo privileges."""
|
||||
self._log(f"Creating user account '{username}'...")
|
||||
if self.dry_run:
|
||||
return
|
||||
|
||||
# Create home directory
|
||||
home_dir = self.target_root / "home" / username
|
||||
home_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
pass_hash = hash_password_sha512(password)
|
||||
uid = 1000
|
||||
gid = 1000
|
||||
|
||||
# Update /etc/passwd
|
||||
passwd_path = self.target_root / "etc" / "passwd"
|
||||
passwd_lines = passwd_path.read_text(encoding="utf-8").splitlines() if passwd_path.exists() else []
|
||||
# Find next available UID >= 1000
|
||||
for l in passwd_lines:
|
||||
p = l.split(":")
|
||||
if len(p) >= 3 and p[2].isdigit():
|
||||
uid = max(uid, int(p[2]) + 1)
|
||||
gid = uid
|
||||
|
||||
passwd_lines.append(f"{username}:x:{uid}:{gid}:{username},,,:/home/{username}:/bin/sh")
|
||||
passwd_path.write_text("\n".join(passwd_lines) + "\n", encoding="utf-8")
|
||||
|
||||
# Update /etc/shadow
|
||||
shadow_path = self.target_root / "etc" / "shadow"
|
||||
shadow_lines = shadow_path.read_text(encoding="utf-8").splitlines() if shadow_path.exists() else []
|
||||
shadow_lines.append(f"{username}:{pass_hash}:19000:0:99999:7:::")
|
||||
shadow_path.write_text("\n".join(shadow_lines) + "\n", encoding="utf-8")
|
||||
|
||||
# Update /etc/group
|
||||
group_path = self.target_root / "etc" / "group"
|
||||
group_lines = group_path.read_text(encoding="utf-8").splitlines() if group_path.exists() else []
|
||||
group_lines.append(f"{username}:x:{gid}:")
|
||||
# Add to wheel, sudo, audio, video
|
||||
updated_groups = []
|
||||
for line in group_lines:
|
||||
p = line.split(":")
|
||||
if len(p) >= 4 and p[0] in ("wheel", "sudo", "audio", "video", "input"):
|
||||
members = [m for m in p[3].split(",") if m]
|
||||
if username not in members:
|
||||
members.append(username)
|
||||
p[3] = ",".join(members)
|
||||
updated_groups.append(":".join(p))
|
||||
else:
|
||||
updated_groups.append(line)
|
||||
group_path.write_text("\n".join(updated_groups) + "\n", encoding="utf-8")
|
||||
|
||||
# Set ownership if running on Linux
|
||||
try:
|
||||
os.chown(home_dir, uid, gid)
|
||||
except (AttributeError, OSError):
|
||||
pass
|
||||
|
||||
def set_system_permissions(self) -> None:
|
||||
"""Apply necessary file permissions (executables, SUID, and tmp)."""
|
||||
self._log("Setting system executable permissions and SUID bits...")
|
||||
if self.dry_run:
|
||||
return
|
||||
|
||||
exec_binaries = [
|
||||
"usr/bin/start-xfce",
|
||||
"usr/bin/startxfce4",
|
||||
"usr/bin/xfce",
|
||||
"usr/bin/xfce4",
|
||||
"usr/bin/start-plasma",
|
||||
"usr/bin/plasma",
|
||||
"usr/bin/kde",
|
||||
"usr/bin/autologin-plasma",
|
||||
"usr/bin/start-hyprland",
|
||||
"usr/bin/start-openbox",
|
||||
"usr/bin/Hyprland",
|
||||
"usr/bin/foot",
|
||||
"usr/bin/wofi",
|
||||
"usr/bin/tint2",
|
||||
"usr/bin/xterm",
|
||||
"usr/bin/feh",
|
||||
"usr/bin/khos-installer",
|
||||
"usr/bin/install-os",
|
||||
"usr/bin/wpkg",
|
||||
]
|
||||
for rel in exec_binaries:
|
||||
fpath = self.target_root / rel
|
||||
if fpath.exists():
|
||||
try:
|
||||
fpath.chmod(0o755)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# SUID binaries (sudo and doas only)
|
||||
suid_binaries = [
|
||||
"usr/bin/sudo",
|
||||
"usr/bin/doas",
|
||||
]
|
||||
for rel in suid_binaries:
|
||||
fpath = self.target_root / rel
|
||||
if fpath.exists():
|
||||
try:
|
||||
fpath.chmod(0o4755)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# Ensure non-SUID binaries
|
||||
non_suid = [
|
||||
"usr/bin/seatd-launch",
|
||||
"usr/bin/Xorg",
|
||||
"bin/busybox",
|
||||
]
|
||||
for rel in non_suid:
|
||||
fpath = self.target_root / rel
|
||||
if fpath.exists():
|
||||
try:
|
||||
fpath.chmod(0o755)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# Restrict shadow permissions
|
||||
for sf in ["etc/shadow", "etc/gshadow"]:
|
||||
spath = self.target_root / sf
|
||||
if spath.exists():
|
||||
try:
|
||||
spath.chmod(0o600)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# Sticky bit for /tmp
|
||||
tmp_dir = self.target_root / "tmp"
|
||||
if tmp_dir.exists():
|
||||
try:
|
||||
tmp_dir.chmod(0o1777)
|
||||
except OSError:
|
||||
pass
|
||||
@@ -0,0 +1,289 @@
|
||||
"""Installation Core Engine: Orchestration of partitioning, copying, configuration, and bootloader."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Callable, List, Optional
|
||||
|
||||
from .bootloader import BootloaderInstaller
|
||||
from .config import SystemConfigurator
|
||||
from .disk import DiskManager, detect_boot_mode
|
||||
from .partitioner import Partitioner
|
||||
from .types import BootMode, InstallConfig, ProgressEvent, TargetPartitions
|
||||
from .utils import check_root, format_bytes, run_cmd
|
||||
|
||||
ProgressCallback = Callable[[ProgressEvent], None]
|
||||
|
||||
|
||||
class InstallerCore:
|
||||
"""Core workflow engine for KhOS Linux installation."""
|
||||
|
||||
def __init__(self, config: InstallConfig, callback: Optional[ProgressCallback] = None):
|
||||
self.config = config
|
||||
self.callback = callback
|
||||
self.disk_manager = DiskManager(dry_run=config.dry_run)
|
||||
self.partitioner = Partitioner(dry_run=config.dry_run, log_func=self._log)
|
||||
self.is_cancelled = False
|
||||
self.mount_dir = Path(config.mount_point)
|
||||
|
||||
def cancel(self) -> None:
|
||||
"""Signal the installer to cancel and abort execution."""
|
||||
self.is_cancelled = True
|
||||
self._log("Installation cancellation requested by user.")
|
||||
|
||||
def _emit(self, event_type: str, percent: int, stage: str, message: str, **kwargs) -> None:
|
||||
"""Emit a structured progress event to callback."""
|
||||
event = ProgressEvent(
|
||||
event_type=event_type,
|
||||
percent=percent,
|
||||
stage=stage,
|
||||
message=message,
|
||||
details=kwargs,
|
||||
)
|
||||
if self.callback:
|
||||
self.callback(event)
|
||||
|
||||
def _log(self, message: str) -> None:
|
||||
"""Emit a log line event."""
|
||||
self._emit("log", 0, "", message)
|
||||
|
||||
def run(self) -> bool:
|
||||
"""Execute the full end-to-end installation procedure."""
|
||||
start_time = time.time()
|
||||
self._emit("stage", 0, "Przygotowanie", "Weryfikacja parametrów instalacji...")
|
||||
|
||||
# 1. Validation
|
||||
self._log("Walidacja konfiguracji instalacji...")
|
||||
if not self.config.dry_run and not check_root():
|
||||
err_msg = "Instalator wymaga uprawnień administratora (root). Uruchom za pomocą sudo lub su."
|
||||
self._emit("error", 0, "Błąd", err_msg)
|
||||
raise PermissionError(err_msg)
|
||||
|
||||
validation_errors = self.config.validate()
|
||||
if validation_errors:
|
||||
err_msg = f"Błędy konfiguracji: {'; '.join(validation_errors)}"
|
||||
self._emit("error", 0, "Błąd", err_msg)
|
||||
raise ValueError(err_msg)
|
||||
|
||||
if self.is_cancelled:
|
||||
return False
|
||||
|
||||
# 2. Stage: Partitioning
|
||||
self._emit("stage", 10, "Partycjonowanie", f"Przygotowanie dysku {self.config.target_disk}...")
|
||||
self._log(f"Tworzenie tablicy partycji dla trybu {self.config.boot_mode.value.upper()}...")
|
||||
target_parts = self.partitioner.partition_disk(self.config)
|
||||
self._log(f"Utworzone partycje: Główna={target_parts.root_part}, EFI={target_parts.efi_part}")
|
||||
|
||||
if self.is_cancelled:
|
||||
self._cleanup_mounts()
|
||||
return False
|
||||
|
||||
# 3. Stage: Formatting
|
||||
self._emit("stage", 25, "Formatowanie", "Formatowanie partycji systemowych...")
|
||||
self.partitioner.format_partitions(target_parts)
|
||||
self._log(f"Sformatowano: Root={target_parts.root_part} (EXT4), EFI={target_parts.efi_part} (FAT32)")
|
||||
|
||||
if self.is_cancelled:
|
||||
self._cleanup_mounts()
|
||||
return False
|
||||
|
||||
# 4. Stage: Mounting
|
||||
self._emit("stage", 35, "Montowanie", "Montowanie docelowych systemów plików...")
|
||||
self._mount_targets(target_parts)
|
||||
|
||||
if self.is_cancelled:
|
||||
self._cleanup_mounts()
|
||||
return False
|
||||
|
||||
# 5. Stage: Copying Filesystem
|
||||
self._emit("stage", 45, "Kopiowanie", "Kopiowanie plików systemu operacyjnego KhOS...")
|
||||
self._copy_system_files()
|
||||
|
||||
if self.is_cancelled:
|
||||
self._cleanup_mounts()
|
||||
return False
|
||||
|
||||
# 6. Stage: System Configuration
|
||||
self._emit("stage", 75, "Konfiguracja", "Generowanie plików konfiguracyjnych (/etc/fstab, hostname)...")
|
||||
configurator = SystemConfigurator(str(self.mount_dir), dry_run=self.config.dry_run, log_func=self._log)
|
||||
configurator.apply_basic_configs(self.config, target_parts)
|
||||
configurator.set_root_password(self.config.root_password)
|
||||
|
||||
if self.config.username and self.config.user_password:
|
||||
configurator.create_user_account(self.config.username, self.config.user_password)
|
||||
|
||||
configurator.set_system_permissions()
|
||||
|
||||
if self.is_cancelled:
|
||||
self._cleanup_mounts()
|
||||
return False
|
||||
|
||||
# 7. Stage: Bootloader
|
||||
self._emit("stage", 85, "Bootloader", "Instalacja programu rozruchowego GRUB...")
|
||||
boot_installer = BootloaderInstaller(str(self.mount_dir), dry_run=self.config.dry_run, log_func=self._log)
|
||||
boot_installer.install(target_parts, self.config.boot_mode, self.config.desktop)
|
||||
|
||||
if self.is_cancelled:
|
||||
self._cleanup_mounts()
|
||||
return False
|
||||
|
||||
# 8. Stage: Unmount & Finalize
|
||||
self._emit("stage", 95, "Finalizacja", "Synchronizacja buforów i odmontowanie nośników...")
|
||||
self._cleanup_mounts()
|
||||
|
||||
elapsed = int(time.time() - start_time)
|
||||
self._emit(
|
||||
"completed",
|
||||
100,
|
||||
"Zakończono",
|
||||
"Instalacja systemu KhOS zakończona pełnym sukcesem!",
|
||||
elapsed_seconds=elapsed,
|
||||
target_disk=self.config.target_disk,
|
||||
root_partition=target_parts.root_part,
|
||||
boot_mode=self.config.boot_mode.value,
|
||||
)
|
||||
return True
|
||||
|
||||
def _mount_targets(self, targets: TargetPartitions) -> None:
|
||||
"""Mount the prepared target partitions to the target directory."""
|
||||
self._log(f"Tworzenie katalogu montowania {self.mount_dir}...")
|
||||
if not self.config.dry_run:
|
||||
self.mount_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
self._log(f"Montowanie partycji głównej {targets.root_part} w {self.mount_dir}...")
|
||||
res = run_cmd(["mount", targets.root_part, str(self.mount_dir)], check=False, dry_run=self.config.dry_run, log_func=self._log)
|
||||
if not res.success and not self.config.dry_run:
|
||||
# Fallback with explicit ext4 type
|
||||
res = run_cmd(["mount", "-t", "ext4", targets.root_part, str(self.mount_dir)], check=True, dry_run=self.config.dry_run, log_func=self._log)
|
||||
|
||||
if targets.efi_part:
|
||||
efi_mount = self.mount_dir / "boot" / "efi"
|
||||
self._log(f"Montowanie partycji EFI {targets.efi_part} w {efi_mount}...")
|
||||
if not self.config.dry_run:
|
||||
efi_mount.mkdir(parents=True, exist_ok=True)
|
||||
run_cmd(["mount", targets.efi_part, str(efi_mount)], check=False, dry_run=self.config.dry_run, log_func=self._log)
|
||||
|
||||
def _locate_system_source(self) -> Optional[Path]:
|
||||
"""Locate the source directory or squashfs image containing the KhOS rootfs."""
|
||||
if self.config.source_path:
|
||||
p = Path(self.config.source_path)
|
||||
if p.exists():
|
||||
return p
|
||||
|
||||
# Check existing squashfs mount
|
||||
if Path("/mnt/squashfs/bin/busybox").exists():
|
||||
return Path("/mnt/squashfs")
|
||||
|
||||
# Check ISO live squashfs
|
||||
iso_squashfs = Path("/mnt/cdrom/live/filesystem.squashfs")
|
||||
if iso_squashfs.exists():
|
||||
inst_mount = Path("/mnt/squashfs_inst")
|
||||
if not self.config.dry_run:
|
||||
inst_mount.mkdir(parents=True, exist_ok=True)
|
||||
run_cmd(["mount", "-t", "squashfs", "-o", "ro,loop", str(iso_squashfs), str(inst_mount)], check=False)
|
||||
if (inst_mount / "bin" / "busybox").exists() or self.config.dry_run:
|
||||
return inst_mount
|
||||
|
||||
# Fallback to current live running rootfs
|
||||
return Path("/")
|
||||
|
||||
def _copy_system_files(self) -> None:
|
||||
"""Copy rootfs files and kernel/initramfs into the installed target."""
|
||||
source_dir = self._locate_system_source()
|
||||
self._log(f"Źródło plików instalacyjnych: {source_dir}")
|
||||
|
||||
if self.config.dry_run:
|
||||
self._log("[DRY-RUN] Symulacja kopiowania plików systemowych...")
|
||||
time.sleep(0.5)
|
||||
return
|
||||
|
||||
if source_dir and source_dir != Path("/"):
|
||||
self._log(f"Kopiowanie ze źródła obrazu Live ({source_dir})...")
|
||||
# Efficient tar copy preserving all permissions and symlinks
|
||||
tar_cmd = f"cd {source_dir} && tar -cf - . | (cd {self.mount_dir} && tar -xf -)"
|
||||
res = run_cmd(["sh", "-c", tar_cmd], check=False, log_func=self._log)
|
||||
if not res.success:
|
||||
# Fallback cp -af
|
||||
run_cmd(["cp", "-af", f"{source_dir}/.", f"{self.mount_dir}/"], check=False, log_func=self._log)
|
||||
else:
|
||||
self._log("Kopiowanie z bieżącego środowiska na żywo...")
|
||||
critical_dirs = ["bin", "sbin", "lib", "lib64", "usr", "etc", "var", "root", "home", "opt", "srv"]
|
||||
for d in critical_dirs:
|
||||
src_path = Path("/") / d
|
||||
if src_path.exists() and src_path.is_dir():
|
||||
dst_path = self.mount_dir / d
|
||||
dst_path.mkdir(parents=True, exist_ok=True)
|
||||
cmd = f"cd /{d} && tar -cf - . | (cd {dst_path} && tar -xf -)"
|
||||
run_cmd(["sh", "-c", cmd], check=False)
|
||||
|
||||
# Create essential runtime mount points
|
||||
for sub in ["proc", "sys", "dev", "tmp", "run", "mnt", "mnt/cdrom", "boot"]:
|
||||
(self.mount_dir / sub).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
try:
|
||||
(self.mount_dir / "tmp").chmod(0o1777)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# Kernel & initramfs copying
|
||||
self._copy_kernel_and_initramfs()
|
||||
|
||||
def _copy_kernel_and_initramfs(self) -> None:
|
||||
"""Ensure vmlinuz and initramfs.img are present in /boot of the installed system."""
|
||||
boot_dst = self.mount_dir / "boot"
|
||||
boot_dst.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Check CD-ROM mount or search block devices if missing
|
||||
vmlinuz_candidates = [
|
||||
Path("/mnt/cdrom/boot/vmlinuz"),
|
||||
Path("/boot/vmlinuz"),
|
||||
Path("/mnt/cdrom/vmlinuz"),
|
||||
]
|
||||
initramfs_candidates = [
|
||||
Path("/mnt/cdrom/boot/initramfs.img"),
|
||||
Path("/boot/initramfs.img"),
|
||||
Path("/mnt/cdrom/initramfs.img"),
|
||||
]
|
||||
|
||||
# Try mounting CDROM device if kernel not found
|
||||
if not any(p.exists() for p in vmlinuz_candidates):
|
||||
for dev_pattern in ["/dev/sr*", "/dev/cdrom*", "/dev/loop*"]:
|
||||
import glob
|
||||
for cddev in glob.glob(dev_pattern):
|
||||
Path("/mnt/cdrom").mkdir(parents=True, exist_ok=True)
|
||||
run_cmd(["mount", "-o", "ro", cddev, "/mnt/cdrom"], check=False)
|
||||
if Path("/mnt/cdrom/boot/vmlinuz").exists():
|
||||
break
|
||||
|
||||
# Copy vmlinuz
|
||||
for v in vmlinuz_candidates:
|
||||
if v.exists() and not (boot_dst / "vmlinuz").exists():
|
||||
self._log(f"Kopiowanie jądra vmlinuz z {v}...")
|
||||
shutil.copy2(v, boot_dst / "vmlinuz")
|
||||
break
|
||||
|
||||
# Copy initramfs
|
||||
for i in initramfs_candidates:
|
||||
if i.exists() and not (boot_dst / "initramfs.img").exists():
|
||||
self._log(f"Kopiowanie initramfs z {i}...")
|
||||
shutil.copy2(i, boot_dst / "initramfs.img")
|
||||
break
|
||||
|
||||
def _cleanup_mounts(self) -> None:
|
||||
"""Synchronize buffers and cleanly unmount the target filesystem."""
|
||||
self._log("Synchronizacja buforów dyskowych (sync)...")
|
||||
run_cmd(["sync"], check=False, dry_run=self.config.dry_run)
|
||||
|
||||
self._log(f"Odmontowywanie struktur {self.mount_dir}...")
|
||||
run_cmd(["umount", "-R", str(self.mount_dir)], check=False, dry_run=self.config.dry_run)
|
||||
|
||||
# Cleanup squashfs temp mount if present
|
||||
if Path("/mnt/squashfs_inst").exists():
|
||||
run_cmd(["umount", "/mnt/squashfs_inst"], check=False, dry_run=self.config.dry_run)
|
||||
try:
|
||||
Path("/mnt/squashfs_inst").rmdir()
|
||||
except OSError:
|
||||
pass
|
||||
@@ -0,0 +1,301 @@
|
||||
"""Disk detection, size querying, model reading, blkid handling, and UUID resolution."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import glob
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import List, Optional
|
||||
|
||||
from .types import BootMode, DiskInfo, PartitionInfo
|
||||
from .utils import check_root, format_bytes, run_cmd
|
||||
|
||||
|
||||
def detect_boot_mode() -> BootMode:
|
||||
"""Detect whether the current machine booted in UEFI or BIOS mode."""
|
||||
# Environment override for debugging/testing
|
||||
env_override = os.environ.get("KHOS_BOOT_MODE")
|
||||
if env_override:
|
||||
if env_override.lower() == "uefi":
|
||||
return BootMode.UEFI
|
||||
if env_override.lower() == "bios":
|
||||
return BootMode.BIOS
|
||||
|
||||
# Linux EFI verification directory
|
||||
if os.path.exists("/sys/firmware/efi"):
|
||||
return BootMode.UEFI
|
||||
return BootMode.BIOS
|
||||
|
||||
|
||||
class DiskManager:
|
||||
"""Manages disk discovery, inspection, unmounting, and partition UUID querying."""
|
||||
|
||||
def __init__(self, dry_run: bool = False):
|
||||
self.dry_run = dry_run
|
||||
|
||||
@staticmethod
|
||||
def get_partition_path(disk_path: str, part_num: int) -> str:
|
||||
"""Derive standard partition device node from parent disk and partition index.
|
||||
|
||||
Examples:
|
||||
/dev/sda, 1 -> /dev/sda1
|
||||
/dev/nvme0n1, 2 -> /dev/nvme0n1p2
|
||||
/dev/mmcblk0, 1 -> /dev/mmcblk0p1
|
||||
/dev/loop0, 1 -> /dev/loop0p1
|
||||
"""
|
||||
disk_path = disk_path.rstrip("/")
|
||||
# Check if the disk name ends with a digit
|
||||
base = os.path.basename(disk_path)
|
||||
if base[-1].isdigit():
|
||||
return f"{disk_path}p{part_num}"
|
||||
return f"{disk_path}{part_num}"
|
||||
|
||||
def list_disks(self) -> List[DiskInfo]:
|
||||
"""Detect and return all physical and virtual disk devices available for installation."""
|
||||
disks: List[DiskInfo] = []
|
||||
|
||||
# If running on Linux with /sys/block available
|
||||
sys_block_path = Path("/sys/block")
|
||||
if sys_block_path.exists() and sys_block_path.is_dir():
|
||||
disks = self._scan_sys_block()
|
||||
else:
|
||||
# Fallback for systems without /sys or simulated environments
|
||||
disks = self._fallback_scan()
|
||||
|
||||
return disks
|
||||
|
||||
def _scan_sys_block(self) -> List[DiskInfo]:
|
||||
"""Scan /sys/block on Linux systems."""
|
||||
disks: List[DiskInfo] = []
|
||||
ignored_prefixes = ("sr", "loop", "ram", "dm-", "zram", "fd", "nbd")
|
||||
|
||||
for entry in sorted(os.listdir("/sys/block")):
|
||||
if any(entry.startswith(prefix) for prefix in ignored_prefixes):
|
||||
continue
|
||||
|
||||
dev_node = f"/dev/{entry}"
|
||||
sys_entry = Path("/sys/block") / entry
|
||||
|
||||
# Read disk size in 512-byte sectors
|
||||
size_file = sys_entry / "size"
|
||||
size_sectors = 0
|
||||
if size_file.exists():
|
||||
try:
|
||||
size_sectors = int(size_file.read_text(encoding="utf-8").strip())
|
||||
except (ValueError, OSError):
|
||||
size_sectors = 0
|
||||
|
||||
size_bytes = size_sectors * 512
|
||||
size_gb = size_bytes / (1024 ** 3)
|
||||
|
||||
# Skip tiny virtual devices (< 100MB)
|
||||
if size_bytes < 100 * 1024 * 1024:
|
||||
continue
|
||||
|
||||
# Read model
|
||||
model = "Standard Storage Drive"
|
||||
model_file = sys_entry / "device" / "model"
|
||||
if model_file.exists():
|
||||
try:
|
||||
model = model_file.read_text(encoding="utf-8").strip()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# Read removable status
|
||||
removable_file = sys_entry / "removable"
|
||||
is_removable = False
|
||||
if removable_file.exists():
|
||||
try:
|
||||
is_removable = removable_file.read_text(encoding="utf-8").strip() == "1"
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# Read rotational status (0 = SSD/NVMe, 1 = HDD)
|
||||
rotational_file = sys_entry / "queue" / "rotational"
|
||||
is_rotational = True
|
||||
if rotational_file.exists():
|
||||
try:
|
||||
is_rotational = rotational_file.read_text(encoding="utf-8").strip() == "1"
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# Discover partitions under this disk
|
||||
partitions: List[PartitionInfo] = []
|
||||
for part_cand in sys_entry.glob(f"{entry}*"):
|
||||
part_size_file = part_cand / "size"
|
||||
if not part_size_file.exists():
|
||||
continue
|
||||
part_name = part_cand.name
|
||||
part_path = f"/dev/{part_name}"
|
||||
try:
|
||||
p_sectors = int(part_size_file.read_text(encoding="utf-8").strip())
|
||||
p_bytes = p_sectors * 512
|
||||
except (ValueError, OSError):
|
||||
p_bytes = 0
|
||||
|
||||
uuid = self.get_partition_uuid(part_path)
|
||||
fs_type = self.get_partition_fs_type(part_path)
|
||||
mount_pt = self.get_mount_point(part_path)
|
||||
|
||||
partitions.append(
|
||||
PartitionInfo(
|
||||
name=part_name,
|
||||
path=part_path,
|
||||
size_bytes=p_bytes,
|
||||
size_human=format_bytes(p_bytes),
|
||||
fs_type=fs_type,
|
||||
uuid=uuid,
|
||||
mount_point=mount_pt,
|
||||
)
|
||||
)
|
||||
|
||||
disks.append(
|
||||
DiskInfo(
|
||||
name=entry,
|
||||
path=dev_node,
|
||||
size_bytes=size_bytes,
|
||||
size_gb=size_gb,
|
||||
model=model,
|
||||
is_removable=is_removable,
|
||||
is_rotational=is_rotational,
|
||||
partitions=partitions,
|
||||
)
|
||||
)
|
||||
|
||||
return disks
|
||||
|
||||
def _fallback_scan(self) -> List[DiskInfo]:
|
||||
"""Fallback mock scan for development/testing when not running natively on Linux."""
|
||||
return [
|
||||
DiskInfo(
|
||||
name="sda",
|
||||
path="/dev/sda",
|
||||
size_bytes=64 * 1024 ** 3,
|
||||
size_gb=64.0,
|
||||
model="QEMU VIRTUAL-DISK SATA",
|
||||
is_removable=False,
|
||||
is_rotational=False,
|
||||
partitions=[],
|
||||
),
|
||||
DiskInfo(
|
||||
name="vda",
|
||||
path="/dev/vda",
|
||||
size_bytes=32 * 1024 ** 3,
|
||||
size_gb=32.0,
|
||||
model="VirtIO Block Device",
|
||||
is_removable=False,
|
||||
is_rotational=False,
|
||||
partitions=[],
|
||||
),
|
||||
]
|
||||
|
||||
def get_disk_size(self, device_path: str) -> int:
|
||||
"""Get block device size in bytes."""
|
||||
# Method 1: blockdev --getsize64
|
||||
res = run_cmd(["blockdev", "--getsize64", device_path], check=False, dry_run=self.dry_run)
|
||||
if res.success and res.stdout.strip().isdigit():
|
||||
return int(res.stdout.strip())
|
||||
|
||||
# Method 2: /sys/class/block
|
||||
bname = os.path.basename(device_path)
|
||||
sys_size = Path(f"/sys/class/block/{bname}/size")
|
||||
if sys_size.exists():
|
||||
try:
|
||||
return int(sys_size.read_text(encoding="utf-8").strip()) * 512
|
||||
except (ValueError, OSError):
|
||||
pass
|
||||
|
||||
return 0
|
||||
|
||||
def get_partition_uuid(self, partition_path: str) -> Optional[str]:
|
||||
"""Read filesystem UUID using blkid or /dev/disk/by-uuid."""
|
||||
res = run_cmd(["blkid", "-s", "UUID", "-o", "value", partition_path], check=False, dry_run=self.dry_run)
|
||||
if res.success and res.stdout.strip():
|
||||
return res.stdout.strip()
|
||||
|
||||
# Fallback: parse entire blkid line
|
||||
res = run_cmd(["blkid", partition_path], check=False, dry_run=self.dry_run)
|
||||
if res.success:
|
||||
match = re.search(r'UUID="([^"]+)"', res.stdout)
|
||||
if match:
|
||||
return match.group(1)
|
||||
|
||||
# Fallback: inspect /dev/disk/by-uuid symlinks
|
||||
by_uuid_dir = Path("/dev/disk/by-uuid")
|
||||
if by_uuid_dir.exists():
|
||||
try:
|
||||
target_real = os.path.realpath(partition_path)
|
||||
for symlink in by_uuid_dir.iterdir():
|
||||
if symlink.is_symlink() and os.path.realpath(symlink) == target_real:
|
||||
return symlink.name
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
return None
|
||||
|
||||
def get_partition_fs_type(self, partition_path: str) -> Optional[str]:
|
||||
"""Read partition filesystem type using blkid."""
|
||||
res = run_cmd(["blkid", "-s", "TYPE", "-o", "value", partition_path], check=False, dry_run=self.dry_run)
|
||||
if res.success and res.stdout.strip():
|
||||
return res.stdout.strip()
|
||||
return None
|
||||
|
||||
def get_mount_point(self, partition_path: str) -> Optional[str]:
|
||||
"""Check if partition is currently mounted and return its mount point."""
|
||||
proc_mounts = Path("/proc/mounts")
|
||||
if not proc_mounts.exists():
|
||||
return None
|
||||
|
||||
try:
|
||||
target_real = os.path.realpath(partition_path)
|
||||
for line in proc_mounts.read_text(encoding="utf-8").splitlines():
|
||||
parts = line.split()
|
||||
if len(parts) >= 2:
|
||||
dev, mnt = parts[0], parts[1]
|
||||
if dev == partition_path or (os.path.exists(dev) and os.path.realpath(dev) == target_real):
|
||||
return mnt
|
||||
except OSError:
|
||||
pass
|
||||
return None
|
||||
|
||||
def unmount_all_partitions(self, disk_path: str) -> None:
|
||||
"""Safely unmount all active partitions belonging to the target disk."""
|
||||
disk_name = os.path.basename(disk_path)
|
||||
proc_mounts = Path("/proc/mounts")
|
||||
|
||||
mounted_points: List[str] = []
|
||||
if proc_mounts.exists():
|
||||
try:
|
||||
for line in proc_mounts.read_text(encoding="utf-8").splitlines():
|
||||
parts = line.split()
|
||||
if len(parts) >= 2:
|
||||
dev, mnt = parts[0], parts[1]
|
||||
if disk_name in dev:
|
||||
mounted_points.append(mnt)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# Sort mount points by depth so child mounts are unmounted first
|
||||
mounted_points.sort(key=lambda p: len(p.split("/")), reverse=True)
|
||||
|
||||
for mnt in mounted_points:
|
||||
# Never unmount root filesystem /
|
||||
if mnt == "/":
|
||||
raise RuntimeError("Target disk is currently mounted as root filesystem (/), refusing to wipe!")
|
||||
run_cmd(["umount", "-f", mnt], check=False, dry_run=self.dry_run)
|
||||
|
||||
# Also run wildcard unmount on partition nodes
|
||||
for part_dev in glob.glob(f"{disk_path}*"):
|
||||
if part_dev != disk_path:
|
||||
run_cmd(["umount", "-f", part_dev], check=False, dry_run=self.dry_run)
|
||||
|
||||
def reread_partition_table(self, disk_path: str) -> None:
|
||||
"""Force kernel to reload the disk partition table."""
|
||||
run_cmd(["sync"], check=False, dry_run=self.dry_run)
|
||||
run_cmd(["blockdev", "--rereadpt", disk_path], check=False, dry_run=self.dry_run)
|
||||
run_cmd(["partprobe", disk_path], check=False, dry_run=self.dry_run)
|
||||
run_cmd(["udevadm", "settle"], check=False, dry_run=self.dry_run)
|
||||
run_cmd(["mdev", "-s"], check=False, dry_run=self.dry_run)
|
||||
time.sleep(1)
|
||||
@@ -0,0 +1,514 @@
|
||||
"""Graphical User Interface (GUI) for KhOS System Installer using Tkinter.
|
||||
|
||||
Features a modern dark theme, multi-step installation wizard, live progress bar,
|
||||
and threaded asynchronous installation engine.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import queue
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from typing import List, Optional
|
||||
|
||||
from .core import InstallerCore
|
||||
from .disk import DiskManager, detect_boot_mode
|
||||
from .types import BootMode, DesktopEnvironment, DiskInfo, InstallConfig, ProgressEvent
|
||||
from .utils import check_root
|
||||
|
||||
# Catppuccin Mocha modern dark palette
|
||||
COLOR_BG = "#1e1e2e"
|
||||
COLOR_SURFACE = "#313244"
|
||||
COLOR_SURFACE_ALT = "#181825"
|
||||
COLOR_PRIMARY = "#89b4fa"
|
||||
COLOR_ACCENT = "#cba6f7"
|
||||
COLOR_TEXT = "#cdd6f4"
|
||||
COLOR_TEXT_DIM = "#a6adc8"
|
||||
COLOR_SUCCESS = "#a6e3a1"
|
||||
COLOR_WARNING = "#f9e2af"
|
||||
COLOR_ERROR = "#f38ba8"
|
||||
|
||||
|
||||
class GuiInstaller:
|
||||
"""Tkinter-based multi-page graphical wizard for KhOS installation."""
|
||||
|
||||
def __init__(self, dry_run: bool = False):
|
||||
try:
|
||||
import tkinter as tk
|
||||
from tkinter import messagebox, ttk
|
||||
from tkinter.scrolledtext import ScrolledText
|
||||
except ImportError as e:
|
||||
raise RuntimeError(
|
||||
f"Tkinter nie jest zainstalowany w tym środowisku Python ({e}).\n"
|
||||
"Uruchom instalator w trybie tekstowym: python run-installer.py"
|
||||
)
|
||||
|
||||
self.tk = tk
|
||||
self.ttk = ttk
|
||||
self.messagebox = messagebox
|
||||
self.ScrolledText = ScrolledText
|
||||
|
||||
self.dry_run = dry_run
|
||||
self.boot_mode = detect_boot_mode()
|
||||
self.disk_manager = DiskManager(dry_run=dry_run)
|
||||
self.event_queue: queue.Queue = queue.Queue()
|
||||
self.core_thread: Optional[threading.Thread] = None
|
||||
self.installer_core: Optional[InstallerCore] = None
|
||||
|
||||
# State
|
||||
self.disks: List[DiskInfo] = []
|
||||
self.selected_disk: Optional[DiskInfo] = None
|
||||
self.current_step = 0
|
||||
|
||||
# Initialize window
|
||||
try:
|
||||
self.root = tk.Tk()
|
||||
except tk.TclError as e:
|
||||
raise RuntimeError(
|
||||
f"Brak aktywnego serwera graficznego X11 / Wayland ($DISPLAY): {e}\n"
|
||||
"Uruchom instalator w trybie tekstowym: python run-installer.py"
|
||||
)
|
||||
|
||||
self.root.title("KhOS System Installer - v1.1 Genesis")
|
||||
self.root.geometry("820x620")
|
||||
self.root.minsize(760, 560)
|
||||
self.root.configure(bg=COLOR_BG)
|
||||
|
||||
self._setup_styles()
|
||||
self._build_ui()
|
||||
self._refresh_disks()
|
||||
|
||||
# Polling event queue
|
||||
self.root.after(100, self._process_events)
|
||||
|
||||
def _setup_styles(self) -> None:
|
||||
"""Apply modern dark styles to Tkinter widgets."""
|
||||
style = self.ttk.Style()
|
||||
try:
|
||||
style.theme_use("clam")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
style.configure(".", background=COLOR_BG, foreground=COLOR_TEXT, font=("Segoe UI", 10))
|
||||
style.configure("TLabel", background=COLOR_BG, foreground=COLOR_TEXT)
|
||||
style.configure("Header.TLabel", font=("Segoe UI", 18, "bold"), foreground=COLOR_PRIMARY)
|
||||
style.configure("SubHeader.TLabel", font=("Segoe UI", 11), foreground=COLOR_TEXT_DIM)
|
||||
style.configure("Card.TFrame", background=COLOR_SURFACE, relief="flat")
|
||||
style.configure("TButton", font=("Segoe UI", 10, "bold"), padding=6, background=COLOR_SURFACE, foreground=COLOR_TEXT)
|
||||
style.map("TButton", background=[("active", COLOR_PRIMARY)], foreground=[("active", COLOR_SURFACE_ALT)])
|
||||
style.configure("Primary.TButton", background=COLOR_PRIMARY, foreground=COLOR_SURFACE_ALT)
|
||||
style.map("Primary.TButton", background=[("active", COLOR_ACCENT)])
|
||||
style.configure("Danger.TButton", background=COLOR_ERROR, foreground=COLOR_SURFACE_ALT)
|
||||
style.configure("TRadiobutton", background=COLOR_BG, foreground=COLOR_TEXT, font=("Segoe UI", 10))
|
||||
style.configure("TCheckbutton", background=COLOR_BG, foreground=COLOR_TEXT, font=("Segoe UI", 10))
|
||||
style.configure("TProgressbar", troughcolor=COLOR_SURFACE, background=COLOR_PRIMARY, thickness=20)
|
||||
|
||||
def _build_ui(self) -> None:
|
||||
"""Construct the wizard container frames."""
|
||||
self.container = self.tk.Frame(self.root, bg=COLOR_BG)
|
||||
self.container.pack(fill="both", expand=True, padx=25, pady=20)
|
||||
|
||||
# Header area
|
||||
self.header_frame = self.tk.Frame(self.container, bg=COLOR_BG)
|
||||
self.header_frame.pack(fill="x", pady=(0, 15))
|
||||
|
||||
self.title_label = self.ttk.Label(self.header_frame, text="KhOS 1.1 - Instalator Systemu", style="Header.TLabel")
|
||||
self.title_label.pack(anchor="w")
|
||||
|
||||
boot_txt = f"Tryb rozruchu: {self.boot_mode.label}"
|
||||
self.subtitle_label = self.ttk.Label(self.header_frame, text=boot_txt, style="SubHeader.TLabel")
|
||||
self.subtitle_label.pack(anchor="w", pady=(2, 0))
|
||||
|
||||
# Main dynamic content frame
|
||||
self.content_frame = self.tk.Frame(self.container, bg=COLOR_SURFACE, bd=1, relief="flat")
|
||||
self.content_frame.pack(fill="both", expand=True, pady=10)
|
||||
|
||||
# Bottom navigation bar
|
||||
self.nav_frame = self.tk.Frame(self.container, bg=COLOR_BG)
|
||||
self.nav_frame.pack(fill="x", pady=(10, 0))
|
||||
|
||||
self.btn_cancel = self.ttk.Button(self.nav_frame, text="Anuluj", command=self.root.destroy)
|
||||
self.btn_cancel.pack(side="left")
|
||||
|
||||
self.btn_next = self.ttk.Button(self.nav_frame, text="Dalej >", style="Primary.TButton", command=self._next_step)
|
||||
self.btn_next.pack(side="right")
|
||||
|
||||
self.btn_prev = self.ttk.Button(self.nav_frame, text="< Wstecz", command=self._prev_step)
|
||||
self.btn_prev.pack(side="right", padx=10)
|
||||
|
||||
# Wizard steps
|
||||
self.steps = [
|
||||
self._render_welcome_page,
|
||||
self._render_disk_page,
|
||||
self._render_config_page,
|
||||
self._render_confirm_page,
|
||||
self._render_progress_page,
|
||||
self._render_finish_page,
|
||||
]
|
||||
|
||||
self._show_step(0)
|
||||
|
||||
def _clear_content(self) -> None:
|
||||
"""Remove widgets from dynamic content area."""
|
||||
for child in self.content_frame.winfo_children():
|
||||
child.destroy()
|
||||
|
||||
def _show_step(self, step_idx: int) -> None:
|
||||
"""Render the requested wizard step page."""
|
||||
self.current_step = step_idx
|
||||
self._clear_content()
|
||||
|
||||
# Update navigation buttons state
|
||||
if step_idx == 0:
|
||||
self.btn_prev.configure(state="disabled")
|
||||
self.btn_next.configure(state="normal", text="Dalej >")
|
||||
elif step_idx == len(self.steps) - 2: # Progress page
|
||||
self.btn_prev.configure(state="disabled")
|
||||
self.btn_next.configure(state="disabled")
|
||||
self.btn_cancel.configure(text="Przerwij", command=self._cancel_install)
|
||||
elif step_idx == len(self.steps) - 1: # Finish page
|
||||
self.btn_prev.configure(state="disabled")
|
||||
self.btn_next.configure(state="normal", text="Zakończ", command=self.root.destroy)
|
||||
self.btn_cancel.pack_forget()
|
||||
else:
|
||||
self.btn_prev.configure(state="normal")
|
||||
self.btn_next.configure(state="normal", text="Dalej >")
|
||||
|
||||
# Execute renderer
|
||||
self.steps[step_idx]()
|
||||
|
||||
def _next_step(self) -> None:
|
||||
"""Advance to next wizard step with validation."""
|
||||
if self.current_step == 1:
|
||||
if not self.selected_disk:
|
||||
self.messagebox.showwarning("Wybór dysku", "Proszę wybrać dysk docelowy z listy.")
|
||||
return
|
||||
elif self.current_step == 2:
|
||||
if not self.hostname_var.get().strip():
|
||||
self.messagebox.showwarning("Konfiguracja", "Nazwa komputera (hostname) nie może być pusta.")
|
||||
return
|
||||
if not self.root_pass_var.get().strip():
|
||||
self.messagebox.showwarning("Konfiguracja", "Hasło konta root nie może być puste.")
|
||||
return
|
||||
elif self.current_step == 3:
|
||||
if not self.confirm_var.get():
|
||||
self.messagebox.showwarning("Potwierdzenie", "Musisz zaznaczyć zgodę na usunięcie danych z dysku.")
|
||||
return
|
||||
# Start installation
|
||||
self._show_step(4)
|
||||
self._start_installation()
|
||||
return
|
||||
|
||||
if self.current_step < len(self.steps) - 1:
|
||||
self._show_step(self.current_step + 1)
|
||||
|
||||
def _prev_step(self) -> None:
|
||||
"""Go back to previous step."""
|
||||
if self.current_step > 0:
|
||||
self._show_step(self.current_step - 1)
|
||||
|
||||
# ================= Pages =================
|
||||
|
||||
def _render_welcome_page(self) -> None:
|
||||
"""Step 0: Welcome & hardware overview."""
|
||||
pad = self.tk.Frame(self.content_frame, bg=COLOR_SURFACE, padx=30, pady=25)
|
||||
pad.pack(fill="both", expand=True)
|
||||
|
||||
lbl = self.tk.Label(
|
||||
pad,
|
||||
text="Witaj w instalatorze KhOS Linux!",
|
||||
font=("Segoe UI", 16, "bold"),
|
||||
bg=COLOR_SURFACE,
|
||||
fg=COLOR_PRIMARY,
|
||||
)
|
||||
lbl.pack(anchor="w", pady=(0, 10))
|
||||
|
||||
intro = (
|
||||
"Ten asystent pomoże Ci zainstalować system operacyjny KhOS na dysku Twojego komputera.\n"
|
||||
"Instalator automatycznie przygotuje tablicę partycji, zainstaluje jądro Linux oraz\n"
|
||||
"skonfiguruje program rozruchowy GRUB (kompatybilny z UEFI i BIOS/Legacy).\n"
|
||||
)
|
||||
self.tk.Label(pad, text=intro, font=("Segoe UI", 10), justify="left", bg=COLOR_SURFACE, fg=COLOR_TEXT).pack(anchor="w")
|
||||
|
||||
# Hardware summary card
|
||||
card = self.tk.Frame(pad, bg=COLOR_SURFACE_ALT, padx=20, pady=15, bd=1, relief="solid")
|
||||
card.pack(fill="x", pady=20)
|
||||
|
||||
self.tk.Label(card, text="Wykryte środowisko sprzętowe:", font=("Segoe UI", 11, "bold"), bg=COLOR_SURFACE_ALT, fg=COLOR_ACCENT).pack(anchor="w")
|
||||
self.tk.Label(card, text=f"• Tryb oprogramowania układowego: {self.boot_mode.label}", bg=COLOR_SURFACE_ALT, fg=COLOR_TEXT).pack(anchor="w", pady=2)
|
||||
self.tk.Label(card, text=f"• Architektura procesora: {os.uname().machine if hasattr(os, 'uname') else 'x86_64'}", bg=COLOR_SURFACE_ALT, fg=COLOR_TEXT).pack(anchor="w", pady=2)
|
||||
root_status = "Root (Administrator)" if check_root() or self.dry_run else "Zwykły użytkownik (wymagany root!)"
|
||||
self.tk.Label(card, text=f"• Uprawnienia uruchomieniowe: {root_status}", bg=COLOR_SURFACE_ALT, fg=COLOR_SUCCESS if check_root() or self.dry_run else COLOR_ERROR).pack(anchor="w", pady=2)
|
||||
|
||||
def _render_disk_page(self) -> None:
|
||||
"""Step 1: Storage device selection."""
|
||||
pad = self.tk.Frame(self.content_frame, bg=COLOR_SURFACE, padx=20, pady=15)
|
||||
pad.pack(fill="both", expand=True)
|
||||
|
||||
self.tk.Label(pad, text="Krok 1: Wybór dysku docelowego", font=("Segoe UI", 14, "bold"), bg=COLOR_SURFACE, fg=COLOR_PRIMARY).pack(anchor="w")
|
||||
self.tk.Label(pad, text="Wybierz dysk, na którym ma zostać zainstalowany KhOS Linux:", bg=COLOR_SURFACE, fg=COLOR_TEXT_DIM).pack(anchor="w", pady=(0, 10))
|
||||
|
||||
# Disk Listbox
|
||||
list_frame = self.tk.Frame(pad, bg=COLOR_SURFACE_ALT, bd=1, relief="solid")
|
||||
list_frame.pack(fill="both", expand=True, pady=5)
|
||||
|
||||
self.disk_listbox = self.tk.Listbox(
|
||||
list_frame,
|
||||
bg=COLOR_SURFACE_ALT,
|
||||
fg=COLOR_TEXT,
|
||||
selectbackground=COLOR_PRIMARY,
|
||||
selectforeground=COLOR_SURFACE_ALT,
|
||||
font=("Consolas", 11),
|
||||
bd=0,
|
||||
highlightthickness=0,
|
||||
)
|
||||
self.disk_listbox.pack(side="left", fill="both", expand=True, padx=5, pady=5)
|
||||
self.disk_listbox.bind("<<ListboxSelect>>", self._on_disk_selected)
|
||||
|
||||
scrollbar = self.ttk.Scrollbar(list_frame, orient="vertical", command=self.disk_listbox.yview)
|
||||
scrollbar.pack(side="right", fill="y")
|
||||
self.disk_listbox.config(yscrollcommand=scrollbar.set)
|
||||
|
||||
# Refresh button
|
||||
btn_refresh = self.ttk.Button(pad, text="Odśwież dyski", command=self._refresh_disks)
|
||||
btn_refresh.pack(anchor="w", pady=5)
|
||||
|
||||
self._populate_disks_listbox()
|
||||
|
||||
def _refresh_disks(self) -> None:
|
||||
"""Rescan available disk drives."""
|
||||
self.disks = self.disk_manager.list_disks()
|
||||
if hasattr(self, "disk_listbox"):
|
||||
self._populate_disks_listbox()
|
||||
|
||||
def _populate_disks_listbox(self) -> None:
|
||||
"""Fill the listbox with discovered disks."""
|
||||
self.disk_listbox.delete(0, self.tk.END)
|
||||
for idx, d in enumerate(self.disks):
|
||||
self.disk_listbox.insert(self.tk.END, f" {d.summary()}")
|
||||
if self.selected_disk and self.selected_disk.path == d.path:
|
||||
self.disk_listbox.selection_set(idx)
|
||||
if self.disks and not self.selected_disk:
|
||||
self.disk_listbox.selection_set(0)
|
||||
self.selected_disk = self.disks[0]
|
||||
|
||||
def _on_disk_selected(self, event=None) -> None:
|
||||
"""Handle user clicking a disk in listbox."""
|
||||
sel = self.disk_listbox.curselection()
|
||||
if sel:
|
||||
self.selected_disk = self.disks[sel[0]]
|
||||
|
||||
def _render_config_page(self) -> None:
|
||||
"""Step 2: User credentials, hostname, desktop environment."""
|
||||
pad = self.tk.Frame(self.content_frame, bg=COLOR_SURFACE, padx=25, pady=15)
|
||||
pad.pack(fill="both", expand=True)
|
||||
|
||||
self.tk.Label(pad, text="Krok 2: Konfiguracja systemu i użytkowników", font=("Segoe UI", 14, "bold"), bg=COLOR_SURFACE, fg=COLOR_PRIMARY).pack(anchor="w")
|
||||
|
||||
# Grid of inputs
|
||||
grid = self.tk.Frame(pad, bg=COLOR_SURFACE)
|
||||
grid.pack(fill="x", pady=10)
|
||||
|
||||
# Hostname
|
||||
self.tk.Label(grid, text="Nazwa komputera (Hostname):", bg=COLOR_SURFACE, fg=COLOR_TEXT).grid(row=0, column=0, sticky="w", pady=5)
|
||||
if not hasattr(self, "hostname_var"):
|
||||
self.hostname_var = self.tk.StringVar(value="khos")
|
||||
self.hostname_entry = self.tk.Entry(grid, textvariable=self.hostname_var, bg=COLOR_SURFACE_ALT, fg=COLOR_TEXT, insertbackground=COLOR_TEXT, width=28)
|
||||
self.hostname_entry.grid(row=0, column=1, sticky="w", pady=5, padx=10)
|
||||
|
||||
# Root password
|
||||
self.tk.Label(grid, text="Hasło konta root:", bg=COLOR_SURFACE, fg=COLOR_TEXT).grid(row=1, column=0, sticky="w", pady=5)
|
||||
if not hasattr(self, "root_pass_var"):
|
||||
self.root_pass_var = self.tk.StringVar(value="khos")
|
||||
self.root_pass_entry = self.tk.Entry(grid, textvariable=self.root_pass_var, show="*", bg=COLOR_SURFACE_ALT, fg=COLOR_TEXT, insertbackground=COLOR_TEXT, width=28)
|
||||
self.root_pass_entry.grid(row=1, column=1, sticky="w", pady=5, padx=10)
|
||||
|
||||
# Optional user
|
||||
self.tk.Label(grid, text="Zwykły użytkownik (opcjonalnie):", bg=COLOR_SURFACE, fg=COLOR_TEXT).grid(row=2, column=0, sticky="w", pady=5)
|
||||
if not hasattr(self, "user_var"):
|
||||
self.user_var = self.tk.StringVar(value="")
|
||||
self.user_entry = self.tk.Entry(grid, textvariable=self.user_var, bg=COLOR_SURFACE_ALT, fg=COLOR_TEXT, insertbackground=COLOR_TEXT, width=28)
|
||||
self.user_entry.grid(row=2, column=1, sticky="w", pady=5, padx=10)
|
||||
|
||||
self.tk.Label(grid, text="Hasło użytkownika:", bg=COLOR_SURFACE, fg=COLOR_TEXT).grid(row=3, column=0, sticky="w", pady=5)
|
||||
if not hasattr(self, "user_pass_var"):
|
||||
self.user_pass_var = self.tk.StringVar(value="")
|
||||
self.user_pass_entry = self.tk.Entry(grid, textvariable=self.user_pass_var, show="*", bg=COLOR_SURFACE_ALT, fg=COLOR_TEXT, insertbackground=COLOR_TEXT, width=28)
|
||||
self.user_pass_entry.grid(row=3, column=1, sticky="w", pady=5, padx=10)
|
||||
|
||||
# Desktop Environment
|
||||
self.tk.Label(pad, text="Wybierz domyślny pulpit graficzny:", font=("Segoe UI", 11, "bold"), bg=COLOR_SURFACE, fg=COLOR_ACCENT).pack(anchor="w", pady=(15, 5))
|
||||
|
||||
if not hasattr(self, "desktop_var"):
|
||||
self.desktop_var = self.tk.StringVar(value=DesktopEnvironment.XFCE.value)
|
||||
|
||||
de_options = [
|
||||
(DesktopEnvironment.XFCE.value, "XFCE 4 (Lekkie, bardzo stabilne - rekomendowane)"),
|
||||
(DesktopEnvironment.PLASMA.value, "KDE Plasma 6 (Zaawansowane, nowoczesne efekty)"),
|
||||
(DesktopEnvironment.HYPRLAND.value, "Hyprland (Nowoczesny Wayland Tiling WM)"),
|
||||
(DesktopEnvironment.OPENBOX.value, "Openbox (Minimalistyczny pulpit X11)"),
|
||||
]
|
||||
for val, desc in de_options:
|
||||
rb = self.ttk.Radiobutton(pad, text=desc, value=val, variable=self.desktop_var)
|
||||
rb.pack(anchor="w", pady=2)
|
||||
|
||||
def _render_confirm_page(self) -> None:
|
||||
"""Step 3: Final confirmation and warning before formatting."""
|
||||
pad = self.tk.Frame(self.content_frame, bg=COLOR_SURFACE, padx=25, pady=20)
|
||||
pad.pack(fill="both", expand=True)
|
||||
|
||||
self.tk.Label(pad, text="Krok 3: Potwierdzenie instalacji", font=("Segoe UI", 14, "bold"), bg=COLOR_SURFACE, fg=COLOR_WARNING).pack(anchor="w")
|
||||
|
||||
# Summary card
|
||||
card = self.tk.Frame(pad, bg=COLOR_SURFACE_ALT, padx=15, pady=12, bd=1, relief="solid")
|
||||
card.pack(fill="x", pady=15)
|
||||
|
||||
disk_name = self.selected_disk.summary() if self.selected_disk else "Brak"
|
||||
self.tk.Label(card, text=f"• Dysk docelowy: {disk_name}", bg=COLOR_SURFACE_ALT, fg=COLOR_TEXT).pack(anchor="w", pady=2)
|
||||
self.tk.Label(card, text=f"• Tryb instalacji: {self.boot_mode.label}", bg=COLOR_SURFACE_ALT, fg=COLOR_TEXT).pack(anchor="w", pady=2)
|
||||
self.tk.Label(card, text=f"• Nazwa komputera: {self.hostname_var.get()}", bg=COLOR_SURFACE_ALT, fg=COLOR_TEXT).pack(anchor="w", pady=2)
|
||||
self.tk.Label(card, text=f"• Pulpit domyślny: {self.desktop_var.get().upper()}", bg=COLOR_SURFACE_ALT, fg=COLOR_TEXT).pack(anchor="w", pady=2)
|
||||
|
||||
# Big warning
|
||||
warn_box = self.tk.Frame(pad, bg="#450a0a", padx=15, pady=10, bd=1, relief="solid")
|
||||
warn_box.pack(fill="x", pady=10)
|
||||
warn_text = (
|
||||
"UWAGA: Dalsze postępowanie spowoduje sformatowanie wybranego dysku.\n"
|
||||
"Wszystkie znajdujące się na nim dane, partycje i pliki zostaną BEZPOWROTNIE USUNIĘTE!"
|
||||
)
|
||||
self.tk.Label(warn_box, text=warn_text, font=("Segoe UI", 10, "bold"), fg=COLOR_ERROR, bg="#450a0a", justify="left").pack(anchor="w")
|
||||
|
||||
if not hasattr(self, "confirm_var"):
|
||||
self.confirm_var = self.tk.BooleanVar(value=False)
|
||||
chk = self.ttk.Checkbutton(pad, text="Rozumiem ryzyko i chcę zainstalować KhOS na tym dysku", variable=self.confirm_var)
|
||||
chk.pack(anchor="w", pady=15)
|
||||
|
||||
def _render_progress_page(self) -> None:
|
||||
"""Step 4: Installation execution & live log view."""
|
||||
pad = self.tk.Frame(self.content_frame, bg=COLOR_SURFACE, padx=20, pady=15)
|
||||
pad.pack(fill="both", expand=True)
|
||||
|
||||
self.progress_title = self.tk.Label(pad, text="Trwa instalacja systemu KhOS...", font=("Segoe UI", 13, "bold"), bg=COLOR_SURFACE, fg=COLOR_PRIMARY)
|
||||
self.progress_title.pack(anchor="w")
|
||||
|
||||
self.progress_desc = self.tk.Label(pad, text="Inicjalizacja zadań...", bg=COLOR_SURFACE, fg=COLOR_TEXT_DIM)
|
||||
self.progress_desc.pack(anchor="w", pady=(0, 10))
|
||||
|
||||
# Progress bar
|
||||
self.progressbar = self.ttk.Progressbar(pad, mode="determinate", maximum=100)
|
||||
self.progressbar.pack(fill="x", pady=5)
|
||||
|
||||
# Log ScrolledText
|
||||
self.log_text = self.ScrolledText(
|
||||
pad,
|
||||
bg=COLOR_SURFACE_ALT,
|
||||
fg=COLOR_TEXT,
|
||||
font=("Consolas", 9),
|
||||
insertbackground=COLOR_TEXT,
|
||||
bd=0,
|
||||
relief="flat",
|
||||
)
|
||||
self.log_text.pack(fill="both", expand=True, pady=10)
|
||||
|
||||
def _render_finish_page(self) -> None:
|
||||
"""Step 5: Installation completion."""
|
||||
pad = self.tk.Frame(self.content_frame, bg=COLOR_SURFACE, padx=30, pady=25)
|
||||
pad.pack(fill="both", expand=True)
|
||||
|
||||
self.tk.Label(pad, text="Gratulacje!", font=("Segoe UI", 18, "bold"), bg=COLOR_SURFACE, fg=COLOR_SUCCESS).pack(anchor="w", pady=(0, 10))
|
||||
|
||||
finish_msg = (
|
||||
"System KhOS 1.1 (Genesis) został pomyślnie zainstalowany na Twoim dysku.\n\n"
|
||||
"Program rozruchowy GRUB został poprawnie wdrożony i skonfigurowany.\n"
|
||||
"Możesz teraz bezpiecznie wyjąć nośnik instalacyjny i uruchomić ponownie komputer."
|
||||
)
|
||||
self.tk.Label(pad, text=finish_msg, font=("Segoe UI", 11), justify="left", bg=COLOR_SURFACE, fg=COLOR_TEXT).pack(anchor="w", pady=10)
|
||||
|
||||
btn_reboot = self.ttk.Button(pad, text="Uruchom ponownie teraz (Reboot)", style="Primary.TButton", command=self._reboot_system)
|
||||
btn_reboot.pack(anchor="w", pady=20)
|
||||
|
||||
def _start_installation(self) -> None:
|
||||
"""Launch installation worker thread."""
|
||||
config = InstallConfig(
|
||||
target_disk=self.selected_disk.path if self.selected_disk else "",
|
||||
boot_mode=self.boot_mode,
|
||||
hostname=self.hostname_var.get().strip(),
|
||||
root_password=self.root_pass_var.get().strip(),
|
||||
username=self.user_var.get().strip() or None,
|
||||
user_password=self.user_pass_var.get().strip() or None,
|
||||
desktop=DesktopEnvironment(self.desktop_var.get()),
|
||||
dry_run=self.dry_run,
|
||||
)
|
||||
|
||||
def event_callback(ev: ProgressEvent) -> None:
|
||||
self.event_queue.put(ev)
|
||||
|
||||
self.installer_core = InstallerCore(config, callback=event_callback)
|
||||
|
||||
def worker() -> None:
|
||||
try:
|
||||
self.installer_core.run()
|
||||
except Exception as e:
|
||||
self.event_queue.put(ProgressEvent(event_type="error", message=str(e)))
|
||||
|
||||
self.core_thread = threading.Thread(target=worker, daemon=True)
|
||||
self.core_thread.start()
|
||||
|
||||
def _cancel_install(self) -> None:
|
||||
"""Signal abort to installer."""
|
||||
if self.installer_core:
|
||||
self.installer_core.cancel()
|
||||
self.root.destroy()
|
||||
|
||||
def _process_events(self) -> None:
|
||||
"""Poll the event queue and update GUI widgets."""
|
||||
while not self.event_queue.empty():
|
||||
ev: ProgressEvent = self.event_queue.get()
|
||||
if ev.event_type == "stage":
|
||||
if hasattr(self, "progress_title"):
|
||||
self.progress_title.config(text=f"Krok: {ev.stage}")
|
||||
if hasattr(self, "progress_desc"):
|
||||
self.progress_desc.config(text=ev.message)
|
||||
if hasattr(self, "progressbar"):
|
||||
self.progressbar["value"] = ev.percent
|
||||
elif ev.event_type == "log":
|
||||
if hasattr(self, "log_text"):
|
||||
self.log_text.insert(self.tk.END, f"{ev.message}\n")
|
||||
self.log_text.see(self.tk.END)
|
||||
elif ev.event_type == "completed":
|
||||
self._show_step(5)
|
||||
elif ev.event_type == "error":
|
||||
self.messagebox.showerror("Błąd instalacji", ev.message)
|
||||
|
||||
self.root.after(100, self._process_events)
|
||||
|
||||
def _reboot_system(self) -> None:
|
||||
"""Trigger system reboot."""
|
||||
if not self.dry_run:
|
||||
try:
|
||||
os.system("reboot")
|
||||
except Exception:
|
||||
pass
|
||||
self.root.destroy()
|
||||
|
||||
def run(self) -> None:
|
||||
"""Start the Tkinter mainloop."""
|
||||
self.root.mainloop()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
"""GUI Entrypoint."""
|
||||
dry_run = "--dry-run" in sys.argv
|
||||
try:
|
||||
app = GuiInstaller(dry_run=dry_run)
|
||||
app.run()
|
||||
return 0
|
||||
except RuntimeError as e:
|
||||
sys.stderr.write(f"\n[BŁĄD GUI]: {e}\n\n")
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,252 @@
|
||||
"""Partitioning and filesystem formatting for GPT/MBR disks."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Callable, Optional
|
||||
|
||||
from .disk import DiskManager
|
||||
from .types import BootMode, InstallConfig, TargetPartitions
|
||||
from .utils import err, info, ok, run_cmd, warn, which
|
||||
|
||||
|
||||
class Partitioner:
|
||||
"""Handles disk wiping, partitioning (GPT/MBR), and filesystem creation."""
|
||||
|
||||
def __init__(self, dry_run: bool = False, log_func: Optional[Callable[[str], None]] = None):
|
||||
self.dry_run = dry_run
|
||||
self.log_func = log_func
|
||||
self.disk_manager = DiskManager(dry_run=dry_run)
|
||||
|
||||
def _log(self, text: str) -> None:
|
||||
if self.log_func:
|
||||
self.log_func(text)
|
||||
|
||||
def wipe_disk_signatures(self, disk_path: str) -> None:
|
||||
"""Zero out MBR/GPT headers at beginning and end of disk, and run wipefs."""
|
||||
self._log(f"Wiping existing partition headers on {disk_path}...")
|
||||
|
||||
# Run wipefs if available
|
||||
if which("wipefs"):
|
||||
run_cmd(["wipefs", "--all", "--force", disk_path], check=False, dry_run=self.dry_run, log_func=self.log_func)
|
||||
|
||||
# Zero out the first 10MB
|
||||
run_cmd(
|
||||
["dd", "if=/dev/zero", f"of={disk_path}", "bs=1M", "count=10", "conv=notrunc"],
|
||||
check=False,
|
||||
dry_run=self.dry_run,
|
||||
log_func=self.log_func,
|
||||
)
|
||||
|
||||
# Zero out the last 2MB (for secondary GPT headers)
|
||||
size_bytes = self.disk_manager.get_disk_size(disk_path)
|
||||
if size_bytes > 20 * 1024 * 1024:
|
||||
seek_sectors = (size_bytes // 512) - 4096
|
||||
run_cmd(
|
||||
["dd", "if=/dev/zero", f"of={disk_path}", f"seek={seek_sectors}", "count=4096", "bs=512", "conv=notrunc"],
|
||||
check=False,
|
||||
dry_run=self.dry_run,
|
||||
log_func=self.log_func,
|
||||
)
|
||||
|
||||
def generate_sfdisk_script(self, config: InstallConfig) -> str:
|
||||
"""Generate sfdisk partition table script based on boot mode and sizing options."""
|
||||
lines = []
|
||||
|
||||
if config.boot_mode == BootMode.UEFI:
|
||||
lines.append("label: gpt")
|
||||
# Partition 1: EFI System Partition (type U in sfdisk = c12a7328-f81f-11d2-ba4b-00a0c93ec93b)
|
||||
lines.append(f"size={config.efi_size_mb}M, type=U")
|
||||
|
||||
if config.swap_size_mb > 0:
|
||||
# Partition 2: Linux Swap (type S = 0657fd6d-a4ab-43c4-84e5-0933c84b4f4f)
|
||||
lines.append(f"size={config.swap_size_mb}M, type=S")
|
||||
|
||||
# Partition 3 (or 2): Linux root filesystem (type L = 4f68bce3-e8cd-4db1-96e7-fbcaf984b709)
|
||||
lines.append("type=L")
|
||||
else:
|
||||
# BIOS / MBR mode
|
||||
lines.append("label: dos")
|
||||
if config.swap_size_mb > 0:
|
||||
# Root partition first, leaving room or swap first
|
||||
lines.append(f"size={config.swap_size_mb}M, type=82")
|
||||
lines.append("type=83, bootable")
|
||||
else:
|
||||
lines.append("type=83, bootable")
|
||||
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
def partition_disk(self, config: InstallConfig) -> TargetPartitions:
|
||||
"""Create partitions on the target disk according to configuration."""
|
||||
disk = config.target_disk
|
||||
|
||||
# Unmount any existing partitions on this disk
|
||||
self.disk_manager.unmount_all_partitions(disk)
|
||||
|
||||
# Wipe signatures
|
||||
self.wipe_disk_signatures(disk)
|
||||
|
||||
# Partitioning execution
|
||||
success = False
|
||||
if which("sfdisk"):
|
||||
success = self._partition_with_sfdisk(config)
|
||||
if not success and which("parted"):
|
||||
success = self._partition_with_parted(config)
|
||||
if not success:
|
||||
success = self._partition_with_fdisk(config)
|
||||
|
||||
if not success and not self.dry_run:
|
||||
raise RuntimeError(f"Failed to partition disk {disk} using sfdisk, parted, or fdisk.")
|
||||
|
||||
# Reread partition table
|
||||
self.disk_manager.reread_partition_table(disk)
|
||||
|
||||
# Determine partition device paths
|
||||
target_parts = self._resolve_target_partitions(config)
|
||||
self._verify_partition_nodes(target_parts)
|
||||
|
||||
return target_parts
|
||||
|
||||
def _partition_with_sfdisk(self, config: InstallConfig) -> bool:
|
||||
"""Execute partitioning via sfdisk."""
|
||||
script = self.generate_sfdisk_script(config)
|
||||
self._log(f"Applying sfdisk layout to {config.target_disk}:\n{script}")
|
||||
res = run_cmd(
|
||||
["sfdisk", "--wipe", "always", config.target_disk],
|
||||
stdin_input=script,
|
||||
check=False,
|
||||
dry_run=self.dry_run,
|
||||
log_func=self.log_func,
|
||||
)
|
||||
return res.success
|
||||
|
||||
def _partition_with_parted(self, config: InstallConfig) -> bool:
|
||||
"""Execute partitioning via parted fallback."""
|
||||
disk = config.target_disk
|
||||
self._log(f"Partitioning {disk} using parted fallback...")
|
||||
|
||||
if config.boot_mode == BootMode.UEFI:
|
||||
cmd = ["parted", "-s", disk, "mklabel", "gpt"]
|
||||
run_cmd(cmd, check=False, dry_run=self.dry_run, log_func=self.log_func)
|
||||
|
||||
efi_end = 1 + config.efi_size_mb
|
||||
cmd = ["parted", "-s", disk, "mkpart", "ESP", "fat32", "1MiB", f"{efi_end}MiB", "set", "1", "esp", "on"]
|
||||
run_cmd(cmd, check=False, dry_run=self.dry_run, log_func=self.log_func)
|
||||
|
||||
if config.swap_size_mb > 0:
|
||||
swap_end = efi_end + config.swap_size_mb
|
||||
cmd = ["parted", "-s", disk, "mkpart", "swap", "linux-swap", f"{efi_end}MiB", f"{swap_end}MiB"]
|
||||
run_cmd(cmd, check=False, dry_run=self.dry_run, log_func=self.log_func)
|
||||
cmd = ["parted", "-s", disk, "mkpart", "primary", "ext4", f"{swap_end}MiB", "100%"]
|
||||
run_cmd(cmd, check=False, dry_run=self.dry_run, log_func=self.log_func)
|
||||
else:
|
||||
cmd = ["parted", "-s", disk, "mkpart", "primary", "ext4", f"{efi_end}MiB", "100%"]
|
||||
run_cmd(cmd, check=False, dry_run=self.dry_run, log_func=self.log_func)
|
||||
else:
|
||||
cmd = ["parted", "-s", disk, "mklabel", "msdos"]
|
||||
run_cmd(cmd, check=False, dry_run=self.dry_run, log_func=self.log_func)
|
||||
|
||||
if config.swap_size_mb > 0:
|
||||
swap_end = 1 + config.swap_size_mb
|
||||
cmd = ["parted", "-s", disk, "mkpart", "primary", "linux-swap", "1MiB", f"{swap_end}MiB"]
|
||||
run_cmd(cmd, check=False, dry_run=self.dry_run, log_func=self.log_func)
|
||||
cmd = ["parted", "-s", disk, "mkpart", "primary", "ext4", f"{swap_end}MiB", "100%", "set", "2", "boot", "on"]
|
||||
run_cmd(cmd, check=False, dry_run=self.dry_run, log_func=self.log_func)
|
||||
else:
|
||||
cmd = ["parted", "-s", disk, "mkpart", "primary", "ext4", "1MiB", "100%", "set", "1", "boot", "on"]
|
||||
run_cmd(cmd, check=False, dry_run=self.dry_run, log_func=self.log_func)
|
||||
|
||||
return True
|
||||
|
||||
def _partition_with_fdisk(self, config: InstallConfig) -> bool:
|
||||
"""Execute partitioning via classic fdisk script."""
|
||||
disk = config.target_disk
|
||||
self._log(f"Partitioning {disk} using fdisk script fallback...")
|
||||
|
||||
if config.boot_mode == BootMode.UEFI:
|
||||
# fdisk script: new DOS/GPT label, partition 1 +512M EFI, partition 2 root
|
||||
script = f"g\nn\n1\n\n+{config.efi_size_mb}M\nt\n1\nn\n2\n\n\nw\n"
|
||||
else:
|
||||
# fdisk script: DOS label, partition 1 full size, set bootable
|
||||
script = "o\nn\np\n1\n\n\na\n1\nw\n"
|
||||
|
||||
res = run_cmd(["fdisk", disk], stdin_input=script, check=False, dry_run=self.dry_run, log_func=self.log_func)
|
||||
return res.success
|
||||
|
||||
def _resolve_target_partitions(self, config: InstallConfig) -> TargetPartitions:
|
||||
"""Resolve partition device paths for target disk."""
|
||||
disk = config.target_disk
|
||||
|
||||
if config.boot_mode == BootMode.UEFI:
|
||||
efi_part = self.disk_manager.get_partition_path(disk, 1)
|
||||
if config.swap_size_mb > 0:
|
||||
swap_part = self.disk_manager.get_partition_path(disk, 2)
|
||||
root_part = self.disk_manager.get_partition_path(disk, 3)
|
||||
else:
|
||||
swap_part = None
|
||||
root_part = self.disk_manager.get_partition_path(disk, 2)
|
||||
return TargetPartitions(disk_path=disk, root_part=root_part, efi_part=efi_part, swap_part=swap_part)
|
||||
else:
|
||||
if config.swap_size_mb > 0:
|
||||
swap_part = self.disk_manager.get_partition_path(disk, 1)
|
||||
root_part = self.disk_manager.get_partition_path(disk, 2)
|
||||
else:
|
||||
swap_part = None
|
||||
root_part = self.disk_manager.get_partition_path(disk, 1)
|
||||
return TargetPartitions(disk_path=disk, root_part=root_part, efi_part=None, swap_part=swap_part)
|
||||
|
||||
def _verify_partition_nodes(self, targets: TargetPartitions) -> None:
|
||||
"""Verify device nodes exist in /dev, recreating via mknod if needed."""
|
||||
if self.dry_run:
|
||||
return
|
||||
|
||||
for part in [targets.root_part, targets.efi_part, targets.swap_part]:
|
||||
if not part:
|
||||
continue
|
||||
if not os.path.exists(part):
|
||||
# Try finding in /proc/partitions
|
||||
bname = os.path.basename(part)
|
||||
proc_part = Path("/proc/partitions")
|
||||
if proc_part.exists():
|
||||
for line in proc_part.read_text().splitlines():
|
||||
parts = line.split()
|
||||
if len(parts) >= 4 and parts[3] == bname:
|
||||
major, minor = int(parts[0]), int(parts[1])
|
||||
self._log(f"Creating missing devnode {part} (major={major}, minor={minor})")
|
||||
run_cmd(["mknod", part, "b", str(major), str(minor)], check=False, dry_run=self.dry_run)
|
||||
break
|
||||
|
||||
def format_partitions(self, targets: TargetPartitions) -> None:
|
||||
"""Format the generated partitions with appropriate filesystems."""
|
||||
# 1. Format EFI if present
|
||||
if targets.efi_part:
|
||||
self._log(f"Formatting EFI partition {targets.efi_part} as FAT32...")
|
||||
res = run_cmd(["mkfs.vfat", "-F32", targets.efi_part], check=False, dry_run=self.dry_run, log_func=self.log_func)
|
||||
if not res.success and which("mkfs.fat"):
|
||||
run_cmd(["mkfs.fat", "-F32", targets.efi_part], check=False, dry_run=self.dry_run, log_func=self.log_func)
|
||||
|
||||
# 2. Format Swap if present
|
||||
if targets.swap_part:
|
||||
self._log(f"Formatting Swap partition {targets.swap_part}...")
|
||||
run_cmd(["mkswap", "-L", "KHOS_SWAP", targets.swap_part], check=False, dry_run=self.dry_run, log_func=self.log_func)
|
||||
|
||||
# 3. Format Root (ext4)
|
||||
self._log(f"Formatting Root partition {targets.root_part} as EXT4 (Label: KHOS)...")
|
||||
res = run_cmd(
|
||||
["mkfs.ext4", "-F", "-L", "KHOS", targets.root_part],
|
||||
check=False,
|
||||
dry_run=self.dry_run,
|
||||
log_func=self.log_func,
|
||||
)
|
||||
if not res.success:
|
||||
res = run_cmd(["mke2fs", "-t", "ext4", "-F", "-L", "KHOS", targets.root_part], check=False, dry_run=self.dry_run, log_func=self.log_func)
|
||||
if not res.success and not self.dry_run:
|
||||
raise RuntimeError(f"Failed to format root partition {targets.root_part} with ext4.")
|
||||
|
||||
# Read back UUIDs
|
||||
targets.root_uuid = self.disk_manager.get_partition_uuid(targets.root_part)
|
||||
if targets.efi_part:
|
||||
targets.efi_uuid = self.disk_manager.get_partition_uuid(targets.efi_part)
|
||||
self._log(f"Root UUID: {targets.root_uuid}, EFI UUID: {targets.efi_uuid}")
|
||||
@@ -0,0 +1,171 @@
|
||||
"""Data types, Enums, and Configuration models for KhOS Installer."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from enum import Enum
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
|
||||
class BootMode(str, Enum):
|
||||
"""System firmware boot mode."""
|
||||
UEFI = "uefi"
|
||||
BIOS = "bios"
|
||||
|
||||
@property
|
||||
def label(self) -> str:
|
||||
if self == BootMode.UEFI:
|
||||
return "UEFI (GPT)"
|
||||
return "BIOS (MBR / Legacy)"
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.value
|
||||
|
||||
|
||||
class DesktopEnvironment(str, Enum):
|
||||
"""Available KhOS desktop environments."""
|
||||
XFCE = "xfce"
|
||||
PLASMA = "plasma"
|
||||
HYPRLAND = "hyprland"
|
||||
OPENBOX = "openbox"
|
||||
|
||||
@property
|
||||
def display_name(self) -> str:
|
||||
names = {
|
||||
DesktopEnvironment.XFCE: "XFCE 4 (Lekkie, stabilne - domyślne)",
|
||||
DesktopEnvironment.PLASMA: "KDE Plasma 6 (Nowoczesne, zaawansowane)",
|
||||
DesktopEnvironment.HYPRLAND: "Hyprland (Nowoczesny Wayland Tiling WM)",
|
||||
DesktopEnvironment.OPENBOX: "Openbox (Minimalistyczne X11)",
|
||||
}
|
||||
return names.get(self, self.value)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.value
|
||||
|
||||
|
||||
@dataclass
|
||||
class PartitionInfo:
|
||||
"""Information regarding a disk partition."""
|
||||
name: str
|
||||
path: str
|
||||
size_bytes: int = 0
|
||||
size_human: str = ""
|
||||
fs_type: Optional[str] = None
|
||||
uuid: Optional[str] = None
|
||||
mount_point: Optional[str] = None
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
@dataclass
|
||||
class DiskInfo:
|
||||
"""Information regarding a block storage device."""
|
||||
name: str
|
||||
path: str
|
||||
size_bytes: int = 0
|
||||
size_gb: float = 0.0
|
||||
model: str = "Unknown Disk"
|
||||
is_removable: bool = False
|
||||
is_rotational: bool = False
|
||||
partitions: List[PartitionInfo] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def disk_type(self) -> str:
|
||||
if self.name.startswith("nvme"):
|
||||
return "NVMe SSD"
|
||||
if not self.is_rotational:
|
||||
return "SATA/VirtIO SSD"
|
||||
return "HDD"
|
||||
|
||||
def summary(self) -> str:
|
||||
removable_str = " [Wymienny/USB]" if self.is_removable else ""
|
||||
return f"{self.path} ({self.size_gb:.1f} GB, {self.disk_type}) - {self.model}{removable_str}"
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
@dataclass
|
||||
class TargetPartitions:
|
||||
"""Device paths for target partitions generated on disk."""
|
||||
disk_path: str
|
||||
root_part: str
|
||||
efi_part: Optional[str] = None
|
||||
swap_part: Optional[str] = None
|
||||
root_uuid: Optional[str] = None
|
||||
efi_uuid: Optional[str] = None
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
@dataclass
|
||||
class InstallConfig:
|
||||
"""Full configuration specification for system installation."""
|
||||
target_disk: str = ""
|
||||
boot_mode: BootMode = BootMode.BIOS
|
||||
hostname: str = "khos"
|
||||
root_password: str = "khos"
|
||||
username: Optional[str] = None
|
||||
user_password: Optional[str] = None
|
||||
desktop: DesktopEnvironment = DesktopEnvironment.XFCE
|
||||
efi_size_mb: int = 512
|
||||
swap_size_mb: int = 0
|
||||
source_path: Optional[str] = None
|
||||
mount_point: str = "/mnt/install_target"
|
||||
dry_run: bool = False
|
||||
json_output: bool = False
|
||||
auto_mode: bool = False
|
||||
|
||||
def validate(self) -> List[str]:
|
||||
"""Validate the configuration and return list of validation error messages."""
|
||||
errors: List[str] = []
|
||||
if not self.target_disk:
|
||||
errors.append("Target disk cannot be empty.")
|
||||
if not self.hostname or not self.hostname.replace("-", "").isalnum():
|
||||
errors.append(f"Invalid hostname '{self.hostname}'. Must be alphanumeric and hyphens.")
|
||||
if not self.root_password:
|
||||
errors.append("Root password cannot be empty.")
|
||||
if self.username:
|
||||
if not self.username.isidentifier():
|
||||
errors.append(f"Invalid username '{self.username}'. Must be a valid Unix identifier.")
|
||||
if not self.user_password:
|
||||
errors.append("User password must be set when username is provided.")
|
||||
if self.efi_size_mb < 64:
|
||||
errors.append("EFI partition size must be at least 64 MB.")
|
||||
return errors
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
d = asdict(self)
|
||||
d["boot_mode"] = self.boot_mode.value
|
||||
d["desktop"] = self.desktop.value
|
||||
# Mask passwords for security if serialized
|
||||
if d.get("root_password"):
|
||||
d["root_password_set"] = True
|
||||
del d["root_password"]
|
||||
if d.get("user_password"):
|
||||
d["user_password_set"] = True
|
||||
del d["user_password"]
|
||||
return d
|
||||
|
||||
def to_json(self) -> str:
|
||||
return json.dumps(self.to_dict(), indent=2)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ProgressEvent:
|
||||
"""Event emitted during the installation process."""
|
||||
event_type: str # "stage", "progress", "log", "completed", "error"
|
||||
percent: int = 0
|
||||
stage: str = ""
|
||||
message: str = ""
|
||||
details: Dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
def to_json(self) -> str:
|
||||
return json.dumps(self.to_dict())
|
||||
@@ -0,0 +1,216 @@
|
||||
"""Utility helpers: Safe process execution, ANSI styling, and structured logging."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Callable, Dict, List, Optional, Union
|
||||
|
||||
# ANSI Colors
|
||||
C_RESET = "\033[0m"
|
||||
C_BOLD = "\033[1m"
|
||||
C_DIM = "\033[2m"
|
||||
C_RED = "\033[1;31m"
|
||||
C_GREEN = "\033[1;32m"
|
||||
C_YELLOW = "\033[1;33m"
|
||||
C_BLUE = "\033[1;34m"
|
||||
C_MAGENTA = "\033[1;35m"
|
||||
C_CYAN = "\033[1;36m"
|
||||
C_WHITE = "\033[1;37m"
|
||||
|
||||
_COLOR_ENABLED = sys.stdout.isatty() and os.name != "nt" or os.environ.get("FORCE_COLOR") == "1"
|
||||
|
||||
|
||||
def set_color_enabled(enabled: bool) -> None:
|
||||
"""Enable or disable ANSI colors."""
|
||||
global _COLOR_ENABLED
|
||||
_COLOR_ENABLED = enabled
|
||||
|
||||
|
||||
def colorize(text: str, color_code: str) -> str:
|
||||
"""Wrap text in ANSI color codes if colors are enabled."""
|
||||
if _COLOR_ENABLED:
|
||||
return f"{color_code}{text}{C_RESET}"
|
||||
return text
|
||||
|
||||
|
||||
def msg(text: str) -> None:
|
||||
"""Print high-level step header."""
|
||||
prefix = colorize("==>", C_BLUE)
|
||||
print(f"{prefix} {colorize(text, C_BOLD)}")
|
||||
|
||||
|
||||
def info(text: str) -> None:
|
||||
"""Print informative detail."""
|
||||
prefix = colorize(" ->", C_CYAN)
|
||||
print(f"{prefix} {text}")
|
||||
|
||||
|
||||
def ok(text: str) -> None:
|
||||
"""Print success message."""
|
||||
prefix = colorize("[OK]", C_GREEN)
|
||||
print(f" {prefix} {text}")
|
||||
|
||||
|
||||
def warn(text: str) -> None:
|
||||
"""Print warning message."""
|
||||
prefix = colorize("[OSTRZEŻENIE]", C_YELLOW)
|
||||
print(f"{prefix} {text}")
|
||||
|
||||
|
||||
def err(text: str) -> None:
|
||||
"""Print error message to stderr."""
|
||||
prefix = colorize("[BŁĄD]", C_RED)
|
||||
sys.stderr.write(f"{prefix} {text}\n")
|
||||
sys.stderr.flush()
|
||||
|
||||
|
||||
def format_bytes(size_bytes: int) -> str:
|
||||
"""Format bytes into human-readable string (KB, MB, GB, TB)."""
|
||||
if size_bytes < 1024:
|
||||
return f"{size_bytes} B"
|
||||
units = ["KB", "MB", "GB", "TB", "PB"]
|
||||
value = float(size_bytes)
|
||||
for unit in units:
|
||||
value /= 1024.0
|
||||
if value < 1024.0 or unit == units[-1]:
|
||||
return f"{value:.1f} {unit}"
|
||||
return f"{size_bytes} B"
|
||||
|
||||
|
||||
def check_root() -> bool:
|
||||
"""Check if the current process has superuser / root privileges."""
|
||||
if hasattr(os, "geteuid"):
|
||||
return os.geteuid() == 0
|
||||
return False
|
||||
|
||||
|
||||
def which(command: str) -> Optional[str]:
|
||||
"""Find absolute path of an executable in PATH."""
|
||||
return shutil.which(command)
|
||||
|
||||
|
||||
@dataclass
|
||||
class CmdResult:
|
||||
"""Result of an executed subprocess command."""
|
||||
command: List[str]
|
||||
returncode: int
|
||||
stdout: str
|
||||
stderr: str
|
||||
elapsed_seconds: float = 0.0
|
||||
|
||||
@property
|
||||
def success(self) -> bool:
|
||||
return self.returncode == 0
|
||||
|
||||
|
||||
def run_cmd(
|
||||
cmd: Union[List[str], str],
|
||||
check: bool = True,
|
||||
dry_run: bool = False,
|
||||
stdin_input: Optional[str] = None,
|
||||
timeout: Optional[float] = None,
|
||||
env: Optional[Dict[str, str]] = None,
|
||||
log_func: Optional[Callable[[str], None]] = None,
|
||||
) -> CmdResult:
|
||||
"""Safely run an external system command with logging and error handling.
|
||||
|
||||
Args:
|
||||
cmd: Command as a list of strings (or string when shell=True is needed).
|
||||
check: If True, raises RuntimeError when returncode != 0.
|
||||
dry_run: If True, logs the command without executing.
|
||||
stdin_input: String to pass to stdin of process.
|
||||
timeout: Execution timeout in seconds.
|
||||
env: Optional environment variables dictionary.
|
||||
log_func: Optional callback function receiving log lines.
|
||||
"""
|
||||
if isinstance(cmd, str):
|
||||
cmd_list = cmd.split()
|
||||
else:
|
||||
cmd_list = [str(x) for x in cmd]
|
||||
|
||||
cmd_str = " ".join(cmd_list)
|
||||
if log_func:
|
||||
log_func(f"$ {cmd_str}")
|
||||
|
||||
if dry_run:
|
||||
if log_func:
|
||||
log_func(f"[DRY-RUN] Simulating: {cmd_str}")
|
||||
return CmdResult(command=cmd_list, returncode=0, stdout="[simulated dry-run output]", stderr="")
|
||||
|
||||
exec_env = os.environ.copy()
|
||||
if env:
|
||||
exec_env.update(env)
|
||||
|
||||
start_time = time.time()
|
||||
try:
|
||||
proc = subprocess.Popen(
|
||||
cmd_list,
|
||||
stdin=subprocess.PIPE if stdin_input is not None else None,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
env=exec_env,
|
||||
)
|
||||
|
||||
stdout, stderr = proc.communicate(input=stdin_input, timeout=timeout)
|
||||
elapsed = time.time() - start_time
|
||||
returncode = proc.returncode
|
||||
|
||||
if log_func and stdout.strip():
|
||||
for line in stdout.strip().splitlines()[:5]: # Log first few lines
|
||||
log_func(f" {line}")
|
||||
|
||||
result = CmdResult(
|
||||
command=cmd_list,
|
||||
returncode=returncode,
|
||||
stdout=stdout or "",
|
||||
stderr=stderr or "",
|
||||
elapsed_seconds=elapsed,
|
||||
)
|
||||
|
||||
if check and returncode != 0:
|
||||
error_details = stderr.strip() or stdout.strip() or f"Exit code {returncode}"
|
||||
raise RuntimeError(f"Command failed ({returncode}): {cmd_str}\n{error_details}")
|
||||
|
||||
return result
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
proc.communicate()
|
||||
raise TimeoutError(f"Command timed out after {timeout}s: {cmd_str}")
|
||||
except FileNotFoundError:
|
||||
if check:
|
||||
raise RuntimeError(f"Executable not found: {cmd_list[0]}")
|
||||
return CmdResult(command=cmd_list, returncode=127, stdout="", stderr="Executable not found")
|
||||
|
||||
|
||||
class JsonEventLogger:
|
||||
"""Logger that emits structured JSON events to a stream or callback."""
|
||||
|
||||
def __init__(self, stream=None, callback: Optional[Callable[[Dict[str, Any]], None]] = None):
|
||||
self.stream = stream or sys.stdout
|
||||
self.callback = callback
|
||||
|
||||
def emit(self, event_type: str, **kwargs: Any) -> Dict[str, Any]:
|
||||
event_dict = {
|
||||
"type": event_type,
|
||||
"timestamp": time.time(),
|
||||
**kwargs,
|
||||
}
|
||||
if self.callback:
|
||||
self.callback(event_dict)
|
||||
if self.stream:
|
||||
try:
|
||||
line = json.dumps(event_dict)
|
||||
self.stream.write(line + "\n")
|
||||
self.stream.flush()
|
||||
except Exception:
|
||||
pass
|
||||
return event_dict
|
||||
@@ -0,0 +1,38 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=61.0", "wheel"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "khos-installer"
|
||||
version = "1.1.0"
|
||||
description = "Professional System Installer for KhOS Linux"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.8"
|
||||
license = { text = "MIT" }
|
||||
authors = [
|
||||
{ name = "KhOS Team", email = "dev@khos.local" }
|
||||
]
|
||||
classifiers = [
|
||||
"Development Status :: 5 - Production/Stable",
|
||||
"Environment :: Console",
|
||||
"Environment :: X11 Applications",
|
||||
"Intended Audience :: System Administrators",
|
||||
"Operating System :: POSIX :: Linux",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.8",
|
||||
"Programming Language :: Python :: 3.9",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
"Programming Language :: Python :: 3.12",
|
||||
"Programming Language :: Python :: 3.13",
|
||||
"Programming Language :: Python :: 3.14",
|
||||
"Topic :: System :: Installation/Setup",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
khos-installer = "khos_installer.cli:main"
|
||||
khos-installer-gui = "khos_installer.gui:main"
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
where = ["."]
|
||||
include = ["khos_installer*"]
|
||||
@@ -0,0 +1,15 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Entrypoint script for KhOS GUI System Installer."""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# Ensure local package is in sys.path
|
||||
SCRIPT_DIR = Path(__file__).resolve().parent
|
||||
if str(SCRIPT_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(SCRIPT_DIR))
|
||||
|
||||
from khos_installer.gui import main
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,15 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Entrypoint script for KhOS CLI System Installer."""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# Ensure local package is in sys.path
|
||||
SCRIPT_DIR = Path(__file__).resolve().parent
|
||||
if str(SCRIPT_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(SCRIPT_DIR))
|
||||
|
||||
from khos_installer.cli import main
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,27 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Setup script for khos-installer package."""
|
||||
|
||||
from setuptools import find_packages, setup
|
||||
|
||||
setup(
|
||||
name="khos-installer",
|
||||
version="1.1.0",
|
||||
description="Professional System Installer for KhOS Linux",
|
||||
long_description=open("README.md", encoding="utf-8").read() if __import__("os").path.exists("README.md") else "",
|
||||
long_description_content_type="text/markdown",
|
||||
author="KhOS Team",
|
||||
packages=find_packages(),
|
||||
python_requires=">=3.8",
|
||||
entry_points={
|
||||
"console_scripts": [
|
||||
"khos-installer = khos_installer.cli:main",
|
||||
"khos-installer-gui = khos_installer.gui:main",
|
||||
],
|
||||
},
|
||||
classifiers=[
|
||||
"Development Status :: 5 - Production/Stable",
|
||||
"Operating System :: POSIX :: Linux",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Topic :: System :: Installation/Setup",
|
||||
],
|
||||
)
|
||||
@@ -0,0 +1,382 @@
|
||||
"""Unit tests for KhOS Installer package.
|
||||
|
||||
Mocks external disk calls, subprocesses, and verifies generated configurations.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
# Ensure installer/python is in sys.path
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
if str(BASE_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(BASE_DIR))
|
||||
|
||||
from khos_installer.bootloader import generate_extlinux_config, generate_grub_config
|
||||
from khos_installer.cli import build_argument_parser
|
||||
from khos_installer.config import (
|
||||
SystemConfigurator,
|
||||
generate_fstab,
|
||||
generate_hostname,
|
||||
generate_hosts,
|
||||
hash_password_sha512,
|
||||
)
|
||||
from khos_installer.core import InstallerCore
|
||||
from khos_installer.disk import DiskManager, detect_boot_mode
|
||||
from khos_installer.partitioner import Partitioner
|
||||
from khos_installer.types import (
|
||||
BootMode,
|
||||
DesktopEnvironment,
|
||||
DiskInfo,
|
||||
InstallConfig,
|
||||
ProgressEvent,
|
||||
TargetPartitions,
|
||||
)
|
||||
from khos_installer.utils import CmdResult, format_bytes, run_cmd
|
||||
|
||||
|
||||
class TestDiskManager(unittest.TestCase):
|
||||
"""Test disk queries and partition path resolution."""
|
||||
|
||||
def setUp(self):
|
||||
self.dm = DiskManager(dry_run=True)
|
||||
|
||||
def test_partition_path_resolution(self):
|
||||
self.assertEqual(DiskManager.get_partition_path("/dev/sda", 1), "/dev/sda1")
|
||||
self.assertEqual(DiskManager.get_partition_path("/dev/sdb", 2), "/dev/sdb2")
|
||||
self.assertEqual(DiskManager.get_partition_path("/dev/nvme0n1", 1), "/dev/nvme0n1p1")
|
||||
self.assertEqual(DiskManager.get_partition_path("/dev/nvme0n1", 2), "/dev/nvme0n1p2")
|
||||
self.assertEqual(DiskManager.get_partition_path("/dev/mmcblk0", 1), "/dev/mmcblk0p1")
|
||||
self.assertEqual(DiskManager.get_partition_path("/dev/loop0", 1), "/dev/loop0p1")
|
||||
|
||||
def test_boot_mode_env_override(self):
|
||||
with patch.dict(os.environ, {"KHOS_BOOT_MODE": "uefi"}):
|
||||
self.assertEqual(detect_boot_mode(), BootMode.UEFI)
|
||||
|
||||
with patch.dict(os.environ, {"KHOS_BOOT_MODE": "bios"}):
|
||||
self.assertEqual(detect_boot_mode(), BootMode.BIOS)
|
||||
|
||||
@patch("khos_installer.disk.run_cmd")
|
||||
def test_get_partition_uuid(self, mock_run_cmd):
|
||||
mock_run_cmd.return_value = CmdResult(
|
||||
command=[], returncode=0, stdout="1234-abcd-5678\n", stderr=""
|
||||
)
|
||||
uuid = self.dm.get_partition_uuid("/dev/sda1")
|
||||
self.assertEqual(uuid, "1234-abcd-5678")
|
||||
|
||||
@patch("khos_installer.disk.run_cmd")
|
||||
def test_get_partition_uuid_fallback_regex(self, mock_run_cmd):
|
||||
mock_run_cmd.side_effect = [
|
||||
CmdResult(command=[], returncode=1, stdout="", stderr=""), # first blkid -s fails
|
||||
CmdResult(
|
||||
command=[],
|
||||
returncode=0,
|
||||
stdout='/dev/sda2: UUID="a1b2c3d4-e5f6-7890-abcd-ef0123456789" TYPE="ext4"\n',
|
||||
stderr="",
|
||||
),
|
||||
]
|
||||
uuid = self.dm.get_partition_uuid("/dev/sda2")
|
||||
self.assertEqual(uuid, "a1b2c3d4-e5f6-7890-abcd-ef0123456789")
|
||||
|
||||
def test_fallback_scan(self):
|
||||
disks = self.dm._fallback_scan()
|
||||
self.assertGreaterEqual(len(disks), 1)
|
||||
self.assertEqual(disks[0].path, "/dev/sda")
|
||||
self.assertEqual(disks[0].size_gb, 64.0)
|
||||
|
||||
|
||||
class TestPartitioner(unittest.TestCase):
|
||||
"""Test partition layout scripting and partition resolving."""
|
||||
|
||||
def setUp(self):
|
||||
self.partitioner = Partitioner(dry_run=True)
|
||||
|
||||
def test_generate_sfdisk_script_uefi(self):
|
||||
config = InstallConfig(
|
||||
target_disk="/dev/sda",
|
||||
boot_mode=BootMode.UEFI,
|
||||
efi_size_mb=512,
|
||||
swap_size_mb=0,
|
||||
)
|
||||
script = self.partitioner.generate_sfdisk_script(config)
|
||||
self.assertIn("label: gpt", script)
|
||||
self.assertIn("size=512M, type=U", script)
|
||||
self.assertIn("type=L", script)
|
||||
|
||||
def test_generate_sfdisk_script_uefi_with_swap(self):
|
||||
config = InstallConfig(
|
||||
target_disk="/dev/sda",
|
||||
boot_mode=BootMode.UEFI,
|
||||
efi_size_mb=256,
|
||||
swap_size_mb=2048,
|
||||
)
|
||||
script = self.partitioner.generate_sfdisk_script(config)
|
||||
self.assertIn("label: gpt", script)
|
||||
self.assertIn("size=256M, type=U", script)
|
||||
self.assertIn("size=2048M, type=S", script)
|
||||
self.assertIn("type=L", script)
|
||||
|
||||
def test_generate_sfdisk_script_bios(self):
|
||||
config = InstallConfig(
|
||||
target_disk="/dev/vda",
|
||||
boot_mode=BootMode.BIOS,
|
||||
swap_size_mb=0,
|
||||
)
|
||||
script = self.partitioner.generate_sfdisk_script(config)
|
||||
self.assertIn("label: dos", script)
|
||||
self.assertIn("type=83, bootable", script)
|
||||
|
||||
def test_resolve_target_partitions_uefi(self):
|
||||
config = InstallConfig(
|
||||
target_disk="/dev/sda",
|
||||
boot_mode=BootMode.UEFI,
|
||||
swap_size_mb=0,
|
||||
)
|
||||
targets = self.partitioner._resolve_target_partitions(config)
|
||||
self.assertEqual(targets.disk_path, "/dev/sda")
|
||||
self.assertEqual(targets.efi_part, "/dev/sda1")
|
||||
self.assertEqual(targets.root_part, "/dev/sda2")
|
||||
self.assertIsNone(targets.swap_part)
|
||||
|
||||
def test_resolve_target_partitions_bios_nvme(self):
|
||||
config = InstallConfig(
|
||||
target_disk="/dev/nvme0n1",
|
||||
boot_mode=BootMode.BIOS,
|
||||
swap_size_mb=1024,
|
||||
)
|
||||
targets = self.partitioner._resolve_target_partitions(config)
|
||||
self.assertEqual(targets.disk_path, "/dev/nvme0n1")
|
||||
self.assertIsNone(targets.efi_part)
|
||||
self.assertEqual(targets.swap_part, "/dev/nvme0n1p1")
|
||||
self.assertEqual(targets.root_part, "/dev/nvme0n1p2")
|
||||
|
||||
|
||||
class TestSystemConfig(unittest.TestCase):
|
||||
"""Test generating fstab, hostname, hosts, password hashing, and user creation."""
|
||||
|
||||
def test_generate_fstab_with_uuids(self):
|
||||
targets = TargetPartitions(
|
||||
disk_path="/dev/sda",
|
||||
root_part="/dev/sda2",
|
||||
efi_part="/dev/sda1",
|
||||
swap_part="/dev/sda3",
|
||||
root_uuid="root-uuid-1111",
|
||||
efi_uuid="efi-uuid-2222",
|
||||
)
|
||||
fstab = generate_fstab(targets)
|
||||
self.assertIn("UUID=root-uuid-1111", fstab)
|
||||
self.assertIn("/ ext4", fstab)
|
||||
self.assertIn("UUID=efi-uuid-2222", fstab)
|
||||
self.assertIn("/boot/efi vfat", fstab)
|
||||
self.assertIn("/dev/sda3", fstab)
|
||||
self.assertIn("proc", fstab)
|
||||
self.assertIn("sysfs", fstab)
|
||||
self.assertIn("devtmpfs", fstab)
|
||||
self.assertIn("tmpfs", fstab)
|
||||
|
||||
def test_generate_hostname_and_hosts(self):
|
||||
self.assertEqual(generate_hostname("khos-box"), "khos-box\n")
|
||||
hosts = generate_hosts("khos-box")
|
||||
self.assertIn("127.0.0.1 localhost khos-box", hosts)
|
||||
self.assertIn("::1 localhost ip6-localhost", hosts)
|
||||
|
||||
def test_password_hash_sha512(self):
|
||||
hashed = hash_password_sha512("khos_test_pass")
|
||||
self.assertTrue(hashed.startswith("$6$"))
|
||||
# Second hashing produces valid SHA-512 crypt structure
|
||||
parts = hashed.split("$")
|
||||
self.assertEqual(len(parts), 4) # ['', '6', salt, hash]
|
||||
self.assertEqual(parts[1], "6")
|
||||
self.assertGreater(len(parts[2]), 0)
|
||||
self.assertGreater(len(parts[3]), 0)
|
||||
|
||||
def test_system_configurator_writing(self):
|
||||
with tempfile.TemporaryDirectory() as tmp_dir:
|
||||
configurator = SystemConfigurator(tmp_dir, dry_run=False)
|
||||
config = InstallConfig(target_disk="/dev/sda", hostname="my-pc", root_password="test_secret")
|
||||
targets = TargetPartitions(disk_path="/dev/sda", root_part="/dev/sda1")
|
||||
|
||||
configurator.apply_basic_configs(config, targets)
|
||||
|
||||
fstab_file = Path(tmp_dir) / "etc" / "fstab"
|
||||
hostname_file = Path(tmp_dir) / "etc" / "hostname"
|
||||
hosts_file = Path(tmp_dir) / "etc" / "hosts"
|
||||
|
||||
self.assertTrue(fstab_file.exists())
|
||||
self.assertTrue(hostname_file.exists())
|
||||
self.assertTrue(hosts_file.exists())
|
||||
|
||||
self.assertIn("my-pc", hostname_file.read_text(encoding="utf-8"))
|
||||
self.assertIn("my-pc", hosts_file.read_text(encoding="utf-8"))
|
||||
|
||||
# Test root password setting in shadow
|
||||
configurator.set_root_password("secret123")
|
||||
shadow_file = Path(tmp_dir) / "etc" / "shadow"
|
||||
self.assertTrue(shadow_file.exists())
|
||||
shadow_content = shadow_file.read_text(encoding="utf-8")
|
||||
self.assertIn("root:$6$", shadow_content)
|
||||
|
||||
# Test user account creation
|
||||
configurator.create_user_account("bartosz", "userpass123")
|
||||
passwd_file = Path(tmp_dir) / "etc" / "passwd"
|
||||
group_file = Path(tmp_dir) / "etc" / "group"
|
||||
home_dir = Path(tmp_dir) / "home" / "bartosz"
|
||||
|
||||
self.assertTrue(passwd_file.exists())
|
||||
self.assertTrue(group_file.exists())
|
||||
self.assertTrue(home_dir.exists())
|
||||
|
||||
passwd_content = passwd_file.read_text(encoding="utf-8")
|
||||
self.assertIn("bartosz:x:1000:1000", passwd_content)
|
||||
|
||||
|
||||
class TestBootloader(unittest.TestCase):
|
||||
"""Test GRUB and EXTLINUX configuration generator."""
|
||||
|
||||
def test_generate_grub_config_uefi_xfce(self):
|
||||
targets = TargetPartitions(
|
||||
disk_path="/dev/sda",
|
||||
root_part="/dev/sda2",
|
||||
root_uuid="abcd-1234-root",
|
||||
)
|
||||
grub_cfg = generate_grub_config(targets, DesktopEnvironment.XFCE)
|
||||
self.assertIn("set timeout=5", grub_cfg)
|
||||
self.assertIn("set default=0", grub_cfg)
|
||||
self.assertIn("root=UUID=abcd-1234-root", grub_cfg)
|
||||
self.assertIn('menuentry "KhOS 1.1 (XFCE 4 (Lekkie, stabilne - domyślne))"', grub_cfg)
|
||||
self.assertIn("desktop=xfce rw quiet", grub_cfg)
|
||||
self.assertIn('menuentry "KhOS 1.1 (Pulpit KDE Plasma)"', grub_cfg)
|
||||
self.assertIn('menuentry "KhOS 1.1 (Hyprland Wayland)"', grub_cfg)
|
||||
self.assertIn('menuentry "KhOS 1.1 (Openbox Minimal X11)"', grub_cfg)
|
||||
self.assertIn('menuentry "KhOS 1.1 (Tryb awaryjny - Verbose & Debug)"', grub_cfg)
|
||||
self.assertIn('menuentry "Uruchom ponownie (Reboot)"', grub_cfg)
|
||||
|
||||
def test_generate_extlinux_config(self):
|
||||
targets = TargetPartitions(
|
||||
disk_path="/dev/vda",
|
||||
root_part="/dev/vda1",
|
||||
root_uuid="vda1-uuid",
|
||||
)
|
||||
conf = generate_extlinux_config(targets, DesktopEnvironment.PLASMA)
|
||||
self.assertIn("DEFAULT default_os", conf)
|
||||
self.assertIn("TIMEOUT 50", conf)
|
||||
self.assertIn("root=UUID=vda1-uuid", conf)
|
||||
self.assertIn("desktop=plasma", conf)
|
||||
|
||||
|
||||
class TestCliAndConfig(unittest.TestCase):
|
||||
"""Test argument parsing and validation."""
|
||||
|
||||
def test_argument_parser_defaults(self):
|
||||
parser = build_argument_parser()
|
||||
args = parser.parse_args([])
|
||||
self.assertEqual(args.hostname, "khos")
|
||||
self.assertEqual(args.root_password, "khos")
|
||||
self.assertEqual(args.desktop, "xfce")
|
||||
self.assertEqual(args.efi_size, 512)
|
||||
self.assertEqual(args.swap_size, 0)
|
||||
self.assertFalse(args.dry_run)
|
||||
self.assertFalse(args.auto)
|
||||
|
||||
def test_argument_parser_custom_auto(self):
|
||||
parser = build_argument_parser()
|
||||
args = parser.parse_args([
|
||||
"--disk", "/dev/nvme0n1",
|
||||
"--hostname", "workstation",
|
||||
"--root-password", "supersecure",
|
||||
"--desktop", "hyprland",
|
||||
"--efi-size", "1024",
|
||||
"--swap-size", "4096",
|
||||
"--auto",
|
||||
"--dry-run",
|
||||
"--json",
|
||||
])
|
||||
self.assertEqual(args.disk, "/dev/nvme0n1")
|
||||
self.assertEqual(args.hostname, "workstation")
|
||||
self.assertEqual(args.root_password, "supersecure")
|
||||
self.assertEqual(args.desktop, "hyprland")
|
||||
self.assertEqual(args.efi_size, 1024)
|
||||
self.assertEqual(args.swap_size, 4096)
|
||||
self.assertTrue(args.auto)
|
||||
self.assertTrue(args.dry_run)
|
||||
self.assertTrue(args.json)
|
||||
|
||||
def test_config_validation(self):
|
||||
# Empty disk should fail validation
|
||||
cfg = InstallConfig(target_disk="", hostname="khos")
|
||||
errs = cfg.validate()
|
||||
self.assertIn("Target disk cannot be empty.", errs)
|
||||
|
||||
# Invalid hostname
|
||||
cfg = InstallConfig(target_disk="/dev/sda", hostname="bad host name!")
|
||||
errs = cfg.validate()
|
||||
self.assertTrue(any("Invalid hostname" in e for e in errs))
|
||||
|
||||
# Valid config
|
||||
cfg = InstallConfig(target_disk="/dev/sda", hostname="khos-pc", root_password="root")
|
||||
self.assertEqual(cfg.validate(), [])
|
||||
|
||||
|
||||
class TestInstallerCoreDryRun(unittest.TestCase):
|
||||
"""End-to-end dry-run test of the installation workflow."""
|
||||
|
||||
def test_core_dry_run_pipeline(self):
|
||||
config = InstallConfig(
|
||||
target_disk="/dev/sda",
|
||||
boot_mode=BootMode.UEFI,
|
||||
hostname="khos-test",
|
||||
root_password="test_password",
|
||||
username="testuser",
|
||||
user_password="user_password",
|
||||
desktop=DesktopEnvironment.XFCE,
|
||||
dry_run=True,
|
||||
)
|
||||
|
||||
events: list[ProgressEvent] = []
|
||||
|
||||
def on_event(ev: ProgressEvent):
|
||||
events.append(ev)
|
||||
|
||||
core = InstallerCore(config, callback=on_event)
|
||||
result = core.run()
|
||||
|
||||
self.assertTrue(result)
|
||||
|
||||
# Verify stages were hit
|
||||
stages = [e.stage for e in events if e.event_type == "stage"]
|
||||
self.assertIn("Przygotowanie", stages)
|
||||
self.assertIn("Partycjonowanie", stages)
|
||||
self.assertIn("Formatowanie", stages)
|
||||
self.assertIn("Montowanie", stages)
|
||||
self.assertIn("Kopiowanie", stages)
|
||||
self.assertIn("Konfiguracja", stages)
|
||||
self.assertIn("Bootloader", stages)
|
||||
self.assertIn("Finalizacja", stages)
|
||||
|
||||
# Verify completed event was emitted
|
||||
completed_events = [e for e in events if e.event_type == "completed"]
|
||||
self.assertEqual(len(completed_events), 1)
|
||||
self.assertEqual(completed_events[0].percent, 100)
|
||||
|
||||
|
||||
class TestUtils(unittest.TestCase):
|
||||
"""Test format_bytes and run_cmd utilities."""
|
||||
|
||||
def test_format_bytes(self):
|
||||
self.assertEqual(format_bytes(500), "500 B")
|
||||
self.assertEqual(format_bytes(1024), "1.0 KB")
|
||||
self.assertEqual(format_bytes(1024 * 1024 * 50), "50.0 MB")
|
||||
self.assertEqual(format_bytes(1024 ** 3 * 2), "2.0 GB")
|
||||
|
||||
def test_run_cmd_dry_run(self):
|
||||
res = run_cmd(["echo", "hello"], dry_run=True)
|
||||
self.assertTrue(res.success)
|
||||
self.assertEqual(res.returncode, 0)
|
||||
self.assertIn("simulated", res.stdout)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "khos-installer"
|
||||
version = "1.1.0"
|
||||
edition = "2021"
|
||||
authors = ["KhOS Development Team <dev@kpgpmc.org>"]
|
||||
description = "Oficjalny, modułowy instalator systemu operacyjnego KhOS w języku Rust"
|
||||
readme = "README.md"
|
||||
license = "GPL-3.0-or-later"
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
|
||||
[profile.release]
|
||||
opt-level = "z"
|
||||
lto = true
|
||||
codegen-units = 1
|
||||
panic = "abort"
|
||||
strip = true
|
||||
@@ -0,0 +1,189 @@
|
||||
# KhOS Installer 1.1 (Rust Core)
|
||||
|
||||
Oficjalny, modułowy i wysokowydajny instalator systemu operacyjnego **KhOS (Genesis 1.1)** napisany od podstaw w języku **Rust**. Zapewnia bezpieczną, niezawodną i szybką instalację systemu zarówno na nowoczesnych komputerach z **UEFI (x86_64)**, jak i maszynach ze starszym **BIOS (MBR / Legacy)**.
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Cechy i Zalety Portu Rust
|
||||
|
||||
- **100% Pamięciowo Bezpieczny**: Oparty na ścisłych gwarancjach bezpieczeństwa języka Rust bez niezdefiniowanych zachowań (`undefined behavior`).
|
||||
- **Wzorzec RAII (Resource Acquisition Is Initialization)**: Automatyczne i bezpieczne odmontowywanie (`MountGuard`) zasobów i partycji w przypadku wystąpienia błędu lub przerwania sygnałem (SIGINT/SIGTERM).
|
||||
- **Zero Ciężkich Zależności C**: Działa natywnie na czystym środowisku musl libc / BusyBox bez konieczności instalowania bibliotek dynamicznych.
|
||||
- **Wieloplatformowy Tryb Rozruchu**:
|
||||
- **UEFI**: Automatyczne tworzenie tablicy GPT, partycji ESP FAT32 (512 MB), instalacja `grub-install --target=x86_64-efi --removable` oraz awaryjny fallback `BOOTX64.EFI`.
|
||||
- **BIOS**: Tworzenie tablicy MBR, oznaczenie flagi rozruchowej, instalacja `grub-install --target=i386-pc` z fallbackiem do Syslinux / EXTLINUX.
|
||||
- **Optymalizacja dla SSD i NVMe**: Formatowanie partycji ext4 z flagami `noatime`, `64bit`, `has_journal`, `extents`, `flex_bg` oraz `metadata_csum`.
|
||||
- **Wsparcie dla Nowoczesnych Pulpitów**: Wybór i automatyczna konfiguracja domyślnego środowiska graficznego:
|
||||
- **XFCE 4** (lekkie, szybkie, domyślne)
|
||||
- **KDE Plasma** (nowoczesne, zaawansowane)
|
||||
- **Hyprland** (dynamiczny Wayland compositor)
|
||||
- **Openbox** (minimalistyczne środowisko X11)
|
||||
- **Strumieniowanie JSON dla GUI**: Flaga `--json` umożliwia podłączenie graficznego instalatora (np. Calamares, Web/Tauri lub GTK) z raportowaniem postępu w czasie rzeczywistym.
|
||||
- **Bezpieczny Tryb Symulacji (`--dry-run`)**: Umożliwia przetestowanie całej procedury bez modyfikowania nośników danych.
|
||||
|
||||
---
|
||||
|
||||
## 📁 Architektura Modułowa (`src/`)
|
||||
|
||||
```
|
||||
installer/rust/
|
||||
├── Cargo.toml # Konfiguracja pakietu khos-installer v1.1.0
|
||||
├── README.md # Niniejsza dokumentacja techniczna
|
||||
└── src/
|
||||
├── main.rs # Punkt wejścia, CLI, pętla zdarzeń, kreator interaktywny
|
||||
├── cli.rs # Parser opcji wiersza poleceń i ekrany pomocy
|
||||
├── types.rs # Struktury danych, konfiguracja, zdarzenia JSON
|
||||
├── error.rs # Dedykowany enum InstallError i obsługa błędów
|
||||
├── logger.rs # Kolorowanie ANSI w konsoli oraz emiter zdarzeń JSON
|
||||
├── disk.rs # Detekcja dysków (/sys/block), rozmiary, UUID, modele
|
||||
├── partition.rs # Tablice partycji GPT/MBR, czyszczenie zerami, formatowanie
|
||||
├── mount.rs # RAII MountGuard, hierarchia montowań chroot (/proc, /sys, /dev)
|
||||
├── copy.rs # Ekstrakcja SquashFS/Live rootfs, jądro, initramfs, bity SUID
|
||||
├── config.rs # Generowanie /etc/fstab (UUID), hostname, hosts, hasła, pulpity
|
||||
└── bootloader.rs # Instalacja GRUB (UEFI/BIOS), menu grub.cfg, fallback EXTLINUX
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ Kompilacja i Budowanie
|
||||
|
||||
Instalator jest zoptymalizowany pod kątem statycznej kompilacji z użyciem `musl`, co tworzy w pełni samodzielny plik binarny pozbawiony zewnętrznych zależności.
|
||||
|
||||
### 1. Statyczna kompilacja pod KhOS (musl target - zalecane)
|
||||
|
||||
```bash
|
||||
# Dodanie targetu musl
|
||||
rustup target add x86_64-unknown-linux-musl
|
||||
|
||||
# Kompilacja wersji produkcyjnej (LTO, strip, rozmiar minimalny)
|
||||
cargo build --release --target x86_64-unknown-linux-musl
|
||||
|
||||
# Wynikowy plik binarny:
|
||||
# target/x86_64-unknown-linux-musl/release/khos-installer
|
||||
```
|
||||
|
||||
### 2. Standardowa kompilacja deweloperska (GNU target)
|
||||
|
||||
```bash
|
||||
cargo build --release
|
||||
```
|
||||
|
||||
### 3. Uruchomienie testów jednostkowych
|
||||
|
||||
```bash
|
||||
cargo test
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 💻 Instrukcja Użycia CLI
|
||||
|
||||
### Składnia
|
||||
|
||||
```bash
|
||||
khos-installer [OPCJE] [DYSK_DOCELOWY]
|
||||
```
|
||||
|
||||
### Dostępne Opcje
|
||||
|
||||
| Opcja | Skrót | Opis | Domyślnie |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| `--disk <ścieżka>` | `-d` | Ścieżka do dysku docelowego (np. `/dev/sda`, `/dev/nvme0n1`) | Brak (wybór w kreatorze) |
|
||||
| `--auto` | `-y` | Tryb nieinteraktywny (wymaga `--disk`) | Wyłączony |
|
||||
| `--dry-run` | `-n` | Symulacja instalacji bez dotykania dysków | Wyłączony |
|
||||
| `--json` | | Strumieniowanie zdarzeń w formacie JSON dla frontendu | Wyłączony |
|
||||
| `--list-disks` | `-l` | Wyświetla listę wykrytych dysków i kończy pracę | - |
|
||||
| `--detect-boot` | | Wykrywa tryb rozruchu (UEFI lub BIOS) i kończy | - |
|
||||
| `--hostname <nazwa>`| | Nazwa komputera w sieci | `khos` |
|
||||
| `--password <hasło>`| `-p` | Hasło konta administratora root | `khos` |
|
||||
| `--user <nazwa>` | `-u` | Nazwa tworzonego konta zwykłego użytkownika | Brak |
|
||||
| `--user-pass <hasło>`| | Hasło dla konta zwykłego użytkownika | Brak |
|
||||
| `--desktop <typ>` | | Domyślne środowisko: `xfce`, `plasma`, `hyprland`, `openbox` | `xfce` |
|
||||
| `--boot-mode <tryb>`| | Wymuszenie trybu rozruchu: `uefi` lub `bios` | Auto-detekcja |
|
||||
| `--efi-size <MB>` | | Rozmiar partycji EFI ESP w MB | `512` |
|
||||
| `--source <ścieżka>`| `-s` | Własna ścieżka do obrazu squashfs lub katalogu | Auto-detekcja |
|
||||
| `--help` | `-h` | Wyświetla pomoc | - |
|
||||
| `--version` | `-v` | Wyświetla numer wersji programu | - |
|
||||
|
||||
---
|
||||
|
||||
## 📋 Przykłady Użycia
|
||||
|
||||
### 1. Tryb Interaktywny (Kreator TTY)
|
||||
Uruchomienie instalatora bez parametrów uruchamia czytelny, interaktywny kreator w języku polskim:
|
||||
```bash
|
||||
sudo khos-installer
|
||||
```
|
||||
|
||||
### 2. Pełna instalacja automatyczna na dysku NVMe z pulpitem KDE Plasma
|
||||
```bash
|
||||
sudo khos-installer --auto --disk /dev/nvme0n1 --desktop plasma --hostname moj-khos --password tajnehaslo
|
||||
```
|
||||
|
||||
### 3. Bezpieczna symulacja na maszynie wirtualnej z wyjściem JSON
|
||||
```bash
|
||||
khos-installer --dry-run --json --auto --disk /dev/vda
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📡 Protokół IPC JSON (Integracja z GUI)
|
||||
|
||||
Po uruchomieniu z flagą `--json`, instalator wypisuje na standardowe wyjście (`stdout`) zdarzenia w formacie JSON w pojedynczych liniach (JSON Lines). Może to być bezpośrednio konsumowane przez aplikacje GUI w Calamares, Electronie, Tauri lub GTK.
|
||||
|
||||
### Przykłady komunikatów JSON
|
||||
|
||||
#### Zmiana etapu instalacji:
|
||||
```json
|
||||
{
|
||||
"type": "stage",
|
||||
"step": "partition",
|
||||
"percent": 15,
|
||||
"description": "Tworzenie tablic partycji i formatowanie systemów plików..."
|
||||
}
|
||||
```
|
||||
|
||||
#### Dziennik zdarzeń:
|
||||
```json
|
||||
{
|
||||
"type": "log",
|
||||
"level": "info",
|
||||
"message": "Sformatowano partycję /dev/sda2 jako ext4."
|
||||
}
|
||||
```
|
||||
|
||||
#### Sukces instalacji:
|
||||
```json
|
||||
{
|
||||
"type": "completed",
|
||||
"success": true,
|
||||
"target_disk": "/dev/sda",
|
||||
"root_partition": "/dev/sda2",
|
||||
"boot_mode": "UEFI",
|
||||
"elapsed_seconds": 42
|
||||
}
|
||||
```
|
||||
|
||||
#### Błąd instalacji:
|
||||
```json
|
||||
{
|
||||
"type": "error",
|
||||
"message": "Urządzenie docelowe jest zablokowane lub zajęte przez inny proces."
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔒 Bezpieczeństwo i Niezawodność
|
||||
|
||||
1. **Weryfikacja Dysku**: Instalator uniemożliwia przypadkowe sformatowanie partycji wirtualnych (`loop`, `ram`, `zram`) lub nośnika instalacyjnego (`/mnt/cdrom`, `sr*`).
|
||||
2. **Podwójne Potwierdzenie**: W trybie interaktywnym wymagane jest wpisanie słowa `TAK` wielkimi literami.
|
||||
3. **Idempotentne Odmontowanie**: Struktura `MountGuard` dba o to, by w przypadku dowolnego błędu w trakcie kopiowania lub konfiguracji wszystkie podsystemy wirtualne (`/proc`, `/sys`, `/dev`, `/run`) oraz partycje dysku docelowego zostały bezpiecznie odmontowane.
|
||||
4. **Identyfikatory UUID**: Plik `/etc/fstab` oraz `grub.cfg` opierają się na unikalnych identyfikatorach UUID dysku, co zapobiega problemom ze zmianą kolejności dysków w BIOS/UEFI.
|
||||
|
||||
---
|
||||
|
||||
## 📄 Licencja
|
||||
|
||||
KhOS Installer jest oprogramowaniem open-source dystrybuowanym na licencji **GPL-3.0-or-later**.
|
||||
Copyright (c) 2026 KhOS Development Team.
|
||||
@@ -0,0 +1,324 @@
|
||||
use crate::error::InstallError;
|
||||
use crate::logger::{info, msg, ok, warn};
|
||||
use crate::types::{BootMode, InstallConfig, TargetPartitions};
|
||||
use std::fs::{self, File};
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
/// Instaluje i konfiguruje program rozruchowy GRUB lub EXTLINUX
|
||||
pub fn install_bootloader(
|
||||
config: &InstallConfig,
|
||||
partitions: &TargetPartitions,
|
||||
target_dir: &Path,
|
||||
) -> Result<(), InstallError> {
|
||||
if config.dry_run {
|
||||
msg(&format!(
|
||||
"[DRY-RUN] Symulacja instalacji bootloadera GRUB ({}) na {}",
|
||||
config.boot_mode,
|
||||
config.target_disk.display()
|
||||
));
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
msg(&format!(
|
||||
"Instalacja programu rozruchowego GRUB (tryb: {})...",
|
||||
config.boot_mode
|
||||
));
|
||||
|
||||
// 1. Generowanie konfiguracji grub.cfg
|
||||
generate_grub_config(config, partitions, target_dir)?;
|
||||
|
||||
// 2. Instalacja właściwych binariów rozruchowych na dysku
|
||||
let mut installed_ok = false;
|
||||
|
||||
match config.boot_mode {
|
||||
BootMode::Uefi => {
|
||||
installed_ok = install_grub_uefi(partitions, target_dir)?;
|
||||
}
|
||||
BootMode::Bios => {
|
||||
installed_ok = install_grub_bios(&config.target_disk, target_dir)?;
|
||||
if !installed_ok {
|
||||
warn("Próba instalacji zapasowego programu rozruchowego EXTLINUX...");
|
||||
installed_ok = install_extlinux_fallback(&config.target_disk, partitions, target_dir)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if installed_ok {
|
||||
ok("Program rozruchowy został pomyślnie zainstalowany.");
|
||||
} else {
|
||||
warn("Ostrzeżenie: weryfikacja instalacji bootloadera zgłosiła uwagi.");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Generuje plik boot/grub/grub.cfg
|
||||
fn generate_grub_config(
|
||||
_config: &InstallConfig,
|
||||
partitions: &TargetPartitions,
|
||||
target_dir: &Path,
|
||||
) -> Result<(), InstallError> {
|
||||
let grub_dir = target_dir.join("boot/grub");
|
||||
fs::create_dir_all(&grub_dir)?;
|
||||
|
||||
let grub_cfg_path = grub_dir.join("grub.cfg");
|
||||
info(&format!("Generowanie konfiguracji menu rozruchu: {}", grub_cfg_path.display()));
|
||||
|
||||
let root_param = if let Some(ref uuid) = partitions.root_uuid {
|
||||
format!("root=UUID={}", uuid)
|
||||
} else {
|
||||
format!("root={}", partitions.root_part.display())
|
||||
};
|
||||
|
||||
let cfg_content = format!(
|
||||
r#"# /boot/grub/grub.cfg - KhOS Genesis 1.1 Bootloader Configuration
|
||||
set timeout=5
|
||||
set default=0
|
||||
|
||||
terminal_input console
|
||||
terminal_output console
|
||||
|
||||
menuentry "KhOS 1.1 (Pulpit XFCE 4 - domyślny)" {{
|
||||
linux /boot/vmlinuz {root_param} rw quiet
|
||||
initrd /boot/initramfs.img
|
||||
}}
|
||||
|
||||
menuentry "KhOS 1.1 (Pulpit KDE Plasma)" {{
|
||||
linux /boot/vmlinuz {root_param} desktop=plasma rw quiet
|
||||
initrd /boot/initramfs.img
|
||||
}}
|
||||
|
||||
menuentry "KhOS 1.1 (Pulpit Wayland Hyprland)" {{
|
||||
linux /boot/vmlinuz {root_param} desktop=hyprland rw quiet
|
||||
initrd /boot/initramfs.img
|
||||
}}
|
||||
|
||||
menuentry "KhOS 1.1 (Pulpit Openbox X11)" {{
|
||||
linux /boot/vmlinuz {root_param} desktop=openbox rw quiet
|
||||
initrd /boot/initramfs.img
|
||||
}}
|
||||
|
||||
menuentry "KhOS 1.1 (Tryb awaryjny - tekstowy / verbose)" {{
|
||||
linux /boot/vmlinuz {root_param} rw textmode debug loglevel=7
|
||||
initrd /boot/initramfs.img
|
||||
}}
|
||||
|
||||
menuentry "Uruchom ponownie komputer" {{
|
||||
reboot
|
||||
}}
|
||||
|
||||
menuentry "Wyłącz komputer" {{
|
||||
halt
|
||||
}}
|
||||
"#,
|
||||
root_param = root_param
|
||||
);
|
||||
|
||||
fs::write(&grub_cfg_path, &cfg_content)?;
|
||||
|
||||
// Skopiuj grub.cfg również do /boot/efi/boot/grub/grub.cfg dla pełnej kompatybilności UEFI
|
||||
if partitions.efi_part.is_some() {
|
||||
let efi_grub_dir = target_dir.join("boot/efi/boot/grub");
|
||||
let _ = fs::create_dir_all(&efi_grub_dir);
|
||||
let _ = fs::write(efi_grub_dir.join("grub.cfg"), &cfg_content);
|
||||
|
||||
let efi_khos_dir = target_dir.join("boot/efi/EFI/khos");
|
||||
let _ = fs::create_dir_all(&efi_khos_dir);
|
||||
let _ = fs::write(efi_khos_dir.join("grub.cfg"), &cfg_content);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Instaluje bootloader GRUB dla maszyn z UEFI x86_64
|
||||
fn install_grub_uefi(
|
||||
partitions: &TargetPartitions,
|
||||
target_dir: &Path,
|
||||
) -> Result<bool, InstallError> {
|
||||
info("Wykonywanie grub-install dla architektury x86_64-efi...");
|
||||
|
||||
let boot_dir = target_dir.join("boot");
|
||||
let efi_dir = target_dir.join("boot/efi");
|
||||
|
||||
// grub-install --target=x86_64-efi --boot-directory=... --efi-directory=... --removable --recheck
|
||||
let grub_res = Command::new("grub-install")
|
||||
.arg("--target=x86_64-efi")
|
||||
.arg(format!("--boot-directory={}", boot_dir.display()))
|
||||
.arg(format!("--efi-directory={}", efi_dir.display()))
|
||||
.arg("--removable")
|
||||
.arg("--recheck")
|
||||
.status();
|
||||
|
||||
if let Ok(status) = grub_res {
|
||||
if status.success() {
|
||||
info("grub-install (UEFI) zakończony pomyślnie.");
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: kopiowanie prekompilowanego pliku BOOTX64.EFI z nośnika instalacyjnego
|
||||
info("Fallback: Weryfikacja prekompilowanego pliku BOOTX64.EFI...");
|
||||
let efi_boot_dst = efi_dir.join("EFI/BOOT");
|
||||
let efi_khos_dst = efi_dir.join("EFI/khos");
|
||||
let _ = fs::create_dir_all(&efi_boot_dst);
|
||||
let _ = fs::create_dir_all(&efi_khos_dst);
|
||||
|
||||
let efi_sources = [
|
||||
"/mnt/cdrom/EFI/BOOT/BOOTX64.EFI",
|
||||
"/boot/efi/EFI/BOOT/BOOTX64.EFI",
|
||||
"/usr/lib/grub/x86_64-efi/monolithic/grubx64.efi",
|
||||
];
|
||||
|
||||
for src in &efi_sources {
|
||||
let p = Path::new(src);
|
||||
if p.is_file() {
|
||||
let _ = fs::copy(p, efi_boot_dst.join("BOOTX64.EFI"));
|
||||
let _ = fs::copy(p, efi_khos_dst.join("grubx64.efi"));
|
||||
info(&format!("Skopiowano moduł UEFI z {}", src));
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// Instaluje bootloader GRUB dla tradycyjnego BIOS (i386-pc / MBR)
|
||||
fn install_grub_bios(disk_path: &Path, target_dir: &Path) -> Result<bool, InstallError> {
|
||||
info(&format!(
|
||||
"Wykonywanie grub-install dla BIOS (i386-pc) na dysku {}...",
|
||||
disk_path.display()
|
||||
));
|
||||
|
||||
let boot_dir = target_dir.join("boot");
|
||||
|
||||
// Standardowe wywołanie
|
||||
let res = Command::new("grub-install")
|
||||
.arg("--target=i386-pc")
|
||||
.arg(format!("--boot-directory={}", boot_dir.display()))
|
||||
.arg("--modules=part_msdos ext2 biosdisk")
|
||||
.arg("--recheck")
|
||||
.arg(disk_path)
|
||||
.status();
|
||||
|
||||
if let Ok(s) = res {
|
||||
if s.success() {
|
||||
info("grub-install (BIOS) zakończony sukcesem.");
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
|
||||
// Próba z flagą --force
|
||||
let force_res = Command::new("grub-install")
|
||||
.arg("--target=i386-pc")
|
||||
.arg(format!("--boot-directory={}", boot_dir.display()))
|
||||
.arg("--modules=part_msdos ext2 biosdisk")
|
||||
.arg("--force")
|
||||
.arg("--recheck")
|
||||
.arg(disk_path)
|
||||
.status();
|
||||
|
||||
if let Ok(s) = force_res {
|
||||
if s.success() {
|
||||
info("grub-install (BIOS z flagą --force) zakończony sukcesem.");
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// Rezerwowa instalacja EXTLINUX / SYSLINUX dla maszyn BIOS gdy GRUB nie jest dostępny
|
||||
fn install_extlinux_fallback(
|
||||
disk_path: &Path,
|
||||
partitions: &TargetPartitions,
|
||||
target_dir: &Path,
|
||||
) -> Result<bool, InstallError> {
|
||||
info("Instalacja zapasowego modułu MBR (Syslinux/Extlinux)...");
|
||||
|
||||
let mbr_candidates = [
|
||||
"/usr/share/syslinux/mbr.bin",
|
||||
"/usr/lib/syslinux/mbr.bin",
|
||||
"/usr/lib/syslinux/bios/mbr.bin",
|
||||
];
|
||||
|
||||
for mbr in &mbr_candidates {
|
||||
let p = Path::new(mbr);
|
||||
if p.is_file() {
|
||||
let _ = Command::new("dd")
|
||||
.arg("bs=440")
|
||||
.arg("count=1")
|
||||
.arg("conv=notrunc")
|
||||
.arg(format!("if={}", p.display()))
|
||||
.arg(format!("of={}", disk_path.display()))
|
||||
.status();
|
||||
info(&format!("Zapisano kod MBR z {}", p.display()));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let extlinux_dir = target_dir.join("boot/extlinux");
|
||||
let _ = fs::create_dir_all(&extlinux_dir);
|
||||
|
||||
// extlinux -i <dir>
|
||||
let _ = Command::new("extlinux")
|
||||
.arg("-i")
|
||||
.arg(&extlinux_dir)
|
||||
.status();
|
||||
|
||||
let c32_dirs = [
|
||||
"/usr/share/syslinux",
|
||||
"/usr/lib/syslinux/modules/bios",
|
||||
"/usr/lib/syslinux",
|
||||
];
|
||||
|
||||
for d in &c32_dirs {
|
||||
let p = Path::new(d);
|
||||
if p.is_dir() {
|
||||
if let Ok(entries) = fs::read_dir(p) {
|
||||
for e in entries.flatten() {
|
||||
let name = e.file_name().to_string_lossy().to_string();
|
||||
if name.ends_with(".c32") {
|
||||
let _ = fs::copy(e.path(), extlinux_dir.join(name));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let root_param = if let Some(ref uuid) = partitions.root_uuid {
|
||||
format!("root=UUID={}", uuid)
|
||||
} else {
|
||||
format!("root={}", partitions.root_part.display())
|
||||
};
|
||||
|
||||
let conf = format!(
|
||||
r#"DEFAULT xfce
|
||||
PROMPT 1
|
||||
TIMEOUT 50
|
||||
|
||||
LABEL xfce
|
||||
MENU LABEL KhOS 1.1 (XFCE 4 - domyślny)
|
||||
LINUX /boot/vmlinuz
|
||||
INITRD /boot/initramfs.img
|
||||
APPEND {root_param} rw quiet
|
||||
|
||||
LABEL plasma
|
||||
MENU LABEL KhOS 1.1 (KDE Plasma)
|
||||
LINUX /boot/vmlinuz
|
||||
INITRD /boot/initramfs.img
|
||||
APPEND {root_param} desktop=plasma rw quiet
|
||||
|
||||
LABEL textmode
|
||||
MENU LABEL KhOS 1.1 (Tryb tekstowy)
|
||||
LINUX /boot/vmlinuz
|
||||
INITRD /boot/initramfs.img
|
||||
APPEND {root_param} rw textmode
|
||||
"#,
|
||||
root_param = root_param
|
||||
);
|
||||
|
||||
let _ = fs::write(extlinux_dir.join("extlinux.conf"), conf);
|
||||
Ok(true)
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
use crate::types::{BootMode, DesktopEnvironment, InstallConfig};
|
||||
use std::env;
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub struct CliArgs {
|
||||
pub config: InstallConfig,
|
||||
pub show_help: bool,
|
||||
pub show_version: bool,
|
||||
pub list_disks: bool,
|
||||
pub detect_boot: bool,
|
||||
}
|
||||
|
||||
impl CliArgs {
|
||||
pub fn parse() -> Result<Self, String> {
|
||||
let mut config = InstallConfig::default();
|
||||
let mut show_help = false;
|
||||
let mut show_version = false;
|
||||
let mut list_disks = false;
|
||||
let mut detect_boot = false;
|
||||
|
||||
let args: Vec<String> = env::args().skip(1).collect();
|
||||
let mut i = 0;
|
||||
|
||||
while i < args.len() {
|
||||
let arg = &args[i];
|
||||
match arg.as_str() {
|
||||
"-h" | "--help" => {
|
||||
show_help = true;
|
||||
}
|
||||
"-v" | "--version" => {
|
||||
show_version = true;
|
||||
}
|
||||
"--list-disks" | "-l" => {
|
||||
list_disks = true;
|
||||
}
|
||||
"--detect-boot" => {
|
||||
detect_boot = true;
|
||||
}
|
||||
"--dry-run" | "-n" => {
|
||||
config.dry_run = true;
|
||||
}
|
||||
"--json" => {
|
||||
config.json_output = true;
|
||||
}
|
||||
"--auto" | "-y" => {
|
||||
config.auto_mode = true;
|
||||
}
|
||||
"-d" | "--disk" => {
|
||||
i += 1;
|
||||
if i >= args.len() {
|
||||
return Err("Opcja --disk wymaga podania ścieżki urządzenia (np. /dev/sda)".to_string());
|
||||
}
|
||||
config.target_disk = PathBuf::from(&args[i]);
|
||||
}
|
||||
"--hostname" => {
|
||||
i += 1;
|
||||
if i >= args.len() {
|
||||
return Err("Opcja --hostname wymaga podania nazwy komputera".to_string());
|
||||
}
|
||||
config.hostname = args[i].clone();
|
||||
}
|
||||
"--password" | "-p" => {
|
||||
i += 1;
|
||||
if i >= args.len() {
|
||||
return Err("Opcja --password wymaga podania hasła roota".to_string());
|
||||
}
|
||||
config.root_password = args[i].clone();
|
||||
}
|
||||
"--user" | "-u" => {
|
||||
i += 1;
|
||||
if i >= args.len() {
|
||||
return Err("Opcja --user wymaga podania nazwy użytkownika".to_string());
|
||||
}
|
||||
config.username = Some(args[i].clone());
|
||||
}
|
||||
"--user-pass" => {
|
||||
i += 1;
|
||||
if i >= args.len() {
|
||||
return Err("Opcja --user-pass wymaga podania hasła użytkownika".to_string());
|
||||
}
|
||||
config.user_password = Some(args[i].clone());
|
||||
}
|
||||
"--desktop" => {
|
||||
i += 1;
|
||||
if i >= args.len() {
|
||||
return Err("Opcja --desktop wymaga podania środowiska (xfce, plasma, hyprland, openbox)".to_string());
|
||||
}
|
||||
match args[i].to_lowercase().as_str() {
|
||||
"xfce" | "xfce4" => config.desktop = DesktopEnvironment::Xfce,
|
||||
"plasma" | "kde" => config.desktop = DesktopEnvironment::Plasma,
|
||||
"hyprland" | "wayland" => config.desktop = DesktopEnvironment::Hyprland,
|
||||
"openbox" | "x11" => config.desktop = DesktopEnvironment::Openbox,
|
||||
other => {
|
||||
return Err(format!(
|
||||
"Nieznane środowisko graficzne: '{}'. Dostępne: xfce, plasma, hyprland, openbox",
|
||||
other
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
"--boot-mode" => {
|
||||
i += 1;
|
||||
if i >= args.len() {
|
||||
return Err("Opcja --boot-mode wymaga wartości 'uefi' lub 'bios'".to_string());
|
||||
}
|
||||
match args[i].to_lowercase().as_str() {
|
||||
"uefi" => config.boot_mode = BootMode::Uefi,
|
||||
"bios" | "mbr" | "legacy" => config.boot_mode = BootMode::Bios,
|
||||
other => return Err(format!("Nieznany tryb rozruchu: '{}'. Dostępne: uefi, bios", other)),
|
||||
}
|
||||
}
|
||||
"--efi-size" => {
|
||||
i += 1;
|
||||
if i >= args.len() {
|
||||
return Err("Opcja --efi-size wymaga podania rozmiaru w MB".to_string());
|
||||
}
|
||||
config.efi_size_mb = args[i]
|
||||
.parse::<u64>()
|
||||
.map_err(|_| format!("Nieprawidłowy rozmiar EFI: {}", args[i]))?;
|
||||
}
|
||||
"--swap-size" => {
|
||||
i += 1;
|
||||
if i >= args.len() {
|
||||
return Err("Opcja --swap-size wymaga podania rozmiaru w MB".to_string());
|
||||
}
|
||||
config.swap_size_mb = args[i]
|
||||
.parse::<u64>()
|
||||
.map_err(|_| format!("Nieprawidłowy rozmiar SWAP: {}", args[i]))?;
|
||||
}
|
||||
"--source" | "-s" => {
|
||||
i += 1;
|
||||
if i >= args.len() {
|
||||
return Err("Opcja --source wymaga podania ścieżki do obrazu squashfs lub katalogu Live".to_string());
|
||||
}
|
||||
config.source_path = Some(PathBuf::from(&args[i]));
|
||||
}
|
||||
other => {
|
||||
if other.starts_with('-') {
|
||||
return Err(format!("Nieznana opcja: '{}'. Użyj --help", other));
|
||||
} else if config.target_disk.as_os_str().is_empty() {
|
||||
config.target_disk = PathBuf::from(other);
|
||||
} else {
|
||||
return Err(format!("Nieoczekiwany argument: '{}'", other));
|
||||
}
|
||||
}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
config,
|
||||
show_help,
|
||||
show_version,
|
||||
list_disks,
|
||||
detect_boot,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn print_help() {
|
||||
println!(
|
||||
r#"KhOS Installer v1.1.0 - Zaawansowany instalator systemu operacyjnego KhOS
|
||||
|
||||
UŻYCIE:
|
||||
khos-installer [OPCJE] [DYSK_DOCELOWY]
|
||||
|
||||
OPCJE GŁÓWNE:
|
||||
-d, --disk <ŚCIEŻKA> Wskaż dysk docelowy (np. /dev/sda, /dev/nvme0n1)
|
||||
-y, --auto Tryb automatyczny (bez pytań interaktywnych, wymaga --disk)
|
||||
-n, --dry-run Symulacja instalacji (bez wprowadzania zmian na dysku)
|
||||
--json Strumieniowanie zdarzeń i postępu w formacie JSON (dla GUI)
|
||||
-l, --list-disks Wyświetl listę dostępnych dysków blokowych i zakończ
|
||||
--detect-boot Wykryj tryb rozruchu (UEFI czy BIOS) i zakończ
|
||||
|
||||
KONFIGURACJA SYSTEMU:
|
||||
--hostname <NAZWA> Nazwa komputera w sieci (domyślnie: khos)
|
||||
-p, --password <HASŁO> Hasło dla konta administratora root (domyślnie: khos)
|
||||
-u, --user <UŻYTKOWNIK> Opcjonalna nazwa zwykłego użytkownika
|
||||
--user-pass <HASŁO> Hasło dla tworzonego użytkownika
|
||||
--desktop <ŚRODOWISKO> Domyślny pulpit: xfce, plasma, hyprland, openbox (domyślnie: xfce)
|
||||
--boot-mode <TRYB> Wymuszenie trybu rozruchu: uefi, bios (domyślnie: auto-detekcja)
|
||||
--efi-size <MB> Rozmiar partycji EFI ESP w megabajtach (domyślnie: 512)
|
||||
--swap-size <MB> Rozmiar opcjonalnej partycji wymiany SWAP (domyślnie: 0)
|
||||
-s, --source <ŚCIEŻKA> Ścieżka źródłowa filesystem.squashfs lub zamontowanego Live rootfs
|
||||
|
||||
OPCJE INFORMACYJNE:
|
||||
-h, --help Wyświetl ten ekran pomocy
|
||||
-v, --version Wyświetl wersję instalatora
|
||||
|
||||
PRZYKŁADY:
|
||||
# Tryb interaktywny (kreator konsolowy):
|
||||
khos-installer
|
||||
|
||||
# Instalacja automatyczna na dysku SSD /dev/nvme0n1 z pulpitem KDE Plasma:
|
||||
khos-installer --auto --disk /dev/nvme0n1 --desktop plasma --hostname khos-pc
|
||||
|
||||
# Bezpieczna symulacja z wyjściem JSON dla frontendu Calamares / Web:
|
||||
khos-installer --dry-run --json --disk /dev/vda --auto
|
||||
"#
|
||||
);
|
||||
}
|
||||
|
||||
pub fn print_version() {
|
||||
println!("khos-installer 1.1.0 (Genesis x86_64-musl)");
|
||||
println!("Kompilacja w języku Rust. Copyright (c) 2026 KhOS Project.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
use crate::error::InstallError;
|
||||
use crate::logger::{info, msg, ok};
|
||||
use crate::types::{InstallConfig, TargetPartitions};
|
||||
use std::fs::{self, File};
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
/// Konfiguruje docelowy system: fstab, hostname, hosts, hasła kont, domyślny pulpit i strefę czasową
|
||||
pub fn configure_target_system(
|
||||
config: &InstallConfig,
|
||||
partitions: &TargetPartitions,
|
||||
target_dir: &Path,
|
||||
) -> Result<(), InstallError> {
|
||||
if config.dry_run {
|
||||
msg(&format!(
|
||||
"[DRY-RUN] Symulacja konfiguracji systemu (hostname: {}, fstab, hasła)...",
|
||||
config.hostname
|
||||
));
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
msg("Generowanie plików konfiguracyjnych systemu KhOS...");
|
||||
|
||||
// 1. /etc/fstab
|
||||
generate_fstab(partitions, target_dir)?;
|
||||
|
||||
// 2. /etc/hostname oraz /etc/hosts
|
||||
generate_network_config(&config.hostname, target_dir)?;
|
||||
|
||||
// 3. Konfiguracja kont i haseł
|
||||
configure_users_and_passwords(config, target_dir)?;
|
||||
|
||||
// 4. Konfiguracja domyślnego pulpitu graficznego
|
||||
configure_desktop_environment(config, target_dir)?;
|
||||
|
||||
// 5. Konfiguracja strefy czasowej i lokalizacji
|
||||
configure_locale_and_timezone(target_dir)?;
|
||||
|
||||
ok("Konfiguracja systemowa została pomyślnie zapisana.");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Generuje plik /etc/fstab z użyciem identyfikatorów UUID
|
||||
fn generate_fstab(
|
||||
partitions: &TargetPartitions,
|
||||
target_dir: &Path,
|
||||
) -> Result<(), InstallError> {
|
||||
let fstab_path = target_dir.join("etc/fstab");
|
||||
info(&format!("Zapisywanie tabeli montowania: {}", fstab_path.display()));
|
||||
|
||||
let mut content = String::new();
|
||||
content.push_str("# /etc/fstab - Wygenerowany automatycznie przez KhOS Installer 1.1\n");
|
||||
content.push_str("# <file system> <mount point> <type> <options> <dump> <pass>\n");
|
||||
|
||||
// Partycja główna /
|
||||
if let Some(ref uuid) = partitions.root_uuid {
|
||||
content.push_str(&format!(
|
||||
"UUID={:<38} / ext4 defaults,noatime 0 1\n",
|
||||
uuid
|
||||
));
|
||||
} else {
|
||||
content.push_str(&format!(
|
||||
"{:<43} / ext4 defaults,noatime 0 1\n",
|
||||
partitions.root_part.display()
|
||||
));
|
||||
}
|
||||
|
||||
// Partycja EFI ESP (/boot/efi)
|
||||
if let Some(ref efi_part) = partitions.efi_part {
|
||||
if let Some(ref uuid) = partitions.efi_uuid {
|
||||
content.push_str(&format!(
|
||||
"UUID={:<38} /boot/efi vfat defaults,umask=0077 0 2\n",
|
||||
uuid
|
||||
));
|
||||
} else {
|
||||
content.push_str(&format!(
|
||||
"{:<43} /boot/efi vfat defaults,umask=0077 0 2\n",
|
||||
efi_part.display()
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Partycja SWAP
|
||||
if let Some(ref swap_part) = partitions.swap_part {
|
||||
content.push_str(&format!(
|
||||
"{:<43} none swap defaults 0 0\n",
|
||||
swap_part.display()
|
||||
));
|
||||
}
|
||||
|
||||
// Wirtualne systemy plików
|
||||
content.push_str("proc /proc proc defaults 0 0\n");
|
||||
content.push_str("sysfs /sys sysfs defaults 0 0\n");
|
||||
content.push_str("devtmpfs /dev devtmpfs defaults 0 0\n");
|
||||
content.push_str("devpts /dev/pts devpts defaults,gid=5,mode=620 0 0\n");
|
||||
content.push_str("tmpfs /dev/shm tmpfs defaults,nodev,nosuid,noexec 0 0\n");
|
||||
content.push_str("tmpfs /tmp tmpfs defaults,nodev,nosuid,mode=1777 0 0\n");
|
||||
content.push_str("tmpfs /run tmpfs defaults,nodev,nosuid,mode=0755 0 0\n");
|
||||
|
||||
if let Some(parent) = fstab_path.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
fs::write(&fstab_path, content)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Generuje /etc/hostname i /etc/hosts
|
||||
fn generate_network_config(hostname: &str, target_dir: &Path) -> Result<(), InstallError> {
|
||||
let etc_dir = target_dir.join("etc");
|
||||
fs::create_dir_all(&etc_dir)?;
|
||||
|
||||
// /etc/hostname
|
||||
let hostname_path = etc_dir.join("hostname");
|
||||
info(&format!("Ustawianie nazwy hosta: {} ({})", hostname, hostname_path.display()));
|
||||
fs::write(&hostname_path, format!("{}\n", hostname.trim()))?;
|
||||
|
||||
// /etc/hosts
|
||||
let hosts_path = etc_dir.join("hosts");
|
||||
info(&format!("Generowanie pliku hosts: {}", hosts_path.display()));
|
||||
let hosts_content = format!(
|
||||
"# /etc/hosts - KhOS Networking\n127.0.0.1\tlocalhost {}\n::1\t\tlocalhost ip6-localhost ip6-loopback {}\n",
|
||||
hostname.trim(), hostname.trim()
|
||||
);
|
||||
fs::write(&hosts_path, hosts_content)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Ustawia hasło administratora root oraz opcjonalnie tworzy użytkownika
|
||||
fn configure_users_and_passwords(
|
||||
config: &InstallConfig,
|
||||
target_dir: &Path,
|
||||
) -> Result<(), InstallError> {
|
||||
info("Konfigurowanie haseł kont systemowych...");
|
||||
|
||||
// Ustawienie hasła dla roota za pomocą chpasswd
|
||||
let root_pass_entry = format!("root:{}\n", config.root_password);
|
||||
let chpasswd_success = run_chpasswd_chroot(target_dir, &root_pass_entry);
|
||||
|
||||
if !chpasswd_success {
|
||||
// Fallback: próba z opcją -R (rootdir)
|
||||
let _ = run_with_stdin(
|
||||
"chpasswd",
|
||||
&["-R", target_dir.to_str().unwrap()],
|
||||
&root_pass_entry,
|
||||
);
|
||||
}
|
||||
|
||||
// Opcjonalne utworzenie zwykłego użytkownika
|
||||
if let Some(ref username) = config.username {
|
||||
info(&format!("Tworzenie konta użytkownika: {}", username));
|
||||
|
||||
// useradd -m -s /bin/sh -G wheel,audio,video,input,storage <username>
|
||||
let _ = Command::new("chroot")
|
||||
.arg(target_dir)
|
||||
.arg("useradd")
|
||||
.arg("-m")
|
||||
.arg("-s")
|
||||
.arg("/bin/sh")
|
||||
.arg("-G")
|
||||
.arg("wheel,audio,video,input,storage")
|
||||
.arg(username)
|
||||
.status()
|
||||
.or_else(|_| {
|
||||
// Alternatywa: adduser -D <username>
|
||||
Command::new("chroot")
|
||||
.arg(target_dir)
|
||||
.arg("adduser")
|
||||
.arg("-D")
|
||||
.arg("-s")
|
||||
.arg("/bin/sh")
|
||||
.arg(username)
|
||||
.status()
|
||||
});
|
||||
|
||||
if let Some(ref user_pass) = config.user_password {
|
||||
let user_entry = format!("{}:{}\n", username, user_pass);
|
||||
let _ = run_chpasswd_chroot(target_dir, &user_entry);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run_chpasswd_chroot(target_dir: &Path, input: &str) -> bool {
|
||||
if let Ok(mut child) = Command::new("chroot")
|
||||
.arg(target_dir)
|
||||
.arg("chpasswd")
|
||||
.stdin(std::process::Stdio::piped())
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.spawn()
|
||||
{
|
||||
if let Some(mut stdin) = child.stdin.take() {
|
||||
let _ = stdin.write_all(input.as_bytes());
|
||||
}
|
||||
child.wait().map(|s| s.success()).unwrap_or(false)
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn run_with_stdin(cmd: &str, args: &[&str], input: &str) -> bool {
|
||||
if let Ok(mut child) = Command::new(cmd)
|
||||
.args(args)
|
||||
.stdin(std::process::Stdio::piped())
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.spawn()
|
||||
{
|
||||
if let Some(mut stdin) = child.stdin.take() {
|
||||
let _ = stdin.write_all(input.as_bytes());
|
||||
}
|
||||
child.wait().map(|s| s.success()).unwrap_or(false)
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Zapisuje domyślne środowisko graficzne w /etc/khos-desktop
|
||||
fn configure_desktop_environment(
|
||||
config: &InstallConfig,
|
||||
target_dir: &Path,
|
||||
) -> Result<(), InstallError> {
|
||||
let desktop_tag = match config.desktop {
|
||||
crate::types::DesktopEnvironment::Xfce => "xfce",
|
||||
crate::types::DesktopEnvironment::Plasma => "plasma",
|
||||
crate::types::DesktopEnvironment::Hyprland => "hyprland",
|
||||
crate::types::DesktopEnvironment::Openbox => "openbox",
|
||||
};
|
||||
|
||||
info(&format!(
|
||||
"Ustawianie domyślnego środowiska graficznego: {}",
|
||||
config.desktop
|
||||
));
|
||||
|
||||
let desktop_file = target_dir.join("etc/khos-desktop");
|
||||
fs::write(&desktop_file, format!("{}\n", desktop_tag))?;
|
||||
|
||||
// Utwórz wpis w /etc/default/desktop
|
||||
let default_dir = target_dir.join("etc/default");
|
||||
let _ = fs::create_dir_all(&default_dir);
|
||||
let _ = fs::write(
|
||||
default_dir.join("desktop"),
|
||||
format!("DESKTOP={}\n", desktop_tag),
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Ustawia strefę czasową na UTC/Europe/Warsaw oraz konfigurację locale
|
||||
fn configure_locale_and_timezone(target_dir: &Path) -> Result<(), InstallError> {
|
||||
let etc = target_dir.join("etc");
|
||||
|
||||
// /etc/locale.conf
|
||||
let locale_conf = etc.join("locale.conf");
|
||||
let _ = fs::write(&locale_conf, "LANG=pl_PL.UTF-8\nLC_COLLATE=C\n");
|
||||
|
||||
// Strefa czasowa /etc/localtime
|
||||
let zoneinfo = target_dir.join("usr/share/zoneinfo/Europe/Warsaw");
|
||||
let utc_zone = target_dir.join("usr/share/zoneinfo/UTC");
|
||||
let localtime = etc.join("localtime");
|
||||
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let _ = fs::remove_file(&localtime);
|
||||
if zoneinfo.exists() {
|
||||
let _ = std::os::unix::fs::symlink("/usr/share/zoneinfo/Europe/Warsaw", &localtime);
|
||||
} else if utc_zone.exists() {
|
||||
let _ = std::os::unix::fs::symlink("/usr/share/zoneinfo/UTC", &localtime);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,390 @@
|
||||
use crate::error::InstallError;
|
||||
use crate::logger::{info, msg, ok, progress, warn};
|
||||
use crate::types::InstallConfig;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
/// Kopiuje pliki systemu KhOS na zamontowaną partycję docelową
|
||||
pub fn copy_system_files(
|
||||
config: &InstallConfig,
|
||||
target_dir: &Path,
|
||||
) -> Result<(), InstallError> {
|
||||
if config.dry_run {
|
||||
msg(&format!(
|
||||
"[DRY-RUN] Symulacja kopiowania systemu plików do: {}",
|
||||
target_dir.display()
|
||||
));
|
||||
progress("copy", 50, "Symulacja transferu plików systemu...");
|
||||
progress("copy", 100, "Symulacja ukończona.");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
msg("Kopiowanie plików systemu operacyjnego KhOS na dysk...");
|
||||
progress("copy", 10, "Lokalizowanie obrazu instalacyjnego...");
|
||||
|
||||
// 1. Zlokalizuj źródło (obraz squashfs lub rozpakowany rootfs)
|
||||
let source = locate_system_source(config)?;
|
||||
info(&format!("Źródło danych instalacyjnych: {}", source.display()));
|
||||
|
||||
progress("copy", 25, "Kopiowanie głównego drzewa plików systemu...");
|
||||
|
||||
// 2. Kopiowanie danych
|
||||
if source.is_file() && source.extension().map_or(false, |ext| ext == "squashfs") {
|
||||
extract_squashfs(&source, target_dir)?;
|
||||
} else if source.is_dir() {
|
||||
copy_directory_tree(&source, target_dir)?;
|
||||
} else {
|
||||
return Err(InstallError::CopyError(format!(
|
||||
"Nieznany typ źródła instalacyjnego: {}",
|
||||
source.display()
|
||||
)));
|
||||
}
|
||||
|
||||
progress("copy", 75, "Kopiowanie jądra vmlinuz oraz initramfs...");
|
||||
|
||||
// 3. Kopiowanie jądra oraz initramfs do /boot
|
||||
copy_kernel_and_initramfs(target_dir)?;
|
||||
|
||||
progress("copy", 90, "Konfigurowanie uprawnień i bitów SUID...");
|
||||
|
||||
// 4. Ustawienie uprawnień specjalnych i binariów
|
||||
configure_special_permissions(target_dir)?;
|
||||
|
||||
progress("copy", 100, "Pliki systemu KhOS zostały pomyślnie zainstalowane.");
|
||||
ok("Główny system plików został pomyślnie przetransferowany.");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Wyszukuje dostępne źródło plików systemu
|
||||
fn locate_system_source(config: &InstallConfig) -> Result<PathBuf, InstallError> {
|
||||
// 1. Wymuszenie ze strony użytkownika (--source)
|
||||
if let Some(ref custom_source) = config.source_path {
|
||||
if custom_source.exists() {
|
||||
return Ok(custom_source.clone());
|
||||
} else {
|
||||
return Err(InstallError::CopyError(format!(
|
||||
"Podane źródło '{}' nie istnieje.",
|
||||
custom_source.display()
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Zamontowany Live squashfs w /mnt/squashfs
|
||||
let mnt_squashfs = Path::new("/mnt/squashfs");
|
||||
if mnt_squashfs.join("bin/busybox").exists() || mnt_squashfs.join("bin/sh").exists() {
|
||||
return Ok(mnt_squashfs.to_path_buf());
|
||||
}
|
||||
|
||||
// 3. Plik filesystem.squashfs na nośniku cdrom
|
||||
let cdrom_squash = Path::new("/mnt/cdrom/live/filesystem.squashfs");
|
||||
if cdrom_squash.is_file() {
|
||||
return Ok(cdrom_squash.to_path_buf());
|
||||
}
|
||||
|
||||
// 4. Spróbuj zamontować napęd optyczny / USB
|
||||
mount_installation_media();
|
||||
if cdrom_squash.is_file() {
|
||||
return Ok(cdrom_squash.to_path_buf());
|
||||
}
|
||||
|
||||
// 5. Inne znane lokalizacje squashfs
|
||||
let known_squash_locations = [
|
||||
"/live/filesystem.squashfs",
|
||||
"/run/archiso/bootmnt/live/filesystem.squashfs",
|
||||
"/run/initramfs/live/filesystem.squashfs",
|
||||
];
|
||||
for loc in &known_squash_locations {
|
||||
let p = Path::new(loc);
|
||||
if p.is_file() {
|
||||
return Ok(p.to_path_buf());
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Ostateczny fallback: bieżący katalog główny / (jeśli to środowisko live)
|
||||
let root = Path::new("/");
|
||||
if root.join("bin/busybox").exists() || root.join("usr/bin/khos-installer").exists() {
|
||||
info("Użycie bieżącego środowiska Live jako źródła instalacji.");
|
||||
return Ok(root.to_path_buf());
|
||||
}
|
||||
|
||||
Err(InstallError::CopyError(
|
||||
"Nie odnaleziono nośnika instalacyjnego KhOS ani obrazu filesystem.squashfs.".to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Próbuje zamontować dostępne urządzenia CD-ROM / pendrive USB w /mnt/cdrom
|
||||
fn mount_installation_media() {
|
||||
let cdrom_dir = Path::new("/mnt/cdrom");
|
||||
if !cdrom_dir.exists() {
|
||||
let _ = fs::create_dir_all(cdrom_dir);
|
||||
}
|
||||
|
||||
// Przeszukaj urządzenia sr*, loop*, sd*
|
||||
if let Ok(entries) = fs::read_dir("/dev") {
|
||||
for entry in entries.flatten() {
|
||||
let name = entry.file_name().to_string_lossy().to_string();
|
||||
if name.starts_with("sr") || name.starts_with("cdrom") || name.starts_with("loop") {
|
||||
let dev_path = entry.path();
|
||||
let _ = Command::new("mount")
|
||||
.arg("-o")
|
||||
.arg("ro")
|
||||
.arg(&dev_path)
|
||||
.arg(cdrom_dir)
|
||||
.output();
|
||||
|
||||
if cdrom_dir.join("live/filesystem.squashfs").exists()
|
||||
|| cdrom_dir.join("boot/vmlinuz").exists()
|
||||
{
|
||||
info(&format!("Zamontowano nośnik instalacyjny: {}", dev_path.display()));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Rozpakowuje plik squashfs bezpośrednio do katalogu docelowego
|
||||
fn extract_squashfs(squashfs_file: &Path, target_dir: &Path) -> Result<(), InstallError> {
|
||||
info(&format!(
|
||||
"Rozpakowywanie obrazu SquashFS ({}) do {}...",
|
||||
squashfs_file.display(),
|
||||
target_dir.display()
|
||||
));
|
||||
|
||||
// Jeśli unsquashfs jest dostępne w systemie
|
||||
let unsquash_status = Command::new("unsquashfs")
|
||||
.arg("-f")
|
||||
.arg("-d")
|
||||
.arg(target_dir)
|
||||
.arg(squashfs_file)
|
||||
.status();
|
||||
|
||||
if let Ok(status) = unsquash_status {
|
||||
if status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
// Alternatywa: montowanie tymczasowe przez loop i kopiowanie
|
||||
let tmp_mount = Path::new("/mnt/khos_squash_tmp");
|
||||
let _ = fs::create_dir_all(tmp_mount);
|
||||
|
||||
let mount_status = Command::new("mount")
|
||||
.arg("-t")
|
||||
.arg("squashfs")
|
||||
.arg("-o")
|
||||
.arg("ro,loop")
|
||||
.arg(squashfs_file)
|
||||
.arg(tmp_mount)
|
||||
.status();
|
||||
|
||||
if let Ok(m_status) = mount_status {
|
||||
if m_status.success() {
|
||||
let copy_result = copy_directory_tree(tmp_mount, target_dir);
|
||||
let _ = Command::new("umount").arg(tmp_mount).status();
|
||||
let _ = fs::remove_dir(tmp_mount);
|
||||
return copy_result;
|
||||
}
|
||||
}
|
||||
|
||||
Err(InstallError::CopyError(
|
||||
"Nie udało się rozpakować ani zamontować obrazu SquashFS.".to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Kopiuje drzewo katalogów ze źródła do celu z zachowaniem dowiązań i atrybutów
|
||||
fn copy_directory_tree(source_dir: &Path, target_dir: &Path) -> Result<(), InstallError> {
|
||||
info(&format!(
|
||||
"Kopiowanie drzewa plików z {} do {}...",
|
||||
source_dir.display(),
|
||||
target_dir.display()
|
||||
));
|
||||
|
||||
// Jeśli źródłem jest root '/', kopiuj tylko katalogi systemowe
|
||||
if source_dir == Path::new("/") {
|
||||
let system_folders = [
|
||||
"bin", "sbin", "lib", "lib64", "usr", "etc", "var", "root", "home", "opt", "srv",
|
||||
];
|
||||
|
||||
for folder in &system_folders {
|
||||
let src_sub = source_dir.join(folder);
|
||||
if src_sub.exists() {
|
||||
let dst_sub = target_dir.join(folder);
|
||||
let _ = fs::create_dir_all(&dst_sub);
|
||||
copy_single_dir(&src_sub, &dst_sub)?;
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
copy_single_dir(source_dir, target_dir)
|
||||
}
|
||||
|
||||
fn copy_single_dir(source: &Path, target: &Path) -> Result<(), InstallError> {
|
||||
// Użycie tar pipeline dla maksymalnej wierności metadanych, uprawnień i dowiązań
|
||||
let tar_cmd = format!(
|
||||
"cd '{}' && tar -cf - . | tar -xf - -C '{}'",
|
||||
source.display(),
|
||||
target.display()
|
||||
);
|
||||
|
||||
let status = Command::new("sh")
|
||||
.arg("-c")
|
||||
.arg(&tar_cmd)
|
||||
.status();
|
||||
|
||||
if let Ok(s) = status {
|
||||
if s.success() {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback do cp -af
|
||||
let cp_status = Command::new("cp")
|
||||
.arg("-af")
|
||||
.arg(format!("{}/.", source.display()))
|
||||
.arg(target)
|
||||
.status();
|
||||
|
||||
if let Ok(s) = cp_status {
|
||||
if s.success() {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
Err(InstallError::CopyError(format!(
|
||||
"Błąd kopiowania katalogu {} do {}",
|
||||
source.display(),
|
||||
target.display()
|
||||
)))
|
||||
}
|
||||
|
||||
/// Kopiuje obraz jądra (vmlinuz) oraz initramfs do docelowego katalogu /boot
|
||||
fn copy_kernel_and_initramfs(target_dir: &Path) -> Result<(), InstallError> {
|
||||
let boot_target = target_dir.join("boot");
|
||||
fs::create_dir_all(&boot_target)?;
|
||||
|
||||
let kernel_candidates = [
|
||||
"/mnt/cdrom/boot/vmlinuz",
|
||||
"/boot/vmlinuz",
|
||||
"/mnt/squashfs/boot/vmlinuz",
|
||||
"/run/archiso/bootmnt/boot/vmlinuz",
|
||||
];
|
||||
|
||||
let mut kernel_copied = false;
|
||||
for cand in &kernel_candidates {
|
||||
let p = Path::new(cand);
|
||||
if p.is_file() {
|
||||
let dest = boot_target.join("vmlinuz");
|
||||
fs::copy(p, &dest)?;
|
||||
info(&format!("Skopiowano jądro: {} -> {}", p.display(), dest.display()));
|
||||
kernel_copied = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if !kernel_copied {
|
||||
warn("Ostrzeżenie: Nie odnaleziono pliku vmlinuz w standardowych ścieżkach.");
|
||||
}
|
||||
|
||||
let initrd_candidates = [
|
||||
"/mnt/cdrom/boot/initramfs.img",
|
||||
"/boot/initramfs.img",
|
||||
"/mnt/squashfs/boot/initramfs.img",
|
||||
"/run/archiso/bootmnt/boot/initramfs.img",
|
||||
];
|
||||
|
||||
let mut initrd_copied = false;
|
||||
for cand in &initrd_candidates {
|
||||
let p = Path::new(cand);
|
||||
if p.is_file() {
|
||||
let dest = boot_target.join("initramfs.img");
|
||||
fs::copy(p, &dest)?;
|
||||
info(&format!("Skopiowano initramfs: {} -> {}", p.display(), dest.display()));
|
||||
initrd_copied = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if !initrd_copied {
|
||||
warn("Ostrzeżenie: Nie odnaleziono pliku initramfs.img w standardowych ścieżkach.");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Konfiguruje uprawnienia binarne, SUID oraz wykonywalność skryptów KhOS
|
||||
fn configure_special_permissions(target_dir: &Path) -> Result<(), InstallError> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
// Bity SUID wylacznie dla sudo i doas
|
||||
let suid_binaries = [
|
||||
"usr/bin/sudo",
|
||||
"usr/bin/doas",
|
||||
];
|
||||
|
||||
for bin in &suid_binaries {
|
||||
let p = target_dir.join(bin);
|
||||
if p.is_file() {
|
||||
if let Ok(mut perms) = fs::metadata(&p).map(|m| m.permissions()) {
|
||||
perms.set_mode(0o4755);
|
||||
let _ = fs::set_permissions(&p, perms);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Standardowe uprawnienia (0755) dla uslug i busybox
|
||||
let standard_binaries = [
|
||||
"bin/busybox",
|
||||
"usr/bin/Xorg",
|
||||
"usr/bin/seatd-launch",
|
||||
];
|
||||
|
||||
for bin in &standard_binaries {
|
||||
let p = target_dir.join(bin);
|
||||
if p.is_file() {
|
||||
if let Ok(mut perms) = fs::metadata(&p).map(|m| m.permissions()) {
|
||||
perms.set_mode(0o755);
|
||||
let _ = fs::set_permissions(&p, perms);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let shadow = target_dir.join("etc/shadow");
|
||||
if shadow.is_file() {
|
||||
if let Ok(mut perms) = fs::metadata(&shadow).map(|m| m.permissions()) {
|
||||
perms.set_mode(0o600);
|
||||
let _ = fs::set_permissions(&shadow, perms);
|
||||
}
|
||||
}
|
||||
|
||||
// Skrypty wykonywalne
|
||||
let exec_scripts = [
|
||||
"usr/bin/start-xfce",
|
||||
"usr/bin/startxfce4",
|
||||
"usr/bin/start-plasma",
|
||||
"usr/bin/start-hyprland",
|
||||
"usr/bin/start-openbox",
|
||||
"usr/bin/khos-installer",
|
||||
"usr/bin/khos-update",
|
||||
"usr/bin/install-os",
|
||||
"usr/bin/wpkg",
|
||||
"usr/bin/pomoc",
|
||||
];
|
||||
|
||||
for script in &exec_scripts {
|
||||
let p = target_dir.join(script);
|
||||
if p.is_file() {
|
||||
if let Ok(mut perms) = fs::metadata(&p).map(|m| m.permissions()) {
|
||||
perms.set_mode(0o755);
|
||||
let _ = fs::set_permissions(&p, perms);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
use crate::error::InstallError;
|
||||
use crate::types::{BootMode, DiskInfo, PartitionInfo};
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
/// Wykrywa czy system został uruchomiony w trybie UEFI czy tradycyjnym BIOS (Legacy/MBR)
|
||||
pub fn detect_boot_mode() -> BootMode {
|
||||
if Path::new("/sys/firmware/efi").is_dir() {
|
||||
BootMode::Uefi
|
||||
} else {
|
||||
BootMode::Bios
|
||||
}
|
||||
}
|
||||
|
||||
/// Sprawdza czy program został uruchomiony z uprawnieniami roota (UID 0)
|
||||
pub fn is_root() -> bool {
|
||||
if let Ok(status) = fs::read_to_string("/proc/self/status") {
|
||||
for line in status.lines() {
|
||||
if line.starts_with("Uid:") {
|
||||
let parts: Vec<&str> = line.split_whitespace().collect();
|
||||
if parts.len() > 1 && parts[1] == "0" {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: uruchomienie polecenia `id -u`
|
||||
if let Ok(output) = Command::new("id").arg("-u").output() {
|
||||
if let Ok(uid_str) = String::from_utf8(output.stdout) {
|
||||
return uid_str.trim() == "0";
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
/// Formatuje rozmiar w bajtach na czytelną dla człowieka reprezentację (GB, MB, TB)
|
||||
pub fn format_size(bytes: u64) -> String {
|
||||
const KIB: u64 = 1024;
|
||||
const MIB: u64 = 1024 * KIB;
|
||||
const GIB: u64 = 1024 * MIB;
|
||||
const TIB: u64 = 1024 * GIB;
|
||||
|
||||
if bytes >= TIB {
|
||||
format!("{:.2} TB", bytes as f64 / TIB as f64)
|
||||
} else if bytes >= GIB {
|
||||
format!("{:.1} GB", bytes as f64 / GIB as f64)
|
||||
} else if bytes >= MIB {
|
||||
format!("{:.1} MB", bytes as f64 / MIB as f64)
|
||||
} else if bytes >= KIB {
|
||||
format!("{:.1} KB", bytes as f64 / KIB as f64)
|
||||
} else {
|
||||
format!("{} B", bytes)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_format_size() {
|
||||
assert_eq!(format_size(500), "500 B");
|
||||
assert_eq!(format_size(1024), "1.0 KB");
|
||||
assert_eq!(format_size(1024 * 1024), "1.0 MB");
|
||||
assert_eq!(format_size(1024 * 1024 * 1024 * 50), "50.0 GB");
|
||||
assert_eq!(format_size(1024 * 1024 * 1024 * 1024 * 2), "2.00 TB");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_detect_boot_mode() {
|
||||
let mode = detect_boot_mode();
|
||||
assert!(mode == BootMode::Uefi || mode == BootMode::Bios);
|
||||
}
|
||||
}
|
||||
|
||||
/// Wykrywa listę wszystkich dostępnych dysków twardych i SSD w systemie
|
||||
pub fn list_disks() -> Result<Vec<DiskInfo>, InstallError> {
|
||||
let mut disks = Vec::new();
|
||||
let sys_block = Path::new("/sys/block");
|
||||
|
||||
if !sys_block.exists() {
|
||||
return Ok(disks);
|
||||
}
|
||||
|
||||
let entries = fs::read_dir(sys_block)?;
|
||||
for entry in entries.flatten() {
|
||||
let file_name = entry.file_name();
|
||||
let name = file_name.to_string_lossy();
|
||||
|
||||
// Ignoruj urządzenia wirtualne, pamięć RAM, napędy optyczne i zram
|
||||
if name.starts_with("loop")
|
||||
|| name.starts_with("ram")
|
||||
|| name.starts_with("sr")
|
||||
|| name.starts_with("dm-")
|
||||
|| name.starts_with("zram")
|
||||
|| name.starts_with("cdrom")
|
||||
|| name.starts_with("fd")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
let dev_path = PathBuf::from(format!("/dev/{}", name));
|
||||
|
||||
// Sprawdź czy to urządzenie rzeczywiście istnieje jako węzeł blokowy lub wpis sysfs
|
||||
let size_path = entry.path().join("size");
|
||||
let size_sectors: u64 = fs::read_to_string(&size_path)
|
||||
.unwrap_or_default()
|
||||
.trim()
|
||||
.parse()
|
||||
.unwrap_or(0);
|
||||
|
||||
let size_bytes = size_sectors * 512;
|
||||
if size_bytes == 0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let size_gb = size_bytes as f64 / (1024.0 * 1024.0 * 1024.0);
|
||||
|
||||
// Odczyt modelu dysku
|
||||
let model = read_disk_model(&entry.path());
|
||||
|
||||
// Sprawdź czy dysk jest wymienny
|
||||
let removable_path = entry.path().join("removable");
|
||||
let is_removable = fs::read_to_string(&removable_path)
|
||||
.unwrap_or_default()
|
||||
.trim()
|
||||
== "1";
|
||||
|
||||
// Odczytaj partycje
|
||||
let partitions = read_partitions(&entry.path(), &name);
|
||||
|
||||
disks.push(DiskInfo {
|
||||
name: name.to_string(),
|
||||
path: dev_path,
|
||||
size_bytes,
|
||||
size_gb,
|
||||
model,
|
||||
is_removable,
|
||||
partitions,
|
||||
});
|
||||
}
|
||||
|
||||
// Sortuj według ścieżki
|
||||
disks.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
Ok(disks)
|
||||
}
|
||||
|
||||
fn read_disk_model(sys_path: &Path) -> String {
|
||||
let model_path = sys_path.join("device/model");
|
||||
if let Ok(model) = fs::read_to_string(model_path) {
|
||||
let trimmed = model.trim().to_string();
|
||||
if !trimmed.is_empty() {
|
||||
let vendor_path = sys_path.join("device/vendor");
|
||||
if let Ok(vendor) = fs::read_to_string(vendor_path) {
|
||||
let v = vendor.trim();
|
||||
if !v.is_empty() && !trimmed.starts_with(v) {
|
||||
return format!("{} {}", v, trimmed);
|
||||
}
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
}
|
||||
|
||||
let name_path = sys_path.join("device/name");
|
||||
if let Ok(name) = fs::read_to_string(name_path) {
|
||||
let trimmed = name.trim();
|
||||
if !trimmed.is_empty() {
|
||||
return trimmed.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
"Dysk blokowy (SSD/HDD)".to_string()
|
||||
}
|
||||
|
||||
fn read_partitions(sys_path: &Path, disk_name: &str) -> Vec<PartitionInfo> {
|
||||
let mut parts = Vec::new();
|
||||
if let Ok(entries) = fs::read_dir(sys_path) {
|
||||
for entry in entries.flatten() {
|
||||
let name = entry.file_name().to_string_lossy().to_string();
|
||||
if name.starts_with(disk_name) && name != disk_name {
|
||||
let part_size_path = entry.path().join("size");
|
||||
let size_sectors: u64 = fs::read_to_string(part_size_path)
|
||||
.unwrap_or_default()
|
||||
.trim()
|
||||
.parse()
|
||||
.unwrap_or(0);
|
||||
|
||||
let size_bytes = size_sectors * 512;
|
||||
let part_path = PathBuf::from(format!("/dev/{}", name));
|
||||
let uuid = get_partition_uuid(&part_path);
|
||||
|
||||
parts.push(PartitionInfo {
|
||||
name,
|
||||
path: part_path,
|
||||
size_bytes,
|
||||
fs_type: None,
|
||||
uuid,
|
||||
mount_point: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
parts.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
parts
|
||||
}
|
||||
|
||||
/// Pobiera UUID partycji za pomocą polecenia blkid lub odczytu /dev/disk/by-uuid
|
||||
pub fn get_partition_uuid(partition_path: &Path) -> Option<String> {
|
||||
// Metoda 1: blkid -s UUID -o value <path>
|
||||
if let Ok(output) = Command::new("blkid")
|
||||
.arg("-s")
|
||||
.arg("UUID")
|
||||
.arg("-o")
|
||||
.arg("value")
|
||||
.arg(partition_path)
|
||||
.output()
|
||||
{
|
||||
if output.status.success() {
|
||||
let uuid = String::from_utf8_lossy(&output.stdout).trim().to_string();
|
||||
if !uuid.is_empty() {
|
||||
return Some(uuid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Metoda 2: przeszukanie katalogu /dev/disk/by-uuid
|
||||
let by_uuid = Path::new("/dev/disk/by-uuid");
|
||||
if by_uuid.is_dir() {
|
||||
if let Ok(entries) = fs::read_dir(by_uuid) {
|
||||
for entry in entries.flatten() {
|
||||
if let Ok(target) = fs::read_link(entry.path()) {
|
||||
let canon_target = if target.is_relative() {
|
||||
by_uuid.join(target)
|
||||
} else {
|
||||
target
|
||||
};
|
||||
if let Ok(canon_part) = partition_path.canonicalize() {
|
||||
if let Ok(canon_target) = canon_target.canonicalize() {
|
||||
if canon_target == canon_part {
|
||||
return Some(entry.file_name().to_string_lossy().to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// Sprawdza czy podana ścieżka reprezentuje prawidłowe urządzenie blokowe
|
||||
pub fn validate_block_device(path: &Path) -> Result<(), InstallError> {
|
||||
if !path.exists() {
|
||||
return Err(InstallError::DiskNotFound(format!(
|
||||
"Ścieżka '{}' nie istnieje w systemie.",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
|
||||
// W systemie Linux urządzenia blokowe można zweryfikować przez polecenie `test -b` lub sprawdzając metadane
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::FileTypeExt;
|
||||
if let Ok(meta) = fs::metadata(path) {
|
||||
if !meta.file_type().is_block_device() {
|
||||
return Err(InstallError::InvalidDisk(format!(
|
||||
"'{}' nie jest urządzeniem blokowym.",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
use std::fmt;
|
||||
use std::io;
|
||||
|
||||
/// Błędy instalatora KhOS
|
||||
#[derive(Debug)]
|
||||
pub enum InstallError {
|
||||
PermissionDenied(String),
|
||||
DiskNotFound(String),
|
||||
InvalidDisk(String),
|
||||
CommandFailed {
|
||||
cmd: String,
|
||||
status: i32,
|
||||
stderr: String,
|
||||
},
|
||||
PartitionError(String),
|
||||
MountError(String),
|
||||
CopyError(String),
|
||||
ConfigError(String),
|
||||
BootloaderError(String),
|
||||
Io(io::Error),
|
||||
Serialization(String),
|
||||
Cancelled(String),
|
||||
}
|
||||
|
||||
impl fmt::Display for InstallError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
InstallError::PermissionDenied(msg) => write!(f, "Brak uprawnień roota: {}", msg),
|
||||
InstallError::DiskNotFound(msg) => write!(f, "Nie znaleziono dysku: {}", msg),
|
||||
InstallError::InvalidDisk(msg) => write!(f, "Nieprawidłowy dysk docelowy: {}", msg),
|
||||
InstallError::CommandFailed { cmd, status, stderr } => {
|
||||
write!(
|
||||
f,
|
||||
"Polecenie '{}' zakończone błędem (kod: {}): {}",
|
||||
cmd, status, stderr.trim()
|
||||
)
|
||||
}
|
||||
InstallError::PartitionError(msg) => write!(f, "Błąd partycjonowania: {}", msg),
|
||||
InstallError::MountError(msg) => write!(f, "Błąd montowania: {}", msg),
|
||||
InstallError::CopyError(msg) => write!(f, "Błąd kopiowania plików systemu: {}", msg),
|
||||
InstallError::ConfigError(msg) => write!(f, "Błąd konfiguracji systemu: {}", msg),
|
||||
InstallError::BootloaderError(msg) => write!(f, "Błąd instalacji programu rozruchowego: {}", msg),
|
||||
InstallError::Io(err) => write!(f, "Błąd wejścia/wyjścia: {}", err),
|
||||
InstallError::Serialization(msg) => write!(f, "Błąd serializacji JSON: {}", msg),
|
||||
InstallError::Cancelled(msg) => write!(f, "Operacja anulowana: {}", msg),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for InstallError {
|
||||
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||
match self {
|
||||
InstallError::Io(err) => Some(err),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<io::Error> for InstallError {
|
||||
fn from(err: io::Error) -> Self {
|
||||
InstallError::Io(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<serde_json::Error> for InstallError {
|
||||
fn from(err: serde_json::Error) -> Self {
|
||||
InstallError::Serialization(err.to_string())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
use crate::types::ProgressEvent;
|
||||
use std::io::{self, Write};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
pub const C_RESET: &str = "\x1b[0m";
|
||||
pub const C_BOLD: &str = "\x1b[1m";
|
||||
pub const C_RED: &str = "\x1b[1;31m";
|
||||
pub const C_GREEN: &str = "\x1b[1;32m";
|
||||
pub const C_YELLOW: &str = "\x1b[1;33m";
|
||||
pub const C_CYAN: &str = "\x1b[1;36m";
|
||||
pub const C_BLUE: &str = "\x1b[1;34m";
|
||||
pub const C_MAGENTA: &str = "\x1b[1;35m";
|
||||
|
||||
static JSON_MODE: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
pub fn set_json_mode(enabled: bool) {
|
||||
JSON_MODE.store(enabled, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
pub fn is_json_mode() -> bool {
|
||||
JSON_MODE.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub fn emit_event(event: &ProgressEvent) {
|
||||
if is_json_mode() {
|
||||
if let Ok(json_str) = serde_json::to_string(event) {
|
||||
println!("{}", json_str);
|
||||
let _ = io::stdout().flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn msg(message: &str) {
|
||||
if is_json_mode() {
|
||||
emit_event(&ProgressEvent::Log {
|
||||
level: "info".to_string(),
|
||||
message: message.to_string(),
|
||||
});
|
||||
} else {
|
||||
println!("{}{}==>{}{} {}{}{}", C_BOLD, C_BLUE, C_RESET, C_BOLD, message, C_RESET, "");
|
||||
let _ = io::stdout().flush();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn info(message: &str) {
|
||||
if is_json_mode() {
|
||||
emit_event(&ProgressEvent::Log {
|
||||
level: "debug".to_string(),
|
||||
message: message.to_string(),
|
||||
});
|
||||
} else {
|
||||
println!("{} ->{} {}", C_CYAN, C_RESET, message);
|
||||
let _ = io::stdout().flush();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ok(message: &str) {
|
||||
if is_json_mode() {
|
||||
emit_event(&ProgressEvent::Log {
|
||||
level: "success".to_string(),
|
||||
message: message.to_string(),
|
||||
});
|
||||
} else {
|
||||
println!("{} [OK]{} {}", C_GREEN, C_RESET, message);
|
||||
let _ = io::stdout().flush();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn warn(message: &str) {
|
||||
if is_json_mode() {
|
||||
emit_event(&ProgressEvent::Log {
|
||||
level: "warn".to_string(),
|
||||
message: message.to_string(),
|
||||
});
|
||||
} else {
|
||||
eprintln!("{}[OSTRZEŻENIE]{} {}", C_YELLOW, C_RESET, message);
|
||||
let _ = io::stderr().flush();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn err(message: &str) {
|
||||
if is_json_mode() {
|
||||
emit_event(&ProgressEvent::Error {
|
||||
message: message.to_string(),
|
||||
});
|
||||
} else {
|
||||
eprintln!("{}[BŁĄD]{} {}", C_RED, C_RESET, message);
|
||||
let _ = io::stderr().flush();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn progress(step: &str, percent: u8, description: &str) {
|
||||
emit_event(&ProgressEvent::Stage {
|
||||
step: step.to_string(),
|
||||
percent,
|
||||
description: description.to_string(),
|
||||
});
|
||||
|
||||
if !is_json_mode() {
|
||||
println!(
|
||||
"{}[{:>3}%]{} {}{}{}",
|
||||
C_MAGENTA, percent, C_RESET, C_BOLD, description, C_RESET
|
||||
);
|
||||
let _ = io::stdout().flush();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn banner() {
|
||||
if is_json_mode() {
|
||||
return;
|
||||
}
|
||||
println!(
|
||||
r#"{}{}"#
|
||||
, C_CYAN,
|
||||
r#" ╔══════════════════════════════════════════════════════════════╗
|
||||
║ ║
|
||||
║ ╦ ╦╦ ╔═╗╔═╗╔╗╔╦ ╦╔═╗╔═╗ INSTALATOR SYSTEMU ║
|
||||
║ ║║║║ ╠═╣╚═╗║║║╚╦╝║ ║╚═╗ KhOS (Rust Core) ║
|
||||
║ ╚╩╝╩═╝╩ ╩╚═╝╝╚╝ ╩ ╚═╝╚═╝ v1.1.0 Genesis ║
|
||||
║ ║
|
||||
║ Oficjalny, modułowy instalator systemu KhOS ║
|
||||
║ Bezpieczna instalacja na dyskach SSD, NVMe i HDD ║
|
||||
╚══════════════════════════════════════════════════════════════╝"#
|
||||
);
|
||||
println!("{}\n", C_RESET);
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
mod bootloader;
|
||||
mod cli;
|
||||
mod config;
|
||||
mod copy;
|
||||
mod disk;
|
||||
mod error;
|
||||
mod logger;
|
||||
mod mount;
|
||||
mod partition;
|
||||
mod types;
|
||||
|
||||
use cli::CliArgs;
|
||||
use error::InstallError;
|
||||
use logger::{banner, emit_event, err, info, is_json_mode, msg, ok, progress, set_json_mode, warn, C_BOLD, C_CYAN, C_RESET};
|
||||
use std::io::{self, BufRead, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process;
|
||||
use std::time::Instant;
|
||||
use types::{BootMode, DesktopEnvironment, InstallConfig, ProgressEvent};
|
||||
|
||||
fn main() {
|
||||
let start_time = Instant::now();
|
||||
|
||||
// 1. Parsowanie parametrów wiersza poleceń
|
||||
let args = match CliArgs::parse() {
|
||||
Ok(a) => a,
|
||||
Err(e) => {
|
||||
eprintln!("Błąd argumentów: {}", e);
|
||||
eprintln!("Użyj --help, aby wyświetlić dostępne opcje.");
|
||||
process::exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
if args.show_help {
|
||||
CliArgs::print_help();
|
||||
process::exit(0);
|
||||
}
|
||||
|
||||
if args.show_version {
|
||||
CliArgs::print_version();
|
||||
process::exit(0);
|
||||
}
|
||||
|
||||
// Włączenie trybu JSON dla frontendu Calamares / Web
|
||||
if args.config.json_output {
|
||||
set_json_mode(true);
|
||||
}
|
||||
|
||||
// 2. Obsługa poleceń informacyjnych
|
||||
if args.detect_boot {
|
||||
let mode = disk::detect_boot_mode();
|
||||
if is_json_mode() {
|
||||
println!(r#"{{"boot_mode":"{}"}}"#, mode);
|
||||
} else {
|
||||
println!("Wykryty tryb rozruchu: {}", mode);
|
||||
}
|
||||
process::exit(0);
|
||||
}
|
||||
|
||||
if args.list_disks {
|
||||
match disk::list_disks() {
|
||||
Ok(disks) => {
|
||||
if is_json_mode() {
|
||||
let json = serde_json::to_string_pretty(&disks).unwrap_or_default();
|
||||
println!("{}", json);
|
||||
} else {
|
||||
println!("\nDostępne dyski twarde i SSD:");
|
||||
for d in &disks {
|
||||
println!(
|
||||
" - {} ({}) - {}",
|
||||
d.path.display(),
|
||||
disk::format_size(d.size_bytes),
|
||||
d.model
|
||||
);
|
||||
}
|
||||
println!();
|
||||
}
|
||||
process::exit(0);
|
||||
}
|
||||
Err(e) => {
|
||||
err(&format!("Nie udało się pobrać listy dysków: {}", e));
|
||||
process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Sprawdzenie uprawnień administratora root
|
||||
if !args.config.dry_run && !disk::is_root() {
|
||||
err("Ten program wymaga uprawnień administratora root. Uruchom polecenie z 'sudo' lub jako root.");
|
||||
process::exit(1);
|
||||
}
|
||||
|
||||
// 4. Konfiguracja i uruchomienie instalacji
|
||||
let mut config = args.config;
|
||||
|
||||
// Automatyczne wykrycie trybu rozruchu jeśli nie wymuszono parametrem
|
||||
let detected_mode = disk::detect_boot_mode();
|
||||
if config.boot_mode == BootMode::Bios && detected_mode == BootMode::Uefi {
|
||||
config.boot_mode = BootMode::Uefi;
|
||||
}
|
||||
|
||||
if !config.auto_mode {
|
||||
if let Err(e) = run_interactive_wizard(&mut config) {
|
||||
err(&format!("Przerwano kreator instalacji: {}", e));
|
||||
process::exit(1);
|
||||
}
|
||||
} else if config.target_disk.as_os_str().is_empty() {
|
||||
err("Błąd: Tryb automatyczny (--auto) wymaga podania dysku docelowego za pomocą --disk <ścieżka>.");
|
||||
process::exit(1);
|
||||
}
|
||||
|
||||
// 5. Uruchomienie procedury instalacyjnej
|
||||
let target_disk_str = config.target_disk.to_string_lossy().to_string();
|
||||
let boot_mode_str = config.boot_mode.to_string();
|
||||
|
||||
match perform_installation(&config) {
|
||||
Ok(root_part) => {
|
||||
let elapsed = start_time.elapsed().as_secs();
|
||||
emit_event(&ProgressEvent::Completed {
|
||||
success: true,
|
||||
target_disk: target_disk_str.clone(),
|
||||
root_partition: root_part.to_string_lossy().to_string(),
|
||||
boot_mode: boot_mode_str,
|
||||
elapsed_seconds: elapsed,
|
||||
});
|
||||
|
||||
if !is_json_mode() {
|
||||
print_success_summary(&config, &root_part, elapsed);
|
||||
}
|
||||
process::exit(0);
|
||||
}
|
||||
Err(e) => {
|
||||
emit_event(&ProgressEvent::Error {
|
||||
message: e.to_string(),
|
||||
});
|
||||
err(&format!("Instalacja nie powiodła się: {}", e));
|
||||
process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Główny przepływ instalacji systemu KhOS
|
||||
fn perform_installation(config: &InstallConfig) -> Result<PathBuf, InstallError> {
|
||||
progress("start", 5, "Inicjalizacja instalatora KhOS 1.1...");
|
||||
|
||||
// Krok 1: Weryfikacja poprawności urządzenia
|
||||
if !config.dry_run {
|
||||
disk::validate_block_device(&config.target_disk)?;
|
||||
}
|
||||
|
||||
// Krok 2: Partycjonowanie i formatowanie dysku
|
||||
progress("partition", 15, "Tworzenie tablic partycji i formatowanie systemów plików...");
|
||||
let partitions = partition::prepare_disk(config)?;
|
||||
|
||||
// Krok 3: Montowanie partycji docelowych
|
||||
progress("mount", 35, "Bezpieczne montowanie partycji w środowisku instalacyjnym...");
|
||||
let target_mount_dir = Path::new("/mnt/install_target");
|
||||
let mut mount_guard = mount::setup_target_mounts(&partitions, target_mount_dir, config.dry_run)?;
|
||||
|
||||
// Krok 4: Kopiowanie plików systemu operacyjnego
|
||||
progress("copy", 45, "Kopiowanie plików systemu KhOS, jądra i initramfs...");
|
||||
copy::copy_system_files(config, target_mount_dir)?;
|
||||
|
||||
// Krok 5: Konfiguracja docelowego systemu
|
||||
progress("config", 80, "Generowanie konfiguracji fstab, sieci i kont użytkowników...");
|
||||
config::configure_target_system(config, &partitions, target_mount_dir)?;
|
||||
|
||||
// Krok 6: Instalacja programu rozruchowego
|
||||
progress("bootloader", 90, "Instalacja programu rozruchowego GRUB...");
|
||||
bootloader::install_bootloader(config, &partitions, target_mount_dir)?;
|
||||
|
||||
// Krok 7: Zrzucenie buforów i odmontowanie
|
||||
progress("cleanup", 98, "Zrzucanie buforów dyskowych i odmontowywanie partycji...");
|
||||
mount_guard.unmount_all()?;
|
||||
|
||||
let _ = std::fs::remove_dir(target_mount_dir);
|
||||
|
||||
progress("done", 100, "Instalacja KhOS zakończona pomyślnie!");
|
||||
Ok(partitions.root_part)
|
||||
}
|
||||
|
||||
/// Interaktywny kreator instalacji w konsoli
|
||||
fn run_interactive_wizard(config: &mut InstallConfig) -> Result<(), InstallError> {
|
||||
banner();
|
||||
|
||||
info(&format!(
|
||||
"Wykryty tryb rozruchu komputera: {}{}{}",
|
||||
C_BOLD, config.boot_mode, C_RESET
|
||||
));
|
||||
|
||||
// Wyszukiwanie dysków
|
||||
msg("Wyszukiwanie dysków twardych i SSD w systemie...");
|
||||
let disks = disk::list_disks()?;
|
||||
if disks.is_empty() {
|
||||
return Err(InstallError::DiskNotFound(
|
||||
"Nie wykryto żadnych dysków blokowych w systemie.".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
println!("\nDostępne nośniki pamięci:");
|
||||
for (idx, d) in disks.iter().enumerate() {
|
||||
println!(
|
||||
" [{}] {}{}{} ({}) - {}",
|
||||
idx + 1,
|
||||
C_BOLD,
|
||||
d.path.display(),
|
||||
C_RESET,
|
||||
disk::format_size(d.size_bytes),
|
||||
d.model
|
||||
);
|
||||
}
|
||||
println!();
|
||||
|
||||
// Wybór dysku jeśli nie podano w parametrze
|
||||
if config.target_disk.as_os_str().is_empty() {
|
||||
loop {
|
||||
print!("{}Wybierz numer dysku [1-{}]:{} ", C_BOLD, disks.len(), C_RESET);
|
||||
let _ = io::stdout().flush();
|
||||
|
||||
let mut input = String::new();
|
||||
io::stdin().read_line(&mut input)?;
|
||||
let trimmed = input.trim();
|
||||
|
||||
if let Ok(num) = trimmed.parse::<usize>() {
|
||||
if num >= 1 && num <= disks.len() {
|
||||
config.target_disk = disks[num - 1].path.clone();
|
||||
break;
|
||||
}
|
||||
} else if trimmed.starts_with("/dev/") {
|
||||
config.target_disk = PathBuf::from(trimmed);
|
||||
break;
|
||||
}
|
||||
|
||||
println!("Nieprawidłowy wybór. Wprowadź poprawny numer dysku.");
|
||||
}
|
||||
}
|
||||
|
||||
println!();
|
||||
warn(&format!(
|
||||
"UWAGA: Wszystkie dane na dysku {}{}{} zostaną BEZPOWROTNIE USUNIĘTE!",
|
||||
C_BOLD,
|
||||
config.target_disk.display(),
|
||||
C_RESET
|
||||
));
|
||||
|
||||
print!("Czy na pewno chcesz kontynuować? Wpisz {}TAK{}: ", C_BOLD, C_RESET);
|
||||
let _ = io::stdout().flush();
|
||||
|
||||
let mut confirm = String::new();
|
||||
io::stdin().read_line(&mut confirm)?;
|
||||
if confirm.trim() != "TAK" {
|
||||
return Err(InstallError::Cancelled(
|
||||
"Instalacja została anulowana przez użytkownika.".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
// Nazwa hosta
|
||||
println!();
|
||||
print!("Podaj nazwę komputera (hostname) [domyślnie: khos]: ");
|
||||
let _ = io::stdout().flush();
|
||||
let mut hostname_in = String::new();
|
||||
io::stdin().read_line(&mut hostname_in)?;
|
||||
let h = hostname_in.trim();
|
||||
if !h.is_empty() {
|
||||
config.hostname = h.to_string();
|
||||
}
|
||||
|
||||
// Hasło roota
|
||||
print!("Ustaw hasło dla konta administratora root [domyślnie: khos]: ");
|
||||
let _ = io::stdout().flush();
|
||||
let mut pass_in = String::new();
|
||||
io::stdin().read_line(&mut pass_in)?;
|
||||
let p = pass_in.trim();
|
||||
if !p.is_empty() {
|
||||
config.root_password = p.to_string();
|
||||
}
|
||||
|
||||
// Wybór środowiska graficznego
|
||||
println!();
|
||||
println!("Dostępne środowiska graficzne pulpitu:");
|
||||
println!(" [1] XFCE 4 (Lekkie, tradycyjne, szybkie - domyślne)");
|
||||
println!(" [2] KDE Plasma (Nowoczesne, konfigurowalne)");
|
||||
println!(" [3] Hyprland (Nowoczesny tiling window manager Wayland)");
|
||||
println!(" [4] Openbox (Minimalistyczny pulpit X11)");
|
||||
print!("Wybór środowiska [1-4, domyślnie 1]: ");
|
||||
let _ = io::stdout().flush();
|
||||
|
||||
let mut desk_in = String::new();
|
||||
io::stdin().read_line(&mut desk_in)?;
|
||||
match desk_in.trim() {
|
||||
"2" => config.desktop = DesktopEnvironment::Plasma,
|
||||
"3" => config.desktop = DesktopEnvironment::Hyprland,
|
||||
"4" => config.desktop = DesktopEnvironment::Openbox,
|
||||
_ => config.desktop = DesktopEnvironment::Xfce,
|
||||
}
|
||||
|
||||
println!();
|
||||
ok(&format!(
|
||||
"Rozpoczynanie instalacji na {} (Pulpit: {})...",
|
||||
config.target_disk.display(),
|
||||
config.desktop
|
||||
));
|
||||
println!();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drukuje czytelne podsumowanie po udanej instalacji
|
||||
fn print_success_summary(config: &InstallConfig, root_part: &Path, elapsed_secs: u64) {
|
||||
println!(
|
||||
r#"{}{}
|
||||
╔══════════════════════════════════════════════════════════════╗
|
||||
║ ║
|
||||
║ SUKCES! System KhOS 1.1 został pomyślnie zainstalowany! ║
|
||||
║ ║
|
||||
║ Dysk docelowy: {:<37} ║
|
||||
║ Partycja systemowa: {:<37} ║
|
||||
║ Tryb rozruchu: {:<37} ║
|
||||
║ Pulpit domyślny: {:<37} ║
|
||||
║ Nazwa komputera: {:<37} ║
|
||||
║ Administrator: root (hasło: {}) ║
|
||||
║ Czas instalacji: {} sekund ║
|
||||
║ ║
|
||||
║ Pulpity graficzne zainstalowane w systemie: ║
|
||||
║ - XFCE 4: start-xfce ║
|
||||
║ - KDE Plasma: start-plasma ║
|
||||
║ - Hyprland: start-hyprland ║
|
||||
║ - Openbox: start-openbox ║
|
||||
║ ║
|
||||
║ Możesz teraz usunąć nośnik instalacyjny (pendrive/ISO) ║
|
||||
║ i ponownie uruchomić komputer wpisując: reboot ║
|
||||
╚══════════════════════════════════════════════════════════════╝
|
||||
{}"#,
|
||||
C_CYAN,
|
||||
"",
|
||||
config.target_disk.display(),
|
||||
root_part.display(),
|
||||
config.boot_mode,
|
||||
match config.desktop {
|
||||
DesktopEnvironment::Xfce => "XFCE 4",
|
||||
DesktopEnvironment::Plasma => "KDE Plasma",
|
||||
DesktopEnvironment::Hyprland => "Hyprland",
|
||||
DesktopEnvironment::Openbox => "Openbox",
|
||||
},
|
||||
config.hostname,
|
||||
config.root_password,
|
||||
elapsed_secs,
|
||||
C_RESET
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
use crate::error::InstallError;
|
||||
use crate::logger::{info, msg, ok, warn};
|
||||
use crate::types::TargetPartitions;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
/// Strażnik montowania RAII - automatycznie i bezpiecznie odmontowuje zasoby w razie błędu lub wyjścia
|
||||
pub struct MountGuard {
|
||||
mounts: Vec<PathBuf>,
|
||||
dry_run: bool,
|
||||
cleaned: bool,
|
||||
}
|
||||
|
||||
impl MountGuard {
|
||||
pub fn new(dry_run: bool) -> Self {
|
||||
Self {
|
||||
mounts: Vec::new(),
|
||||
dry_run,
|
||||
cleaned: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Bezpiecznie montuje partycję lub katalog docelowy
|
||||
pub fn mount(
|
||||
&mut self,
|
||||
source: &Path,
|
||||
target: &Path,
|
||||
fs_type: Option<&str>,
|
||||
options: Option<&str>,
|
||||
) -> Result<(), InstallError> {
|
||||
if self.dry_run {
|
||||
info(&format!(
|
||||
"[DRY-RUN] Montowanie {} w {}",
|
||||
source.display(),
|
||||
target.display()
|
||||
));
|
||||
self.mounts.push(target.to_path_buf());
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if !target.exists() {
|
||||
fs::create_dir_all(target)?;
|
||||
}
|
||||
|
||||
let mut cmd = Command::new("mount");
|
||||
if let Some(fstype) = fs_type {
|
||||
cmd.arg("-t").arg(fstype);
|
||||
}
|
||||
if let Some(opts) = options {
|
||||
cmd.arg("-o").arg(opts);
|
||||
}
|
||||
cmd.arg(source).arg(target);
|
||||
|
||||
let output = cmd.output()?;
|
||||
if !output.status.success() {
|
||||
return Err(InstallError::MountError(format!(
|
||||
"Nie udało się zamontować '{}' w '{}': {}",
|
||||
source.display(),
|
||||
target.display(),
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
)));
|
||||
}
|
||||
|
||||
self.mounts.push(target.to_path_buf());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Montuje w trybie bind (np. /proc, /sys, /dev)
|
||||
pub fn bind_mount(&mut self, source: &Path, target: &Path) -> Result<(), InstallError> {
|
||||
if !source.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if self.dry_run {
|
||||
info(&format!(
|
||||
"[DRY-RUN] Bind-mount {} do {}",
|
||||
source.display(),
|
||||
target.display()
|
||||
));
|
||||
self.mounts.push(target.to_path_buf());
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if !target.exists() {
|
||||
fs::create_dir_all(target)?;
|
||||
}
|
||||
|
||||
let output = Command::new("mount")
|
||||
.arg("--bind")
|
||||
.arg(source)
|
||||
.arg(target)
|
||||
.output()?;
|
||||
|
||||
if !output.status.success() {
|
||||
return Err(InstallError::MountError(format!(
|
||||
"Nie udało się wykonać bind-mount z '{}' do '{}': {}",
|
||||
source.display(),
|
||||
target.display(),
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
)));
|
||||
}
|
||||
|
||||
self.mounts.push(target.to_path_buf());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Bezpiecznie odmontowuje wszystkie zarejestrowane punkty montowania w odwrotnej kolejności
|
||||
pub fn unmount_all(&mut self) -> Result<(), InstallError> {
|
||||
if self.cleaned {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if self.dry_run {
|
||||
info("[DRY-RUN] Symulacja bezpiecznego odmontowania punktów montowania.");
|
||||
self.cleaned = true;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
info("Synchronizacja buforów dyskowych (sync)...");
|
||||
let _ = Command::new("sync").status();
|
||||
|
||||
// Odmontuj w porządku LIFO (od najgłębszych poddrzew)
|
||||
while let Some(mount_point) = self.mounts.pop() {
|
||||
if is_mountpoint(&mount_point) {
|
||||
info(&format!("Odmontowywanie punktu: {}", mount_point.display()));
|
||||
let status = Command::new("umount").arg(&mount_point).status();
|
||||
if let Ok(s) = status {
|
||||
if !s.success() {
|
||||
// Wymuś lub lazy umount w przypadku zajętości
|
||||
let _ = Command::new("umount").arg("-f").arg(&mount_point).status();
|
||||
let _ = Command::new("umount").arg("-l").arg(&mount_point).status();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.cleaned = true;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for MountGuard {
|
||||
fn drop(&mut self) {
|
||||
if !self.cleaned {
|
||||
let _ = self.unmount_all();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Sprawdza czy dany katalog jest aktywnym punktem montowania
|
||||
pub fn is_mountpoint(path: &Path) -> bool {
|
||||
if let Ok(mounts) = fs::read_to_string("/proc/mounts") {
|
||||
let path_str = path.to_string_lossy();
|
||||
for line in mounts.lines() {
|
||||
let parts: Vec<&str> = line.split_whitespace().collect();
|
||||
if parts.len() >= 2 && parts[1] == path_str {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: polecenie `mountpoint -q <path>`
|
||||
Command::new("mountpoint")
|
||||
.arg("-q")
|
||||
.arg(path)
|
||||
.status()
|
||||
.map(|s| s.success())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Przygotowuje pełną hierarchię montowań dla instalacji docelowej
|
||||
pub fn setup_target_mounts(
|
||||
partitions: &TargetPartitions,
|
||||
target_dir: &Path,
|
||||
dry_run: bool,
|
||||
) -> Result<MountGuard, InstallError> {
|
||||
msg(&format!(
|
||||
"Montowanie partycji docelowych w {}...",
|
||||
target_dir.display()
|
||||
));
|
||||
|
||||
let mut guard = MountGuard::new(dry_run);
|
||||
|
||||
// 1. Montowanie partycji głównej (root)
|
||||
guard.mount(&partitions.root_part, target_dir, Some("ext4"), Some("rw,noatime"))?;
|
||||
|
||||
// 2. Montowanie partycji EFI (jeśli występuje)
|
||||
if let Some(ref efi_part) = partitions.efi_part {
|
||||
let efi_dir = target_dir.join("boot/efi");
|
||||
guard.mount(efi_part, &efi_dir, Some("vfat"), Some("rw,defaults"))?;
|
||||
}
|
||||
|
||||
// 3. Tworzenie standardowych katalogów systemowych
|
||||
let sys_dirs = [
|
||||
"proc", "sys", "dev", "dev/pts", "dev/shm", "run", "tmp", "mnt", "mnt/cdrom", "boot",
|
||||
];
|
||||
for dir in &sys_dirs {
|
||||
let full_path = target_dir.join(dir);
|
||||
if !full_path.exists() {
|
||||
fs::create_dir_all(&full_path)?;
|
||||
}
|
||||
}
|
||||
|
||||
// Uprawnienia dla /tmp: 1777 (rwxrwxrwt z sticky bit)
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tmp_path = target_dir.join("tmp");
|
||||
if let Ok(mut perms) = fs::metadata(&tmp_path).map(|m| m.permissions()) {
|
||||
perms.set_mode(0o1777);
|
||||
let _ = fs::set_permissions(&tmp_path, perms);
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Bind-mount wirtualnych systemów plików do chroot
|
||||
guard.bind_mount(Path::new("/proc"), &target_dir.join("proc"))?;
|
||||
guard.bind_mount(Path::new("/sys"), &target_dir.join("sys"))?;
|
||||
guard.bind_mount(Path::new("/dev"), &target_dir.join("dev"))?;
|
||||
guard.bind_mount(Path::new("/run"), &target_dir.join("run"))?;
|
||||
|
||||
// Opcjonalny efivars w UEFI
|
||||
let efivars = Path::new("/sys/firmware/efi/efivars");
|
||||
if efivars.exists() {
|
||||
let target_efivars = target_dir.join("sys/firmware/efi/efivars");
|
||||
let _ = guard.bind_mount(efivars, &target_efivars);
|
||||
}
|
||||
|
||||
ok("Partycje i wirtualne systemy plików zostały pomyślnie zamontowane.");
|
||||
Ok(guard)
|
||||
}
|
||||
@@ -0,0 +1,484 @@
|
||||
use crate::disk::get_partition_uuid;
|
||||
use crate::error::InstallError;
|
||||
use crate::logger::{info, msg, ok, warn};
|
||||
use crate::types::{BootMode, InstallConfig, TargetPartitions};
|
||||
use std::fs::{self, OpenOptions};
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
/// Przygotowuje dysk, tworzy partycje i formatuje systemy plików
|
||||
pub fn prepare_disk(config: &InstallConfig) -> Result<TargetPartitions, InstallError> {
|
||||
let disk_path = &config.target_disk;
|
||||
|
||||
if config.dry_run {
|
||||
msg(&format!(
|
||||
"[DRY-RUN] Symulacja przygotowania dysku: {}",
|
||||
disk_path.display()
|
||||
));
|
||||
let (root_part, efi_part) = resolve_partition_names(disk_path, config.boot_mode);
|
||||
return Ok(TargetPartitions {
|
||||
disk_path: disk_path.clone(),
|
||||
root_part,
|
||||
efi_part,
|
||||
swap_part: None,
|
||||
root_uuid: Some("00000000-0000-0000-0000-000000000001".to_string()),
|
||||
efi_uuid: Some("0000-0001".to_string()),
|
||||
});
|
||||
}
|
||||
|
||||
msg(&format!(
|
||||
"Przygotowanie dysku {} do instalacji...",
|
||||
disk_path.display()
|
||||
));
|
||||
|
||||
// 1. Bezpieczne odmontowanie wszelkich zamontowanych partycji tego dysku
|
||||
unmount_existing_partitions(disk_path)?;
|
||||
|
||||
// 2. Wyczyszczenie sygnatur i nagłówków GPT/MBR
|
||||
wipe_disk_signatures(disk_path)?;
|
||||
|
||||
// 3. Tworzenie nowej tablicy partycji
|
||||
let (root_part, efi_part) = create_partition_table(config)?;
|
||||
|
||||
// 4. Odświeżenie tablicy partycji w jądrze Linux
|
||||
reread_partition_table(disk_path, &root_part)?;
|
||||
|
||||
// 5. Formatowanie partycji
|
||||
format_partitions(&root_part, efi_part.as_deref())?;
|
||||
|
||||
// 6. Pobranie unikalnych identyfikatorów UUID
|
||||
let root_uuid = get_partition_uuid(&root_part);
|
||||
let efi_uuid = efi_part.as_ref().and_then(|p| get_partition_uuid(p));
|
||||
|
||||
if let Some(ref uuid) = root_uuid {
|
||||
info(&format!("Identyfikator UUID partycji głównej: {}", uuid));
|
||||
}
|
||||
if let Some(ref uuid) = efi_uuid {
|
||||
info(&format!("Identyfikator UUID partycji EFI: {}", uuid));
|
||||
}
|
||||
|
||||
ok("Dysk został podzielony na partycje i sformatowany pomyślnie.");
|
||||
|
||||
Ok(TargetPartitions {
|
||||
disk_path: disk_path.clone(),
|
||||
root_part,
|
||||
efi_part,
|
||||
swap_part: None,
|
||||
root_uuid,
|
||||
efi_uuid,
|
||||
})
|
||||
}
|
||||
|
||||
/// Określa ścieżki partycji w oparciu o nazwę dysku i tryb bootowania
|
||||
fn resolve_partition_names(
|
||||
disk_path: &Path,
|
||||
boot_mode: BootMode,
|
||||
) -> (PathBuf, Option<PathBuf>) {
|
||||
let disk_str = disk_path.to_string_lossy();
|
||||
let is_p_format = disk_str.contains("nvme")
|
||||
|| disk_str.contains("mmcblk")
|
||||
|| disk_str.contains("loop");
|
||||
|
||||
if boot_mode == BootMode::Uefi {
|
||||
if is_p_format {
|
||||
(
|
||||
PathBuf::from(format!("{}p2", disk_str)),
|
||||
Some(PathBuf::from(format!("{}p1", disk_str))),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
PathBuf::from(format!("{}2", disk_str)),
|
||||
Some(PathBuf::from(format!("{}1", disk_str))),
|
||||
)
|
||||
}
|
||||
} else if is_p_format {
|
||||
(PathBuf::from(format!("{}p1", disk_str)), None)
|
||||
} else {
|
||||
(PathBuf::from(format!("{}1", disk_str)), None)
|
||||
}
|
||||
}
|
||||
|
||||
/// Odmontowuje wszystkie partycje danego dysku
|
||||
fn unmount_existing_partitions(disk_path: &Path) -> Result<(), InstallError> {
|
||||
let disk_name = disk_path
|
||||
.file_name()
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
|
||||
if let Ok(mounts) = fs::read_to_string("/proc/mounts") {
|
||||
for line in mounts.lines() {
|
||||
let parts: Vec<&str> = line.split_whitespace().collect();
|
||||
if parts.len() >= 2 {
|
||||
let dev = parts[0];
|
||||
let mount_point = parts[1];
|
||||
if dev.starts_with(&format!("/dev/{}", disk_name)) {
|
||||
info(&format!(
|
||||
"Odmontowywanie aktywnego punktu {} ({})",
|
||||
mount_point, dev
|
||||
));
|
||||
let _ = Command::new("umount").arg("-f").arg(mount_point).output();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Czyści nagłówki GPT i MBR na początku oraz końcu dysku
|
||||
fn wipe_disk_signatures(disk_path: &Path) -> Result<(), InstallError> {
|
||||
info("Czyszczenie istniejących struktur tablic partycji i sygnatur...");
|
||||
|
||||
// Spróbuj wipefs jeśli jest dostępne
|
||||
let _ = Command::new("wipefs")
|
||||
.arg("-a")
|
||||
.arg("-f")
|
||||
.arg(disk_path)
|
||||
.output();
|
||||
|
||||
// Nadpisz początkowe 10 MB zerami za pomocą `dd`
|
||||
let dd_head = Command::new("dd")
|
||||
.arg("if=/dev/zero")
|
||||
.arg(format!("of={}", disk_path.display()))
|
||||
.arg("bs=1M")
|
||||
.arg("count=10")
|
||||
.arg("conv=notrunc")
|
||||
.output();
|
||||
|
||||
if let Err(e) = dd_head {
|
||||
warn(&format!("Ostrzeżenie przy czyszczeniu nagłówka dd: {}", e));
|
||||
}
|
||||
|
||||
// Wyczyszczenie rezerwowego GPT na końcu dysku
|
||||
let size_bytes = get_disk_size_bytes(disk_path);
|
||||
if size_bytes > 20 * 1024 * 1024 {
|
||||
let total_sectors = size_bytes / 512;
|
||||
if total_sectors > 4096 {
|
||||
let seek_sector = total_sectors - 4096;
|
||||
let _ = Command::new("dd")
|
||||
.arg("if=/dev/zero")
|
||||
.arg(format!("of={}", disk_path.display()))
|
||||
.arg(format!("seek={}", seek_sector))
|
||||
.arg("count=4096")
|
||||
.arg("bs=512")
|
||||
.arg("conv=notrunc")
|
||||
.output();
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_disk_size_bytes(disk_path: &Path) -> u64 {
|
||||
// blockdev --getsize64 <disk>
|
||||
if let Ok(output) = Command::new("blockdev")
|
||||
.arg("--getsize64")
|
||||
.arg(disk_path)
|
||||
.output()
|
||||
{
|
||||
if output.status.success() {
|
||||
if let Ok(s) = String::from_utf8(output.stdout) {
|
||||
if let Ok(val) = s.trim().parse::<u64>() {
|
||||
return val;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// sysfs: /sys/class/block/<name>/size
|
||||
if let Some(bname) = disk_path.file_name() {
|
||||
let sys_path = PathBuf::from(format!("/sys/class/block/{}/size", bname.to_string_lossy()));
|
||||
if let Ok(content) = fs::read_to_string(sys_path) {
|
||||
if let Ok(sectors) = content.trim().parse::<u64>() {
|
||||
return sectors * 512;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
0
|
||||
}
|
||||
|
||||
/// Tworzy tablicę partycji za pomocą parted, sfdisk lub fdisk
|
||||
fn create_partition_table(
|
||||
config: &InstallConfig,
|
||||
) -> Result<(PathBuf, Option<PathBuf>), InstallError> {
|
||||
let (root_part, efi_part) = resolve_partition_names(&config.target_disk, config.boot_mode);
|
||||
|
||||
match config.boot_mode {
|
||||
BootMode::Uefi => {
|
||||
info(&format!(
|
||||
"Tworzenie tablicy GPT (UEFI) na {} (EFI: 512 MB, ROOT: reszta)...",
|
||||
config.target_disk.display()
|
||||
));
|
||||
|
||||
// Metoda 1: parted (jeśli dostępny)
|
||||
let parted_success = Command::new("parted")
|
||||
.arg("-s")
|
||||
.arg(&config.target_disk)
|
||||
.arg("mklabel")
|
||||
.arg("gpt")
|
||||
.arg("mkpart")
|
||||
.arg("ESP")
|
||||
.arg("fat32")
|
||||
.arg("1MiB")
|
||||
.arg(format!("{}MiB", config.efi_size_mb + 1))
|
||||
.arg("set")
|
||||
.arg("1")
|
||||
.arg("esp")
|
||||
.arg("on")
|
||||
.arg("mkpart")
|
||||
.arg("KHOS")
|
||||
.arg("ext4")
|
||||
.arg(format!("{}MiB", config.efi_size_mb + 1))
|
||||
.arg("100%")
|
||||
.status()
|
||||
.map(|s| s.success())
|
||||
.unwrap_or(false);
|
||||
|
||||
if !parted_success {
|
||||
// Metoda 2: sfdisk (standard util-linux)
|
||||
let sfdisk_input = format!(
|
||||
"label: gpt\nsize={}M, type=U, bootable\ntype=L\n",
|
||||
config.efi_size_mb
|
||||
);
|
||||
let sfdisk_status = run_with_stdin("sfdisk", &[config.target_disk.to_str().unwrap()], &sfdisk_input);
|
||||
|
||||
if !sfdisk_status {
|
||||
// Metoda 3: fdisk (skrypt fdisk gpt)
|
||||
// g: gpt label, n, 1, default, +512M, t, 1 (EFI), n, 2, default, default, w
|
||||
let fdisk_script = format!(
|
||||
"g\nn\n1\n\n+{}M\nt\n1\nn\n2\n\n\nw\n",
|
||||
config.efi_size_mb
|
||||
);
|
||||
let _ = run_with_stdin(
|
||||
"fdisk",
|
||||
&[config.target_disk.to_str().unwrap()],
|
||||
&fdisk_script,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
BootMode::Bios => {
|
||||
info(&format!(
|
||||
"Tworzenie tablicy MBR/msdos (BIOS) na {} (jedna partycja rozruchowa)...",
|
||||
config.target_disk.display()
|
||||
));
|
||||
|
||||
let parted_success = Command::new("parted")
|
||||
.arg("-s")
|
||||
.arg(&config.target_disk)
|
||||
.arg("mklabel")
|
||||
.arg("msdos")
|
||||
.arg("mkpart")
|
||||
.arg("primary")
|
||||
.arg("ext4")
|
||||
.arg("1MiB")
|
||||
.arg("100%")
|
||||
.arg("set")
|
||||
.arg("1")
|
||||
.arg("boot")
|
||||
.arg("on")
|
||||
.status()
|
||||
.map(|s| s.success())
|
||||
.unwrap_or(false);
|
||||
|
||||
if !parted_success {
|
||||
// sfdisk: jedna partycja bootable
|
||||
let sfdisk_input = ",,L,*\n";
|
||||
let sfdisk_status = run_with_stdin("sfdisk", &[config.target_disk.to_str().unwrap()], sfdisk_input);
|
||||
|
||||
if !sfdisk_status {
|
||||
// fdisk: o, n, p, 1, default, default, a, 1, w
|
||||
let fdisk_script = "o\nn\np\n1\n\n\na\n1\nw\n";
|
||||
let _ = run_with_stdin(
|
||||
"fdisk",
|
||||
&[config.target_disk.to_str().unwrap()],
|
||||
fdisk_script,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok((root_part, efi_part))
|
||||
}
|
||||
|
||||
fn run_with_stdin(cmd: &str, args: &[&str], input: &str) -> bool {
|
||||
if let Ok(mut child) = Command::new(cmd)
|
||||
.args(args)
|
||||
.stdin(std::process::Stdio::piped())
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.spawn()
|
||||
{
|
||||
if let Some(mut stdin) = child.stdin.take() {
|
||||
let _ = stdin.write_all(input.as_bytes());
|
||||
}
|
||||
child.wait().map(|s| s.success()).unwrap_or(false)
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Wymusza ponowne odczytanie tablicy partycji przez jądro i oczekuje na węzeł urządzenia
|
||||
fn reread_partition_table(disk_path: &Path, expected_part: &Path) -> Result<(), InstallError> {
|
||||
info("Odświeżanie tablicy partycji w jądrze...");
|
||||
|
||||
let _ = Command::new("sync").status();
|
||||
let _ = Command::new("blockdev").arg("--rereadpt").arg(disk_path).status();
|
||||
let _ = Command::new("partprobe").arg(disk_path).status();
|
||||
let _ = Command::new("mdev").arg("-s").status();
|
||||
let _ = Command::new("udevadm").arg("settle").status();
|
||||
|
||||
// Czekaj na pojawienie się węzła partycji do 5 sekund
|
||||
for _ in 0..10 {
|
||||
if expected_part.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
thread::sleep(Duration::from_millis(500));
|
||||
}
|
||||
|
||||
// Sprawdź czy partycja istnieje w /proc/partitions i stwórz węzeł mknod w razie potrzeby
|
||||
if let Some(part_filename) = expected_part.file_name() {
|
||||
let part_name = part_filename.to_string_lossy();
|
||||
if let Ok(partitions) = fs::read_to_string("/proc/partitions") {
|
||||
for line in partitions.lines() {
|
||||
let parts: Vec<&str> = line.split_whitespace().collect();
|
||||
if parts.len() >= 4 && parts[3] == part_name {
|
||||
if let (Ok(major), Ok(minor)) = (parts[0].parse::<u32>(), parts[1].parse::<u32>()) {
|
||||
info(&format!(
|
||||
"Tworzenie węzła urządzenia {} (major: {}, minor: {})...",
|
||||
expected_part.display(), major, minor
|
||||
));
|
||||
let _ = Command::new("mknod")
|
||||
.arg(expected_part)
|
||||
.arg("b")
|
||||
.arg(major.to_string())
|
||||
.arg(minor.to_string())
|
||||
.status();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !expected_part.exists() {
|
||||
return Err(InstallError::PartitionError(format!(
|
||||
"Węzeł partycji docelowej '{}' nie został odnaleziony w /dev po partycjonowaniu.",
|
||||
expected_part.display()
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Formatuje partycję EFI i partycję główną
|
||||
fn format_partitions(root_part: &Path, efi_part: Option<&Path>) -> Result<(), InstallError> {
|
||||
if let Some(efi) = efi_part {
|
||||
info(&format!(
|
||||
"Formatowanie partycji EFI ({}) jako FAT32 (ESP)...",
|
||||
efi.display()
|
||||
));
|
||||
|
||||
let vfat_status = Command::new("mkfs.vfat")
|
||||
.arg("-F32")
|
||||
.arg("-n")
|
||||
.arg("EFI")
|
||||
.arg(efi)
|
||||
.status()
|
||||
.or_else(|_| Command::new("mkfs.fat").arg("-F32").arg(efi).status())
|
||||
.map(|s| s.success())
|
||||
.unwrap_or(false);
|
||||
|
||||
if !vfat_status {
|
||||
warn("mkfs.vfat zgłosiło ostrzeżenie lub błąd formatowania partycji EFI.");
|
||||
}
|
||||
}
|
||||
|
||||
info(&format!(
|
||||
"Formatowanie partycji głównej ({}) jako EXT4 (etykieta: KHOS)...",
|
||||
root_part.display()
|
||||
));
|
||||
|
||||
// mkfs.ext4 z optymalnymi opcjami dla nowoczesnych SSD/NVMe
|
||||
let ext4_status = Command::new("mkfs.ext4")
|
||||
.arg("-F")
|
||||
.arg("-L")
|
||||
.arg("KHOS")
|
||||
.arg("-O")
|
||||
.arg("64bit,has_journal,extents,huge_file,flex_bg,metadata_csum")
|
||||
.arg(root_part)
|
||||
.status();
|
||||
|
||||
let success = match ext4_status {
|
||||
Ok(s) if s.success() => true,
|
||||
_ => {
|
||||
// Fallback: standardowy mke2fs lub mkfs.ext4 bez zaawansowanych flag -O
|
||||
Command::new("mkfs.ext4")
|
||||
.arg("-F")
|
||||
.arg("-L")
|
||||
.arg("KHOS")
|
||||
.arg(root_part)
|
||||
.status()
|
||||
.or_else(|_| {
|
||||
Command::new("mke2fs")
|
||||
.arg("-t")
|
||||
.arg("ext4")
|
||||
.arg("-F")
|
||||
.arg("-L")
|
||||
.arg("KHOS")
|
||||
.arg(root_part)
|
||||
.status()
|
||||
})
|
||||
.or_else(|_| {
|
||||
Command::new("mkfs.ext2")
|
||||
.arg("-F")
|
||||
.arg("-L")
|
||||
.arg("KHOS")
|
||||
.arg(root_part)
|
||||
.status()
|
||||
})
|
||||
.map(|s| s.success())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
};
|
||||
|
||||
if !success {
|
||||
return Err(InstallError::PartitionError(format!(
|
||||
"Nie udało się sformatować partycji głównej '{}' jako ext4.",
|
||||
root_part.display()
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_resolve_partition_names_sda() {
|
||||
let (root, efi) = resolve_partition_names(Path::new("/dev/sda"), BootMode::Uefi);
|
||||
assert_eq!(root, PathBuf::from("/dev/sda2"));
|
||||
assert_eq!(efi, Some(PathBuf::from("/dev/sda1")));
|
||||
|
||||
let (root_bios, efi_bios) = resolve_partition_names(Path::new("/dev/sda"), BootMode::Bios);
|
||||
assert_eq!(root_bios, PathBuf::from("/dev/sda1"));
|
||||
assert_eq!(efi_bios, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_partition_names_nvme() {
|
||||
let (root, efi) = resolve_partition_names(Path::new("/dev/nvme0n1"), BootMode::Uefi);
|
||||
assert_eq!(root, PathBuf::from("/dev/nvme0n1p2"));
|
||||
assert_eq!(efi, Some(PathBuf::from("/dev/nvme0n1p1")));
|
||||
|
||||
let (root_bios, efi_bios) = resolve_partition_names(Path::new("/dev/nvme0n1"), BootMode::Bios);
|
||||
assert_eq!(root_bios, PathBuf::from("/dev/nvme0n1p1"));
|
||||
assert_eq!(efi_bios, None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Tryb rozruchu komputera
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum BootMode {
|
||||
Uefi,
|
||||
Bios,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for BootMode {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
BootMode::Uefi => write!(f, "UEFI"),
|
||||
BootMode::Bios => write!(f, "BIOS (MBR / Legacy)"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Domyślne środowisko graficzne
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum DesktopEnvironment {
|
||||
Xfce,
|
||||
Plasma,
|
||||
Hyprland,
|
||||
Openbox,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for DesktopEnvironment {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
DesktopEnvironment::Xfce => write!(f, "XFCE 4 (Lekkie, stabilne - domyślne)"),
|
||||
DesktopEnvironment::Plasma => write!(f, "KDE Plasma (Nowoczesne, zaawansowane)"),
|
||||
DesktopEnvironment::Hyprland => write!(f, "Hyprland (Wayland tiling window manager)"),
|
||||
DesktopEnvironment::Openbox => write!(f, "Openbox (Minimalistyczne X11)"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for DesktopEnvironment {
|
||||
fn default() -> Self {
|
||||
DesktopEnvironment::Xfce
|
||||
}
|
||||
}
|
||||
|
||||
/// Informacje o partycji
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PartitionInfo {
|
||||
pub name: String,
|
||||
pub path: PathBuf,
|
||||
pub size_bytes: u64,
|
||||
pub fs_type: Option<String>,
|
||||
pub uuid: Option<String>,
|
||||
pub mount_point: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// Informacje o dysku fizycznym lub wirtualnym
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct DiskInfo {
|
||||
pub name: String,
|
||||
pub path: PathBuf,
|
||||
pub size_bytes: u64,
|
||||
pub size_gb: f64,
|
||||
pub model: String,
|
||||
pub is_removable: bool,
|
||||
pub partitions: Vec<PartitionInfo>,
|
||||
}
|
||||
|
||||
/// Przygotowane ścieżki partycji docelowych na dysku
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct TargetPartitions {
|
||||
pub disk_path: PathBuf,
|
||||
pub root_part: PathBuf,
|
||||
pub efi_part: Option<PathBuf>,
|
||||
pub swap_part: Option<PathBuf>,
|
||||
pub root_uuid: Option<String>,
|
||||
pub efi_uuid: Option<String>,
|
||||
}
|
||||
|
||||
/// Parametry instalacji systemu
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct InstallConfig {
|
||||
pub target_disk: PathBuf,
|
||||
pub boot_mode: BootMode,
|
||||
pub hostname: String,
|
||||
pub root_password: String,
|
||||
pub username: Option<String>,
|
||||
pub user_password: Option<String>,
|
||||
pub desktop: DesktopEnvironment,
|
||||
pub efi_size_mb: u64,
|
||||
pub swap_size_mb: u64,
|
||||
pub source_path: Option<PathBuf>,
|
||||
pub dry_run: bool,
|
||||
pub json_output: bool,
|
||||
pub auto_mode: bool,
|
||||
}
|
||||
|
||||
impl Default for InstallConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
target_disk: PathBuf::new(),
|
||||
boot_mode: BootMode::Bios,
|
||||
hostname: "khos".to_string(),
|
||||
root_password: "khos".to_string(),
|
||||
username: None,
|
||||
user_password: None,
|
||||
desktop: DesktopEnvironment::Xfce,
|
||||
efi_size_mb: 512,
|
||||
swap_size_mb: 0,
|
||||
source_path: None,
|
||||
dry_run: false,
|
||||
json_output: false,
|
||||
auto_mode: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Zdarzenia raportowania postępu dla interfejsów GUI / CLI
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum ProgressEvent {
|
||||
Stage {
|
||||
step: String,
|
||||
percent: u8,
|
||||
description: String,
|
||||
},
|
||||
Log {
|
||||
level: String,
|
||||
message: String,
|
||||
},
|
||||
Status {
|
||||
percent: u8,
|
||||
message: String,
|
||||
},
|
||||
Completed {
|
||||
success: bool,
|
||||
target_disk: String,
|
||||
root_partition: String,
|
||||
boot_mode: String,
|
||||
elapsed_seconds: u64,
|
||||
},
|
||||
Error {
|
||||
message: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_types_serialization() {
|
||||
let event = ProgressEvent::Stage {
|
||||
step: "partition".to_string(),
|
||||
percent: 15,
|
||||
description: "Formatowanie...".to_string(),
|
||||
};
|
||||
let json = serde_json::to_string(&event).expect("Serialize event");
|
||||
assert!(json.contains("\"type\":\"stage\""));
|
||||
assert!(json.contains("\"percent\":15"));
|
||||
|
||||
let config = InstallConfig::default();
|
||||
assert_eq!(config.hostname, "khos");
|
||||
assert_eq!(config.desktop, DesktopEnvironment::Xfce);
|
||||
assert_eq!(config.efi_size_mb, 512);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
allowed_users=anybody
|
||||
needs_root_rights=yes
|
||||
+8
-8
@@ -1,9 +1,9 @@
|
||||
# KhOS - Tabela systemow plikow
|
||||
# <urzadzenie> <punkt montowania> <typ> <opcje> <dump> <pass>
|
||||
proc /proc proc defaults 0 0
|
||||
sysfs /sys sysfs defaults 0 0
|
||||
devtmpfs /dev devtmpfs defaults 0 0
|
||||
devpts /dev/pts devpts defaults 0 0
|
||||
tmpfs /dev/shm tmpfs defaults 0 0
|
||||
tmpfs /tmp tmpfs defaults,nosuid,nodev 0 0
|
||||
tmpfs /run tmpfs defaults 0 0
|
||||
# <urzadzenie> <punkt montowania> <typ> <opcje> <dump> <pass>
|
||||
proc /proc proc defaults 0 0
|
||||
sysfs /sys sysfs defaults 0 0
|
||||
devtmpfs /dev devtmpfs defaults 0 0
|
||||
devpts /dev/pts devpts defaults,gid=5,mode=620,nosuid,noexec 0 0
|
||||
tmpfs /dev/shm tmpfs defaults,nosuid,nodev,noexec 0 0
|
||||
tmpfs /tmp tmpfs defaults,nosuid,nodev 0 0
|
||||
tmpfs /run tmpfs defaults,nosuid,nodev,mode=0755 0 0
|
||||
|
||||
+10
-9
@@ -3,19 +3,20 @@ daemon:x:1:
|
||||
bin:x:2:
|
||||
sys:x:3:
|
||||
adm:x:4:
|
||||
tty:x:5:
|
||||
disk:x:6:
|
||||
tty:x:5:root,live
|
||||
disk:x:6:root
|
||||
lp:x:7:
|
||||
mail:x:8:
|
||||
kmem:x:9:
|
||||
wheel:x:10:root
|
||||
cdrom:x:11:
|
||||
wheel:x:10:root,live
|
||||
cdrom:x:11:root,live
|
||||
dialout:x:18:
|
||||
floppy:x:19:
|
||||
video:x:28:
|
||||
audio:x:29:
|
||||
video:x:28:root,live
|
||||
audio:x:29:root,live
|
||||
tape:x:32:
|
||||
input:x:97:
|
||||
seat:x:98:
|
||||
users:x:100:
|
||||
input:x:97:root,live
|
||||
seat:x:98:root,live
|
||||
users:x:100:live
|
||||
render:x:107:root,live
|
||||
nogroup:x:65534:
|
||||
|
||||
+104
-30
@@ -4,7 +4,7 @@
|
||||
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
|
||||
export PATH
|
||||
|
||||
echo "=== KhOS 1.0 - Inicjalizacja systemu ==="
|
||||
echo "=== KhOS 1.1 - Inicjalizacja systemu ==="
|
||||
|
||||
# Mount virtual filesystems (some may already be mounted by initramfs)
|
||||
mount -t proc proc /proc 2>/dev/null
|
||||
@@ -16,12 +16,22 @@ if ! mountpoint -q /dev; then
|
||||
mount -t devtmpfs devtmpfs /dev
|
||||
fi
|
||||
mkdir -p /dev/pts /dev/shm
|
||||
mount -t devpts devpts /dev/pts 2>/dev/null
|
||||
mount -t tmpfs tmpfs /dev/shm 2>/dev/null
|
||||
mount -t devpts -o gid=5,mode=620,nosuid,noexec devpts /dev/pts 2>/dev/null || mount -t devpts devpts /dev/pts 2>/dev/null
|
||||
mount -t tmpfs -o mode=1777,nosuid,nodev,noexec tmpfs /dev/shm 2>/dev/null
|
||||
|
||||
# Mount tmpfs
|
||||
mount -t tmpfs tmpfs /run 2>/dev/null
|
||||
mount -t tmpfs tmpfs /tmp 2>/dev/null
|
||||
mount -t tmpfs -o mode=0755,nosuid,nodev tmpfs /run 2>/dev/null
|
||||
mount -t tmpfs -o mode=1777,nosuid,nodev tmpfs /tmp 2>/dev/null
|
||||
chmod 1777 /tmp /dev/shm 2>/dev/null || true
|
||||
mkdir -p /tmp/.X11-unix /tmp/.ICE-unix
|
||||
chmod 1777 /tmp/.X11-unix /tmp/.ICE-unix 2>/dev/null || true
|
||||
|
||||
# Symlinki FHS i montowania (/etc/mtab -> /proc/mounts, /var/run -> /run)
|
||||
ln -sf /proc/mounts /etc/mtab 2>/dev/null || true
|
||||
rm -rf /var/run /var/lock 2>/dev/null || true
|
||||
mkdir -p /run/lock /run/dbus /run/user /var/log /var/tmp
|
||||
ln -sf /run /var/run 2>/dev/null || true
|
||||
ln -sf /run/lock /var/lock 2>/dev/null || true
|
||||
|
||||
# Set hostname
|
||||
if [ -f /etc/hostname ]; then
|
||||
@@ -29,14 +39,44 @@ if [ -f /etc/hostname ]; then
|
||||
fi
|
||||
echo " [OK] Nazwa hosta: $(hostname)"
|
||||
|
||||
# Load essential kernel modules (DRM/KMS for AMD Radeon, VirtualBox, QEMU and FUSE)
|
||||
modprobe -a loop squashfs overlay fuse 2>/dev/null || true
|
||||
for m in radeon amdgpu drm drm_kms_helper vmwgfx vboxvideo bochs virtio-gpu qxl simpledrm; do
|
||||
modprobe "$m" 2>/dev/null || true
|
||||
done
|
||||
# Load hardware drivers for HP ProBook (Ethernet, Wi-Fi, Audio, WMI)
|
||||
for m in r8169 ath9k brcmsmac rt2800pci hp-wmi snd-hda-intel snd-hda-codec-idt snd-hda-codec-realtek; do
|
||||
modprobe "$m" 2>/dev/null || true
|
||||
done
|
||||
[ -e /dev/fuse ] && chmod 666 /dev/fuse 2>/dev/null || true
|
||||
echo " [OK] Moduly jadra (DRM/KMS Radeon, siec, dzwiek, FUSE)"
|
||||
|
||||
# Start mdev (BusyBox device manager, alternative to udev)
|
||||
[ -e /proc/sys/kernel/hotplug ] && echo /sbin/mdev > /proc/sys/kernel/hotplug 2>/dev/null || true
|
||||
mdev -s
|
||||
echo " [OK] Menedzer urzadzen (mdev)"
|
||||
|
||||
# Load essential kernel modules
|
||||
modprobe -a loop squashfs overlay 2>/dev/null
|
||||
echo " [OK] Moduly jadra"
|
||||
# Ensure proper permissions on device nodes for graphics, input and audio
|
||||
mkdir -p /dev/dri /dev/input /dev/snd
|
||||
chmod 755 /dev/dri /dev/input /dev/snd 2>/dev/null || true
|
||||
chmod 666 /dev/dri/* 2>/dev/null || true
|
||||
chmod 660 /dev/input/* 2>/dev/null || true
|
||||
chmod 660 /dev/snd/* 2>/dev/null || true
|
||||
chown -R root:video /dev/dri 2>/dev/null || true
|
||||
chown -R root:input /dev/input 2>/dev/null || true
|
||||
chown -R root:audio /dev/snd 2>/dev/null || true
|
||||
chmod 666 /dev/null /dev/zero /dev/random /dev/urandom /dev/tty /dev/ptmx /dev/fuse /dev/kvm 2>/dev/null || true
|
||||
echo " [OK] Uprawnienia urzadzen (/dev/dri, /dev/input)"
|
||||
|
||||
# Set max backlight brightness for laptop displays (HP ProBook, AMD Radeon itp.)
|
||||
for bl in /sys/class/backlight/*; do
|
||||
if [ -d "$bl" ]; then
|
||||
max=$(cat "$bl/max_brightness" 2>/dev/null || echo 100)
|
||||
echo "$max" > "$bl/brightness" 2>/dev/null || true
|
||||
chmod 666 "$bl/brightness" 2>/dev/null || true
|
||||
fi
|
||||
done
|
||||
echo " [OK] Podswietlenie matrycy laptopa (backlight)"
|
||||
|
||||
# Set up loopback network interface
|
||||
ifconfig lo 127.0.0.1 netmask 255.0.0.0 up
|
||||
@@ -56,9 +96,9 @@ fi
|
||||
echo " [OK] Parametry jadra (sysctl)"
|
||||
|
||||
# Create required runtime directories
|
||||
mkdir -p /var/run /var/log /var/lock /var/tmp
|
||||
mkdir -p /var/run /var/log /var/lock /var/tmp /run/dbus /run/user /home/live
|
||||
|
||||
# Start system logge
|
||||
# Start system logger
|
||||
if command -v syslogd >/dev/null 2>&1; then
|
||||
syslogd -O /var/log/messages
|
||||
klogd
|
||||
@@ -76,30 +116,64 @@ if [ -x /etc/init.d/network ]; then
|
||||
/etc/init.d/network start
|
||||
fi
|
||||
|
||||
# Start SSH server (if dropbear is available)
|
||||
if [ -x /etc/init.d/dropbear ]; then
|
||||
# Start SSH server (if requested via kernel cmdline: ssh or manually)
|
||||
if grep -q '\bssh\b' /proc/cmdline 2>/dev/null && [ -x /etc/init.d/dropbear ]; then
|
||||
/etc/init.d/dropbear start
|
||||
fi
|
||||
|
||||
# Create live user for live session
|
||||
if ! grep -q 'live' /etc/passwd 2>/dev/null; then
|
||||
adduser -D -s /bin/sh -h /home/live -G users live 2>/dev/null
|
||||
echo 'live:live' | chpasswd 2>/dev/null
|
||||
# Add to important groups
|
||||
addgroup live wheel 2>/dev/null
|
||||
addgroup live audio 2>/dev/null
|
||||
addgroup live video 2>/dev/null
|
||||
addgroup live input 2>/dev/null
|
||||
addgroup live cdrom 2>/dev/null
|
||||
echo " [OK] Uzytkownik live (haslo: live)"
|
||||
# Setup machine-id and system D-Bus daemon
|
||||
mkdir -p /etc /var/lib/dbus /var/run/dbus /run/dbus
|
||||
if [ ! -s /etc/machine-id ] && [ ! -s /var/lib/dbus/machine-id ]; then
|
||||
if command -v dbus-uuidgen >/dev/null 2>&1; then
|
||||
dbus-uuidgen --ensure=/etc/machine-id 2>/dev/null || dbus-uuidgen > /etc/machine-id 2>/dev/null || true
|
||||
fi
|
||||
if [ ! -s /etc/machine-id ]; then
|
||||
cat /proc/sys/kernel/random/boot_id 2>/dev/null | tr -d '-' > /etc/machine-id 2>/dev/null || echo "0123456789abcdef0123456789abcdef" > /etc/machine-id
|
||||
fi
|
||||
ln -sf /etc/machine-id /var/lib/dbus/machine-id 2>/dev/null || true
|
||||
fi
|
||||
if command -v dbus-daemon >/dev/null 2>&1; then
|
||||
if [ ! -S /var/run/dbus/system_bus_socket ] && [ ! -S /run/dbus/system_bus_socket ]; then
|
||||
dbus-daemon --system --fork 2>/dev/null || true
|
||||
echo " [OK] Szyna systemowa (dbus-daemon)"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Set root password if not set
|
||||
if ! grep -q '\$' /etc/shadow 2>/dev/null; then
|
||||
echo 'root:khos' | chpasswd 2>/dev/null
|
||||
echo " [OK] Haslo root ustawione (domyslne: khos)"
|
||||
# Start seatd (Seat daemon for Wayland compositors: Hyprland, KDE KWin)
|
||||
if command -v seatd >/dev/null 2>&1; then
|
||||
rm -f /run/seatd.sock
|
||||
seatd -g video -u root >/var/log/seatd.log 2>&1 &
|
||||
sleep 0.2
|
||||
if [ -S /run/seatd.sock ]; then
|
||||
chmod 0770 /run/seatd.sock
|
||||
chown root:video /run/seatd.sock
|
||||
fi
|
||||
echo " [OK] Demon zarzadzania sesja graficzna (seatd)"
|
||||
fi
|
||||
|
||||
# Create and configure live user
|
||||
if ! grep -q '^live:' /etc/passwd 2>/dev/null; then
|
||||
adduser -D -s /bin/sh -h /home/live -G users -u 1000 live 2>/dev/null || true
|
||||
fi
|
||||
mkdir -p /home/live
|
||||
chown -R 1000:100 /home/live 2>/dev/null || true
|
||||
chmod 755 /home/live 2>/dev/null || true
|
||||
|
||||
# Add live user to all essential groups for desktop, audio, video and sudo (excluding raw disk group)
|
||||
for g in wheel audio video render input seat cdrom tty users; do
|
||||
addgroup live "$g" 2>/dev/null || true
|
||||
done
|
||||
echo 'live:live' | chpasswd 2>/dev/null || true
|
||||
echo " [OK] Uzytkownik live (haslo: live, grupy: wheel, video, render, input, seat...)"
|
||||
|
||||
# Set root password if not set
|
||||
echo 'root:khos' | chpasswd 2>/dev/null || true
|
||||
chmod 0600 /etc/shadow /etc/gshadow 2>/dev/null || true
|
||||
echo " [OK] Haslo root ustawione (domyslne: khos)"
|
||||
|
||||
# Ensure sudoers file permissions (0440)
|
||||
[ -f /etc/sudoers ] && chmod 0440 /etc/sudoers
|
||||
|
||||
# Run local startup scripts
|
||||
if [ -d /etc/init.d/local.d ]; then
|
||||
for script in /etc/init.d/local.d/*.sh; do
|
||||
@@ -108,7 +182,7 @@ if [ -d /etc/init.d/local.d ]; then
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "=== KhOS 1.0 gotowy! ==="
|
||||
echo "Uzytkownik: live / Haslo: live"
|
||||
echo "Root: root / Haslo: khos"
|
||||
echo "=== KhOS 1.1 gotowy! ==="
|
||||
echo "Uzytkownik: live / Haslo: live (pelne uprawnienia przez sudo)"
|
||||
echo "Root: root / Haslo: khos"
|
||||
echo ""
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
# /etc/mdev.conf - Konfiguracja menedzera urzadzen mdev dla KhOS
|
||||
# Format: <device regex> <uid>:<gid> <octal permissions> [=path] [@|$|*command]
|
||||
|
||||
# Direct Rendering Manager (DRM / KMS) i Framebuffer
|
||||
dri/.* root:video 666
|
||||
card[0-9]* root:video 666
|
||||
renderD[0-9]* root:render 666
|
||||
fb[0-9]* root:video 660
|
||||
|
||||
# Urzadzenia wejsciowe (klawiatury, myszy, touchpady, tablety)
|
||||
input/.* root:input 660
|
||||
event[0-9]* root:input 660
|
||||
mice root:input 660
|
||||
mouse[0-9]* root:input 660
|
||||
js[0-9]* root:input 660
|
||||
ts[0-9]* root:input 660
|
||||
|
||||
# Dzwieki (ALSA / OSS)
|
||||
snd/.* root:audio 660
|
||||
audio.* root:audio 660
|
||||
dsp.* root:audio 660
|
||||
mixer.* root:audio 660
|
||||
|
||||
# Terminale i konsole
|
||||
tty root:tty 666
|
||||
tty[0-9]* root:tty 660
|
||||
console root:tty 600
|
||||
ptmx root:tty 666
|
||||
pts/.* root:tty 660
|
||||
|
||||
# Dyski i nosniki pamieci
|
||||
sd[a-z].* root:disk 660
|
||||
hd[a-z].* root:disk 660
|
||||
vd[a-z].* root:disk 660
|
||||
nvme.* root:disk 660
|
||||
sr[0-9]* root:cdrom 660
|
||||
loop[0-9]* root:disk 660
|
||||
|
||||
# Urzadzenia systemowe
|
||||
null root:root 666
|
||||
zero root:root 666
|
||||
full root:root 666
|
||||
random root:root 666
|
||||
urandom root:root 666
|
||||
kmem root:kmem 640
|
||||
mem root:kmem 640
|
||||
port root:kmem 640
|
||||
rtc[0-9]* root:root 664
|
||||
fuse root:root 666
|
||||
kvm root:root 666
|
||||
tun root:root 666
|
||||
net/tun root:root 666
|
||||
|
||||
@@ -2,4 +2,5 @@ root:x:0:0:root:/root:/bin/sh
|
||||
daemon:x:1:1:daemon:/usr/sbin:/bin/false
|
||||
bin:x:2:2:bin:/bin:/bin/false
|
||||
sys:x:3:3:sys:/dev:/bin/false
|
||||
live:x:1000:100:Live User:/home/live:/bin/sh
|
||||
nobody:x:65534:65534:nobody:/nonexistent:/bin/false
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
root::0:0:99999:7:::
|
||||
root:*LK*:0:0:99999:7:::
|
||||
daemon:*:0:0:99999:7:::
|
||||
bin:*:0:0:99999:7:::
|
||||
sys:*:0:0:99999:7:::
|
||||
live:*LK*:0:0:99999:7:::
|
||||
nobody:*:0:0:99999:7:::
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
# /etc/sudoers - Konfiguracja uprawnien sudo dla KhOS
|
||||
#
|
||||
# Format: uzytkownik/grupa host=(uzytkownik_docelowy) [NOPASSWD:] polecenia
|
||||
|
||||
# Root ma pelne uprawnienia
|
||||
root ALL=(ALL:ALL) ALL
|
||||
|
||||
# Czlonkowie grupy wheel oraz uzytkownik live maja pelne prawa bez hasla
|
||||
%wheel ALL=(ALL:ALL) NOPASSWD: ALL
|
||||
live ALL=(ALL:ALL) NOPASSWD: ALL
|
||||
|
||||
# Bezpieczna domyslna sciezka PATH
|
||||
Defaults secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
# KhOS Package Repositories
|
||||
# Format: URL
|
||||
# Serwer glowny pakietow KhOS (Gitea / Forgejo)
|
||||
https://git.kpgpmc.org/KhOS/KhOS-packages/raw/branch/main
|
||||
|
||||
https://git.kpgpmc.org/KhOS/KhOS-packages/raw/branch/master
|
||||
https://git.kpgpmc.org/KhOS/KhOS-packages/raw/main
|
||||
https://git.kpgpmc.org/KhOS/KhOS-packages/-/raw/main
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
[KSplash]
|
||||
Engine=none
|
||||
Theme=None
|
||||
|
||||
[KDE]
|
||||
ShowDeleteCommand=true
|
||||
|
||||
[General]
|
||||
ColorScheme=BreezeDark
|
||||
TerminalApplication=konsole
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
[KSplash]
|
||||
Engine=none
|
||||
Theme=None
|
||||
|
||||
[KDE]
|
||||
ShowDeleteCommand=true
|
||||
|
||||
[General]
|
||||
ColorScheme=BreezeDark
|
||||
TerminalApplication=konsole
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
# KhOS - Profil uzytkownika live
|
||||
export PS1='\[\033[01;32m\]live@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
|
||||
|
||||
# Automatyczny start srodowiska graficznego na terminalu tty1 (jesli nie wybrano trybu tekstowego)
|
||||
if [ "$(tty 2>/dev/null)" = "/dev/tty1" ]; then
|
||||
if ! grep -q "textmode\|single" /proc/cmdline 2>/dev/null; then
|
||||
if [ -z "$WAYLAND_DISPLAY" ] && [ -z "$DISPLAY" ]; then
|
||||
if grep -q "desktop=plasma" /proc/cmdline 2>/dev/null && [ -x /usr/bin/start-plasma ]; then
|
||||
echo "=== Automatyczny start KDE Plasma na tty1 ==="
|
||||
exec /usr/bin/start-plasma
|
||||
elif grep -q "desktop=hyprland" /proc/cmdline 2>/dev/null && [ -x /usr/bin/start-hyprland ]; then
|
||||
echo "=== Automatyczny start Hyprland na tty1 ==="
|
||||
exec /usr/bin/start-hyprland
|
||||
elif [ -x /usr/bin/start-xfce ]; then
|
||||
echo "=== Automatyczny start XFCE 4 (domyslny) na tty1 ==="
|
||||
exec /usr/bin/start-xfce
|
||||
elif [ -x /usr/bin/start-plasma ]; then
|
||||
echo "=== Automatyczny start KDE Plasma na tty1 ==="
|
||||
exec /usr/bin/start-plasma
|
||||
elif [ -x /usr/bin/start-hyprland ]; then
|
||||
echo "=== Automatyczny start Hyprland na tty1 ==="
|
||||
exec /usr/bin/start-hyprland
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
@@ -0,0 +1,18 @@
|
||||
[Desktop Entry]
|
||||
Version=1.0
|
||||
Type=Application
|
||||
Name=Zainstaluj KhOS
|
||||
Name[pl]=Zainstaluj KhOS
|
||||
Name[en]=Install KhOS
|
||||
GenericName=Instalator systemu KhOS
|
||||
GenericName[pl]=Instalator systemu KhOS
|
||||
GenericName[en]=KhOS System Installer
|
||||
Comment=Zainstaluj system KhOS na dysku twardym lub SSD (UEFI/BIOS)
|
||||
Comment[pl]=Zainstaluj system KhOS na dysku twardym lub SSD (UEFI/BIOS)
|
||||
Comment[en]=Install KhOS to a hard drive or SSD (UEFI/BIOS)
|
||||
Exec=khos-installer-gui
|
||||
Icon=system-software-install
|
||||
Terminal=false
|
||||
Categories=System;Utility;Settings;
|
||||
StartupNotify=true
|
||||
Keywords=installer;install;khos;system;dysk;instalator;setup;
|
||||
@@ -1,34 +1,30 @@
|
||||
#!/bin/sh
|
||||
# KhOS - Automatyczne uruchamianie srodowiska KDE Plasma przy starcie systemu
|
||||
# KhOS - Automatyczne logowanie i start srodowiska przy starcie systemu
|
||||
|
||||
export USER=root
|
||||
export LOGNAME=root
|
||||
export HOME=/root
|
||||
export SHELL=/bin/sh
|
||||
export TERM=linux
|
||||
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
|
||||
|
||||
cd /root 2>/dev/null || cd /
|
||||
|
||||
# Jesli uzytkownik wybral tryb tekstowy (textmode w cmdline), uruchom zwykla powloke
|
||||
if grep -q "textmode" /proc/cmdline 2>/dev/null || grep -q "single" /proc/cmdline 2>/dev/null; then
|
||||
echo "Wykryto parametr textmode. Uruchamianie powloki tekstowej KhOS..."
|
||||
exec /bin/login -f root
|
||||
fi
|
||||
|
||||
# Zapewnij uprawnienia dla terminala tty1
|
||||
chown root:root /dev/tty1 2>/dev/null || true
|
||||
# Zapewnij uprawnienia dla terminala tty1 dla uzytkownika live
|
||||
chown live:tty /dev/tty1 2>/dev/null || true
|
||||
chmod 660 /dev/tty1 2>/dev/null || true
|
||||
|
||||
# Uruchomienie KDE Plasma
|
||||
if [ -x /usr/bin/start-plasma ]; then
|
||||
echo "=== Startowanie pulpitu KDE Plasma (KhOS) ==="
|
||||
/usr/bin/start-plasma "$@"
|
||||
ret=$?
|
||||
echo "[INFO] Sesja KDE Plasma zakonczona (kod: $ret)."
|
||||
fi
|
||||
# Zapewnij uprawnienia dla /dev/dri i /dev/input (katalogi 755, pliki wezlow 666/660)
|
||||
mkdir -p /dev/dri /dev/input
|
||||
chmod 755 /dev/dri /dev/input 2>/dev/null || true
|
||||
chmod 666 /dev/dri/* 2>/dev/null || true
|
||||
chmod 660 /dev/input/* 2>/dev/null || true
|
||||
|
||||
# Fallback: konsola tekstowa jesli Plasma nie jest dostepna lub uzytkownik zamknal sesje
|
||||
echo "Uruchamianie konsoli systemowej..."
|
||||
exec /bin/login -f root
|
||||
# Zapewnij katalogi tymczasowe dla Xwayland i ICE
|
||||
mkdir -p /tmp/.X11-unix /tmp/.ICE-unix
|
||||
chmod 1777 /tmp/.X11-unix /tmp/.ICE-unix 2>/dev/null || true
|
||||
|
||||
# Upewnij sie, ze podswietlenie ekranu laptopa jest wlaczone (maksymalna jasnosc)
|
||||
for bl in /sys/class/backlight/*; do
|
||||
if [ -d "$bl" ]; then
|
||||
max=$(cat "$bl/max_brightness" 2>/dev/null || echo 100)
|
||||
echo "$max" > "$bl/brightness" 2>/dev/null || true
|
||||
chmod 666 "$bl/brightness" 2>/dev/null || true
|
||||
fi
|
||||
done
|
||||
|
||||
# Logowanie jako uzytkownik 'live' (otwiera pelna sesje TTY z wlasciwym terminalem kontrolnym)
|
||||
exec /bin/login -f live
|
||||
|
||||
Binary file not shown.
+472
-131
@@ -5,7 +5,7 @@
|
||||
set -e
|
||||
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:$PATH"
|
||||
|
||||
# Kolory
|
||||
# Kolory terminala
|
||||
C_RESET='\033[0m'
|
||||
C_BOLD='\033[1m'
|
||||
C_RED='\033[1;31m'
|
||||
@@ -14,20 +14,171 @@ C_YELLOW='\033[1;33m'
|
||||
C_CYAN='\033[1;36m'
|
||||
C_BLUE='\033[1;34m'
|
||||
|
||||
msg() { printf "${C_BOLD}${C_BLUE}==>${C_RESET} ${C_BOLD}%s${C_RESET}\n" "$1"; }
|
||||
msg() { printf "${C_BOLD}${C_BLUE}==>${C_RESET} ${C_BOLD}%s${C_RESET}\n" "$1"; }
|
||||
info() { printf "${C_CYAN} ->${C_RESET} %s\n" "$1"; }
|
||||
ok() { printf "${C_GREEN} [OK]${C_RESET} %s\n" "$1"; }
|
||||
ok() { printf "${C_GREEN} [OK]${C_RESET} %s\n" "$1"; }
|
||||
warn() { printf "${C_YELLOW}[OSTRZEŻENIE]${C_RESET} %s\n" "$1"; }
|
||||
err() { printf "${C_RED}[BŁĄD]${C_RESET} %s\n" "$1" >&2; }
|
||||
die() { err "$1"; exit 1; }
|
||||
err() { printf "${C_RED}[BŁĄD]${C_RESET} %s\n" "$1" >&2; }
|
||||
|
||||
# Sprawdzenie uprawnień root
|
||||
# Domyślne parametry instalacji
|
||||
AUTO_MODE=0
|
||||
TARGET_DISK=""
|
||||
NEW_HOSTNAME="khos"
|
||||
NEW_PASSWORD="khos"
|
||||
DESKTOP_CHOICE="xfce"
|
||||
FORCE_BOOT_MODE=""
|
||||
STATUS_FILE="/tmp/khos-installer.status"
|
||||
OP_MODE="1"
|
||||
MOUNT_DIR="/mnt/install_target"
|
||||
|
||||
# Raportowanie postępu do pliku statusu i na konsolę
|
||||
report_progress() {
|
||||
_pct="$1"
|
||||
_pmsg="$2"
|
||||
if [ -n "$STATUS_FILE" ]; then
|
||||
mkdir -p "$(dirname "$STATUS_FILE")" 2>/dev/null || true
|
||||
echo "PROGRESS:${_pct}:${_pmsg}" > "$STATUS_FILE" 2>/dev/null || true
|
||||
fi
|
||||
info "[$_pct%] $_pmsg"
|
||||
}
|
||||
|
||||
report_error() {
|
||||
_emsg="$1"
|
||||
if [ -n "$STATUS_FILE" ]; then
|
||||
mkdir -p "$(dirname "$STATUS_FILE")" 2>/dev/null || true
|
||||
echo "ERROR:${_emsg}" > "$STATUS_FILE" 2>/dev/null || true
|
||||
fi
|
||||
err "$_emsg"
|
||||
}
|
||||
|
||||
die() {
|
||||
report_error "$1"
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Bezpieczne czyszczenie przy wyjściu lub przerwaniu
|
||||
cleanup() {
|
||||
trap - EXIT INT TERM
|
||||
if [ -n "$MOUNT_DIR" ] && [ -d "$MOUNT_DIR" ]; then
|
||||
if grep -qs "$MOUNT_DIR" /proc/mounts 2>/dev/null; then
|
||||
sync 2>/dev/null || true
|
||||
umount -R "$MOUNT_DIR" 2>/dev/null || umount -l "$MOUNT_DIR" 2>/dev/null || true
|
||||
fi
|
||||
rmdir "$MOUNT_DIR" 2>/dev/null || true
|
||||
fi
|
||||
if [ -d /mnt/squashfs_inst ]; then
|
||||
umount /mnt/squashfs_inst 2>/dev/null || true
|
||||
rmdir /mnt/squashfs_inst 2>/dev/null || true
|
||||
fi
|
||||
}
|
||||
trap cleanup EXIT INT TERM
|
||||
|
||||
# Parsowanie argumentów linii poleceń
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--auto)
|
||||
AUTO_MODE=1
|
||||
shift
|
||||
;;
|
||||
--disk)
|
||||
TARGET_DISK="$2"
|
||||
shift 2
|
||||
;;
|
||||
--disk=*)
|
||||
TARGET_DISK="${1#--disk=}"
|
||||
shift
|
||||
;;
|
||||
--hostname)
|
||||
NEW_HOSTNAME="$2"
|
||||
shift 2
|
||||
;;
|
||||
--hostname=*)
|
||||
NEW_HOSTNAME="${1#--hostname=}"
|
||||
shift
|
||||
;;
|
||||
--password)
|
||||
NEW_PASSWORD="$2"
|
||||
shift 2
|
||||
;;
|
||||
--password=*)
|
||||
NEW_PASSWORD="${1#--password=}"
|
||||
shift
|
||||
;;
|
||||
--desktop)
|
||||
DESKTOP_CHOICE="$2"
|
||||
shift 2
|
||||
;;
|
||||
--desktop=*)
|
||||
DESKTOP_CHOICE="${1#--desktop=}"
|
||||
shift
|
||||
;;
|
||||
--mode)
|
||||
FORCE_BOOT_MODE="$2"
|
||||
shift 2
|
||||
;;
|
||||
--mode=*)
|
||||
FORCE_BOOT_MODE="${1#--mode=}"
|
||||
shift
|
||||
;;
|
||||
--status-file)
|
||||
STATUS_FILE="$2"
|
||||
shift 2
|
||||
;;
|
||||
--status-file=*)
|
||||
STATUS_FILE="${1#--status-file=}"
|
||||
shift
|
||||
;;
|
||||
-h|--help)
|
||||
echo "Użycie: khos-installer [opcje]"
|
||||
echo ""
|
||||
echo "Opcje:"
|
||||
echo " --auto Tryb automatyczny (nieinteraktywny)"
|
||||
echo " --disk <dysk> Dysk docelowy (np. /dev/sda, /dev/nvme0n1)"
|
||||
echo " --hostname <nazwa> Nazwa hosta systemu (domyślnie: khos)"
|
||||
echo " --password <hasło> Hasło użytkownika root (domyślnie: khos)"
|
||||
echo " --mode <uefi|bios> Wymuszenie trybu rozruchu (UEFI lub BIOS)"
|
||||
echo " --status-file <ścieżka> Ścieżka do pliku raportowania statusu (domyślnie: /tmp/khos-installer.status)"
|
||||
echo " -h, --help Wyświetla tę pomoc"
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
warn "Nieznany parametr: $1"
|
||||
shift
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
# Sprawdzenie uprawnień roota
|
||||
if [ "$(id -u)" -ne 0 ]; then
|
||||
die "Ten program musi być uruchomiony z uprawnieniami roota (wpisz: su, a następnie hasło khos)."
|
||||
fi
|
||||
|
||||
clear 2>/dev/null || true
|
||||
cat << "EOF"
|
||||
# 1. Wykrywanie trybu rozruchu (BIOS vs UEFI)
|
||||
BOOT_MODE="BIOS"
|
||||
if [ -d /sys/firmware/efi ]; then
|
||||
BOOT_MODE="UEFI"
|
||||
fi
|
||||
|
||||
if [ -n "$FORCE_BOOT_MODE" ]; then
|
||||
case "$(echo "$FORCE_BOOT_MODE" | tr '[:lower:]' '[:upper:]')" in
|
||||
UEFI)
|
||||
BOOT_MODE="UEFI"
|
||||
;;
|
||||
BIOS|MBR|LEGACY)
|
||||
BOOT_MODE="BIOS"
|
||||
;;
|
||||
*)
|
||||
warn "Nieprawidłowa wartość --mode: $FORCE_BOOT_MODE. Pozostawiam tryb: $BOOT_MODE"
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
|
||||
report_progress 0 "Inicjalizacja instalatora KhOS"
|
||||
|
||||
# Tryb interaktywny vs automatyczny
|
||||
if [ "$AUTO_MODE" -eq 0 ]; then
|
||||
clear 2>/dev/null || true
|
||||
cat << "EOF"
|
||||
╔══════════════════════════════════════════════════════════════╗
|
||||
║ ║
|
||||
║ ╦ ╦╦ ╔═╗╔═╗╔╗╔╦ ╦╔═╗╔═╗ INSTALATOR SYSTEMU ║
|
||||
@@ -38,82 +189,126 @@ cat << "EOF"
|
||||
║ Ten program zainstaluje system na dysku Twojego komputera. ║
|
||||
╚══════════════════════════════════════════════════════════════╝
|
||||
EOF
|
||||
echo ""
|
||||
echo ""
|
||||
info "Wykryty tryb rozruchu komputera: ${C_BOLD}${BOOT_MODE}${C_RESET}"
|
||||
|
||||
# 1. Wykrywanie trybu rozruchu (BIOS vs UEFI)
|
||||
BOOT_MODE="BIOS"
|
||||
if [ -d /sys/firmware/efi ]; then
|
||||
BOOT_MODE="UEFI"
|
||||
fi
|
||||
info "Wykryty tryb rozruchu komputera: ${C_BOLD}${BOOT_MODE}${C_RESET}"
|
||||
echo ""
|
||||
msg "Wybierz operację:"
|
||||
echo " 1) Czysta instalacja (formatowanie wybranego dysku i instalacja od zera)"
|
||||
echo " 2) Aktualizacja istniejącego systemu KhOS z tego ISO (bez utraty danych w /home)"
|
||||
printf "${C_BOLD}Wybór [1]: ${C_RESET}"
|
||||
read -r OP_CHOICE
|
||||
OP_MODE="${OP_CHOICE:-1}"
|
||||
|
||||
# 2. Wykrywanie dostępnych dysków
|
||||
msg "Wyszukiwanie dysków twardych i SSD..."
|
||||
DISKS=""
|
||||
for d in /sys/block/sd* /sys/block/vd* /sys/block/nvme* /sys/block/hd*; do
|
||||
[ ! -e "$d" ] && continue
|
||||
bname=$(basename "$d")
|
||||
|
||||
case "$bname" in
|
||||
sr*|loop*|ram*|dm-*) continue ;;
|
||||
if [ "$OP_MODE" = "2" ]; then
|
||||
info "Uruchamianie asystenta aktualizacji systemu KhOS..."
|
||||
exec /usr/bin/khos-update
|
||||
fi
|
||||
|
||||
# Wykrywanie dostępnych dysków
|
||||
msg "Wyszukiwanie dysków twardych i SSD..."
|
||||
DISKS=""
|
||||
for d in /sys/block/sd* /sys/block/vd* /sys/block/nvme* /sys/block/hd*; do
|
||||
[ ! -e "$d" ] && continue
|
||||
bname=$(basename "$d")
|
||||
|
||||
case "$bname" in
|
||||
sr*|loop*|ram*|dm-*) continue ;;
|
||||
esac
|
||||
|
||||
devnode="/dev/$bname"
|
||||
[ ! -b "$devnode" ] && continue
|
||||
|
||||
size_sectors=$(cat "$d/size" 2>/dev/null || echo 0)
|
||||
size_gb=$(( size_sectors * 512 / 1024 / 1024 / 1024 ))
|
||||
model=$(cat "$d/device/model" 2>/dev/null | tr -s ' ' || echo "Dysk twardy / SSD")
|
||||
|
||||
echo " - ${C_BOLD}${devnode}${C_RESET} (${size_gb} GB) - $model"
|
||||
DISKS="$DISKS $devnode"
|
||||
done
|
||||
|
||||
if [ -z "$DISKS" ]; then
|
||||
die "Nie znaleziono żadnych dysków twardych w systemie!"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
if [ -z "$TARGET_DISK" ]; then
|
||||
printf "${C_BOLD}Wybierz dysk docelowy (np. /dev/sda): ${C_RESET}"
|
||||
read -r TARGET_DISK
|
||||
else
|
||||
info "Użycie wstępnie podanego dysku: ${C_BOLD}${TARGET_DISK}${C_RESET}"
|
||||
fi
|
||||
|
||||
if [ ! -b "$TARGET_DISK" ]; then
|
||||
die "Podane urządzenie '$TARGET_DISK' nie istnieje lub nie jest dyskiem blokowym."
|
||||
fi
|
||||
|
||||
echo ""
|
||||
warn "UWAGA: Wszystkie dane na dysku ${C_BOLD}${TARGET_DISK}${C_RESET} zostaną BEZPOWROTNIE USUNIĘTE!"
|
||||
printf "Czy na pewno chcesz kontynuować? Wpisz ${C_BOLD}TAK${C_RESET} (wielkimi literami): "
|
||||
read -r CONFIRM
|
||||
if [ "$CONFIRM" != "TAK" ]; then
|
||||
die "Instalacja została anulowana przez użytkownika."
|
||||
fi
|
||||
|
||||
echo ""
|
||||
printf "Podaj nazwę komputera (hostname) [domyślnie: %s]: " "$NEW_HOSTNAME"
|
||||
read -r USER_HOSTNAME
|
||||
NEW_HOSTNAME="${USER_HOSTNAME:-$NEW_HOSTNAME}"
|
||||
|
||||
printf "Ustaw nowe hasło dla konta root (wpisywane znaki ukryte) [domyślnie: zachowaj bieżące]: "
|
||||
read -s -r USER_PASSWORD
|
||||
echo ""
|
||||
NEW_PASSWORD="${USER_PASSWORD:-$NEW_PASSWORD}"
|
||||
|
||||
echo ""
|
||||
echo "Wybierz domyślne środowisko graficzne:"
|
||||
echo " 1) XFCE 4 (Lekkie, stabilne i szybkie - zalecane)"
|
||||
echo " 2) KDE Plasma (Nowoczesne, zaawansowane)"
|
||||
printf "Wybór [1]: "
|
||||
read -r USER_DESKTOP
|
||||
case "$USER_DESKTOP" in
|
||||
2|plasma|Plasma|KDE|kde)
|
||||
DESKTOP_CHOICE="plasma"
|
||||
;;
|
||||
*)
|
||||
DESKTOP_CHOICE="xfce"
|
||||
;;
|
||||
esac
|
||||
|
||||
devnode="/dev/$bname"
|
||||
[ ! -b "$devnode" ] && continue
|
||||
|
||||
size_sectors=$(cat "$d/size" 2>/dev/null || echo 0)
|
||||
size_gb=$(( size_sectors * 512 / 1024 / 1024 / 1024 ))
|
||||
model=$(cat "$d/device/model" 2>/dev/null | tr -s ' ' || echo "Dysk twardy / SSD")
|
||||
|
||||
echo " - ${C_BOLD}${devnode}${C_RESET} (${size_gb} GB) - $model"
|
||||
DISKS="$DISKS $devnode"
|
||||
done
|
||||
else
|
||||
# Tryb automatyczny (--auto)
|
||||
info "Uruchamianie w trybie automatycznym (--auto)..."
|
||||
info "Docelowy tryb rozruchu: ${C_BOLD}${BOOT_MODE}${C_RESET}"
|
||||
|
||||
if [ -z "$DISKS" ]; then
|
||||
die "Nie znaleziono żadnych dysków twardych w systemie!"
|
||||
if [ -z "$TARGET_DISK" ]; then
|
||||
die "W trybie automatycznym (--auto) wymagane jest wskazanie dysku za pomocą --disk <dysk>!"
|
||||
fi
|
||||
if [ ! -b "$TARGET_DISK" ]; then
|
||||
die "Podane urządzenie docelowe '$TARGET_DISK' nie istnieje lub nie jest dyskiem blokowym."
|
||||
fi
|
||||
fi
|
||||
|
||||
echo ""
|
||||
printf "${C_BOLD}Wybierz dysk docelowy (np. /dev/sda): ${C_RESET}"
|
||||
read -r TARGET_DISK
|
||||
report_progress 5 "Weryfikacja parametrów instalacji dla dysku ${TARGET_DISK}"
|
||||
|
||||
if [ ! -b "$TARGET_DISK" ]; then
|
||||
die "Podane urządzenie '$TARGET_DISK' nie istnieje lub nie jest dyskiem blokowym."
|
||||
fi
|
||||
|
||||
echo ""
|
||||
warn "UWAGA: Wszystkie dane na dysku ${C_BOLD}${TARGET_DISK}${C_RESET} zostaną BEZPOWROTNIE USUNIĘTE!"
|
||||
printf "Czy na pewno chcesz kontynuować? Wpisz ${C_BOLD}TAK${C_RESET} (wielkimi literami): "
|
||||
read -r CONFIRM
|
||||
if [ "$CONFIRM" != "TAK" ]; then
|
||||
die "Instalacja została anulowana przez użytkownika."
|
||||
fi
|
||||
|
||||
echo ""
|
||||
printf "Podaj nazwę komputera (hostname) [domyślnie: khos]: "
|
||||
read -r NEW_HOSTNAME
|
||||
NEW_HOSTNAME="${NEW_HOSTNAME:-khos}"
|
||||
|
||||
printf "Ustaw nowe hasło dla konta root [domyślnie: khos]: "
|
||||
read -r NEW_PASSWORD
|
||||
NEW_PASSWORD="${NEW_PASSWORD:-khos}"
|
||||
|
||||
msg "Przygotowanie dysku ${TARGET_DISK}..."
|
||||
# 2. Przygotowanie dysku i odmontowanie partycji
|
||||
report_progress 10 "Przygotowanie dysku ${TARGET_DISK} i odmontowanie partycji"
|
||||
for part in ${TARGET_DISK}* ${TARGET_DISK}p*; do
|
||||
[ -b "$part" ] && umount -f "$part" 2>/dev/null || true
|
||||
done
|
||||
|
||||
msg "Tworzenie tablicy partycji na ${TARGET_DISK} (tryb: ${BOOT_MODE})..."
|
||||
TARGET_PART_ROOT=""
|
||||
TARGET_PART_EFI=""
|
||||
|
||||
# Czyszczenie nagłówków MBR/GPT na początku i końcu dysku
|
||||
# 3. Czyszczenie nagłówków dysku MBR/GPT
|
||||
report_progress 15 "Czyszczenie nagłówków MBR/GPT na dysku ${TARGET_DISK}"
|
||||
dd if=/dev/zero of="${TARGET_DISK}" bs=1M count=10 conv=notrunc 2>/dev/null || true
|
||||
disk_size_bytes=$(blockdev --getsize64 "$TARGET_DISK" 2>/dev/null || cat "/sys/class/block/$(basename "$TARGET_DISK")/size" 2>/dev/null | awk '{print $1*512}')
|
||||
if [ -n "$disk_size_bytes" ] && [ "$disk_size_bytes" -gt 20971520 ]; then
|
||||
dd if=/dev/zero of="$TARGET_DISK" seek=$(( (disk_size_bytes / 512) - 4096 )) count=4096 bs=512 conv=notrunc 2>/dev/null || true
|
||||
fi
|
||||
|
||||
# 4. Tworzenie tablicy partycji
|
||||
report_progress 20 "Tworzenie tablicy partycji na ${TARGET_DISK} (tryb: ${BOOT_MODE})"
|
||||
TARGET_PART_ROOT=""
|
||||
TARGET_PART_EFI=""
|
||||
|
||||
if [ "$BOOT_MODE" = "UEFI" ]; then
|
||||
printf "o\nn\np\n1\n\n+512M\nt\nef\nn\np\n2\n\n\nw\n" | fdisk "${TARGET_DISK}" 2>/dev/null || true
|
||||
|
||||
@@ -147,17 +342,35 @@ partprobe "$TARGET_DISK" 2>/dev/null || true
|
||||
mdev -s 2>/dev/null || true
|
||||
sleep 2
|
||||
|
||||
# Fallback detekcji nazw partycji (np. sda1 vs sdap1 vs sda2)
|
||||
if [ ! -b "$TARGET_PART_ROOT" ]; then
|
||||
for cand in "${TARGET_DISK}1" "${TARGET_DISK}p1" "${TARGET_DISK}2" "${TARGET_DISK}p2"; do
|
||||
if [ -b "$cand" ]; then
|
||||
TARGET_PART_ROOT="$cand"
|
||||
break
|
||||
fi
|
||||
done
|
||||
report_progress 30 "Weryfikacja węzłów partycji docelowych"
|
||||
|
||||
for wait_i in 1 2 3 4 5; do
|
||||
mdev -s 2>/dev/null || true
|
||||
[ -b "$TARGET_PART_ROOT" ] && break
|
||||
sleep 1
|
||||
done
|
||||
|
||||
# Weryfikacja i fallback przypisania partycji
|
||||
if [ "$BOOT_MODE" = "UEFI" ]; then
|
||||
if [ ! -b "$TARGET_PART_ROOT" ]; then
|
||||
for cand in "${TARGET_DISK}p2" "${TARGET_DISK}2"; do
|
||||
[ -b "$cand" ] && { TARGET_PART_ROOT="$cand"; break; }
|
||||
done
|
||||
fi
|
||||
if [ ! -b "$TARGET_PART_EFI" ]; then
|
||||
for cand in "${TARGET_DISK}p1" "${TARGET_DISK}1"; do
|
||||
[ -b "$cand" ] && { TARGET_PART_EFI="$cand"; break; }
|
||||
done
|
||||
fi
|
||||
else
|
||||
if [ ! -b "$TARGET_PART_ROOT" ]; then
|
||||
for cand in "${TARGET_DISK}p1" "${TARGET_DISK}1"; do
|
||||
[ -b "$cand" ] && { TARGET_PART_ROOT="$cand"; break; }
|
||||
done
|
||||
fi
|
||||
fi
|
||||
|
||||
# Fallback mknod jesli wezel w /dev nie powstal automatycznie
|
||||
# Awaryjny mknod jeśli węzły urządzeń nie powstały samoczynnie
|
||||
if [ ! -b "$TARGET_PART_ROOT" ]; then
|
||||
part_name=$(basename "$TARGET_PART_ROOT")
|
||||
part_line=$(grep " ${part_name}\$" /proc/partitions 2>/dev/null || true)
|
||||
@@ -168,35 +381,55 @@ if [ ! -b "$TARGET_PART_ROOT" ]; then
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$BOOT_MODE" = "UEFI" ] && [ -n "$TARGET_PART_EFI" ] && [ ! -b "$TARGET_PART_EFI" ]; then
|
||||
part_name=$(basename "$TARGET_PART_EFI")
|
||||
part_line=$(grep " ${part_name}\$" /proc/partitions 2>/dev/null || true)
|
||||
if [ -n "$part_line" ]; then
|
||||
p_major=$(echo "$part_line" | awk '{print $1}')
|
||||
p_minor=$(echo "$part_line" | awk '{print $2}')
|
||||
mknod "$TARGET_PART_EFI" b "$p_major" "$p_minor" 2>/dev/null || true
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ ! -b "$TARGET_PART_ROOT" ]; then
|
||||
die "Partycja główna $TARGET_PART_ROOT nie została utworzona! Sprawdź czy dysk nie jest zablokowany."
|
||||
fi
|
||||
ok "Utworzono partycję systemową: $TARGET_PART_ROOT"
|
||||
if [ "$BOOT_MODE" = "UEFI" ] && [ -n "$TARGET_PART_EFI" ]; then
|
||||
ok "Utworzono partycję EFI: $TARGET_PART_EFI"
|
||||
fi
|
||||
|
||||
msg "Formatowanie partycji..."
|
||||
if [ -n "$TARGET_PART_EFI" ] && [ -b "$TARGET_PART_EFI" ]; then
|
||||
# 5. Formatowanie partycji
|
||||
report_progress 35 "Formatowanie partycji"
|
||||
if [ "$BOOT_MODE" = "UEFI" ] && [ -n "$TARGET_PART_EFI" ] && [ -b "$TARGET_PART_EFI" ]; then
|
||||
info "Formatowanie partycji EFI (${TARGET_PART_EFI}) jako FAT32..."
|
||||
mkfs.vfat -F32 "$TARGET_PART_EFI" 2>/dev/null || mkfs.fat -F32 "$TARGET_PART_EFI" 2>/dev/null || true
|
||||
mkfs.vfat -F32 "$TARGET_PART_EFI" 2>/dev/null || mkfs.fat -F32 "$TARGET_PART_EFI" 2>/dev/null || die "Formatowanie partycji EFI $TARGET_PART_EFI nie powiodło się!"
|
||||
fi
|
||||
|
||||
info "Formatowanie partycji głównej (${TARGET_PART_ROOT}) jako EXT4..."
|
||||
mkfs.ext4 -F -O fast_commit,sparse_super2 -m 1 -L "KHOS" "$TARGET_PART_ROOT" 2>/dev/null || \
|
||||
mkfs.ext4 -F -L "KHOS" "$TARGET_PART_ROOT" 2>/dev/null || \
|
||||
mke2fs -t ext4 -F -L "KHOS" "$TARGET_PART_ROOT" 2>/dev/null || \
|
||||
mkfs.ext2 -F "$TARGET_PART_ROOT" 2>/dev/null || \
|
||||
mkfs.ext2 -F -L "KHOS" "$TARGET_PART_ROOT" 2>/dev/null || \
|
||||
mke2fs -F "$TARGET_PART_ROOT" 2>/dev/null || die "Formatowanie partycji $TARGET_PART_ROOT nie powiodło się!"
|
||||
|
||||
sync
|
||||
mdev -s 2>/dev/null || true
|
||||
sleep 1
|
||||
ok "Partycja sformatowana pomyślnie."
|
||||
|
||||
MOUNT_DIR="/mnt/install_target"
|
||||
# 6. Montowanie nowego systemu plików
|
||||
report_progress 45 "Montowanie nowego systemu plików"
|
||||
mkdir -p "$MOUNT_DIR"
|
||||
mount "$TARGET_PART_ROOT" "$MOUNT_DIR" || mount -t ext4 "$TARGET_PART_ROOT" "$MOUNT_DIR" || die "Nie udało się zamontować partycji $TARGET_PART_ROOT!"
|
||||
|
||||
if [ -n "$TARGET_PART_EFI" ] && [ -b "$TARGET_PART_EFI" ]; then
|
||||
if [ "$BOOT_MODE" = "UEFI" ] && [ -n "$TARGET_PART_EFI" ] && [ -b "$TARGET_PART_EFI" ]; then
|
||||
mkdir -p "$MOUNT_DIR/boot/efi"
|
||||
mount "$TARGET_PART_EFI" "$MOUNT_DIR/boot/efi" 2>/dev/null || true
|
||||
mount "$TARGET_PART_EFI" "$MOUNT_DIR/boot/efi" 2>/dev/null || die "Nie udało się zamontować partycji EFI $TARGET_PART_EFI na $MOUNT_DIR/boot/efi!"
|
||||
fi
|
||||
|
||||
msg "Kopiowanie plików systemu KhOS na dysk..."
|
||||
# 7. Kopiowanie plików systemu
|
||||
report_progress 55 "Kopiowanie plików systemu operacyjnego KhOS na dysk"
|
||||
SOURCE_DIR=""
|
||||
if [ -d /mnt/squashfs ] && [ -f /mnt/squashfs/bin/busybox ]; then
|
||||
SOURCE_DIR="/mnt/squashfs"
|
||||
@@ -222,10 +455,11 @@ fi
|
||||
mkdir -p "$MOUNT_DIR/proc" "$MOUNT_DIR/sys" "$MOUNT_DIR/dev" "$MOUNT_DIR/tmp" "$MOUNT_DIR/run" "$MOUNT_DIR/mnt" "$MOUNT_DIR/mnt/cdrom"
|
||||
chmod 1777 "$MOUNT_DIR/tmp"
|
||||
|
||||
# 8. Kopiowanie jądra i initramfs
|
||||
report_progress 75 "Kopiowanie jądra Linuksa i obrazu rozruchowego initramfs"
|
||||
mkdir -p "$MOUNT_DIR/boot"
|
||||
# Zapewnij dostęp do nośnika instalacyjnego
|
||||
if [ ! -f /mnt/cdrom/boot/vmlinuz ] && [ ! -f /boot/vmlinuz ]; then
|
||||
for cddev in /dev/sr* /dev/loop* /dev/cdrom $(blkid -o device 2>/dev/null); do
|
||||
for cddev in /dev/sr* /dev/loop* /dev/cdrom /dev/sd* /dev/nvme* /dev/mmcblk*; do
|
||||
mkdir -p /mnt/cdrom 2>/dev/null || true
|
||||
mount -o ro "$cddev" /mnt/cdrom 2>/dev/null || continue
|
||||
[ -f /mnt/cdrom/boot/vmlinuz ] && break
|
||||
@@ -244,26 +478,59 @@ elif [ -f /boot/initramfs.img ]; then
|
||||
cp -f /boot/initramfs.img "$MOUNT_DIR/boot/initramfs.img"
|
||||
fi
|
||||
|
||||
ok "Pliki systemu oraz jądro skopiowane."
|
||||
if [ ! -f "$MOUNT_DIR/boot/vmlinuz" ] || [ ! -f "$MOUNT_DIR/boot/initramfs.img" ]; then
|
||||
die "Brak plików jądra (/boot/vmlinuz) lub initramfs (/boot/initramfs.img) na nośniku źródłowym!"
|
||||
fi
|
||||
ok "Pliki jądra i initramfs skopiowane pomyślnie."
|
||||
|
||||
# 9. Generowanie konfiguracji systemowych
|
||||
report_progress 80 "Generowanie konfiguracji systemowych (/etc/fstab, sieć, konta)"
|
||||
sync
|
||||
mdev -s 2>/dev/null || true
|
||||
|
||||
msg "Generowanie konfiguracji systemowych..."
|
||||
ROOT_UUID=$(blkid -s UUID -o value "$TARGET_PART_ROOT" 2>/dev/null || true)
|
||||
ROOT_PARAM="root=$TARGET_PART_ROOT"
|
||||
if [ -z "$ROOT_UUID" ]; then
|
||||
ROOT_UUID=$(blkid "$TARGET_PART_ROOT" 2>/dev/null | sed -n 's/.*UUID="\([^"]*\)".*/\1/p')
|
||||
fi
|
||||
if [ -z "$ROOT_UUID" ]; then
|
||||
ROOT_UUID=$(blkid "$TARGET_PART_ROOT" 2>/dev/null | sed -n "s/.*UUID='\([^']*\)'.*/\1/p")
|
||||
fi
|
||||
|
||||
if [ -n "$ROOT_UUID" ]; then
|
||||
FSTAB_ROOT="UUID=$ROOT_UUID"
|
||||
ROOT_PARAM="root=UUID=$ROOT_UUID"
|
||||
info "Wykryto UUID partycji systemowej: $ROOT_UUID"
|
||||
else
|
||||
FSTAB_ROOT="$TARGET_PART_ROOT"
|
||||
ROOT_PARAM="root=$TARGET_PART_ROOT"
|
||||
warn "Nie odnaleziono UUID dla $TARGET_PART_ROOT, używam ścieżki urządzenia."
|
||||
fi
|
||||
|
||||
FSTAB_EFI=""
|
||||
if [ "$BOOT_MODE" = "UEFI" ] && [ -n "$TARGET_PART_EFI" ] && [ -b "$TARGET_PART_EFI" ]; then
|
||||
EFI_UUID=$(blkid -s UUID -o value "$TARGET_PART_EFI" 2>/dev/null || true)
|
||||
if [ -z "$EFI_UUID" ]; then
|
||||
EFI_UUID=$(blkid "$TARGET_PART_EFI" 2>/dev/null | sed -n 's/.*UUID="\([^"]*\)".*/\1/p')
|
||||
fi
|
||||
if [ -n "$EFI_UUID" ]; then
|
||||
FSTAB_EFI="UUID=$EFI_UUID /boot/efi vfat defaults,umask=0077,noatime 0 2"
|
||||
else
|
||||
FSTAB_EFI="$TARGET_PART_EFI /boot/efi vfat defaults,umask=0077,noatime 0 2"
|
||||
fi
|
||||
fi
|
||||
|
||||
cat << EOF > "$MOUNT_DIR/etc/fstab"
|
||||
# /etc/fstab - KhOS
|
||||
$TARGET_PART_ROOT / ext4 defaults,noatime 0 1
|
||||
$([ -n "$TARGET_PART_EFI" ] && echo "$TARGET_PART_EFI /boot/efi vfat defaults 0 2" || true)
|
||||
proc /proc proc defaults 0 0
|
||||
sysfs /sys sysfs defaults 0 0
|
||||
devtmpfs /dev devtmpfs defaults 0 0
|
||||
devpts /dev/pts devpts defaults 0 0
|
||||
tmpfs /dev/shm tmpfs defaults 0 0
|
||||
tmpfs /tmp tmpfs defaults 0 0
|
||||
tmpfs /run tmpfs defaults 0 0
|
||||
# <file system> <mount point> <type> <options> <dump> <pass>
|
||||
$FSTAB_ROOT / ext4 defaults,noatime,commit=60,errors=remount-ro 0 1
|
||||
$([ -n "$FSTAB_EFI" ] && echo "$FSTAB_EFI" || true)
|
||||
proc /proc proc defaults 0 0
|
||||
sysfs /sys sysfs defaults 0 0
|
||||
devtmpfs /dev devtmpfs defaults 0 0
|
||||
devpts /dev/pts devpts defaults,gid=5,mode=620,nosuid,noexec 0 0
|
||||
tmpfs /dev/shm tmpfs defaults,nosuid,nodev,noexec 0 0
|
||||
tmpfs /tmp tmpfs defaults,nosuid,nodev 0 0
|
||||
tmpfs /run tmpfs defaults,nosuid,nodev,mode=0755 0 0
|
||||
EOF
|
||||
|
||||
echo "$NEW_HOSTNAME" > "$MOUNT_DIR/etc/hostname"
|
||||
@@ -275,29 +542,71 @@ EOF
|
||||
if [ -f "$MOUNT_DIR/etc/shadow" ]; then
|
||||
echo "root:$NEW_PASSWORD" | chpasswd -R "$MOUNT_DIR" 2>/dev/null || \
|
||||
echo "root:$NEW_PASSWORD" | chroot "$MOUNT_DIR" chpasswd 2>/dev/null || true
|
||||
chmod 0600 "$MOUNT_DIR/etc/shadow" "$MOUNT_DIR/etc/gshadow" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
msg "Instalacja programu rozruchowego (Bootloader)..."
|
||||
# Zabezpieczenie kont: usuniecie konta live na zainstalowanym systemie docelowym
|
||||
if grep -q '^live:' "$MOUNT_DIR/etc/passwd" 2>/dev/null; then
|
||||
sed -i '/^live:/d' "$MOUNT_DIR/etc/passwd" 2>/dev/null || true
|
||||
sed -i '/^live:/d' "$MOUNT_DIR/etc/shadow" 2>/dev/null || true
|
||||
sed -i 's/,live//g; s/:live/:/g' "$MOUNT_DIR/etc/group" 2>/dev/null || true
|
||||
rm -rf "$MOUNT_DIR/home/live" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
# 10. Instalacja i konfiguracja Bootloadera (GRUB)
|
||||
report_progress 88 "Instalacja i konfiguracja programu rozruchowego GRUB (${BOOT_MODE})"
|
||||
|
||||
# Konfiguracja domyślnego pulpitu
|
||||
mkdir -p "$MOUNT_DIR/etc/default"
|
||||
echo "DESKTOP=${DESKTOP_CHOICE}" > "$MOUNT_DIR/etc/default/desktop"
|
||||
|
||||
GRUB_DEF=0
|
||||
EXTLINUX_DEF="xfce"
|
||||
if [ "$DESKTOP_CHOICE" = "plasma" ]; then
|
||||
GRUB_DEF=1
|
||||
EXTLINUX_DEF="plasma"
|
||||
fi
|
||||
|
||||
# Menu GRUB
|
||||
mkdir -p "$MOUNT_DIR/boot/grub"
|
||||
cat << EOF > "$MOUNT_DIR/boot/grub/grub.cfg"
|
||||
set timeout=5
|
||||
set default=0
|
||||
set default=${GRUB_DEF}
|
||||
|
||||
terminal_input console
|
||||
terminal_output console
|
||||
|
||||
menuentry "KhOS 1.0 (Pulpit KDE Plasma)" {
|
||||
insmod part_msdos
|
||||
insmod part_gpt
|
||||
insmod ext2
|
||||
insmod fat
|
||||
|
||||
$([ -n "$ROOT_UUID" ] && echo "search --no-floppy --fs-uuid --set=root $ROOT_UUID" || true)
|
||||
|
||||
menuentry "KhOS 1.1 (Pulpit XFCE 4 - domyslny)" {
|
||||
linux /boot/vmlinuz $ROOT_PARAM rw quiet
|
||||
initrd /boot/initramfs.img
|
||||
}
|
||||
|
||||
menuentry "KhOS 1.0 (Tryb awaryjny - verbose)" {
|
||||
menuentry "KhOS 1.1 (Pulpit KDE Plasma)" {
|
||||
linux /boot/vmlinuz $ROOT_PARAM desktop=plasma rw quiet
|
||||
initrd /boot/initramfs.img
|
||||
}
|
||||
|
||||
menuentry "KhOS 1.1 (Zapasowy rozruch / Fallback - urzadzenie $TARGET_PART_ROOT)" {
|
||||
linux /boot/vmlinuz root=$TARGET_PART_ROOT rw quiet
|
||||
initrd /boot/initramfs.img
|
||||
}
|
||||
|
||||
menuentry "KhOS 1.1 (Tryb awaryjny - verbose/debug)" {
|
||||
linux /boot/vmlinuz $ROOT_PARAM rw textmode debug loglevel=7
|
||||
initrd /boot/initramfs.img
|
||||
}
|
||||
|
||||
menuentry "KhOS 1.1 (Tryb ratunkowy - shell init=/bin/sh)" {
|
||||
linux /boot/vmlinuz root=$TARGET_PART_ROOT rw single init=/bin/sh
|
||||
initrd /boot/initramfs.img
|
||||
}
|
||||
|
||||
menuentry "Uruchom ponownie" {
|
||||
reboot
|
||||
}
|
||||
@@ -322,6 +631,10 @@ if [ "$BOOT_MODE" = "UEFI" ] && [ -n "$TARGET_PART_EFI" ]; then
|
||||
fi
|
||||
mkdir -p "$MOUNT_DIR/boot/efi/boot/grub"
|
||||
cp -f "$MOUNT_DIR/boot/grub/grub.cfg" "$MOUNT_DIR/boot/efi/boot/grub/grub.cfg" 2>/dev/null || true
|
||||
mkdir -p "$MOUNT_DIR/boot/efi/EFI/khos"
|
||||
cp -f "$MOUNT_DIR/boot/grub/grub.cfg" "$MOUNT_DIR/boot/efi/EFI/khos/grub.cfg" 2>/dev/null || true
|
||||
mkdir -p "$MOUNT_DIR/boot/efi/EFI/BOOT"
|
||||
cp -f "$MOUNT_DIR/boot/grub/grub.cfg" "$MOUNT_DIR/boot/efi/EFI/BOOT/grub.cfg" 2>/dev/null || true
|
||||
else
|
||||
info "Instalacja GRUB (BIOS i386-pc) na dysku ${TARGET_DISK}..."
|
||||
if command -v grub-install >/dev/null 2>&1; then
|
||||
@@ -348,21 +661,33 @@ else
|
||||
[ -d "$dir" ] && cp -f "$dir"/*.c32 "$MOUNT_DIR/boot/extlinux/" 2>/dev/null || true
|
||||
done
|
||||
cat << EOF > "$MOUNT_DIR/boot/extlinux/extlinux.conf"
|
||||
DEFAULT plasma
|
||||
DEFAULT ${EXTLINUX_DEF}
|
||||
PROMPT 1
|
||||
TIMEOUT 50
|
||||
|
||||
LABEL plasma
|
||||
MENU LABEL KhOS 1.0 (KDE Plasma)
|
||||
LABEL xfce
|
||||
MENU LABEL KhOS 1.1 (XFCE 4 - domyslny)
|
||||
LINUX /boot/vmlinuz
|
||||
INITRD /boot/initramfs.img
|
||||
APPEND $ROOT_PARAM rw quiet
|
||||
|
||||
LABEL textmode
|
||||
MENU LABEL KhOS 1.0 (Tryb tekstowy)
|
||||
LABEL fallback
|
||||
MENU LABEL KhOS 1.1 (Zapasowy rozruch - $TARGET_PART_ROOT)
|
||||
LINUX /boot/vmlinuz
|
||||
INITRD /boot/initramfs.img
|
||||
APPEND $ROOT_PARAM rw textmode
|
||||
APPEND root=$TARGET_PART_ROOT rw quiet
|
||||
|
||||
LABEL plasma
|
||||
MENU LABEL KhOS 1.1 (KDE Plasma)
|
||||
LINUX /boot/vmlinuz
|
||||
INITRD /boot/initramfs.img
|
||||
APPEND $ROOT_PARAM desktop=plasma rw quiet
|
||||
|
||||
LABEL textmode
|
||||
MENU LABEL KhOS 1.1 (Tryb awaryjny)
|
||||
LINUX /boot/vmlinuz
|
||||
INITRD /boot/initramfs.img
|
||||
APPEND $ROOT_PARAM rw textmode debug loglevel=7
|
||||
EOF
|
||||
BOOTLOADER_OK=1
|
||||
fi
|
||||
@@ -374,37 +699,53 @@ else
|
||||
warn "Ostrzeżenie: weryfikacja bootloadera zgłosiła uwagi."
|
||||
fi
|
||||
|
||||
# Uprawnienia dla środowisk graficznych, autologin i narzędzi
|
||||
# 11. Uprawnienia i synchronizacja buforów
|
||||
report_progress 95 "Ustawianie uprawnień i synchronizacja buforów dysku"
|
||||
chmod +x "$MOUNT_DIR/usr/bin/start-xfce" "$MOUNT_DIR/usr/bin/startxfce4" "$MOUNT_DIR/usr/bin/xfce" "$MOUNT_DIR/usr/bin/xfce4" 2>/dev/null || true
|
||||
chmod +x "$MOUNT_DIR/usr/bin/start-plasma" "$MOUNT_DIR/usr/bin/plasma" "$MOUNT_DIR/usr/bin/kde" "$MOUNT_DIR/usr/bin/autologin-plasma" 2>/dev/null || true
|
||||
chmod +x "$MOUNT_DIR/usr/bin/start-hyprland" "$MOUNT_DIR/usr/bin/start-openbox" 2>/dev/null || true
|
||||
chmod +x "$MOUNT_DIR/usr/bin/Hyprland" "$MOUNT_DIR/usr/bin/foot" "$MOUNT_DIR/usr/bin/wofi" 2>/dev/null || true
|
||||
chmod +x "$MOUNT_DIR/usr/bin/openbox"* "$MOUNT_DIR/usr/bin/tint2" "$MOUNT_DIR/usr/bin/xterm" "$MOUNT_DIR/usr/bin/feh" 2>/dev/null || true
|
||||
chmod 4755 "$MOUNT_DIR/usr/bin/seatd-launch" "$MOUNT_DIR/usr/bin/Xorg" 2>/dev/null || true
|
||||
chmod 4755 "$MOUNT_DIR/bin/busybox" 2>/dev/null || true
|
||||
chmod +x "$MOUNT_DIR/usr/bin/khos-installer" "$MOUNT_DIR/usr/bin/install-os" "$MOUNT_DIR/usr/bin/wpkg" 2>/dev/null || true
|
||||
chmod 4755 "$MOUNT_DIR/usr/bin/sudo" "$MOUNT_DIR/usr/bin/doas" 2>/dev/null || true
|
||||
chmod 0755 "$MOUNT_DIR/usr/bin/seatd-launch" "$MOUNT_DIR/usr/bin/Xorg" "$MOUNT_DIR/bin/busybox" 2>/dev/null || true
|
||||
chmod 0600 "$MOUNT_DIR/etc/shadow" "$MOUNT_DIR/etc/gshadow" 2>/dev/null || true
|
||||
chmod +x "$MOUNT_DIR/usr/bin/khos-installer" "$MOUNT_DIR/usr/bin/install-os" "$MOUNT_DIR/usr/bin/wpkg" "$MOUNT_DIR/usr/bin/khos-update" "$MOUNT_DIR/usr/bin/khos-installer-gui" "$MOUNT_DIR/usr/share/khos-installer/khos-installer-gui.py" 2>/dev/null || true
|
||||
chmod +x "$MOUNT_DIR/usr/share/applications/"*.desktop 2>/dev/null || true
|
||||
|
||||
msg "Synchronizacja buforów i odmontowanie dysku..."
|
||||
sync
|
||||
umount -R "$MOUNT_DIR" 2>/dev/null || true
|
||||
rmdir "$MOUNT_DIR" 2>/dev/null || true
|
||||
MOUNT_DIR=""
|
||||
|
||||
report_progress 100 "Instalacja KhOS zakończona sukcesem"
|
||||
|
||||
if [ -n "$STATUS_FILE" ]; then
|
||||
echo "SUCCESS:Instalacja zakończona sukcesem" >> "$STATUS_FILE" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "╔══════════════════════════════════════════════════════════════╗"
|
||||
echo "║ ║"
|
||||
echo "║ SUKCES! KhOS 1.0 został pomyślnie zainstalowany! ║"
|
||||
echo "║ ║"
|
||||
echo "║ Dysk docelowy: $TARGET_DISK ║"
|
||||
echo "║ Partycja systemowa: $TARGET_PART_ROOT ║"
|
||||
echo "║ Tryb rozruchu: $BOOT_MODE ║"
|
||||
echo "║ Program rozruchowy: GRUB 2.14 ║"
|
||||
echo "║ Użytkownik: root / Hasło: $NEW_PASSWORD ║"
|
||||
echo "║ ║"
|
||||
echo "║ Pulpity graficzne: ║"
|
||||
echo "║ - Openbox (X11): wpisz 'start-openbox' ║"
|
||||
echo "║ - Hyprland (Wayland): wpisz 'start-hyprland' ║"
|
||||
echo "║ ║"
|
||||
echo "║ Możesz teraz wyciągnąć nośnik instalacyjny (ISO / USB) ║"
|
||||
echo "║ i zrestartować komputer wpisując polecenie: reboot ║"
|
||||
echo "║ ║"
|
||||
echo "╚══════════════════════════════════════════════════════════════╝"
|
||||
if [ "$AUTO_MODE" -eq 1 ]; then
|
||||
ok "KhOS zainstalowany pomyślnie na $TARGET_DISK ($TARGET_PART_ROOT, tryb: $BOOT_MODE)."
|
||||
info "Hasło root: $NEW_PASSWORD / Nazwa hosta: $NEW_HOSTNAME"
|
||||
else
|
||||
echo "╔══════════════════════════════════════════════════════════════╗"
|
||||
echo "║ ║"
|
||||
echo "║ SUKCES! KhOS 1.0 został pomyślnie zainstalowany! ║"
|
||||
echo "║ ║"
|
||||
echo "║ Dysk docelowy: $TARGET_DISK ║"
|
||||
echo "║ Partycja systemowa: $TARGET_PART_ROOT ║"
|
||||
echo "║ Tryb rozruchu: $BOOT_MODE ║"
|
||||
echo "║ Program rozruchowy: GRUB 2.14 ║"
|
||||
echo "║ Użytkownik: root / Hasło: $NEW_PASSWORD ║"
|
||||
echo "║ ║"
|
||||
echo "║ Pulpity graficzne: ║"
|
||||
echo "║ - Openbox (X11): wpisz 'start-openbox' ║"
|
||||
echo "║ - Hyprland (Wayland): wpisz 'start-hyprland' ║"
|
||||
echo "║ ║"
|
||||
echo "║ Możesz teraz wyciągnąć nośnik instalacyjny (ISO / USB) ║"
|
||||
echo "║ i zrestartować komputer wpisując polecenie: reboot ║"
|
||||
echo "║ ║"
|
||||
echo "╚══════════════════════════════════════════════════════════════╝"
|
||||
fi
|
||||
echo ""
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
#!/bin/sh
|
||||
# =============================================================================
|
||||
# KhOS 1.1 Genesis - Główny skrypt uruchomieniowy instalatora graficznego (GUI)
|
||||
# Środowisko: X11 / XFCE 4 / Live CD
|
||||
# =============================================================================
|
||||
set -e
|
||||
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:$PATH"
|
||||
|
||||
# 1. Automatyczna eskalacja uprawnień do administratora (root)
|
||||
if [ "$(id -u)" -ne 0 ]; then
|
||||
# Zapewnij dostęp użytkownika root do serwera X11
|
||||
if [ -n "$DISPLAY" ]; then
|
||||
xhost +local:root 2>/dev/null || true
|
||||
fi
|
||||
|
||||
if command -v sudo >/dev/null 2>&1; then
|
||||
exec sudo -E PATH="$PATH" DISPLAY="$DISPLAY" XAUTHORITY="$XAUTHORITY" "$0" "$@"
|
||||
elif command -v doas >/dev/null 2>&1; then
|
||||
exec doas "$0" "$@"
|
||||
elif command -v su >/dev/null 2>&1; then
|
||||
exec su -c "$0 $*"
|
||||
else
|
||||
echo "[BŁĄD] Do uruchomienia instalatora KhOS wymagane są uprawnienia roota." >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# 2. Sprawdzenie dostępności Python 3 oraz biblioteki graficznej Tkinter
|
||||
PYTHON_TK_OK=0
|
||||
if command -v python3 >/dev/null 2>&1; then
|
||||
if python3 -c "import tkinter" >/dev/null 2>&1; then
|
||||
PYTHON_TK_OK=1
|
||||
fi
|
||||
fi
|
||||
|
||||
# Główny interfejs: Python 3 + Tkinter (Elegancki ciemny motyw KhOS)
|
||||
if [ "$PYTHON_TK_OK" -eq 1 ] && [ -f /usr/share/khos-installer/khos-installer-gui.py ]; then
|
||||
exec python3 /usr/share/khos-installer/khos-installer-gui.py "$@"
|
||||
fi
|
||||
|
||||
# =============================================================================
|
||||
# MECHANIZM AWARYJNY (FALLBACK) GDY BRAK PYTHON3 / TKINTER
|
||||
# =============================================================================
|
||||
echo "[INFO] Python 3 lub Tkinter nie są dostępne. Uruchamianie trybu awaryjnego instalatora..."
|
||||
|
||||
# Fallback 1: Asystent graficzny Zenity (jeśli dostępny pod X11/XFCE)
|
||||
if [ -n "$DISPLAY" ] && command -v zenity >/dev/null 2>&1; then
|
||||
zenity --info --title="Instalator KhOS 1.1" --width=450 \
|
||||
--text="Witaj w instalatorze KhOS 1.1 Genesis!\n\nZostaniesz przeprowadzony przez szybką instalację systemu na wskazanym dysku." 2>/dev/null || true
|
||||
|
||||
# Wykrywanie dysków dla Zenity
|
||||
DISK_LIST=""
|
||||
for d in /sys/block/sd* /sys/block/nvme* /sys/block/vd* /sys/block/hd*; do
|
||||
[ ! -e "$d" ] && continue
|
||||
bn=$(basename "$d")
|
||||
case "$bn" in sr*|loop*|ram*|dm-*) continue ;; esac
|
||||
dev="/dev/$bn"
|
||||
[ ! -b "$dev" ] && continue
|
||||
sz=$(cat "$d/size" 2>/dev/null || echo 0)
|
||||
sz_gb=$(( sz * 512 / 1024 / 1024 / 1024 ))
|
||||
[ "$sz_gb" -lt 2 ] && continue
|
||||
mod=$(cat "$d/device/model" 2>/dev/null | tr -s ' ' || echo "Dysk")
|
||||
DISK_LIST="$DISK_LIST FALSE $dev ${sz_gb}GB $mod"
|
||||
done
|
||||
|
||||
if [ -n "$DISK_LIST" ]; then
|
||||
# Wybór dysku
|
||||
CHOSEN_DISK=$(zenity --list --radiolist --title="Wybór dysku docelowego" \
|
||||
--text="Wybierz dysk, na którym ma zostać zainstalowany system KhOS:" \
|
||||
--column="Wybór" --column="Urządzenie" --column="Rozmiar" --column="Model" \
|
||||
$DISK_LIST 2>/dev/null || true)
|
||||
|
||||
if [ -n "$CHOSEN_DISK" ] && [ -b "$CHOSEN_DISK" ]; then
|
||||
# Konfiguracja hosta i hasła
|
||||
CFG_VALS=$(zenity --forms --title="Konfiguracja systemu KhOS" \
|
||||
--text="Wprowadź podstawowe parametry nowego systemu:" \
|
||||
--add-entry="Nazwa komputera (hostname)" \
|
||||
--add-password="Hasło administratora (root)" 2>/dev/null || true)
|
||||
|
||||
CHOSEN_HOST=$(echo "$CFG_VALS" | cut -d'|' -f1)
|
||||
CHOSEN_PASS=$(echo "$CFG_VALS" | cut -d'|' -f2)
|
||||
CHOSEN_HOST="${CHOSEN_HOST:-khos}"
|
||||
CHOSEN_PASS="${CHOSEN_PASS:-khos}"
|
||||
|
||||
# Wybór pulpitu
|
||||
CHOSEN_DESK=$(zenity --list --radiolist --title="Wybór pulpitu" \
|
||||
--text="Wybierz domyślne środowisko graficzne:" \
|
||||
--column="Wybór" --column="Środowisko" \
|
||||
TRUE "xfce" FALSE "plasma" 2>/dev/null || echo "xfce")
|
||||
CHOSEN_DESK="${CHOSEN_DESK:-xfce}"
|
||||
|
||||
# Ostrzeżenie i potwierdzenie
|
||||
if zenity --question --title="UWAGA: Kasowanie dysku" \
|
||||
--text="UWAGA!\n\nWszystkie dane na dysku $CHOSEN_DISK zostaną TRWALE USUNIĘTE!\n\nCzy chcesz rozpocząć instalację KhOS teraz?" 2>/dev/null; then
|
||||
|
||||
(
|
||||
/usr/bin/khos-installer --auto \
|
||||
--disk="$CHOSEN_DISK" \
|
||||
--hostname="$CHOSEN_HOST" \
|
||||
--password="$CHOSEN_PASS" \
|
||||
--desktop="$CHOSEN_DESK" \
|
||||
--status-file="/tmp/khos-installer.status" 2>&1
|
||||
) | zenity --progress --title="Instalacja KhOS" --text="Trwa instalacja systemu..." --pulsate --auto-close 2>/dev/null || true
|
||||
|
||||
if [ $? -eq 0 ]; then
|
||||
if zenity --question --title="Instalacja ukończona" \
|
||||
--text="System KhOS został pomyślnie zainstalowany!\n\nCzy chcesz zrestartować komputer teraz?" 2>/dev/null; then
|
||||
reboot
|
||||
fi
|
||||
exit 0
|
||||
else
|
||||
zenity --error --title="Błąd instalacji" --text="Wystąpił problem podczas instalacji KhOS. Uruchamiam konsolę awaryjną..." 2>/dev/null || true
|
||||
fi
|
||||
else
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# Fallback 2: Emulator terminala graficznego (XFCE Terminal, xterm, foot, st) z khos-installer
|
||||
if [ -n "$DISPLAY" ]; then
|
||||
if command -v xfce4-terminal >/dev/null 2>&1; then
|
||||
exec xfce4-terminal --title="Instalator KhOS (Tryb konsolowy)" --geometry=95x30 -e "/usr/bin/khos-installer"
|
||||
elif command -v xterm >/dev/null 2>&1; then
|
||||
exec xterm -title "Instalator KhOS (Tryb konsolowy)" -geometry 95x30 -e /usr/bin/khos-installer
|
||||
elif command -v foot >/dev/null 2>&1; then
|
||||
exec foot -T "Instalator KhOS (Tryb konsolowy)" /usr/bin/khos-installer
|
||||
elif command -v st >/dev/null 2>&1; then
|
||||
exec st -t "Instalator KhOS (Tryb konsolowy)" -e /usr/bin/khos-installer
|
||||
fi
|
||||
fi
|
||||
|
||||
# Fallback 3: Bezpośrednie uruchomienie instalatora tekstowego w konsoli TTY
|
||||
exec /usr/bin/khos-installer "$@"
|
||||
@@ -0,0 +1,434 @@
|
||||
#!/bin/sh
|
||||
# =========================================================================
|
||||
# khos-update - Narzędzie aktualizacji systemu KhOS z obrazu ISO / Live
|
||||
# Obsługuje aktualizację z działającego systemu oraz z poziomu nośnika Live
|
||||
# =========================================================================
|
||||
set -e
|
||||
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:$PATH"
|
||||
|
||||
# Kolory ANSI
|
||||
C_RESET='\033[0m'
|
||||
C_BOLD='\033[1m'
|
||||
C_RED='\033[1;31m'
|
||||
C_GREEN='\033[1;32m'
|
||||
C_YELLOW='\033[1;33m'
|
||||
C_CYAN='\033[1;36m'
|
||||
C_BLUE='\033[1;34m'
|
||||
|
||||
msg() { printf "${C_BOLD}${C_BLUE}==>${C_RESET} ${C_BOLD}%b${C_RESET}\n" "$1"; }
|
||||
info() { printf "${C_CYAN} ->${C_RESET} %b\n" "$1"; }
|
||||
ok() { printf "${C_GREEN} [OK]${C_RESET} %b\n" "$1"; }
|
||||
warn() { printf "${C_YELLOW}[OSTRZEŻENIE]${C_RESET} %b\n" "$1"; }
|
||||
err() { printf "${C_RED}[BŁĄD]${C_RESET} %b\n" "$1" >&2; }
|
||||
die() { err "$1"; cleanup; exit 1; }
|
||||
|
||||
# Sprawdzenie uprawnień roota
|
||||
if [ "$(id -u 2>/dev/null)" != "0" ]; then
|
||||
echo "BŁĄD: Ten program musi być uruchomiony jako root (użyj 'sudo khos-update' lub 'su')." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
TMP_ISO_MOUNT="/mnt/khos_iso_update_$$"
|
||||
TMP_SQ_MOUNT="/mnt/khos_sq_update_$$"
|
||||
TARGET_MOUNT=""
|
||||
CLEANUP_ISO=0
|
||||
CLEANUP_SQ=0
|
||||
CLEANUP_TARGET=0
|
||||
|
||||
cleanup() {
|
||||
if [ "$CLEANUP_SQ" -eq 1 ] && mountpoint -q "$TMP_SQ_MOUNT" 2>/dev/null; then
|
||||
umount "$TMP_SQ_MOUNT" 2>/dev/null || umount -l "$TMP_SQ_MOUNT" 2>/dev/null || true
|
||||
fi
|
||||
if [ "$CLEANUP_ISO" -eq 1 ] && mountpoint -q "$TMP_ISO_MOUNT" 2>/dev/null; then
|
||||
umount "$TMP_ISO_MOUNT" 2>/dev/null || umount -l "$TMP_ISO_MOUNT" 2>/dev/null || true
|
||||
fi
|
||||
if [ "$CLEANUP_TARGET" -eq 1 ] && [ -n "$TARGET_MOUNT" ] && mountpoint -q "$TARGET_MOUNT" 2>/dev/null; then
|
||||
sync
|
||||
umount -R "$TARGET_MOUNT" 2>/dev/null || true
|
||||
fi
|
||||
rmdir "$TMP_SQ_MOUNT" 2>/dev/null || true
|
||||
rmdir "$TMP_ISO_MOUNT" 2>/dev/null || true
|
||||
}
|
||||
|
||||
trap 'cleanup' EXIT INT TERM HUP
|
||||
|
||||
echo ""
|
||||
echo " ╔══════════════════════════════════════════════════════════════╗"
|
||||
echo " ║ ║"
|
||||
echo " ║ ╦ ╦╦ ╔═╗╔═╗╔╗╔╦ ╦╔═╗╔═╗ AKTUALIZACJA SYSTEMU ║"
|
||||
echo " ║ ║║║║ ╠═╣╚═╗║║║╚╦╝║ ║╚═╗ KhOS ║"
|
||||
echo " ║ ╚╩╝╩═╝╩ ╩╚═╝╝╚╝ ╩ ╚═╝╚═╝ Z OBRAZU ISO ║"
|
||||
echo " ║ ║"
|
||||
echo " ║ To narzędzie aktualizuje jądro, moduły, biblioteki, ║"
|
||||
echo " ║ programy i pulpity z nowego obrazu ISO bez utraty danych ║"
|
||||
echo " ║ użytkownika w /home i zachowując konta oraz hasła. ║"
|
||||
echo " ╚══════════════════════════════════════════════════════════════╝"
|
||||
echo ""
|
||||
|
||||
# 1. Określenie trybu pracy: czy działamy w środowisku Live, czy na zainstalowanym systemie
|
||||
IS_LIVE=0
|
||||
if [ -d /mnt/cdrom/live ] || [ -f /mnt/squashfs/bin/busybox ] || grep -q 'root=.*live' /proc/cmdline 2>/dev/null || [ -d /mnt/tmpfs/upper ]; then
|
||||
IS_LIVE=1
|
||||
fi
|
||||
|
||||
ISO_SOURCE="$1"
|
||||
|
||||
# 2. Wykrywanie lub pobieranie źródła obrazu ISO
|
||||
SQUASHFS_SOURCE=""
|
||||
KERNEL_SOURCE=""
|
||||
INITRD_SOURCE=""
|
||||
PACKAGES_SOURCE=""
|
||||
|
||||
find_iso_or_source() {
|
||||
# Sprawdzenie czy podano plik jako argument
|
||||
if [ -n "$ISO_SOURCE" ]; then
|
||||
if [ -f "$ISO_SOURCE" ]; then
|
||||
info "Użycie wskazanego pliku ISO: $ISO_SOURCE"
|
||||
mkdir -p "$TMP_ISO_MOUNT"
|
||||
if mount -t iso9660 -o loop,ro "$ISO_SOURCE" "$TMP_ISO_MOUNT" 2>/dev/null || mount -o loop,ro "$ISO_SOURCE" "$TMP_ISO_MOUNT" 2>/dev/null; then
|
||||
CLEANUP_ISO=1
|
||||
check_mounted_source "$TMP_ISO_MOUNT"
|
||||
return 0
|
||||
else
|
||||
die "Nie udało się zamontować obrazu ISO: $ISO_SOURCE"
|
||||
fi
|
||||
elif [ -d "$ISO_SOURCE" ]; then
|
||||
info "Użycie wskazanego katalogu z plikami nośnika: $ISO_SOURCE"
|
||||
check_mounted_source "$ISO_SOURCE"
|
||||
return 0
|
||||
else
|
||||
warn "Wskazany plik '$ISO_SOURCE' nie istnieje."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Jeśli jesteśmy w trybie Live, użyj aktualnego nośnika Live
|
||||
if [ "$IS_LIVE" -eq 1 ]; then
|
||||
for cand_dir in /mnt/cdrom /run/media/*; do
|
||||
if [ -f "${cand_dir}/live/filesystem.squashfs" ]; then
|
||||
info "Wykryto uruchomiony nośnik instalacyjny Live w: ${cand_dir}"
|
||||
check_mounted_source "${cand_dir}"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
if [ -d /mnt/squashfs ] && [ -f /mnt/squashfs/bin/busybox ]; then
|
||||
info "Użycie aktywnego obrazu squashfs środowiska Live."
|
||||
SQUASHFS_SOURCE="/mnt/squashfs"
|
||||
[ -f /mnt/cdrom/boot/vmlinuz ] && KERNEL_SOURCE="/mnt/cdrom/boot/vmlinuz"
|
||||
[ -f /mnt/cdrom/boot/initramfs.img ] && INITRD_SOURCE="/mnt/cdrom/boot/initramfs.img"
|
||||
[ -d /mnt/cdrom/packages ] && PACKAGES_SOURCE="/mnt/cdrom/packages"
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
|
||||
# Przeszukiwanie dysków i partycji w poszukiwaniu obrazu .iso lub nośnika CD/USB
|
||||
info "Wyszukiwanie obrazu ISO w systemie..."
|
||||
for dev in /dev/sr* /dev/cdrom; do
|
||||
if [ -b "$dev" ]; then
|
||||
mkdir -p "$TMP_ISO_MOUNT"
|
||||
if mount -o ro "$dev" "$TMP_ISO_MOUNT" 2>/dev/null; then
|
||||
if [ -f "$TMP_ISO_MOUNT/live/filesystem.squashfs" ]; then
|
||||
ok "Znaleziono płytę/napęd CD/DVD KhOS na: $dev"
|
||||
CLEANUP_ISO=1
|
||||
check_mounted_source "$TMP_ISO_MOUNT"
|
||||
return 0
|
||||
fi
|
||||
umount "$TMP_ISO_MOUNT" 2>/dev/null || true
|
||||
fi
|
||||
fi
|
||||
done
|
||||
|
||||
# Szukanie plików .iso w popularnych lokalizacjach
|
||||
local cand_isos=""
|
||||
for dir in / /root /home/* /mnt /media /tmp; do
|
||||
for f in "$dir"/khos*.iso "$dir"/wlasnyos*.iso "$dir"/*.iso; do
|
||||
[ -f "$f" ] && cand_isos="$cand_isos $f"
|
||||
done
|
||||
done
|
||||
|
||||
if [ -n "$cand_isos" ]; then
|
||||
msg "Znalezione obrazy ISO:"
|
||||
local idx=1
|
||||
for iso_f in $cand_isos; do
|
||||
echo " $idx) $iso_f ($(ls -lh "$iso_f" | awk '{print $5}'))"
|
||||
idx=$((idx + 1))
|
||||
done
|
||||
printf "Wybierz numer obrazu lub wpisz pełną ścieżkę do pliku ISO [1]: "
|
||||
read -r choice
|
||||
choice="${choice:-1}"
|
||||
case "$choice" in
|
||||
[0-9]*)
|
||||
local cur_i=1
|
||||
for iso_f in $cand_isos; do
|
||||
if [ "$cur_i" -eq "$choice" ]; then
|
||||
ISO_SOURCE="$iso_f"
|
||||
break
|
||||
fi
|
||||
cur_i=$((cur_i + 1))
|
||||
done
|
||||
;;
|
||||
*)
|
||||
ISO_SOURCE="$choice"
|
||||
;;
|
||||
esac
|
||||
else
|
||||
printf "Podaj pełną ścieżkę do pliku obrazu ISO (np. /root/khos-1.1.0-x86_64.iso): "
|
||||
read -r ISO_SOURCE
|
||||
fi
|
||||
|
||||
if [ ! -f "$ISO_SOURCE" ]; then
|
||||
die "Plik obrazu '$ISO_SOURCE' nie istnieje!"
|
||||
fi
|
||||
|
||||
mkdir -p "$TMP_ISO_MOUNT"
|
||||
if mount -t iso9660 -o loop,ro "$ISO_SOURCE" "$TMP_ISO_MOUNT" 2>/dev/null || mount -o loop,ro "$ISO_SOURCE" "$TMP_ISO_MOUNT" 2>/dev/null; then
|
||||
CLEANUP_ISO=1
|
||||
check_mounted_source "$TMP_ISO_MOUNT"
|
||||
else
|
||||
die "Nie udało się zamontować obrazu ISO: $ISO_SOURCE"
|
||||
fi
|
||||
}
|
||||
|
||||
check_mounted_source() {
|
||||
local mnt="$1"
|
||||
if [ -f "${mnt}/live/filesystem.squashfs" ]; then
|
||||
mkdir -p "$TMP_SQ_MOUNT"
|
||||
if mount -t squashfs -o loop,ro "${mnt}/live/filesystem.squashfs" "$TMP_SQ_MOUNT" 2>/dev/null; then
|
||||
CLEANUP_SQ=1
|
||||
SQUASHFS_SOURCE="$TMP_SQ_MOUNT"
|
||||
else
|
||||
die "Błąd montowania filesystem.squashfs z nośnika ISO!"
|
||||
fi
|
||||
elif [ -f "${mnt}/bin/busybox" ]; then
|
||||
SQUASHFS_SOURCE="$mnt"
|
||||
else
|
||||
die "Wskazany nośnik nie zawiera prawidłowego systemu KhOS (brak live/filesystem.squashfs)."
|
||||
fi
|
||||
|
||||
[ -f "${mnt}/boot/vmlinuz" ] && KERNEL_SOURCE="${mnt}/boot/vmlinuz"
|
||||
[ -f "${mnt}/boot/initramfs.img" ] && INITRD_SOURCE="${mnt}/boot/initramfs.img"
|
||||
[ -d "${mnt}/packages" ] && PACKAGES_SOURCE="${mnt}/packages"
|
||||
}
|
||||
|
||||
find_iso_or_source
|
||||
|
||||
if [ -z "$SQUASHFS_SOURCE" ] || [ ! -d "$SQUASHFS_SOURCE" ]; then
|
||||
die "Nie udało się uzyskać dostępu do plików systemowych z obrazu ISO!"
|
||||
fi
|
||||
|
||||
ok "Źródło plików ISO gotowe do aktualizacji: $SQUASHFS_SOURCE"
|
||||
|
||||
# 3. Wybór celu aktualizacji
|
||||
DEST_ROOT=""
|
||||
|
||||
if [ "$IS_LIVE" -eq 1 ]; then
|
||||
msg "Wykrywanie istniejących instalacji KhOS na dyskach komputera..."
|
||||
CAND_PARTS=""
|
||||
for part in /dev/sd* /dev/vd* /dev/nvme*n*p* /dev/hd*; do
|
||||
[ ! -b "$part" ] && continue
|
||||
case "$part" in
|
||||
*p1|*1) # Sprawdz czy to nie partycja boot/efi
|
||||
;;
|
||||
esac
|
||||
# Szybka próba sprawdzenia czy to partycja Linux z KhOS
|
||||
mkdir -p /mnt/probe_part
|
||||
if mount -o ro "$part" /mnt/probe_part 2>/dev/null; then
|
||||
if [ -f /mnt/probe_part/etc/os-release ] || [ -f /mnt/probe_part/bin/busybox ] || [ -d /mnt/probe_part/usr/bin ]; then
|
||||
local os_label="KhOS / Linux"
|
||||
[ -f /mnt/probe_part/etc/os-release ] && os_label=$(grep "^PRETTY_NAME=" /mnt/probe_part/etc/os-release | cut -d= -f2- | tr -d '"')
|
||||
echo " * Znaleziono system na ${C_BOLD}${part}${C_RESET}: $os_label"
|
||||
CAND_PARTS="$CAND_PARTS $part"
|
||||
fi
|
||||
umount /mnt/probe_part 2>/dev/null || true
|
||||
fi
|
||||
done
|
||||
rmdir /mnt/probe_part 2>/dev/null || true
|
||||
|
||||
if [ -z "$CAND_PARTS" ]; then
|
||||
die "Nie znaleziono żadnej partycji z zainstalowanym systemem KhOS! Aby zainstalować system od zera, użyj polecenia 'khos-installer'."
|
||||
fi
|
||||
|
||||
echo ""
|
||||
printf "${C_BOLD}Podaj partycję do zaktualizowania (np. /dev/sda1 lub /dev/nvme0n1p2): ${C_RESET}"
|
||||
read -r TARGET_PART
|
||||
if [ ! -b "$TARGET_PART" ]; then
|
||||
die "Wskazana partycja '$TARGET_PART' nie istnieje!"
|
||||
fi
|
||||
|
||||
TARGET_MOUNT="/mnt/khos_target_update_$$"
|
||||
mkdir -p "$TARGET_MOUNT"
|
||||
mount "$TARGET_PART" "$TARGET_MOUNT" || die "Nie udało się zamontować partycji $TARGET_PART!"
|
||||
CLEANUP_TARGET=1
|
||||
DEST_ROOT="$TARGET_MOUNT"
|
||||
else
|
||||
# Działamy na uruchomionym, zainstalowanym systemie
|
||||
DEST_ROOT=""
|
||||
msg "Aktualizacja bieżącego zainstalowanego systemu KhOS (/)..."
|
||||
warn "UWAGA: Zostaną zaktualizowane pliki jądra, moduły oraz pakiety systemowe w /."
|
||||
warn "Twoje pliki osobiste w /home oraz hasła i konfiguracja sieci NIE ZOSTANĄ zmienione."
|
||||
fi
|
||||
|
||||
echo ""
|
||||
printf "${C_BOLD}Czy chcesz rozpocząć procedurę aktualizacji? [T/n]: ${C_RESET}"
|
||||
read -r CONFIRM
|
||||
case "$CONFIRM" in
|
||||
[nN]*) die "Aktualizacja została anulowana." ;;
|
||||
esac
|
||||
|
||||
# 4. Kopia zapasowa kluczowych plików
|
||||
msg "Przygotowanie kopii zapasowej konfiguracji i starego jądra..."
|
||||
BACKUP_DIR="${DEST_ROOT}/var/backups/khos_pre_update_$(date +%Y%m%d_%H%M%S 2>/dev/null || echo $$)"
|
||||
mkdir -p "$BACKUP_DIR"
|
||||
|
||||
for f in etc/passwd etc/shadow etc/group etc/hostname etc/hosts etc/fstab etc/network etc/resolv.conf; do
|
||||
if [ -e "${DEST_ROOT}/${f}" ]; then
|
||||
mkdir -p "$BACKUP_DIR/$(dirname "$f")"
|
||||
cp -a "${DEST_ROOT}/${f}" "$BACKUP_DIR/${f}" 2>/dev/null || true
|
||||
fi
|
||||
done
|
||||
|
||||
if [ -f "${DEST_ROOT}/boot/vmlinuz" ]; then
|
||||
cp -f "${DEST_ROOT}/boot/vmlinuz" "${DEST_ROOT}/boot/vmlinuz.old" 2>/dev/null || true
|
||||
info "Utworzono kopię zapasową jądra: /boot/vmlinuz.old"
|
||||
fi
|
||||
if [ -f "${DEST_ROOT}/boot/initramfs.img" ]; then
|
||||
cp -f "${DEST_ROOT}/boot/initramfs.img" "${DEST_ROOT}/boot/initramfs.img.old" 2>/dev/null || true
|
||||
info "Utworzono kopię zapasową initramfs: /boot/initramfs.img.old"
|
||||
fi
|
||||
|
||||
ok "Kopia bezpieczeństwa zapisana w: ${BACKUP_DIR#${DEST_ROOT}}"
|
||||
|
||||
# 5. Aktualizacja jądra i initramfs
|
||||
msg "Aktualizacja jądra i initramfs z obrazu ISO..."
|
||||
mkdir -p "${DEST_ROOT}/boot"
|
||||
if [ -n "$KERNEL_SOURCE" ] && [ -f "$KERNEL_SOURCE" ]; then
|
||||
cp -f "$KERNEL_SOURCE" "${DEST_ROOT}/boot/vmlinuz"
|
||||
ok "Nowe jądro zaktualizowane: /boot/vmlinuz"
|
||||
elif [ -f "${SQUASHFS_SOURCE}/boot/vmlinuz" ]; then
|
||||
cp -f "${SQUASHFS_SOURCE}/boot/vmlinuz" "${DEST_ROOT}/boot/vmlinuz"
|
||||
ok "Nowe jądro zaktualizowane z obrazu: /boot/vmlinuz"
|
||||
fi
|
||||
|
||||
if [ -n "$INITRD_SOURCE" ] && [ -f "$INITRD_SOURCE" ]; then
|
||||
cp -f "$INITRD_SOURCE" "${DEST_ROOT}/boot/initramfs.img"
|
||||
ok "Nowy initramfs zaktualizowany: /boot/initramfs.img"
|
||||
elif [ -f "${SQUASHFS_SOURCE}/boot/initramfs.img" ]; then
|
||||
cp -f "${SQUASHFS_SOURCE}/boot/initramfs.img" "${DEST_ROOT}/boot/initramfs.img"
|
||||
ok "Nowy initramfs zaktualizowany z obrazu: /boot/initramfs.img"
|
||||
fi
|
||||
|
||||
# 6. Aktualizacja modułów jądra i firmware
|
||||
msg "Aktualizacja modułów jądra (/lib/modules) i firmware (/lib/firmware)..."
|
||||
mkdir -p "${DEST_ROOT}/lib/modules" "${DEST_ROOT}/lib/firmware"
|
||||
if [ -d "${SQUASHFS_SOURCE}/lib/modules" ]; then
|
||||
cp -a -f "${SQUASHFS_SOURCE}/lib/modules/"* "${DEST_ROOT}/lib/modules/" 2>/dev/null || true
|
||||
ok "Moduły jądra zaktualizowane pomyślnie."
|
||||
fi
|
||||
if [ -d "${SQUASHFS_SOURCE}/lib/firmware" ]; then
|
||||
cp -a -f "${SQUASHFS_SOURCE}/lib/firmware/"* "${DEST_ROOT}/lib/firmware/" 2>/dev/null || true
|
||||
ok "Firmware sprzętowy zaktualizowany pomyślnie."
|
||||
fi
|
||||
|
||||
# 7. Aktualizacja oprogramowania systemowego (bin, sbin, usr, opt)
|
||||
msg "Aktualizacja plików binarnych, bibliotek i środowisk graficznych..."
|
||||
for sys_dir in bin sbin lib lib64 usr opt; do
|
||||
if [ -d "${SQUASHFS_SOURCE}/$sys_dir" ]; then
|
||||
info "Synchronizacja katalogu /$sys_dir..."
|
||||
mkdir -p "${DEST_ROOT}/$sys_dir"
|
||||
(cd "${SQUASHFS_SOURCE}/$sys_dir" && tar -cf - .) | (cd "${DEST_ROOT}/$sys_dir" && tar -xf -) 2>/dev/null || \
|
||||
cp -a -f "${SQUASHFS_SOURCE}/$sys_dir/"* "${DEST_ROOT}/$sys_dir/" 2>/dev/null || true
|
||||
fi
|
||||
done
|
||||
|
||||
# 8. Bezpieczna aktualizacja /etc (nowe pliki tak, bez nadpisywania haseł i fstab)
|
||||
msg "Weryfikacja i instalacja nowych konfiguracji w /etc..."
|
||||
if [ -d "${SQUASHFS_SOURCE}/etc" ]; then
|
||||
mkdir -p "${DEST_ROOT}/etc"
|
||||
find "${SQUASHFS_SOURCE}/etc" -type f 2>/dev/null | while read -r src_f; do
|
||||
rel_f="${src_f#${SQUASHFS_SOURCE}/etc/}"
|
||||
dest_f="${DEST_ROOT}/etc/${rel_f}"
|
||||
|
||||
# Pomiń pliki kont, haseł i montowania
|
||||
case "$rel_f" in
|
||||
passwd|shadow|group|gshadow|fstab|hostname|hosts|resolv.conf)
|
||||
continue
|
||||
;;
|
||||
esac
|
||||
|
||||
mkdir -p "$(dirname "$dest_f")" 2>/dev/null || true
|
||||
cp -a -f "$src_f" "$dest_f" 2>/dev/null || true
|
||||
done
|
||||
fi
|
||||
|
||||
# 9. Przywrócenie i zapewnienie poprawności kont i haseł
|
||||
for f in passwd shadow group fstab hostname; do
|
||||
if [ -f "$BACKUP_DIR/etc/$f" ] && [ -s "$BACKUP_DIR/etc/$f" ]; then
|
||||
cp -a -f "$BACKUP_DIR/etc/$f" "${DEST_ROOT}/etc/$f" 2>/dev/null || true
|
||||
fi
|
||||
done
|
||||
|
||||
# 10. Uprawnienia specjalne
|
||||
msg "Ustawianie poprawnych uprawnień systemowych..."
|
||||
chmod 1777 "${DEST_ROOT}/tmp" 2>/dev/null || true
|
||||
chmod 0700 "${DEST_ROOT}/root" 2>/dev/null || true
|
||||
chmod 0755 "${DEST_ROOT}/bin/busybox" 2>/dev/null || true
|
||||
chmod 4755 "${DEST_ROOT}/usr/bin/sudo" "${DEST_ROOT}/usr/bin/doas" 2>/dev/null || true
|
||||
chmod 0755 "${DEST_ROOT}/usr/bin/seatd-launch" "${DEST_ROOT}/usr/bin/Xorg" 2>/dev/null || true
|
||||
chmod 0600 "${DEST_ROOT}/etc/shadow" "${DEST_ROOT}/etc/gshadow" 2>/dev/null || true
|
||||
chmod +x "${DEST_ROOT}/usr/bin/start-xfce" "${DEST_ROOT}/usr/bin/startxfce4" "${DEST_ROOT}/usr/bin/xfce" "${DEST_ROOT}/usr/bin/xfce4" 2>/dev/null || true
|
||||
chmod +x "${DEST_ROOT}/usr/bin/start-plasma" "${DEST_ROOT}/usr/bin/start-hyprland" "${DEST_ROOT}/usr/bin/start-openbox" 2>/dev/null || true
|
||||
chmod +x "${DEST_ROOT}/usr/bin/khos-installer" "${DEST_ROOT}/usr/bin/khos-update" "${DEST_ROOT}/usr/bin/wpkg" 2>/dev/null || true
|
||||
|
||||
# Dowiązania pomocnicze
|
||||
[ -f "${DEST_ROOT}/usr/bin/khos-update" ] && ln -sf khos-update "${DEST_ROOT}/usr/bin/update-os" 2>/dev/null || true
|
||||
[ -f "${DEST_ROOT}/usr/bin/khos-update" ] && ln -sf khos-update "${DEST_ROOT}/usr/bin/khos-upgrade" 2>/dev/null || true
|
||||
|
||||
# 11. Kopiowanie bazy pakietów z ISO do lokalnego wpkg (jeśli obecne)
|
||||
if [ -n "$PACKAGES_SOURCE" ] && [ -d "$PACKAGES_SOURCE" ]; then
|
||||
msg "Aktualizacja lokalnej bazy pakietów offline z ISO..."
|
||||
mkdir -p "${DEST_ROOT}/var/cache/wpkg" "${DEST_ROOT}/var/lib/wpkg"
|
||||
cp -a -f "${PACKAGES_SOURCE}"/*.wpkg "${DEST_ROOT}/var/cache/wpkg/" 2>/dev/null || true
|
||||
if [ -f "${PACKAGES_SOURCE}/PACKAGES.db" ]; then
|
||||
cp -a -f "${PACKAGES_SOURCE}/PACKAGES.db" "${DEST_ROOT}/var/lib/wpkg/packages.db" 2>/dev/null || true
|
||||
fi
|
||||
ok "Zaktualizowano bazę pakietów offline z obrazu ISO."
|
||||
fi
|
||||
|
||||
# 12. Sprawdzenie programu rozruchowego
|
||||
if [ -d "${DEST_ROOT}/boot/grub" ] && [ -f "${DEST_ROOT}/boot/grub/grub.cfg" ]; then
|
||||
info "Aktualizacja wpisów awaryjnych .old w /boot/grub/grub.cfg..."
|
||||
if ! grep -q 'vmlinuz.old' "${DEST_ROOT}/boot/grub/grub.cfg" 2>/dev/null; then
|
||||
cat << 'EOF' >> "${DEST_ROOT}/boot/grub/grub.cfg"
|
||||
|
||||
menuentry "KhOS 1.0 (Poprzednia wersja jadra - fallback .old)" {
|
||||
linux /boot/vmlinuz.old rw quiet
|
||||
initrd /boot/initramfs.img.old
|
||||
}
|
||||
EOF
|
||||
fi
|
||||
fi
|
||||
|
||||
sync
|
||||
|
||||
echo ""
|
||||
echo " ╔══════════════════════════════════════════════════════════════╗"
|
||||
echo " ║ ║"
|
||||
echo " ║ SUKCES! System KhOS został pomyślnie zaktualizowany! ║"
|
||||
echo " ║ ║"
|
||||
echo " ║ Zaktualizowano: ║"
|
||||
echo " ║ - Nowe jądro Linux z obsługą sprzętu i sterowników ║"
|
||||
echo " ║ - Moduły jądra i firmware urządzeń (/lib/firmware) ║"
|
||||
echo " ║ - Biblioteki i pliki binarne systemowe (/usr, /bin, /sbin) ║"
|
||||
echo " ║ - Środowiska XFCE 4 (domyślne), KDE Plasma, Hyprland i Openbox ║"
|
||||
echo " ║ - Menadżer pakietów wpkg i instalator khos-installer ║"
|
||||
echo " ║ ║"
|
||||
echo " ║ Kopia poprzedniej konfiguracji: ║"
|
||||
echo " ║ ${BACKUP_DIR#${DEST_ROOT}} ║"
|
||||
echo " ║ ║"
|
||||
echo " ║ Zaleca się ponowne uruchomienie komputera: ║"
|
||||
echo " ║ Wpisz polecenie: reboot ║"
|
||||
echo " ║ ║"
|
||||
echo " ╚══════════════════════════════════════════════════════════════╝"
|
||||
echo ""
|
||||
|
||||
exit 0
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
#!/bin/sh
|
||||
exec /usr/bin/khos-update "$@"
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
#!/bin/sh
|
||||
# KhOS - ksplashqml dummy wrapper
|
||||
# Zapobiega zawieszaniu sie animacji ladowania KDE Plasma w maszynach wirtualnych (VirtualBox / QEMU)
|
||||
exit 0
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
#!/bin/sh
|
||||
# KhOS - Wrapper dla plasma_waitforname zapobiegajacy blokowaniu uruchamiania pulpitu KDE
|
||||
# W maszynach wirtualnych i przy renderowaniu programowym ksplashqml potrafi wisiec,
|
||||
# blokujac start sesji Plasma na kilka minut.
|
||||
|
||||
if [ "$1" = "org.kde.KSplash" ] || [ -z "$1" ]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ -x /usr/bin/plasma_waitforname.real ]; then
|
||||
exec /usr/bin/plasma_waitforname.real "$@"
|
||||
fi
|
||||
|
||||
exit 0
|
||||
|
||||
+16
-10
@@ -4,7 +4,7 @@ if [ -x /usr/local/bin/pomoc ]; then
|
||||
else
|
||||
cat << 'EOF'
|
||||
╔══════════════════════════════════════════════╗
|
||||
║ KhOS 1.0 - Pomoc ║
|
||||
║ KhOS 1.1 - Pomoc ║
|
||||
╠══════════════════════════════════════════════╣
|
||||
║ ║
|
||||
║ PODSTAWOWE KOMENDY: ║
|
||||
@@ -21,6 +21,7 @@ else
|
||||
║ ifconfig - konfiguracja sieci ║
|
||||
║ ping - test polaczenia ║
|
||||
║ wget - pobieranie plikow ║
|
||||
║ curl - pobieranie / transfer danych ║
|
||||
║ route - tablica routingu ║
|
||||
║ ║
|
||||
║ SYSTEM: ║
|
||||
@@ -31,11 +32,16 @@ else
|
||||
║ mount - zamontowane systemy plikow ║
|
||||
║ reboot - restart systemu ║
|
||||
║ poweroff - wylaczenie systemu ║
|
||||
║ INSTALACJA I GRAFIKA: ║
|
||||
║ khos-installer - instalator na dysk ║
|
||||
║ start-hyprland - pulpit Hyprland Wayland ║
|
||||
║ start-openbox - pulpit Openbox X11 ║
|
||||
║ start-plasma - pulpit KDE Plasma Wayland ║
|
||||
║ ║
|
||||
║ INSTALACJA I AKTUALIZACJA: ║
|
||||
║ khos-installer - instalator systemu na dysk ║
|
||||
║ khos-update - aktualizacja z obrazu ISO ║
|
||||
║ ║
|
||||
║ SRODOWISKA GRAFICZNE: ║
|
||||
║ start-xfce - pulpit XFCE 4 (domyslny, X11)║
|
||||
║ start-plasma - pulpit KDE Plasma (Wayland)║
|
||||
║ start-hyprland - pulpit Hyprland (Wayland) ║
|
||||
║ start-openbox - pulpit Openbox (X11) ║
|
||||
║ ║
|
||||
║ MENEDZER PAKIETOW (wpkg): ║
|
||||
║ wpkg search <nazwa> - szukanie pakietu ║
|
||||
@@ -44,15 +50,15 @@ else
|
||||
║ wpkg list - lista zainstalowanych║
|
||||
║ wpkg update - aktualizacja bazy ║
|
||||
║ ║
|
||||
║ UZYTKOWNICY: ║
|
||||
║ ADMINISTRACJA I UZYTKOWNICY: ║
|
||||
║ sudo - uruchomienie jako administrator ║
|
||||
║ su - przelaczenie uzytkownika ║
|
||||
║ passwd - zmiana hasla ║
|
||||
║ su - zmiana uzytkownika ║
|
||||
║ adduser - dodanie uzytkownika ║
|
||||
║ ║
|
||||
║ Uzytkownik: live / Haslo: live ║
|
||||
║ Uzytkownik: live / Haslo: live (ma sudo) ║
|
||||
║ Root: root / Haslo: khos ║
|
||||
║ ║
|
||||
╚══════════════════════════════════════════════╝
|
||||
EOF
|
||||
fi
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/bin/sh
|
||||
# KhOS - Skrypt startowy Hyprland (Wayland)
|
||||
# Zoptymalizowany pod katem stabilnosci i eliminacji gliczow graficznych
|
||||
# Zoptymalizowany pod katem stabilnosci i obslugi uzytkownika nieuprzywilejowanego
|
||||
|
||||
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
|
||||
|
||||
@@ -29,15 +29,41 @@ fi
|
||||
mkdir -p "$XDG_RUNTIME_DIR"
|
||||
chmod 0700 "$XDG_RUNTIME_DIR"
|
||||
|
||||
# --- Sterowniki DRM/KMS ---
|
||||
# --- Szyna sesyjna D-Bus ---
|
||||
if [ -z "$DBUS_SESSION_BUS_ADDRESS" ]; then
|
||||
if command -v dbus-run-session >/dev/null 2>&1; then
|
||||
exec dbus-run-session -- "$0" "$@"
|
||||
fi
|
||||
fi
|
||||
|
||||
# --- Sterowniki DRM/KMS i uprawnienia ---
|
||||
if [ "$UID_NOW" -eq 0 ]; then
|
||||
mkdir -p /dev/dri /dev/input
|
||||
chmod 755 /dev/dri /dev/input 2>/dev/null || true
|
||||
chmod 666 /dev/dri/* 2>/dev/null || true
|
||||
chmod 660 /dev/input/* 2>/dev/null || true
|
||||
elif command -v sudo >/dev/null 2>&1; then
|
||||
sudo chmod 755 /dev/dri /dev/input 2>/dev/null || true
|
||||
sudo chmod 666 /dev/dri/* 2>/dev/null || true
|
||||
sudo chmod 660 /dev/input/* 2>/dev/null || true
|
||||
fi
|
||||
|
||||
if ! ls /dev/dri/card* >/dev/null 2>&1; then
|
||||
info "Ladowanie modulow jadra dla grafiki (DRM/KMS)..."
|
||||
for m in drm vmwgfx vboxvideo bochs virtio-gpu qxl simpledrm; do
|
||||
modprobe "$m" 2>/dev/null
|
||||
done
|
||||
mdev -s 2>/dev/null
|
||||
if [ "$UID_NOW" -eq 0 ]; then
|
||||
info "Ladowanie modulow jadra dla grafiki (DRM/KMS)..."
|
||||
for m in drm vmwgfx vboxvideo bochs virtio-gpu qxl simpledrm; do
|
||||
modprobe "$m" 2>/dev/null
|
||||
done
|
||||
mdev -s 2>/dev/null
|
||||
chmod 755 /dev/dri /dev/input 2>/dev/null || true
|
||||
chmod 666 /dev/dri/* 2>/dev/null || true
|
||||
elif command -v sudo >/dev/null 2>&1; then
|
||||
sudo modprobe -a drm vmwgfx vboxvideo bochs virtio-gpu qxl simpledrm 2>/dev/null || true
|
||||
sudo chmod 755 /dev/dri /dev/input 2>/dev/null || true
|
||||
sudo chmod 666 /dev/dri/* 2>/dev/null || true
|
||||
fi
|
||||
i=0
|
||||
while [ $i -lt 10 ] && ! ls /dev/dri/card* >/dev/null 2>&1; do
|
||||
while [ $i -lt 5 ] && ! ls /dev/dri/card* >/dev/null 2>&1; do
|
||||
sleep 1; i=$((i + 1))
|
||||
done
|
||||
fi
|
||||
@@ -130,6 +156,9 @@ if ! pidof seatd >/dev/null 2>&1; then
|
||||
if [ "$UID_NOW" -eq 0 ]; then
|
||||
info "Uruchamianie uslugi seatd..."
|
||||
seatd -g video >/tmp/seatd.log 2>&1 &
|
||||
elif command -v sudo >/dev/null 2>&1; then
|
||||
info "Uruchamianie uslugi seatd przez sudo..."
|
||||
sudo seatd -g video >/tmp/seatd.log 2>&1 &
|
||||
elif command -v seatd-launch >/dev/null 2>&1; then
|
||||
info "Uruchamianie przez seatd-launch..."
|
||||
LOG="$XDG_RUNTIME_DIR/hyprland-start.log"
|
||||
@@ -138,7 +167,7 @@ if ! pidof seatd >/dev/null 2>&1; then
|
||||
[ $rc -ne 0 ] && { err "Hyprland zakonczyl sie bledem ($rc). Log: $LOG"; tail -n 20 "$LOG"; }
|
||||
exit $rc
|
||||
else
|
||||
err "seatd nie dziala. Uruchom jako root lub dodaj sie do grupy video/seat."
|
||||
err "seatd nie dziala. Uruchom jako root lub uzyj sudo."
|
||||
exit 1
|
||||
fi
|
||||
i=0
|
||||
@@ -148,7 +177,7 @@ if ! pidof seatd >/dev/null 2>&1; then
|
||||
done
|
||||
fi
|
||||
|
||||
if [ ! -S "$SEATD_SOCK" ]; then
|
||||
if [ ! -S "$SEATD_SOCK" ] && ! command -v seatd-launch >/dev/null 2>&1; then
|
||||
err "seatd nie utworzyl gniazda $SEATD_SOCK. Log: /tmp/seatd.log"
|
||||
cat /tmp/seatd.log 2>/dev/null
|
||||
exit 1
|
||||
|
||||
+174
-57
@@ -1,75 +1,192 @@
|
||||
#!/bin/sh
|
||||
# KhOS - Skrypt startowy KDE Plasma 6 (Wayland)
|
||||
# Zoptymalizowany dla srodowiska bez systemd (BusyBox init) i dla uzytkownika zwyklego/live
|
||||
|
||||
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
|
||||
|
||||
echo "=== Uruchamianie KDE Plasma (KhOS) ==="
|
||||
info() { printf '\033[1;36m[INFO]\033[0m %s\n' "$*"; }
|
||||
warn() { printf '\033[1;33m[UWAGA]\033[0m %s\n' "$*"; }
|
||||
err() { printf '\033[1;31m[BLAD]\033[0m %s\n' "$*"; }
|
||||
|
||||
# 1. Zapewnij symlink qdbus -> qdbus6 jesli nie istnieje (wymagany przez startplasmacompositor)
|
||||
if ! command -v qdbus >/dev/null 2>&1; then
|
||||
if command -v qdbus6 >/dev/null 2>&1; then
|
||||
ln -sf "$(command -v qdbus6)" /usr/bin/qdbus 2>/dev/null || true
|
||||
elif [ -x /usr/lib/qt6/bin/qdbus ]; then
|
||||
ln -sf /usr/lib/qt6/bin/qdbus /usr/bin/qdbus 2>/dev/null || true
|
||||
fi
|
||||
fi
|
||||
if ! command -v qdbusviewer >/dev/null 2>&1 && command -v qdbusviewer6 >/dev/null 2>&1; then
|
||||
ln -sf "$(command -v qdbusviewer6)" /usr/bin/qdbusviewer 2>/dev/null || true
|
||||
fi
|
||||
echo "=== Uruchamianie KDE Plasma 6 (KhOS) ==="
|
||||
|
||||
# 2. Katalog wykonawczy XDG (XDG_RUNTIME_DIR)
|
||||
UID_NOW="$(id -u)"
|
||||
export XDG_RUNTIME_DIR="/tmp/runtime-${UID_NOW}"
|
||||
|
||||
# 1. Katalog wykonawczy XDG (XDG_RUNTIME_DIR)
|
||||
if [ -z "$XDG_RUNTIME_DIR" ] || [ ! -d "$XDG_RUNTIME_DIR" ]; then
|
||||
export XDG_RUNTIME_DIR="/tmp/runtime-${UID_NOW}"
|
||||
fi
|
||||
mkdir -p "$XDG_RUNTIME_DIR"
|
||||
chmod 0700 "$XDG_RUNTIME_DIR"
|
||||
|
||||
# 3. Zapewnij machine-id dla D-Bus i Qt (wymagane przez KDE)
|
||||
mkdir -p /etc /var/lib/dbus /var/run/dbus /run/dbus
|
||||
if [ ! -s /etc/machine-id ] && [ ! -s /var/lib/dbus/machine-id ]; then
|
||||
if command -v dbus-uuidgen >/dev/null 2>&1; then
|
||||
dbus-uuidgen --ensure=/etc/machine-id 2>/dev/null || dbus-uuidgen > /etc/machine-id 2>/dev/null || true
|
||||
fi
|
||||
if [ ! -s /etc/machine-id ]; then
|
||||
cat /proc/sys/kernel/random/boot_id 2>/dev/null | tr -d '-' > /etc/machine-id 2>/dev/null || echo "0123456789abcdef0123456789abcdef" > /etc/machine-id
|
||||
fi
|
||||
ln -sf /etc/machine-id /var/lib/dbus/machine-id 2>/dev/null || true
|
||||
fi
|
||||
# 2. Katalogi dla gniazd Xwayland i ICE
|
||||
mkdir -p /tmp/.X11-unix /tmp/.ICE-unix
|
||||
chmod 1777 /tmp/.X11-unix /tmp/.ICE-unix 2>/dev/null || true
|
||||
|
||||
# 4. Uruchom systemowy demon D-Bus jesli nie dziala
|
||||
if command -v dbus-daemon >/dev/null 2>&1; then
|
||||
if [ ! -S /var/run/dbus/system_bus_socket ] && [ ! -S /run/dbus/system_bus_socket ]; then
|
||||
dbus-daemon --system --fork 2>/dev/null || true
|
||||
fi
|
||||
fi
|
||||
|
||||
# 5. Wykrywanie wirtualizacji / wymuszenie programowego renderowania
|
||||
if grep -qi 'hypervisor' /proc/cpuinfo 2>/dev/null || [ "${KHOS_SW_RENDER:-0}" = "1" ] || [ ! -e /dev/dri/card0 ]; then
|
||||
echo "[INFO] Wymuszanie programowego renderowania (llvmpipe)..."
|
||||
export LIBGL_ALWAYS_SOFTWARE=1
|
||||
export GALLIUM_DRIVER=llvmpipe
|
||||
export QT_QUICK_BACKEND=software
|
||||
fi
|
||||
|
||||
export XDG_CURRENT_DESKTOP=KDE
|
||||
export XDG_SESSION_TYPE=wayland
|
||||
export XDG_SESSION_DESKTOP=KDE
|
||||
export QT_QPA_PLATFORM=wayland
|
||||
export GDK_BACKEND=wayland
|
||||
export KDE_FULL_SESSION=true
|
||||
|
||||
# 6. Jesli sesja D-Bus nie jest aktywna, uruchom wewnatrz dbus-run-session
|
||||
# 3. Szyna sesyjna D-Bus (krytyczna dla KDE i aplikacji Wayland)
|
||||
if [ -z "$DBUS_SESSION_BUS_ADDRESS" ]; then
|
||||
if command -v dbus-run-session >/dev/null 2>&1; then
|
||||
exec dbus-run-session -- "$0" "$@"
|
||||
fi
|
||||
fi
|
||||
|
||||
# 7. Uruchomienie kompozytora i srodowiska Plasma
|
||||
if command -v startplasma-wayland >/dev/null 2>&1; then
|
||||
exec startplasma-wayland "$@"
|
||||
elif command -v kwin_wayland >/dev/null 2>&1; then
|
||||
exec kwin_wayland --no-lockscreen --exit-with-session plasmashell
|
||||
else
|
||||
echo "[BLAD] Nie znaleziono plikow wykonywalnych KDE Plasma!"
|
||||
exit 1
|
||||
# 4. Zapewnij machine-id jesli brak
|
||||
if [ ! -s /etc/machine-id ] && [ "$UID_NOW" -eq 0 ]; then
|
||||
if command -v dbus-uuidgen >/dev/null 2>&1; then
|
||||
dbus-uuidgen --ensure=/etc/machine-id 2>/dev/null || true
|
||||
fi
|
||||
if [ ! -s /etc/machine-id ]; then
|
||||
echo "0123456789abcdef0123456789abcdef" > /etc/machine-id 2>/dev/null || true
|
||||
fi
|
||||
fi
|
||||
|
||||
|
||||
# 5. Sterowniki DRM/KMS i uprawnienia do wezlow graficznych
|
||||
if [ "$UID_NOW" -eq 0 ]; then
|
||||
mkdir -p /dev/dri /dev/input
|
||||
chmod 755 /dev/dri /dev/input 2>/dev/null || true
|
||||
chmod 666 /dev/dri/* 2>/dev/null || true
|
||||
chmod 660 /dev/input/* 2>/dev/null || true
|
||||
elif command -v sudo >/dev/null 2>&1; then
|
||||
sudo chmod 755 /dev/dri /dev/input 2>/dev/null || true
|
||||
sudo chmod 666 /dev/dri/* 2>/dev/null || true
|
||||
sudo chmod 660 /dev/input/* 2>/dev/null || true
|
||||
fi
|
||||
|
||||
if ! ls /dev/dri/card* >/dev/null 2>&1; then
|
||||
if [ "$UID_NOW" -eq 0 ]; then
|
||||
info "Ladowanie modulow DRM/KMS..."
|
||||
for m in radeon amdgpu drm vmwgfx vboxvideo bochs virtio-gpu qxl simpledrm; do
|
||||
modprobe "$m" 2>/dev/null || true
|
||||
done
|
||||
mdev -s 2>/dev/null || true
|
||||
chmod 755 /dev/dri /dev/input 2>/dev/null || true
|
||||
chmod 666 /dev/dri/* 2>/dev/null || true
|
||||
elif command -v sudo >/dev/null 2>&1; then
|
||||
sudo modprobe -a radeon amdgpu drm vmwgfx vboxvideo bochs virtio-gpu qxl simpledrm 2>/dev/null || true
|
||||
sudo chmod 755 /dev/dri /dev/input 2>/dev/null || true
|
||||
sudo chmod 666 /dev/dri/* 2>/dev/null || true
|
||||
fi
|
||||
fi
|
||||
|
||||
# 6. Demon zarzadzania sesja (seatd)
|
||||
SEATD_SOCK=/run/seatd.sock
|
||||
if ! pidof seatd >/dev/null 2>&1; then
|
||||
rm -f "$SEATD_SOCK"
|
||||
if [ "$UID_NOW" -eq 0 ]; then
|
||||
seatd -g video >/tmp/seatd.log 2>&1 &
|
||||
elif command -v sudo >/dev/null 2>&1; then
|
||||
sudo seatd -g video >/tmp/seatd.log 2>&1 &
|
||||
fi
|
||||
i=0
|
||||
while [ $i -lt 15 ] && [ ! -S "$SEATD_SOCK" ]; do
|
||||
sleep 0.2 2>/dev/null || sleep 1
|
||||
i=$((i + 1))
|
||||
done
|
||||
fi
|
||||
|
||||
# 7. Wykrywanie parametrow jadra, wirtualizacji i konfiguracja renderowania
|
||||
for param in $(cat /proc/cmdline 2>/dev/null); do
|
||||
case "$param" in
|
||||
nomodeset|radeon.modeset=0|swrender|swrender=1|safe|safegraphics)
|
||||
KHOS_SW_RENDER=1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
IS_VM=0
|
||||
if grep -qi 'hypervisor' /proc/cpuinfo 2>/dev/null; then
|
||||
IS_VM=1
|
||||
elif [ -e /sys/class/dmi/id/sys_vendor ] && grep -qi 'qemu\|kvm\|virtualbox\|innotek\|vmware\|xen\|bochs\|parallels' /sys/class/dmi/id/sys_vendor /sys/class/dmi/id/product_name 2>/dev/null; then
|
||||
IS_VM=1
|
||||
fi
|
||||
|
||||
# Zapewnij maksymalna jasnosc podswietlenia matrycy laptopa (HP ProBook itp.)
|
||||
for bl in /sys/class/backlight/*; do
|
||||
if [ -d "$bl" ]; then
|
||||
max=$(cat "$bl/max_brightness" 2>/dev/null || echo 100)
|
||||
echo "$max" > "$bl/brightness" 2>/dev/null || true
|
||||
fi
|
||||
done
|
||||
|
||||
# Inteligentne wykrywanie aktywnej karty graficznej (dla ukladow Dual GPU / APU + dGPU)
|
||||
ACTIVE_CARD=""
|
||||
for card_conn in /sys/class/drm/card*-*/status; do
|
||||
if [ -f "$card_conn" ] && grep -qi '^connected' "$card_conn" 2>/dev/null; then
|
||||
c_name=$(echo "$card_conn" | sed 's|/sys/class/drm/||; s|-.*||')
|
||||
if [ -c "/dev/dri/$c_name" ]; then
|
||||
ACTIVE_CARD="/dev/dri/$c_name"
|
||||
info "Wykryto aktywny wyswietlacz na karcie: $ACTIVE_CARD ($card_conn)"
|
||||
break
|
||||
fi
|
||||
fi
|
||||
done
|
||||
|
||||
if [ -n "$ACTIVE_CARD" ]; then
|
||||
export KWIN_DRM_DEVICES="$ACTIVE_CARD"
|
||||
elif [ -e /dev/dri/card0 ]; then
|
||||
export KWIN_DRM_DEVICES=/dev/dri/card0
|
||||
fi
|
||||
|
||||
if [ "$IS_VM" = "1" ] || [ "${KHOS_SW_RENDER:-0}" = "1" ] || [ ! -e /dev/dri/card0 ]; then
|
||||
info "Aktywacja bezpiecznego renderowania programowego (llvmpipe)."
|
||||
export LIBGL_ALWAYS_SOFTWARE=1
|
||||
export GALLIUM_DRIVER=llvmpipe
|
||||
fi
|
||||
|
||||
# 8. Zmienne srodowiskowe sesji KDE Plasma dla systemow bez systemd
|
||||
export KDE_SYSTEMD_BOOT=0
|
||||
export PLASMA_ENABLE_SYSTEMD=0
|
||||
export SEATD_SOCK=/run/seatd.sock
|
||||
export LIBSEAT_BACKEND=seatd
|
||||
export KWIN_COM_ALLOW_SOFTWARE=1
|
||||
export KWIN_WAYLAND_NO_LOCKSCREEN=1
|
||||
export KWIN_DRM_NO_ATOMIC=1
|
||||
export KWIN_DRM_NO_MODIFIERS=1
|
||||
export KWIN_FORCE_SW_CURSOR=1
|
||||
export WLR_NO_HARDWARE_CURSORS=1
|
||||
export WLR_RENDERER_ALLOW_SOFTWARE=1
|
||||
export XDG_CURRENT_DESKTOP=KDE
|
||||
export XDG_SESSION_TYPE=wayland
|
||||
export XDG_SESSION_DESKTOP=KDE
|
||||
export GDK_BACKEND=wayland
|
||||
export KDE_FULL_SESSION=true
|
||||
export XCURSOR_SIZE=24
|
||||
export QT_QPA_PLATFORMTHEME=kde
|
||||
|
||||
# Zapewnij wylaczenie splash screen w konfiguracji uzytkownika (zapobiega zawieszaniu sie ksplashqml w VM)
|
||||
mkdir -p "$HOME/.config"
|
||||
if [ ! -f "$HOME/.config/kdeglobals" ] && [ -f /etc/xdg/kdeglobals ]; then
|
||||
cp /etc/xdg/kdeglobals "$HOME/.config/kdeglobals" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
# WAZNE: kwin_wayland jest kompozytorem (serwerem Wayland), a nie klientem.
|
||||
# Ustawienie QT_QPA_PLATFORM=wayland przed startem KWin powoduje blad inicjalizacji Qt.
|
||||
unset QT_QPA_PLATFORM
|
||||
|
||||
# Aktualizacja zmiennych w srodowisku aktywacji D-Bus
|
||||
if command -v dbus-update-activation-environment >/dev/null 2>&1; then
|
||||
dbus-update-activation-environment --all 2>/dev/null || true
|
||||
fi
|
||||
|
||||
# 9. Uruchomienie srodowiska
|
||||
# W systemach bez systemd bezposrednie uruchomienie kwin_wayland z sesja plasmashell
|
||||
# jest natychmiastowe i w 100% niezawodne. Jesli kompozytor napotka blad sterownika GPU,
|
||||
# automatycznie wznawia sesje z renderowaniem programowym llvmpipe.
|
||||
info "Uruchamianie kompozytora KWin Wayland oraz powloki Plasma..."
|
||||
|
||||
if command -v kwin_wayland >/dev/null 2>&1; then
|
||||
kwin_wayland --no-lockscreen --xwayland --exit-with-session /usr/bin/plasmashell || {
|
||||
warn "KWin napotkal problem ze sterownikiem GPU. Wznawianie w trybie awaryjnym (llvmpipe)..."
|
||||
export LIBGL_ALWAYS_SOFTWARE=1
|
||||
export GALLIUM_DRIVER=llvmpipe
|
||||
exec kwin_wayland --no-lockscreen --xwayland --exit-with-session /usr/bin/plasmashell
|
||||
}
|
||||
elif command -v startplasma-wayland >/dev/null 2>&1; then
|
||||
exec startplasma-wayland "$@"
|
||||
elif command -v start-hyprland >/dev/null 2>&1; then
|
||||
warn "Brak KWin. Uruchamianie kompozytora Hyprland..."
|
||||
exec start-hyprland
|
||||
else
|
||||
err "Nie znaleziono plikow wykonywalnych kwin_wayland ani start-hyprland!"
|
||||
exit 1
|
||||
fi
|
||||
@@ -0,0 +1,136 @@
|
||||
#!/bin/sh
|
||||
# KhOS - Skrypt startowy srodowiska XFCE 4 (X11)
|
||||
# Domyslne, stabilne srodowisko graficzne dla komputerow PC i laptopow (m.in. HP ProBook 4545s)
|
||||
|
||||
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:$PATH"
|
||||
export XDG_CURRENT_DESKTOP=XFCE
|
||||
export XDG_SESSION_DESKTOP=xfce
|
||||
export XDG_SESSION_TYPE=x11
|
||||
|
||||
info() { printf '\033[1;36m[INFO]\033[0m %s\n' "$*"; }
|
||||
warn() { printf '\033[1;33m[UWAGA]\033[0m %s\n' "$*"; }
|
||||
err() { printf '\033[1;31m[BLAD]\033[0m %s\n' "$*"; }
|
||||
|
||||
echo "=== Uruchamianie srodowiska XFCE 4 (KhOS X11) ==="
|
||||
|
||||
UID_NOW="$(id -u)"
|
||||
|
||||
# 1. Czyszczenie starych blokad X11 z poprzednich sesji
|
||||
rm -f /tmp/.X0-lock /tmp/.X11-unix/X0 2>/dev/null || true
|
||||
unset DISPLAY
|
||||
|
||||
# 2. Katalog wykonawczy XDG (XDG_RUNTIME_DIR)
|
||||
if [ -z "$XDG_RUNTIME_DIR" ] || [ ! -d "$XDG_RUNTIME_DIR" ]; then
|
||||
export XDG_RUNTIME_DIR="/tmp/runtime-${UID_NOW}"
|
||||
fi
|
||||
mkdir -p "$XDG_RUNTIME_DIR"
|
||||
chmod 0700 "$XDG_RUNTIME_DIR"
|
||||
|
||||
# 3. Katalogi gniazd X11 i ICE
|
||||
mkdir -p /tmp/.X11-unix /tmp/.ICE-unix
|
||||
chmod 1777 /tmp/.X11-unix /tmp/.ICE-unix 2>/dev/null || true
|
||||
|
||||
# 4. Szyna sesyjna D-Bus (krytyczna dla XFCE, paneli, wygaszacza i xfconf)
|
||||
if [ -z "$DBUS_SESSION_BUS_ADDRESS" ]; then
|
||||
if command -v dbus-run-session >/dev/null 2>&1; then
|
||||
exec dbus-run-session -- "$0" "$@"
|
||||
fi
|
||||
fi
|
||||
|
||||
# 5. Zapewnij machine-id jesli brak
|
||||
if [ ! -s /etc/machine-id ] && [ "$UID_NOW" -eq 0 ]; then
|
||||
if command -v dbus-uuidgen >/dev/null 2>&1; then
|
||||
dbus-uuidgen --ensure=/etc/machine-id 2>/dev/null || true
|
||||
fi
|
||||
if [ ! -s /etc/machine-id ]; then
|
||||
echo "0123456789abcdef0123456789abcdef" > /etc/machine-id 2>/dev/null || true
|
||||
fi
|
||||
fi
|
||||
|
||||
# 6. Uprawnienia do wezlow DRM/KMS i urzadzen wejscia
|
||||
if [ "$UID_NOW" -eq 0 ]; then
|
||||
mkdir -p /dev/dri /dev/input
|
||||
chmod 755 /dev/dri /dev/input 2>/dev/null || true
|
||||
chmod 666 /dev/dri/* 2>/dev/null || true
|
||||
chmod 660 /dev/input/* 2>/dev/null || true
|
||||
elif command -v sudo >/dev/null 2>&1; then
|
||||
sudo chmod 755 /dev/dri /dev/input 2>/dev/null || true
|
||||
sudo chmod 666 /dev/dri/* 2>/dev/null || true
|
||||
sudo chmod 660 /dev/input/* 2>/dev/null || true
|
||||
fi
|
||||
|
||||
# 7. Ladowanie modulow DRM/KMS (w tym radeon / amdgpu dla HP ProBook 4545s)
|
||||
if [ ! -e /dev/dri/card0 ]; then
|
||||
if [ "$UID_NOW" -eq 0 ]; then
|
||||
info "Inicjalizacja sterownikow DRM/KMS..."
|
||||
for m in radeon amdgpu drm vmwgfx vboxvideo bochs virtio-gpu qxl simpledrm; do
|
||||
modprobe "$m" 2>/dev/null || true
|
||||
done
|
||||
mdev -s 2>/dev/null || true
|
||||
chmod 755 /dev/dri /dev/input 2>/dev/null || true
|
||||
chmod 666 /dev/dri/* 2>/dev/null || true
|
||||
elif command -v sudo >/dev/null 2>&1; then
|
||||
sudo modprobe -a radeon amdgpu drm vmwgfx vboxvideo bochs virtio-gpu qxl simpledrm 2>/dev/null || true
|
||||
sudo chmod 755 /dev/dri /dev/input 2>/dev/null || true
|
||||
sudo chmod 666 /dev/dri/* 2>/dev/null || true
|
||||
fi
|
||||
fi
|
||||
|
||||
# 8. Upewnij sie, ze podswietlenie matrycy laptopa jest wlaczone (maksymalna jasnosc)
|
||||
for bl in /sys/class/backlight/*; do
|
||||
if [ -d "$bl" ]; then
|
||||
max=$(cat "$bl/max_brightness" 2>/dev/null || echo 100)
|
||||
echo "$max" > "$bl/brightness" 2>/dev/null || true
|
||||
fi
|
||||
done
|
||||
|
||||
# 9. Przygotowanie domyslnych katalogow konfiguracyjnych XFCE dla uzytkownika
|
||||
mkdir -p "$HOME/.config/xfce4" "$HOME/.config/menus" 2>/dev/null || true
|
||||
|
||||
# Flagi startowe serwera Xorg
|
||||
XORG_ARGS="-keeptty"
|
||||
|
||||
# 10. Start sesji XFCE 4
|
||||
info "Uruchamianie serwera Xorg i sesji XFCE 4..."
|
||||
|
||||
rm -f /tmp/.X0-lock /tmp/.X11-unix/X0 2>/dev/null || true
|
||||
unset DISPLAY
|
||||
|
||||
# Skrypt powłoki sesji z aktualizacją środowiska D-Bus w sesji X11
|
||||
SESSION_WRAPPER="/tmp/xfce-session-$$.sh"
|
||||
cat << 'EOF' > "$SESSION_WRAPPER"
|
||||
#!/bin/sh
|
||||
# Aktualizacja srodowiska D-Bus zapobiega 25-sekundowym opoznieniom paneli i ustawien
|
||||
if command -v dbus-update-activation-environment >/dev/null 2>&1; then
|
||||
dbus-update-activation-environment DISPLAY XAUTHORITY XDG_CURRENT_DESKTOP XDG_SESSION_TYPE 2>/dev/null || true
|
||||
fi
|
||||
CLIENTRC="/etc/xdg/xfce4/xinitrc"
|
||||
if [ ! -f "$CLIENTRC" ]; then
|
||||
if [ -x /usr/bin/xfce4-session ]; then
|
||||
CLIENTRC="/usr/bin/xfce4-session"
|
||||
elif [ -x /usr/bin/startxfce4 ]; then
|
||||
CLIENTRC="/usr/bin/startxfce4"
|
||||
fi
|
||||
fi
|
||||
if [ -f "$CLIENTRC" ]; then
|
||||
exec /bin/sh "$CLIENTRC"
|
||||
else
|
||||
exec /usr/bin/xfce4-session
|
||||
fi
|
||||
EOF
|
||||
chmod +x "$SESSION_WRAPPER"
|
||||
|
||||
if command -v xinit >/dev/null 2>&1; then
|
||||
exec xinit "$SESSION_WRAPPER" -- :0 vt1 -novtswitch -sharevts $XORG_ARGS
|
||||
elif command -v Xorg >/dev/null 2>&1; then
|
||||
Xorg :0 vt1 -novtswitch -sharevts $XORG_ARGS &
|
||||
export DISPLAY=:0
|
||||
for i in 1 2 3 4 5; do
|
||||
[ -e /tmp/.X11-unix/X0 ] && break
|
||||
sleep 0.2
|
||||
done
|
||||
exec /bin/sh "$SESSION_WRAPPER"
|
||||
else
|
||||
err "Nie znaleziono xinit ani Xorg! Zainstaluj pakiet xfce4: wpkg install xfce4"
|
||||
exit 1
|
||||
fi
|
||||
@@ -0,0 +1,3 @@
|
||||
#!/bin/sh
|
||||
exec /usr/bin/khos-update "$@"
|
||||
|
||||
Binary file not shown.
+165
-6
@@ -19,6 +19,7 @@ YES=0
|
||||
FORCE=0
|
||||
COMMAND=""
|
||||
TARGET=""
|
||||
ISO_ARG=""
|
||||
|
||||
# --- Kolory ANSI ---
|
||||
C_RESET='\033[0m'
|
||||
@@ -45,7 +46,7 @@ acquire_lock() {
|
||||
case "$COMMAND" in
|
||||
install|remove|upgrade|update|clean)
|
||||
if [ "$(id -u 2>/dev/null)" != "0" ] && [ -z "$WPKG_ROOT" ]; then
|
||||
die "Ta operacja wymaga uprawnień administratora (root). Zaloguj się jako root lub użyj 'su'."
|
||||
die "Ta operacja wymaga uprawnień administratora (root). Użyj 'sudo wpkg $COMMAND $TARGET' lub zaloguj się jako root."
|
||||
fi
|
||||
if ! mkdir "$LOCK_DIR" 2>/dev/null; then
|
||||
local old_pid=""
|
||||
@@ -80,15 +81,18 @@ ver_gt() {
|
||||
[ "$highest" = "$1" ]
|
||||
}
|
||||
|
||||
# Pobieranie pliku z obsługą curl / wget (bezpieczny TLS bez segfaultów)
|
||||
# Pobieranie pliku z obsługą curl / wget z weryfikacją TLS
|
||||
wpkg_download() {
|
||||
local url="$1"
|
||||
local dest="$2"
|
||||
rm -f "$dest" 2>/dev/null
|
||||
local ca_opt=""
|
||||
[ -f /etc/ssl/certs/ca-certificates.crt ] && ca_opt="--cacert /etc/ssl/certs/ca-certificates.crt"
|
||||
|
||||
if command -v curl >/dev/null 2>&1; then
|
||||
curl -fsSL --insecure -o "$dest" "$url" 2>/dev/null
|
||||
curl -fsSL $ca_opt -o "$dest" "$url" 2>/dev/null || curl -fsSL -o "$dest" "$url" 2>/dev/null
|
||||
elif command -v wget >/dev/null 2>&1; then
|
||||
wget -q --no-check-certificate -O "$dest" "$url" 2>/dev/null || wget -q -O "$dest" "$url" 2>/dev/null
|
||||
wget -q -O "$dest" "$url" 2>/dev/null
|
||||
else
|
||||
return 1
|
||||
fi
|
||||
@@ -145,7 +149,9 @@ Komendy:
|
||||
install <pakiet|plik> Instaluje pakiet z repozytorium lub lokalnego pliku .wpkg
|
||||
remove <pakiet> Usuwa zainstalowany pakiet
|
||||
update Aktualizuje bazę pakietów (packages.db) z repozytoriów
|
||||
update-from-iso [iso] Aktualizuje bazę i pamięć podręczną pakietów bezpośrednio z obrazu ISO
|
||||
upgrade Aktualizuje wszystkie zainstalowane pakiety do nowszych wersji
|
||||
system-upgrade [iso] Wykonuje pełną aktualizację jądra i systemu operacyjnego z ISO
|
||||
search <fraza> Wyszukuje pakiety w bazie po nazwie lub opisie
|
||||
list Wyświetla listę aktualnie zainstalowanych pakietów
|
||||
info <pakiet> Wyświetla szczegółowe informacje o pakiecie
|
||||
@@ -158,6 +164,7 @@ Komendy:
|
||||
Opcje:
|
||||
-y, --yes Automatyczna akceptacja pytań (tryb nieinteraktywny)
|
||||
-f, --force Wymuś operację (ignorowanie zależności / wersji)
|
||||
--iso <ścieżka> Wskazuje plik ISO jako źródło pakietów lub aktualizacji
|
||||
EOF
|
||||
}
|
||||
|
||||
@@ -168,7 +175,11 @@ cmd_clean() {
|
||||
}
|
||||
|
||||
cmd_update() {
|
||||
msg "Aktualizacja bazy pakietów..."
|
||||
if [ -n "$ISO_ARG" ]; then
|
||||
cmd_update_from_iso "$ISO_ARG"
|
||||
return 0
|
||||
fi
|
||||
msg "Aktualizacja bazy pakietów z sieci..."
|
||||
if [ ! -f "$ETC_CONF" ]; then
|
||||
die "Brak pliku konfiguracyjnego repozytoriów: $ETC_CONF"
|
||||
fi
|
||||
@@ -202,7 +213,7 @@ cmd_update() {
|
||||
done < "$ETC_CONF"
|
||||
|
||||
if [ "$success_count" -eq 0 ] && [ ! -s "$temp_db" ]; then
|
||||
die "Nie udało się zaktualizować bazy z żadnego repozytorium! Sprawdź połączenie z siecią (np. 'ping -c 3 8.8.8.8')."
|
||||
die "Nie udało się zaktualizować bazy z żadnego repozytorium! Sprawdź połączenie z siecią (np. 'ping -c 3 8.8.8.8') lub użyj 'wpkg update-from-iso'."
|
||||
fi
|
||||
|
||||
mv "$temp_db" "$DB_FILE"
|
||||
@@ -210,6 +221,116 @@ cmd_update() {
|
||||
ok "Baza pakietów została zaktualizowana (dostępnych pakietów w bazie: $total_pkgs)."
|
||||
}
|
||||
|
||||
cmd_update_from_iso() {
|
||||
local iso_target="$1"
|
||||
local iso_mnt="${TMP_DIR}/iso_mnt_$$"
|
||||
local cleanup_iso_mnt=0
|
||||
|
||||
if [ -z "$iso_target" ]; then
|
||||
# Automatyczne szukanie ISO lub nośnika CD-ROM
|
||||
for cand in /mnt/cdrom /run/media/*; do
|
||||
if [ -d "$cand/packages" ] || [ -f "$cand/live/filesystem.squashfs" ]; then
|
||||
iso_target="$cand"
|
||||
break
|
||||
fi
|
||||
done
|
||||
if [ -z "$iso_target" ]; then
|
||||
for f in / /root /home/* /tmp; do
|
||||
for isof in "$f"/khos*.iso "$f"/wlasnyos*.iso "$f"/*.iso; do
|
||||
if [ -f "$isof" ]; then
|
||||
iso_target="$isof"
|
||||
break 2
|
||||
fi
|
||||
done
|
||||
done
|
||||
fi
|
||||
fi
|
||||
|
||||
[ -z "$iso_target" ] && die "Podaj ścieżkę do pliku ISO lub zamontowanego nośnika (np. 'wpkg update-from-iso /root/khos-1.1.0-x86_64.iso')."
|
||||
|
||||
local src_pkg_dir=""
|
||||
local src_db=""
|
||||
|
||||
if [ -d "$iso_target" ]; then
|
||||
if [ -d "${iso_target}/packages" ]; then
|
||||
src_pkg_dir="${iso_target}/packages"
|
||||
[ -f "${src_pkg_dir}/PACKAGES.db" ] && src_db="${src_pkg_dir}/PACKAGES.db"
|
||||
else
|
||||
src_pkg_dir="$iso_target"
|
||||
[ -f "${src_pkg_dir}/PACKAGES.db" ] && src_db="${src_pkg_dir}/PACKAGES.db"
|
||||
fi
|
||||
elif [ -f "$iso_target" ]; then
|
||||
msg "Montowanie obrazu ISO: $iso_target..."
|
||||
mkdir -p "$iso_mnt"
|
||||
if mount -t iso9660 -o loop,ro "$iso_target" "$iso_mnt" 2>/dev/null || mount -o loop,ro "$iso_target" "$iso_mnt" 2>/dev/null; then
|
||||
cleanup_iso_mnt=1
|
||||
if [ -d "${iso_mnt}/packages" ]; then
|
||||
src_pkg_dir="${iso_mnt}/packages"
|
||||
[ -f "${src_pkg_dir}/PACKAGES.db" ] && src_db="${src_pkg_dir}/PACKAGES.db"
|
||||
elif [ -f "${iso_mnt}/PACKAGES.db" ]; then
|
||||
src_pkg_dir="$iso_mnt"
|
||||
src_db="${iso_mnt}/PACKAGES.db"
|
||||
fi
|
||||
else
|
||||
die "Nie udało się zamontować pliku ISO: $iso_target"
|
||||
fi
|
||||
else
|
||||
die "Wskazany plik lub katalog '$iso_target' nie istnieje!"
|
||||
fi
|
||||
|
||||
msg "Synchronizacja pakietów i bazy z nośnika ISO..."
|
||||
mkdir -p "$VAR_CACHE" "$VAR_LIB"
|
||||
|
||||
# Kopiowanie pakietów do lokalnego cache
|
||||
if [ -n "$src_pkg_dir" ] && [ -d "$src_pkg_dir" ]; then
|
||||
local copied=0
|
||||
for pkg_f in "$src_pkg_dir"/*.wpkg; do
|
||||
if [ -f "$pkg_f" ]; then
|
||||
cp -f "$pkg_f" "$VAR_CACHE/" 2>/dev/null && copied=$((copied + 1)) || true
|
||||
fi
|
||||
done
|
||||
ok "Skopiowano $copied pakietów z ISO do pamięci podręcznej ${VAR_CACHE}"
|
||||
fi
|
||||
|
||||
# Aktualizacja bazy
|
||||
if [ -n "$src_db" ] && [ -f "$src_db" ]; then
|
||||
tr -d '\r' < "$src_db" > "$DB_FILE"
|
||||
local total_pkgs=$(grep -c "^name=" "$DB_FILE" 2>/dev/null || echo 0)
|
||||
ok "Baza pakietów została zaktualizowana z ISO (dostępnych pakietów: $total_pkgs)."
|
||||
else
|
||||
info "Generowanie wpisów bazy pakietów z plików .wpkg w cache..."
|
||||
for pkg_f in "$VAR_CACHE"/*.wpkg; do
|
||||
[ ! -f "$pkg_f" ] && continue
|
||||
local bname=$(basename "$pkg_f")
|
||||
local p_name=$(echo "$bname" | sed 's/-[0-9].*//')
|
||||
if ! grep -q "^name=${p_name}$" "$DB_FILE" 2>/dev/null; then
|
||||
local p_sha=$(sha256sum "$pkg_f" | awk '{print $1}')
|
||||
local p_size=$(wc -c < "$pkg_f" | tr -d ' ')
|
||||
cat << EOF >> "$DB_FILE"
|
||||
name=${p_name}
|
||||
version=1.0
|
||||
release=1
|
||||
description=Pakiet z nośnika ISO ($bname)
|
||||
depends=
|
||||
arch=x86_64
|
||||
size=${p_size}
|
||||
filename=${bname}
|
||||
sha256=${p_sha}
|
||||
|
||||
EOF
|
||||
fi
|
||||
done
|
||||
local total_pkgs=$(grep -c "^name=" "$DB_FILE" 2>/dev/null || echo 0)
|
||||
ok "Zsynchronizowano bazę pakietów ($total_pkgs pakietów)."
|
||||
fi
|
||||
|
||||
if [ "$cleanup_iso_mnt" -eq 1 ]; then
|
||||
umount "$iso_mnt" 2>/dev/null || true
|
||||
rmdir "$iso_mnt" 2>/dev/null || true
|
||||
fi
|
||||
}
|
||||
|
||||
|
||||
cmd_search() {
|
||||
local query="$1"
|
||||
[ -z "$query" ] && die "Podaj frazę do wyszukania (np. 'wpkg search nano')."
|
||||
@@ -451,6 +572,16 @@ cmd_install() {
|
||||
pkg_file="${VAR_CACHE}/${cache_filename}"
|
||||
mkdir -p "$VAR_CACHE"
|
||||
|
||||
if [ ! -f "$pkg_file" ] || [ ! -s "$pkg_file" ]; then
|
||||
# Sprawdź czy pakiet znajduje się na lokalnym nośniku (np. ISO, CD-ROM, /packages)
|
||||
for local_cand in /mnt/cdrom/packages/"$cache_filename" /mnt/cdrom/"$cache_filename" /packages/"$cache_filename" /KhOS-packages/packages/"$cache_filename" /run/media/*/"$cache_filename" /run/media/*/packages/"$cache_filename"; do
|
||||
if [ -f "$local_cand" ]; then
|
||||
info "Znaleziono pakiet na nośniku lokalnym: $local_cand"
|
||||
cp -f "$local_cand" "$pkg_file" 2>/dev/null && break || true
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
if [ ! -f "$pkg_file" ] || [ ! -s "$pkg_file" ]; then
|
||||
msg "Pobieranie pakietu $pkg_name ($filename)..."
|
||||
local found_repo=0
|
||||
@@ -792,6 +923,11 @@ cmd_upgrade() {
|
||||
esac
|
||||
fi
|
||||
|
||||
if [ -n "$ISO_ARG" ]; then
|
||||
info "Wczytywanie pakietów z obrazu ISO przed wykonaniem aktualizacji..."
|
||||
cmd_update_from_iso "$ISO_ARG"
|
||||
fi
|
||||
|
||||
for pkg in $upgrades_avail; do
|
||||
cmd_install "$pkg"
|
||||
done
|
||||
@@ -805,8 +941,18 @@ while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
-y|--yes) YES=1; shift ;;
|
||||
-f|--force) FORCE=1; shift ;;
|
||||
--iso) ISO_ARG="$2"; shift 2; continue ;;
|
||||
--iso=*) ISO_ARG="${1#--iso=}"; shift; continue ;;
|
||||
-h|--help|-help|-\?|/\?) COMMAND="help"; shift ;;
|
||||
-*) die "Nieznana opcja: $1" ;;
|
||||
update-from-iso|update-iso)
|
||||
COMMAND="update_from_iso"
|
||||
shift
|
||||
;;
|
||||
system-upgrade|system_upgrade|upgrade-system)
|
||||
COMMAND="system_upgrade"
|
||||
shift
|
||||
;;
|
||||
*)
|
||||
if [ -z "$COMMAND" ]; then
|
||||
COMMAND="$1"
|
||||
@@ -827,6 +973,16 @@ case "$COMMAND" in
|
||||
help|"") cmd_help ;;
|
||||
clean) cmd_clean ;;
|
||||
update) cmd_update ;;
|
||||
update_from_iso|update-from-iso) cmd_update_from_iso "${TARGET:-$ISO_ARG}" ;;
|
||||
system_upgrade|system-upgrade)
|
||||
if [ -x "${WPKG_ROOT:-}/usr/bin/khos-update" ]; then
|
||||
exec "${WPKG_ROOT:-}/usr/bin/khos-update" "${TARGET:-$ISO_ARG}"
|
||||
elif [ -x /usr/bin/khos-update ]; then
|
||||
exec /usr/bin/khos-update "${TARGET:-$ISO_ARG}"
|
||||
else
|
||||
die "Brak narzędzia /usr/bin/khos-update do aktualizacji systemu z ISO."
|
||||
fi
|
||||
;;
|
||||
search) cmd_search "$TARGET" ;;
|
||||
list) cmd_list ;;
|
||||
info) cmd_info "$TARGET" ;;
|
||||
@@ -838,6 +994,9 @@ case "$COMMAND" in
|
||||
provides) cmd_provides "$TARGET" ;;
|
||||
install)
|
||||
[ -z "$TARGET" ] && die "Podaj nazwę pakietu do instalacji (np. 'wpkg install nano')."
|
||||
if [ -n "$ISO_ARG" ]; then
|
||||
cmd_update_from_iso "$ISO_ARG"
|
||||
fi
|
||||
for t in $TARGET; do
|
||||
cmd_install "$t"
|
||||
done
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
cat << 'EOF'
|
||||
╔══════════════════════════════════════════════╗
|
||||
║ KhOS 1.0 - Pomoc ║
|
||||
║ KhOS 1.1 - Pomoc ║
|
||||
╠══════════════════════════════════════════════╣
|
||||
║ ║
|
||||
║ PODSTAWOWE KOMENDY: ║
|
||||
@@ -20,6 +20,7 @@ cat << 'EOF'
|
||||
║ ifconfig - konfiguracja sieci ║
|
||||
║ ping - test polaczenia ║
|
||||
║ wget - pobieranie plikow ║
|
||||
║ curl - pobieranie / transfer danych ║
|
||||
║ route - tablica routingu ║
|
||||
║ ║
|
||||
║ SYSTEM: ║
|
||||
@@ -30,11 +31,16 @@ cat << 'EOF'
|
||||
║ mount - zamontowane systemy plikow ║
|
||||
║ reboot - restart systemu ║
|
||||
║ poweroff - wylaczenie systemu ║
|
||||
║ INSTALACJA I GRAFIKA: ║
|
||||
║ khos-installer - instalator na dysk ║
|
||||
║ start-hyprland - pulpit Hyprland Wayland ║
|
||||
║ start-openbox - pulpit Openbox X11 ║
|
||||
║ start-plasma - pulpit KDE Plasma Wayland ║
|
||||
║ ║
|
||||
║ INSTALACJA I AKTUALIZACJA: ║
|
||||
║ khos-installer - instalator systemu na dysk ║
|
||||
║ khos-update - aktualizacja z obrazu ISO ║
|
||||
║ ║
|
||||
║ SRODOWISKA GRAFICZNE: ║
|
||||
║ start-xfce - pulpit XFCE 4 (domyslny, X11)║
|
||||
║ start-plasma - pulpit KDE Plasma (Wayland)║
|
||||
║ start-hyprland - pulpit Hyprland (Wayland) ║
|
||||
║ start-openbox - pulpit Openbox (X11) ║
|
||||
║ ║
|
||||
║ MENEDZER PAKIETOW (wpkg): ║
|
||||
║ wpkg search <nazwa> - szukanie pakietu ║
|
||||
@@ -43,12 +49,13 @@ cat << 'EOF'
|
||||
║ wpkg list - lista zainstalowanych║
|
||||
║ wpkg update - aktualizacja bazy ║
|
||||
║ ║
|
||||
║ UZYTKOWNICY: ║
|
||||
║ ADMINISTRACJA I UZYTKOWNICY: ║
|
||||
║ sudo - uruchomienie jako administrator ║
|
||||
║ su - przelaczenie uzytkownika ║
|
||||
║ passwd - zmiana hasla ║
|
||||
║ su - zmiana uzytkownika ║
|
||||
║ adduser - dodanie uzytkownika ║
|
||||
║ ║
|
||||
║ Uzytkownik: live / Haslo: live ║
|
||||
║ Uzytkownik: live / Haslo: live (ma sudo) ║
|
||||
║ Root: root / Haslo: khos ║
|
||||
║ ║
|
||||
╚══════════════════════════════════════════════╝
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
[Desktop Entry]
|
||||
Version=1.0
|
||||
Type=Application
|
||||
Name=Zainstaluj KhOS
|
||||
Name[pl]=Zainstaluj KhOS
|
||||
Name[en]=Install KhOS
|
||||
GenericName=Instalator systemu KhOS
|
||||
GenericName[pl]=Instalator systemu KhOS
|
||||
GenericName[en]=KhOS System Installer
|
||||
Comment=Zainstaluj system KhOS na dysku twardym lub SSD (UEFI/BIOS)
|
||||
Comment[pl]=Zainstaluj system KhOS na dysku twardym lub SSD (UEFI/BIOS)
|
||||
Comment[en]=Install KhOS to a hard drive or SSD (UEFI/BIOS)
|
||||
Exec=khos-installer-gui
|
||||
Icon=system-software-install
|
||||
Terminal=false
|
||||
Categories=System;Utility;Settings;
|
||||
StartupNotify=true
|
||||
Keywords=installer;install;khos;system;dysk;instalator;setup;
|
||||
Actions=CLI;
|
||||
|
||||
[Desktop Action CLI]
|
||||
Name=Instalator w terminalu (tekstowy)
|
||||
Name[en]=Installer in Terminal (CLI)
|
||||
Exec=xfce4-terminal -e /usr/bin/khos-installer
|
||||
@@ -0,0 +1,19 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Launcher for KhOS GUI Installer from /usr/share/khos-installer/."""
|
||||
import sys
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
# Add installer/python or local directory to path
|
||||
for p in ["/usr/share/khos-installer", "/installer/python", str(Path(__file__).resolve().parent)]:
|
||||
if os.path.isdir(p) and p not in sys.path:
|
||||
sys.path.insert(0, p)
|
||||
|
||||
try:
|
||||
from khos_installer.gui import main
|
||||
sys.exit(main())
|
||||
except Exception as e:
|
||||
# If Python GUI fails or cannot load, fallback to CLI
|
||||
print(f"[UWAGA] Nie mozna uruchomic interfejsu graficznego: {e}")
|
||||
print("[INFO] Uruchamianie instalatora konsolowego /usr/bin/khos-installer...")
|
||||
os.execv("/usr/bin/khos-installer", ["khos-installer"] + sys.argv[1:])
|
||||
@@ -0,0 +1,30 @@
|
||||
"""KhOS System Installer package.
|
||||
|
||||
A modern, robust installation engine and user interface for KhOS.
|
||||
Supports both UEFI and BIOS, multiple desktop environments (XFCE, KDE Plasma, Hyprland, Openbox),
|
||||
GPT and MBR partitioning, CLI interactive/automated modes, and Tkinter GUI.
|
||||
"""
|
||||
|
||||
from .core import InstallerCore, ProgressCallback, ProgressEvent
|
||||
from .disk import BootMode, DiskInfo, DiskManager, PartitionInfo, detect_boot_mode
|
||||
from .partitioner import Partitioner, TargetPartitions
|
||||
from .types import DesktopEnvironment, InstallConfig
|
||||
|
||||
__version__ = "1.1.0"
|
||||
__author__ = "KhOS Team"
|
||||
|
||||
__all__ = [
|
||||
"InstallerCore",
|
||||
"InstallConfig",
|
||||
"BootMode",
|
||||
"DesktopEnvironment",
|
||||
"DiskInfo",
|
||||
"PartitionInfo",
|
||||
"TargetPartitions",
|
||||
"DiskManager",
|
||||
"Partitioner",
|
||||
"ProgressCallback",
|
||||
"ProgressEvent",
|
||||
"detect_boot_mode",
|
||||
"__version__",
|
||||
]
|
||||
@@ -0,0 +1,170 @@
|
||||
"""Data types, Enums, and Configuration models for KhOS Installer."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from enum import Enum
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
|
||||
class BootMode(str, Enum):
|
||||
"""System firmware boot mode."""
|
||||
UEFI = "uefi"
|
||||
BIOS = "bios"
|
||||
|
||||
@property
|
||||
def label(self) -> str:
|
||||
if self == BootMode.UEFI:
|
||||
return "UEFI (GPT)"
|
||||
return "BIOS (MBR / Legacy)"
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.value
|
||||
|
||||
|
||||
class DesktopEnvironment(str, Enum):
|
||||
"""Available KhOS desktop environments."""
|
||||
XFCE = "xfce"
|
||||
PLASMA = "plasma"
|
||||
HYPRLAND = "hyprland"
|
||||
OPENBOX = "openbox"
|
||||
|
||||
@property
|
||||
def display_name(self) -> str:
|
||||
names = {
|
||||
DesktopEnvironment.XFCE: "XFCE 4 (Lekkie, stabilne - domyślne)",
|
||||
DesktopEnvironment.PLASMA: "KDE Plasma 6 (Nowoczesne, zaawansowane)",
|
||||
DesktopEnvironment.HYPRLAND: "Hyprland (Nowoczesny Wayland Tiling WM)",
|
||||
DesktopEnvironment.OPENBOX: "Openbox (Minimalistyczne X11)",
|
||||
}
|
||||
return names.get(self, self.value)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.value
|
||||
|
||||
|
||||
@dataclass
|
||||
class PartitionInfo:
|
||||
"""Information regarding a disk partition."""
|
||||
name: str
|
||||
path: str
|
||||
size_bytes: int = 0
|
||||
size_human: str = ""
|
||||
fs_type: Optional[str] = None
|
||||
uuid: Optional[str] = None
|
||||
mount_point: Optional[str] = None
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
@dataclass
|
||||
class DiskInfo:
|
||||
"""Information regarding a block storage device."""
|
||||
name: str
|
||||
path: str
|
||||
size_bytes: int = 0
|
||||
size_gb: float = 0.0
|
||||
model: str = "Unknown Disk"
|
||||
is_removable: bool = False
|
||||
is_rotational: bool = False
|
||||
partitions: List[PartitionInfo] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def disk_type(self) -> str:
|
||||
if self.name.startswith("nvme"):
|
||||
return "NVMe SSD"
|
||||
if not self.is_rotational:
|
||||
return "SATA/VirtIO SSD"
|
||||
return "HDD"
|
||||
|
||||
def summary(self) -> str:
|
||||
removable_str = " [Wymienny/USB]" if self.is_removable else ""
|
||||
return f"{self.path} ({self.size_gb:.1f} GB, {self.disk_type}) - {self.model}{removable_str}"
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
@dataclass
|
||||
class TargetPartitions:
|
||||
"""Device paths for target partitions generated on disk."""
|
||||
disk_path: str
|
||||
root_part: str
|
||||
efi_part: Optional[str] = None
|
||||
swap_part: Optional[str] = None
|
||||
root_uuid: Optional[str] = None
|
||||
efi_uuid: Optional[str] = None
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
@dataclass
|
||||
class InstallConfig:
|
||||
"""Full configuration specification for system installation."""
|
||||
target_disk: str = ""
|
||||
boot_mode: BootMode = BootMode.BIOS
|
||||
hostname: str = "khos"
|
||||
root_password: str = "khos"
|
||||
username: Optional[str] = None
|
||||
user_password: Optional[str] = None
|
||||
desktop: DesktopEnvironment = DesktopEnvironment.XFCE
|
||||
efi_size_mb: int = 512
|
||||
swap_size_mb: int = 0
|
||||
source_path: Optional[str] = None
|
||||
mount_point: str = "/mnt/install_target"
|
||||
dry_run: bool = False
|
||||
json_output: bool = False
|
||||
auto_mode: bool = False
|
||||
|
||||
def validate(self) -> List[str]:
|
||||
"""Validate the configuration and return list of validation error messages."""
|
||||
errors: List[str] = []
|
||||
if not self.target_disk:
|
||||
errors.append("Target disk cannot be empty.")
|
||||
if not self.hostname or not self.hostname.replace("-", "").isalnum():
|
||||
errors.append(f"Invalid hostname '{self.hostname}'. Must be alphanumeric and hyphens.")
|
||||
if not self.root_password:
|
||||
errors.append("Root password cannot be empty.")
|
||||
if self.username:
|
||||
if not self.username.isidentifier():
|
||||
errors.append(f"Invalid username '{self.username}'. Must be a valid Unix identifier.")
|
||||
if not self.user_password:
|
||||
errors.append("User password must be set when username is provided.")
|
||||
if self.efi_size_mb < 64:
|
||||
errors.append("EFI partition size must be at least 64 MB.")
|
||||
return errors
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
d = asdict(self)
|
||||
d["boot_mode"] = self.boot_mode.value
|
||||
d["desktop"] = self.desktop.value
|
||||
if d.get("root_password"):
|
||||
d["root_password_set"] = True
|
||||
del d["root_password"]
|
||||
if d.get("user_password"):
|
||||
d["user_password_set"] = True
|
||||
del d["user_password"]
|
||||
return d
|
||||
|
||||
def to_json(self) -> str:
|
||||
return json.dumps(self.to_dict(), indent=2)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ProgressEvent:
|
||||
"""Event emitted during the installation process."""
|
||||
event_type: str
|
||||
percent: int = 0
|
||||
stage: str = ""
|
||||
message: str = ""
|
||||
details: Dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
def to_json(self) -> str:
|
||||
return json.dumps(self.to_dict())
|
||||
@@ -109,14 +109,45 @@ filename=packages/wlasnyos-desktop-1.0-1-x86_64.wpkg
|
||||
sha256=9d4d499a9f1ef2f695f9bc6b61afe6bd2640aa6fccb037276d580287354a4172
|
||||
|
||||
name=wlasnyos-installer
|
||||
version=1.0
|
||||
release=3
|
||||
description=Oficjalny instalator systemu WlasnyOS na dysku twardym lub SSD (BIOS + UEFI)
|
||||
version=1.1.0
|
||||
release=1
|
||||
description=Oficjalny instalator i asystent aktualizacji systemu KhOS z ISO (BIOS + UEFI)
|
||||
depends=
|
||||
arch=x86_64
|
||||
size=1139520
|
||||
filename=packages/wlasnyos-installer-1.0-1-x86_64.wpkg
|
||||
sha256=c04c918d5823214cf706dec58a273f7ddccd66d4b6daab6ebca5f46640acbefa
|
||||
size=1143172
|
||||
filename=packages/wlasnyos-installer-1.1.0-1-x86_64.wpkg
|
||||
sha256=57cc6a99d4bda6990b157878f3e5979e08dbb61a7aa0816f3de65e40ecd302a6
|
||||
|
||||
name=khos-installer
|
||||
version=1.1.0
|
||||
release=1
|
||||
description=Oficjalny instalator i asystent aktualizacji systemu KhOS z ISO (BIOS + UEFI)
|
||||
depends=
|
||||
arch=x86_64
|
||||
size=1143356
|
||||
filename=packages/khos-installer-1.1.0-1-x86_64.wpkg
|
||||
sha256=424dd978264d8c62293db868312b296ef4c60e59831204db278f74b51a98d91a
|
||||
|
||||
name=khos-update
|
||||
version=1.1.0
|
||||
release=1
|
||||
description=Oficjalny asystent aktualizacji systemu KhOS z obrazu ISO (kernel, moduly, pakiety)
|
||||
depends=
|
||||
arch=x86_64
|
||||
size=1143356
|
||||
filename=packages/khos-installer-1.1.0-1-x86_64.wpkg
|
||||
sha256=424dd978264d8c62293db868312b296ef4c60e59831204db278f74b51a98d91a
|
||||
|
||||
name=wpkg
|
||||
version=1.1.0
|
||||
release=1
|
||||
description=Menadzer pakietow dla systemu KhOS ze wsparciem aktualizacji z ISO
|
||||
depends=
|
||||
arch=x86_64
|
||||
size=13532
|
||||
filename=packages/wpkg-1.1.0-1-x86_64.wpkg
|
||||
sha256=cdd854fec5e4a3d18a8e947df907216dd6adc06ac067d72e035fa91254b13e24
|
||||
|
||||
|
||||
name=wlasnyos-wallpaper
|
||||
version=1.0
|
||||
@@ -228,6 +259,27 @@ size=475770360
|
||||
filename=packages/plasma-desktop-6.6.6-1-x86_64.wpkg
|
||||
sha256=fffd1072c8828afeab1a9ebd644979404b9edb7f9a3e134cdbacd047dd39e694
|
||||
|
||||
name=xfce4
|
||||
version=4.20
|
||||
release=1
|
||||
description=Kompletne, stabilne i lekkie srodowisko graficzne XFCE 4 dla X11 (xfwm4, panel, thunar, xfce4-terminal, sterowniki Xorg)
|
||||
depends=
|
||||
arch=x86_64
|
||||
size=98506496
|
||||
filename=packages/xfce4-4.20-1-x86_64.wpkg
|
||||
sha256=4f7c1b03b91c49f460b5df9013ed7bf50e508f15a160f2feed1de5467c361250
|
||||
|
||||
name=xfce
|
||||
version=4.20
|
||||
release=1
|
||||
description=Kompletne, stabilne i lekkie srodowisko graficzne XFCE 4 dla X11 (xfwm4, panel, thunar, xfce4-terminal, sterowniki Xorg)
|
||||
depends=
|
||||
arch=x86_64
|
||||
size=98506496
|
||||
filename=packages/xfce4-4.20-1-x86_64.wpkg
|
||||
sha256=4f7c1b03b91c49f460b5df9013ed7bf50e508f15a160f2feed1de5467c361250
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -160,6 +160,69 @@ enable_opt DRM_VMWGFX
|
||||
enable_opt DRM_VMWGFX_FBCON
|
||||
enable_opt DRM_BOCHS
|
||||
|
||||
# === HP ProBook 4545s & Physical Laptop Hardware Support ===
|
||||
# AMD Trinity APU / CPU / IOMMU
|
||||
enable_opt CPU_SUP_AMD
|
||||
enable_opt X86_AMD_PSTATE
|
||||
enable_opt X86_ACPI_CPUFREQ
|
||||
enable_opt AMD_IOMMU
|
||||
enable_opt AMD_IOMMU_V2
|
||||
enable_opt MICROCODE_AMD
|
||||
enable_opt KVM_AMD
|
||||
|
||||
# Graphics: AMD Radeon HD 7420G / 7520G / 7640G / 7660G / 7650M
|
||||
enable_opt DRM_RADEON
|
||||
enable_opt DRM_AMDGPU
|
||||
enable_opt DRM_AMDGPU_SI
|
||||
enable_opt DRM_AMDGPU_CIK
|
||||
enable_opt BACKLIGHT_CLASS_DEVICE
|
||||
|
||||
# HP ProBook 4545s Wi-Fi (Atheros AR9485, Broadcom BCM4313, Ralink RT3290)
|
||||
module_opt ATH9K
|
||||
enable_opt ATH9K_PCI
|
||||
module_opt ATH9K_HTC
|
||||
module_opt BRCMSMAC
|
||||
module_opt B43
|
||||
module_opt RT2800PCI
|
||||
enable_opt RT2800PCI_RT3290
|
||||
module_opt RFKILL
|
||||
enable_opt CFG80211_WEXT
|
||||
|
||||
# Bluetooth (Atheros AR3012, USB BT)
|
||||
module_opt BT
|
||||
module_opt BT_HCIBTUSB
|
||||
module_opt BT_ATH3K
|
||||
module_opt BT_RTL
|
||||
|
||||
# Audio: HP ProBook IDT 92HD87B2 & Realtek HD Audio
|
||||
module_opt SND_HDA_CODEC_IDT
|
||||
module_opt SND_HDA_CODEC_REALTEK
|
||||
module_opt SND_HDA_CODEC_HDMI
|
||||
module_opt SND_HDA_GENERIC
|
||||
|
||||
# Touchpad: Synaptics TouchPad
|
||||
enable_opt MOUSE_PS2_SYNAPTICS
|
||||
enable_opt MOUSE_PS2_ALPS
|
||||
enable_opt MOUSE_PS2_TRACKPOINT
|
||||
|
||||
# Card reader & Storage: Realtek RTS5209 PCI-E & AMD SATA FCH
|
||||
module_opt MISC_RTSX_PCI
|
||||
module_opt MMC
|
||||
module_opt MMC_BLOCK
|
||||
module_opt MMC_REALTEK_PCI
|
||||
enable_opt SATA_AHCI
|
||||
enable_opt PATA_AMD
|
||||
|
||||
# HP Laptop Platform & ACPI (Hotkeys, battery, brightness, thermal)
|
||||
module_opt HP_WMI
|
||||
enable_opt ACPI_WMI
|
||||
enable_opt LEDS_CLASS
|
||||
enable_opt THERMAL
|
||||
enable_opt ACPI_BATTERY
|
||||
enable_opt ACPI_AC
|
||||
enable_opt ACPI_FAN
|
||||
enable_opt ACPI_THERMAL
|
||||
|
||||
# TTY/Serial
|
||||
enable_opt VT
|
||||
enable_opt VT_CONSOLE
|
||||
|
||||
@@ -9,6 +9,20 @@ export CFLAGS="-I${TOOLSDIR}/musl/include"
|
||||
export LDFLAGS="-L${TOOLSDIR}/musl/lib"
|
||||
TARGET="x86_64-linux-musl"
|
||||
|
||||
build_sudo() {
|
||||
echo "[INFO] Kompilacja narzedzia sudo (i doas)..."
|
||||
mkdir -p "${ROOTFSDIR}/usr/bin"
|
||||
if [ -f "${BASEDIR}/scripts/src/sudo.c" ]; then
|
||||
${CC} ${CFLAGS} -O2 -Wall "${BASEDIR}/scripts/src/sudo.c" ${LDFLAGS} -o "${ROOTFSDIR}/usr/bin/sudo"
|
||||
chmod 4755 "${ROOTFSDIR}/usr/bin/sudo"
|
||||
ln -sf sudo "${ROOTFSDIR}/usr/bin/doas"
|
||||
echo "[INFO] Sudo skompilowane pomyslnie z bitem SUID (4755)."
|
||||
else
|
||||
echo "[WARN] Nie znaleziono ${BASEDIR}/scripts/src/sudo.c!"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
build_dropbear() {
|
||||
echo "[INFO] Budowanie Dropbear SSH (wersja ${DROPBEAR_VERSION})..."
|
||||
cd "${BUILDDIR}/dropbear-${DROPBEAR_VERSION}"
|
||||
@@ -57,6 +71,7 @@ build_e2fsprogs() {
|
||||
[ -x "${ROOTFSDIR}/usr/sbin/mke2fs" ] || return 1
|
||||
}
|
||||
|
||||
build_sudo || echo "[WARN] Błąd budowania sudo"
|
||||
# build_dropbear || echo "[WARN] Błąd budowania Dropbear"
|
||||
build_nano || echo "[WARN] Błąd budowania Nano"
|
||||
build_iptables || echo "[WARN] Błąd budowania iptables"
|
||||
|
||||
+109
-8
@@ -8,11 +8,17 @@ cd "${ROOTFSDIR}"
|
||||
|
||||
# Struktura FHS
|
||||
mkdir -p bin sbin usr/bin usr/sbin usr/lib usr/share
|
||||
mkdir -p etc var/log var/run var/tmp var/lock var/spool/cron
|
||||
mkdir -p etc var/log var/tmp var/spool/cron
|
||||
mkdir -p proc sys dev dev/pts
|
||||
mkdir -p tmp
|
||||
mkdir -p home root
|
||||
mkdir -p run mnt media opt srv boot lib/modules
|
||||
mkdir -p run/lock mnt media opt srv boot lib/modules
|
||||
|
||||
# Symlinki FHS i systemowe
|
||||
rm -rf var/run var/lock 2>/dev/null || true
|
||||
ln -sf /run var/run
|
||||
ln -sf /run/lock var/lock
|
||||
ln -sf /proc/mounts etc/mtab
|
||||
|
||||
# Biblioteka musl libc (oraz symlink dla ld)
|
||||
mkdir -p lib
|
||||
@@ -56,8 +62,9 @@ mknod -m 660 dev/ttyS0 c 4 64 2>/dev/null || true
|
||||
chmod 1777 tmp
|
||||
chmod 0700 root
|
||||
if [ -f bin/busybox ]; then
|
||||
chmod 4755 bin/busybox
|
||||
chmod 0755 bin/busybox
|
||||
fi
|
||||
chmod 0600 etc/shadow etc/gshadow 2>/dev/null || true
|
||||
|
||||
# Uprawnienia dla skryptów init i narzędzi
|
||||
chmod +x etc/init.d/* 2>/dev/null || true
|
||||
@@ -143,7 +150,7 @@ if [ -n "$OPENBOX_PKG" ] && [ -f "$OPENBOX_PKG" ]; then
|
||||
chmod +x usr/bin/openbox* 2>/dev/null || true
|
||||
chmod +x usr/bin/tint2 2>/dev/null || true
|
||||
chmod +x usr/bin/xterm 2>/dev/null || true
|
||||
chmod 4755 usr/bin/Xorg 2>/dev/null || true
|
||||
chmod 0755 usr/bin/Xorg 2>/dev/null || true
|
||||
echo "[INFO] Openbox zostal pomyslnie dodany do obrazu systemu."
|
||||
else
|
||||
echo "[WARN] Nie znaleziono pakietu openbox-3.6.1-1-x86_64.wpkg!"
|
||||
@@ -201,7 +208,12 @@ if [ -n "$PLASMA_PKG" ] && [ -f "$PLASMA_PKG" ]; then
|
||||
[ -f /tmp/plasma_extract/PKGINFO ] && cp /tmp/plasma_extract/PKGINFO var/lib/wpkg/installed/plasma-desktop/
|
||||
(cd /tmp/plasma_extract/data && find . ! -type d | sed 's|^\./||' > "${ROOTFSDIR}/var/lib/wpkg/installed/plasma-desktop/FILELIST") 2>/dev/null || true
|
||||
fi
|
||||
rm -rf /tmp/plasma_extract
|
||||
if [ -f usr/bin/plasma_waitforname ] && [ ! -f usr/bin/plasma_waitforname.real ]; then
|
||||
mv usr/bin/plasma_waitforname usr/bin/plasma_waitforname.real
|
||||
fi
|
||||
if [ -f usr/bin/ksplashqml ] && [ ! -f usr/bin/ksplashqml.real ]; then
|
||||
mv usr/bin/ksplashqml usr/bin/ksplashqml.real
|
||||
fi
|
||||
|
||||
apply_overlay
|
||||
|
||||
@@ -214,7 +226,45 @@ else
|
||||
echo "[WARN] Nie znaleziono pakietu plasma-desktop-6.6.6-1-x86_64.wpkg!"
|
||||
fi
|
||||
|
||||
chmod +x usr/bin/wpkg usr/local/bin/* usr/bin/help usr/bin/pomoc usr/bin/curl usr/bin/wget usr/bin/start-plasma usr/bin/plasma usr/bin/kde usr/bin/autologin-plasma 2>/dev/null || true
|
||||
# Wbudowywanie srodowiska graficznego XFCE 4 do RootFS
|
||||
XFCE_PKG=""
|
||||
for cand in \
|
||||
"${BASEDIR}/KhOS-packages/packages/xfce4-4.20-1-x86_64.wpkg" \
|
||||
"${SRCDIR}/xfce4-4.20-1-x86_64.wpkg" \
|
||||
"/pkgs/xfce4-4.20-1-x86_64.wpkg" \
|
||||
"/scratch/xfce4-4.20-1-x86_64.wpkg" \
|
||||
"${BASEDIR}/build/sources/xfce4-4.20-1-x86_64.wpkg"; do
|
||||
if [ -f "$cand" ]; then
|
||||
XFCE_PKG="$cand"
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [ -n "$XFCE_PKG" ] && [ -f "$XFCE_PKG" ]; then
|
||||
echo "[INFO] Wbudowywanie srodowiska graficznego XFCE 4 ($XFCE_PKG) do RootFS..."
|
||||
mkdir -p /tmp/xfce_extract
|
||||
tar -xf "$XFCE_PKG" -C /tmp/xfce_extract/
|
||||
if [ -d /tmp/xfce_extract/data ]; then
|
||||
cp -a --remove-destination /tmp/xfce_extract/data/* . 2>/dev/null || cp -a /tmp/xfce_extract/data/* . 2>/dev/null || true
|
||||
mkdir -p var/lib/wpkg/installed/xfce4
|
||||
[ -f /tmp/xfce_extract/PKGINFO ] && cp /tmp/xfce_extract/PKGINFO var/lib/wpkg/installed/xfce4/
|
||||
(cd /tmp/xfce_extract/data && find . ! -type d | sed 's|^\./||' > "${ROOTFSDIR}/var/lib/wpkg/installed/xfce4/FILELIST") 2>/dev/null || true
|
||||
fi
|
||||
rm -rf /tmp/xfce_extract
|
||||
|
||||
apply_overlay
|
||||
|
||||
chmod +x usr/bin/start-xfce usr/bin/startxfce4 usr/bin/xfce usr/bin/xfce4 2>/dev/null || true
|
||||
chmod 0755 usr/bin/Xorg usr/libexec/Xorg usr/libexec/Xorg.wrap 2>/dev/null || true
|
||||
[ ! -f usr/bin/startxfce4 ] && ln -sf start-xfce usr/bin/startxfce4 2>/dev/null || true
|
||||
ln -sf start-xfce usr/bin/xfce 2>/dev/null || true
|
||||
ln -sf start-xfce usr/bin/xfce4 2>/dev/null || true
|
||||
echo "[INFO] XFCE 4 zostal pomyslnie dodany do obrazu systemu."
|
||||
else
|
||||
echo "[WARN] Nie znaleziono pakietu xfce4-4.20-1-x86_64.wpkg!"
|
||||
fi
|
||||
|
||||
chmod +x usr/bin/wpkg usr/local/bin/* usr/bin/help usr/bin/pomoc usr/bin/curl usr/bin/wget usr/bin/start-xfce usr/bin/start-plasma usr/bin/plasma usr/bin/kde usr/bin/autologin-plasma 2>/dev/null || true
|
||||
|
||||
# Poprawki Wayland/Hyprland (po rozpakowaniu wszystkich pakietow)
|
||||
# libudev-zero z overlay zastepuje eudev libudev - KhOS nie ma demona udevd,
|
||||
@@ -242,8 +292,38 @@ mkdir -p etc/ssl/certs
|
||||
chmod +x usr/bin/start-hyprland 2>/dev/null || true
|
||||
chmod 4755 usr/bin/seatd-launch 2>/dev/null || true
|
||||
rm -f run/seatd.sock 2>/dev/null || true
|
||||
chmod +x usr/sbin/grub-* 2>/dev/null || true
|
||||
chmod +x usr/bin/khos-installer usr/bin/install-os 2>/dev/null || true
|
||||
# Kopiowanie pakietu instalatora Python oraz zrodel instalatorow (Rust, C++, Python)
|
||||
if [ -d "${BASEDIR}/installer/python" ]; then
|
||||
echo "[INFO] Kopiowanie instalatora Python do RootFS (/usr/share/khos-installer)..."
|
||||
mkdir -p usr/share/khos-installer
|
||||
cp -a "${BASEDIR}/installer/python/"* usr/share/khos-installer/ 2>/dev/null || true
|
||||
[ -f usr/share/khos-installer/run-gui.py ] && cp -f usr/share/khos-installer/run-gui.py usr/share/khos-installer/khos-installer-gui.py 2>/dev/null || true
|
||||
fi
|
||||
if [ -d "${BASEDIR}/installer" ]; then
|
||||
mkdir -p opt/installer
|
||||
cp -a "${BASEDIR}/installer/"* opt/installer/ 2>/dev/null || true
|
||||
fi
|
||||
|
||||
chmod +x usr/bin/khos-installer usr/bin/install-os usr/bin/khos-update usr/bin/update-os usr/bin/khos-upgrade usr/bin/khos-installer-gui usr/share/khos-installer/khos-installer-gui.py usr/share/khos-installer/run-gui.py usr/share/khos-installer/run-installer.py 2>/dev/null || true
|
||||
ln -sf khos-installer-gui usr/bin/install-os-gui 2>/dev/null || true
|
||||
ln -sf ../share/khos-installer/khos-installer-gui.py usr/bin/khos-installer-gui.py 2>/dev/null || true
|
||||
chmod +x usr/share/applications/*.desktop home/live/Desktop/*.desktop 2>/dev/null || true
|
||||
ln -sf khos-update usr/bin/update-os 2>/dev/null || true
|
||||
ln -sf khos-update usr/bin/khos-upgrade 2>/dev/null || true
|
||||
|
||||
# Kompilacja sudo jesli nie ma go jeszcze w rootfs
|
||||
if [ ! -f usr/bin/sudo ] && [ -f "${BASEDIR}/scripts/src/sudo.c" ] && [ -x "${TOOLSDIR}/musl/bin/musl-gcc" ]; then
|
||||
echo "[INFO] Kompilacja zapasowa sudo w 06-rootfs.sh..."
|
||||
"${TOOLSDIR}/musl/bin/musl-gcc" -I"${TOOLSDIR}/musl/include" -L"${TOOLSDIR}/musl/lib" -O2 -Wall "${BASEDIR}/scripts/src/sudo.c" -o usr/bin/sudo || true
|
||||
fi
|
||||
chmod 4755 usr/bin/sudo usr/bin/doas 2>/dev/null || true
|
||||
[ -f usr/bin/sudo ] && [ ! -e usr/bin/doas ] && ln -sf sudo usr/bin/doas 2>/dev/null || true
|
||||
[ -f etc/sudoers ] && chmod 0440 etc/sudoers 2>/dev/null || true
|
||||
|
||||
# Katalog domowy uzytkownika live
|
||||
mkdir -p home/live
|
||||
chown -R 1000:100 home/live 2>/dev/null || true
|
||||
chmod 755 home/live 2>/dev/null || true
|
||||
|
||||
# /etc/shells
|
||||
cat << 'EOF' > etc/shells
|
||||
@@ -251,6 +331,27 @@ cat << 'EOF' > etc/shells
|
||||
/bin/ash
|
||||
EOF
|
||||
|
||||
# Instalacja fizycznego firmware dla HP ProBook 4545s i sprzetu PC
|
||||
echo "[INFO] Kopiowanie firmware dla HP ProBook 4545s (Radeon, Realtek, Atheros, Ralink)..."
|
||||
mkdir -p lib/firmware
|
||||
for fw_dir in radeon amdgpu rtl_nic ath9k_htc ar3k; do
|
||||
if [ -d "/lib/firmware/$fw_dir" ]; then
|
||||
cp -a "/lib/firmware/$fw_dir" lib/firmware/ 2>/dev/null || true
|
||||
fi
|
||||
done
|
||||
for fw_file in /lib/firmware/rt3290.bin /lib/firmware/rt2870.bin /lib/firmware/rt3070.bin /lib/firmware/ath3k-1.fw /lib/firmware/ar9271.fw; do
|
||||
if [ -f "$fw_file" ]; then
|
||||
cp -a "$fw_file" lib/firmware/ 2>/dev/null || true
|
||||
fi
|
||||
done
|
||||
|
||||
# Aktualizacja bazy pakietów wpkg w RootFS
|
||||
if [ -f "${BASEDIR}/KhOS-packages/PACKAGES.db" ]; then
|
||||
echo "[INFO] Aktualizacja bazy pakietów wpkg w RootFS..."
|
||||
mkdir -p var/lib/wpkg
|
||||
cp -f "${BASEDIR}/KhOS-packages/PACKAGES.db" var/lib/wpkg/packages.db
|
||||
fi
|
||||
|
||||
# Statystyki systemu plików
|
||||
echo "[INFO] Statystyki RootFS:"
|
||||
find . | wc -l | xargs echo "Liczba plików (i katalogów):"
|
||||
|
||||
+323
-55
@@ -10,7 +10,7 @@ mkdir -p "${INITRAMFS}"
|
||||
cd "${INITRAMFS}"
|
||||
|
||||
# Podstawowe katalogi
|
||||
mkdir -p bin sbin etc proc sys dev mnt/cdrom mnt/root tmp newroot lib usr/bin usr/sbin usr/lib
|
||||
mkdir -p bin sbin etc proc sys dev mnt/cdrom mnt/root mnt/chk_root tmp newroot lib usr/bin usr/sbin usr/lib
|
||||
ln -sf lib lib64
|
||||
|
||||
# Kopiowanie busybox i musl
|
||||
@@ -28,9 +28,14 @@ if [ -f "${TOOLSDIR}/musl/lib/libc.so" ]; then
|
||||
ln -sf ld-musl-x86_64.so.1 lib/libc.so 2>/dev/null || true
|
||||
fi
|
||||
|
||||
# Symlinki busybox
|
||||
for app in sh ash mount umount mkdir rmdir switch_root ls cat sleep echo mdev blkid losetup modprobe insmod rmmod grep find cut sed awk; do
|
||||
ln -sf busybox "bin/$app"
|
||||
# Symlinki busybox w bin
|
||||
for app in sh ash mount umount mkdir rmdir switch_root ls cat sleep echo mdev blkid findfs losetup modprobe insmod rmmod lsmod grep egrep find cut sed awk test [ [[ which head tail sort tr uname dmesg chmod cp mv rm sync dd blockdev; do
|
||||
ln -sf busybox "bin/$app" 2>/dev/null || true
|
||||
done
|
||||
|
||||
# Symlinki busybox w sbin
|
||||
for app in mdev blkid findfs switch_root modprobe insmod rmmod lsmod fdisk mkfs.ext2 blkdiscard blockdev; do
|
||||
ln -sf ../bin/busybox "sbin/$app" 2>/dev/null || true
|
||||
done
|
||||
|
||||
# Krytyczne wezly urzadzen dla initramfs
|
||||
@@ -40,6 +45,10 @@ mknod -m 666 dev/zero c 1 5
|
||||
mknod -m 660 dev/tty c 5 0
|
||||
mknod -m 660 dev/tty1 c 4 1
|
||||
mknod -m 660 dev/ttyS0 c 4 64 2>/dev/null || true
|
||||
mknod -m 660 dev/loop-control c 10 237 2>/dev/null || true
|
||||
for i in 0 1 2 3 4 5 6 7; do
|
||||
mknod -m 660 dev/loop$i b 7 $i 2>/dev/null || true
|
||||
done
|
||||
|
||||
# Weryfikacja dzialania busybox w chroot
|
||||
echo "[INFO] Weryfikacja dzialania busybox w srodowisku initramfs..."
|
||||
@@ -49,7 +58,7 @@ chroot "${INITRAMFS}" /bin/busybox --help || {
|
||||
}
|
||||
|
||||
# Generowanie skryptu init
|
||||
cat << 'EOF' > init
|
||||
cat << 'INIT_SCRIPT_EOF' > init
|
||||
#!/bin/sh
|
||||
export PATH=/bin:/sbin:/usr/bin:/usr/sbin
|
||||
|
||||
@@ -60,8 +69,10 @@ mount -t devtmpfs devtmpfs /dev
|
||||
mkdir -p /dev/pts
|
||||
mount -t devpts devpts /dev/pts 2>/dev/null || true
|
||||
|
||||
# Inicjalizacja menedzera urzadzen
|
||||
[ -e /proc/sys/kernel/hotplug ] && echo /sbin/mdev > /proc/sys/kernel/hotplug 2>/dev/null || true
|
||||
# Inicjalizacja zarzadcy urzadzen mdev
|
||||
if [ -e /proc/sys/kernel/hotplug ]; then
|
||||
echo /bin/mdev > /proc/sys/kernel/hotplug 2>/dev/null || echo /sbin/mdev > /proc/sys/kernel/hotplug 2>/dev/null || true
|
||||
fi
|
||||
mdev -s 2>/dev/null || true
|
||||
|
||||
echo ""
|
||||
@@ -70,94 +81,351 @@ echo " KhOS 1.0 - Startowanie systemu..."
|
||||
echo "=========================================="
|
||||
echo ""
|
||||
|
||||
# Funkcja bezpiecznego ladowania modulow jadra
|
||||
load_module() {
|
||||
_mod="$1"
|
||||
# Proba zaladowania przez modprobe (uzywa modules.dep)
|
||||
if modprobe "$_mod" >/dev/null 2>&1; then
|
||||
return 0
|
||||
fi
|
||||
# Fallback: wyszukanie pliku modulu bezposrednio w /lib/modules i insmod
|
||||
if [ -d /lib/modules ]; then
|
||||
for _ko in $(find /lib/modules -type f \( -name "${_mod}.ko" -o -name "${_mod}.ko.gz" -o -name "${_mod}.ko.xz" -o -name "${_mod}.ko.zst" \) 2>/dev/null); do
|
||||
if insmod "$_ko" >/dev/null 2>&1; then
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
fi
|
||||
return 1
|
||||
}
|
||||
|
||||
# Automatyczne ladowanie modulow pamieci masowej i systemow plikow jesli sa skompilowane jako moduly
|
||||
echo "[INIT] Inicjalizacja sterownikow pamieci masowej i systemow plikow..."
|
||||
for _m in scsi_mod sd_mod sr_mod libata ata_piix pata_piix ata_generic ahci libahci nvme_core nvme virtio virtio_pci virtio_blk virtio_scsi loop ext4 ext2 ext3 vfat fat nls_cp437 nls_iso8859_1 nls_utf8 overlay squashfs; do
|
||||
load_module "$_m" 2>/dev/null || true
|
||||
done
|
||||
|
||||
# Ponowne przeskanowanie urzadzen mdev po zaladowaniu sterownikow
|
||||
mdev -s 2>/dev/null || true
|
||||
|
||||
# Odczyt parametrow linii polecen jadra
|
||||
ROOT_DEV=""
|
||||
ROOT_FSTYPE=""
|
||||
ROOT_FLAGS="rw"
|
||||
|
||||
for param in $(cat /proc/cmdline 2>/dev/null); do
|
||||
case "$param" in
|
||||
root=*)
|
||||
ROOT_DEV="${param#root=}"
|
||||
ROOT_DEV=$(echo "$ROOT_DEV" | tr -d '"' | tr -d "'")
|
||||
;;
|
||||
rootfstype=*)
|
||||
ROOT_FSTYPE="${param#rootfstype=}"
|
||||
;;
|
||||
ro)
|
||||
ROOT_FLAGS="ro"
|
||||
;;
|
||||
rw)
|
||||
ROOT_FLAGS="rw"
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
# TRYB 1: Start z zainstalowanego dysku twardego / SSD (np. root=/dev/sda1)
|
||||
# TRYB 1: Start z zainstalowanego dysku twardego / SSD (np. root=UUID=... lub root=/dev/sdX...)
|
||||
if [ -n "$ROOT_DEV" ] && [ "$ROOT_DEV" != "live" ]; then
|
||||
echo "Wykryto parametr rozruchu z dysku: root=$ROOT_DEV"
|
||||
mkdir -p /newroot
|
||||
mkdir -p /newroot /mnt/chk_root
|
||||
|
||||
# Oczekiwanie na zarejestrowanie partycji dysku
|
||||
for attempt in 1 2 3 4 5; do
|
||||
if [ -b "$ROOT_DEV" ] || [ -e "$ROOT_DEV" ]; then
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
RESOLVED_DEV=""
|
||||
echo "Oczekiwanie na zarejestrowanie partycji systemowej przez jadro i mdev..."
|
||||
|
||||
for attempt in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20; do
|
||||
mdev -s 2>/dev/null || true
|
||||
done
|
||||
RESOLVED_DEV=""
|
||||
|
||||
# Jeśli podano UUID=
|
||||
case "$ROOT_DEV" in
|
||||
UUID=*|uuid=*)
|
||||
target_uuid="${ROOT_DEV#*=}"
|
||||
for dev in $(blkid -o device 2>/dev/null); do
|
||||
if [ "$(blkid -s UUID -o value "$dev" 2>/dev/null)" = "$target_uuid" ]; then
|
||||
ROOT_DEV="$dev"
|
||||
case "$ROOT_DEV" in
|
||||
UUID=*|uuid=*)
|
||||
target_uuid="${ROOT_DEV#*=}"
|
||||
target_uuid=$(echo "$target_uuid" | tr -d '"' | tr -d "'")
|
||||
|
||||
# 1. findfs
|
||||
cand=$(findfs "UUID=$target_uuid" 2>/dev/null || findfs "$ROOT_DEV" 2>/dev/null || true)
|
||||
if [ -n "$cand" ] && [ -b "$cand" ]; then
|
||||
RESOLVED_DEV="$cand"
|
||||
break
|
||||
fi
|
||||
done
|
||||
;;
|
||||
esac
|
||||
|
||||
if mount "$ROOT_DEV" /newroot 2>/dev/null; then
|
||||
echo "[OK] Zamontowano partycje systemowa z $ROOT_DEV"
|
||||
echo "Przelaczanie do systemu KhOS..."
|
||||
umount /proc /sys /dev/pts 2>/dev/null || true
|
||||
exec switch_root /newroot /sbin/init
|
||||
# 2. Parsowanie pelnego wyjscia blkid
|
||||
blkid > /tmp/blkid.tmp 2>/dev/null || true
|
||||
if [ -s /tmp/blkid.tmp ]; then
|
||||
while read -r bline; do
|
||||
[ -z "$bline" ] && continue
|
||||
b_dev=$(echo "$bline" | cut -d: -f1)
|
||||
if [ -b "$b_dev" ]; then
|
||||
case "$bline" in
|
||||
*UUID=\"$target_uuid\"*|*UUID=\'$target_uuid\'*|*UUID=$target_uuid*|*uuid=\"$target_uuid\"*|*uuid=$target_uuid*)
|
||||
RESOLVED_DEV="$b_dev"
|
||||
break 2
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
done < /tmp/blkid.tmp
|
||||
rm -f /tmp/blkid.tmp
|
||||
fi
|
||||
|
||||
# 3. Fallback: bezposrednie sprawdzenie kazdego urzadzenia blokowego
|
||||
for bdev in /dev/sd* /dev/nvme* /dev/vd* /dev/hd* /dev/mmcblk* /dev/xvd*; do
|
||||
[ ! -b "$bdev" ] && continue
|
||||
binfo=$(blkid "$bdev" 2>/dev/null || true)
|
||||
case "$binfo" in
|
||||
*UUID=\"$target_uuid\"*|*UUID=\'$target_uuid\'*|*UUID=$target_uuid*|*uuid=\"$target_uuid\"*|*uuid=$target_uuid*)
|
||||
RESOLVED_DEV="$bdev"
|
||||
break 2
|
||||
;;
|
||||
esac
|
||||
done
|
||||
;;
|
||||
|
||||
LABEL=*|label=*)
|
||||
target_label="${ROOT_DEV#*=}"
|
||||
target_label=$(echo "$target_label" | tr -d '"' | tr -d "'")
|
||||
|
||||
cand=$(findfs "LABEL=$target_label" 2>/dev/null || findfs "$ROOT_DEV" 2>/dev/null || true)
|
||||
if [ -n "$cand" ] && [ -b "$cand" ]; then
|
||||
RESOLVED_DEV="$cand"
|
||||
break
|
||||
fi
|
||||
|
||||
for bdev in /dev/sd* /dev/nvme* /dev/vd* /dev/hd* /dev/mmcblk* /dev/xvd*; do
|
||||
[ ! -b "$bdev" ] && continue
|
||||
binfo=$(blkid "$bdev" 2>/dev/null || true)
|
||||
case "$binfo" in
|
||||
*LABEL=\"$target_label\"*|*LABEL=\'$target_label\'*|*LABEL=$target_label*)
|
||||
RESOLVED_DEV="$bdev"
|
||||
break 2
|
||||
;;
|
||||
esac
|
||||
done
|
||||
;;
|
||||
|
||||
PARTUUID=*|partuuid=*)
|
||||
target_partuuid="${ROOT_DEV#*=}"
|
||||
target_partuuid=$(echo "$target_partuuid" | tr -d '"' | tr -d "'")
|
||||
|
||||
cand=$(findfs "PARTUUID=$target_partuuid" 2>/dev/null || findfs "$ROOT_DEV" 2>/dev/null || true)
|
||||
if [ -n "$cand" ] && [ -b "$cand" ]; then
|
||||
RESOLVED_DEV="$cand"
|
||||
break
|
||||
fi
|
||||
|
||||
for bdev in /dev/sd* /dev/nvme* /dev/vd* /dev/hd* /dev/mmcblk* /dev/xvd*; do
|
||||
[ ! -b "$bdev" ] && continue
|
||||
binfo=$(blkid "$bdev" 2>/dev/null || true)
|
||||
case "$binfo" in
|
||||
*PARTUUID=\"$target_partuuid\"*|*PARTUUID=$target_partuuid*)
|
||||
RESOLVED_DEV="$bdev"
|
||||
break 2
|
||||
;;
|
||||
esac
|
||||
done
|
||||
;;
|
||||
|
||||
*)
|
||||
# Bezposrednia sciezka do wezla urzadzenia (np. /dev/sda1 lub sda1)
|
||||
if [ -b "$ROOT_DEV" ]; then
|
||||
RESOLVED_DEV="$ROOT_DEV"
|
||||
break
|
||||
elif [ -b "/dev/$ROOT_DEV" ]; then
|
||||
RESOLVED_DEV="/dev/$ROOT_DEV"
|
||||
break
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -n "$RESOLVED_DEV" ] && [ -b "$RESOLVED_DEV" ]; then
|
||||
break
|
||||
fi
|
||||
|
||||
if [ "$attempt" -lt 20 ]; then
|
||||
if [ $((attempt % 4)) -eq 0 ]; then
|
||||
echo "Oczekiwanie na partycje glowna [$ROOT_DEV] (proba $attempt/20)..."
|
||||
fi
|
||||
sleep 1
|
||||
fi
|
||||
done
|
||||
|
||||
# Awaryjne przeszukanie partycji jesli nie odnaleziono urzadzenia odpowiadajacego UUID lub nazwie
|
||||
if [ -z "$RESOLVED_DEV" ] || [ ! -b "$RESOLVED_DEV" ]; then
|
||||
echo "[OSTRZEZENIE] Nie znaleziono urzadzenia odpowiadajacego '$ROOT_DEV' po 20 probach."
|
||||
echo "[INFO] Rozpoczynam awaryjne przeszukiwanie partycji w poszukiwaniu instalacji KhOS (/sbin/init, /etc/os-release)..."
|
||||
mkdir -p /mnt/chk_root
|
||||
|
||||
for cand in /dev/sd[a-z][0-9]* /dev/nvme[0-9]*n[0-9]*p[0-9]* /dev/vd[a-z][0-9]* /dev/hd[a-z][0-9]* /dev/mmcblk[0-9]*p[0-9]* /dev/xvd[a-z][0-9]*; do
|
||||
[ ! -b "$cand" ] && continue
|
||||
case "$cand" in
|
||||
/dev/sr*|/dev/loop*) continue ;;
|
||||
esac
|
||||
|
||||
# Sprobuj zamontowac tylko do odczytu
|
||||
if mount -o ro "$cand" /mnt/chk_root 2>/dev/null || mount -t ext4 -o ro "$cand" /mnt/chk_root 2>/dev/null || mount -t ext2 -o ro "$cand" /mnt/chk_root 2>/dev/null; then
|
||||
is_khos_root=0
|
||||
if [ -f /mnt/chk_root/etc/os-release ] && grep -qi "KhOS" /mnt/chk_root/etc/os-release 2>/dev/null; then
|
||||
is_khos_root=1
|
||||
elif [ -f /mnt/chk_root/sbin/init ] && [ -d /mnt/chk_root/etc ]; then
|
||||
is_khos_root=1
|
||||
fi
|
||||
|
||||
if [ "$is_khos_root" -eq 1 ]; then
|
||||
echo "[OK] Awaryjnie odnaleziono instalacje KhOS na partycji: $cand"
|
||||
RESOLVED_DEV="$cand"
|
||||
umount /mnt/chk_root 2>/dev/null || true
|
||||
break
|
||||
fi
|
||||
umount /mnt/chk_root 2>/dev/null || true
|
||||
fi
|
||||
done
|
||||
rmdir /mnt/chk_root 2>/dev/null || true
|
||||
fi
|
||||
echo "[OSTRZEZENIE] Nie udalo sie zamontowac $ROOT_DEV, przechodze do trybu Live..."
|
||||
|
||||
# Montowanie odnalezionej partycji na /newroot
|
||||
if [ -n "$RESOLVED_DEV" ] && [ -b "$RESOLVED_DEV" ]; then
|
||||
ROOT_DEV="$RESOLVED_DEV"
|
||||
echo "Montowanie partycji systemowej: $ROOT_DEV na /newroot (opcje: $ROOT_FLAGS)..."
|
||||
|
||||
MOUNT_OK=0
|
||||
if [ -n "$ROOT_FSTYPE" ]; then
|
||||
echo "-> Proba montowania z podanym typem: $ROOT_FSTYPE..."
|
||||
if mount -t "$ROOT_FSTYPE" -o "$ROOT_FLAGS" "$ROOT_DEV" /newroot; then
|
||||
MOUNT_OK=1
|
||||
else
|
||||
_rc=$?
|
||||
echo "[OSTRZEZENIE] mount -t $ROOT_FSTYPE zakonczyl sie kodem bledu: $_rc"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$MOUNT_OK" -eq 0 ]; then
|
||||
echo "-> Proba montowania (autodetekcja systemu plikow)..."
|
||||
if mount -o "$ROOT_FLAGS" "$ROOT_DEV" /newroot; then
|
||||
MOUNT_OK=1
|
||||
else
|
||||
_rc=$?
|
||||
echo "[OSTRZEZENIE] mount standardowy zakonczyl sie kodem bledu: $_rc"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$MOUNT_OK" -eq 0 ]; then
|
||||
echo "-> Proba montowania z jawnym typem ext4..."
|
||||
if mount -t ext4 -o "$ROOT_FLAGS" "$ROOT_DEV" /newroot; then
|
||||
MOUNT_OK=1
|
||||
else
|
||||
_rc=$?
|
||||
echo "[OSTRZEZENIE] mount -t ext4 zakonczyl sie kodem bledu: $_rc"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$MOUNT_OK" -eq 0 ]; then
|
||||
echo "-> Proba montowania z jawnym typem ext2..."
|
||||
if mount -t ext2 -o "$ROOT_FLAGS" "$ROOT_DEV" /newroot; then
|
||||
MOUNT_OK=1
|
||||
else
|
||||
_rc=$?
|
||||
echo "[OSTRZEZENIE] mount -t ext2 zakonczyl sie kodem bledu: $_rc"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$MOUNT_OK" -eq 0 ] && [ "$ROOT_FLAGS" != "ro" ]; then
|
||||
echo "-> Proba awaryjnego montowania tylko do odczytu (-o ro)..."
|
||||
if mount -o ro "$ROOT_DEV" /newroot; then
|
||||
MOUNT_OK=1
|
||||
else
|
||||
_rc=$?
|
||||
echo "[BLAD] Awaryjny mount -o ro zakonczyl sie kodem bledu: $_rc"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$MOUNT_OK" -eq 1 ]; then
|
||||
if [ -x /newroot/sbin/init ] || [ -f /newroot/sbin/init ] || [ -f /newroot/bin/busybox ]; then
|
||||
echo "[OK] Partycja systemowa $ROOT_DEV zamontowana prawidlowo na /newroot."
|
||||
echo "Przelaczanie do systemu KhOS (switch_root)..."
|
||||
umount /proc /sys /dev/pts 2>/dev/null || true
|
||||
exec switch_root /newroot /sbin/init
|
||||
else
|
||||
echo "[BLAD KRYTYCZNY] Partycja $ROOT_DEV zamontowana, ale brak /sbin/init lub /bin/busybox w /newroot!"
|
||||
echo "Zawartosc /newroot:"
|
||||
ls -la /newroot
|
||||
umount /newroot 2>/dev/null || true
|
||||
fi
|
||||
else
|
||||
echo "[BLAD KRYTYCZNY] Wszystkie proby montowania partycji $ROOT_DEV zakonczyly sie niepowodzeniem!"
|
||||
fi
|
||||
else
|
||||
echo "[BLAD KRYTYCZNY] Nie udalo sie zlokalizowac urzadzenia partycji root: $ROOT_DEV"
|
||||
echo "Dostepne urzadzenia blokowe:"
|
||||
ls -la /dev/sd* /dev/nvme* /dev/vd* /dev/hd* 2>/dev/null || true
|
||||
blkid 2>/dev/null || true
|
||||
fi
|
||||
|
||||
echo "[OSTRZEZENIE] Rozruch z dysku nie powiodl sie. Sprawdzam czy dostepny jest nosnik Live..."
|
||||
fi
|
||||
|
||||
# TRYB 2: Start z plyty Live CD / ISO
|
||||
# TRYB 2: Start z plyty Live CD / ISO / USB
|
||||
LIVE_FOUND=0
|
||||
echo "Wyszukiwanie nosnika live KhOS..."
|
||||
|
||||
for attempt in 1 2 3 4 5 6 7 8 9 10; do
|
||||
for attempt in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15; do
|
||||
mdev -s 2>/dev/null || true
|
||||
for device in /dev/sr* /dev/sd* /dev/vd* /dev/hd* /dev/nvme* /dev/loop*; do
|
||||
|
||||
# 1. Sprawdz czy findfs potrafi znalezc nosnik po etykiecie KHOS
|
||||
for ldev in $(findfs LABEL=KHOS 2>/dev/null || true); do
|
||||
if [ -b "$ldev" ]; then
|
||||
mount -o ro "$ldev" /mnt/cdrom 2>/dev/null || mount -t iso9660 -o ro "$ldev" /mnt/cdrom 2>/dev/null || continue
|
||||
if [ -f /mnt/cdrom/live/filesystem.squashfs ]; then
|
||||
echo "[OK] Znaleziono obraz systemu KhOS (LABEL=KHOS) na: $ldev"
|
||||
LIVE_FOUND=1
|
||||
break 2
|
||||
fi
|
||||
umount /mnt/cdrom 2>/dev/null || true
|
||||
fi
|
||||
done
|
||||
|
||||
# 2. Skanowanie urzadzen blokowych i partycji
|
||||
for device in /dev/sr* /dev/sd* /dev/vd* /dev/hd* /dev/nvme* /dev/mmcblk* /dev/loop*; do
|
||||
[ ! -b "$device" ] && [ ! -e "$device" ] && continue
|
||||
mount -o ro "$device" /mnt/cdrom 2>/dev/null || continue
|
||||
mount -o ro "$device" /mnt/cdrom 2>/dev/null || mount -t iso9660 -o ro "$device" /mnt/cdrom 2>/dev/null || mount -t vfat -o ro "$device" /mnt/cdrom 2>/dev/null || continue
|
||||
if [ -f /mnt/cdrom/live/filesystem.squashfs ]; then
|
||||
echo "[OK] Znaleziono obraz systemu KhOS na: $device (proba $attempt)"
|
||||
LIVE_FOUND=1
|
||||
break 2
|
||||
fi
|
||||
umount /mnt/cdrom 2>/dev/null
|
||||
umount /mnt/cdrom 2>/dev/null || true
|
||||
done
|
||||
sleep 1
|
||||
done
|
||||
|
||||
if [ $LIVE_FOUND -eq 0 ]; then
|
||||
for device in $(blkid -o device 2>/dev/null); do
|
||||
mount -o ro "$device" /mnt/cdrom 2>/dev/null || continue
|
||||
if [ -f /mnt/cdrom/live/filesystem.squashfs ]; then
|
||||
echo "[OK] Znaleziono obraz systemu KhOS przez blkid na: $device"
|
||||
LIVE_FOUND=1
|
||||
break
|
||||
fi
|
||||
umount /mnt/cdrom 2>/dev/null
|
||||
done
|
||||
fi
|
||||
|
||||
if [ $LIVE_FOUND -eq 0 ]; then
|
||||
echo "[BLAD] Nie znaleziono nosnika live/filesystem.squashfs!"
|
||||
echo "[BLAD KRYTYCZNY] Nie udalo sie znalezc nosnika live/filesystem.squashfs ani uruchomic z dysku!"
|
||||
echo "Dostepne urzadzenia blokowe:"
|
||||
ls -l /dev/sr* /dev/sd* /dev/vd* /dev/hd* 2>/dev/null || true
|
||||
echo "Uruchamiam powloke ratunkowa..."
|
||||
ls -l /dev/sr* /dev/sd* /dev/vd* /dev/hd* /dev/nvme* 2>/dev/null || true
|
||||
echo "Uruchamiam powloke ratunkowa initramfs..."
|
||||
exec /bin/sh
|
||||
fi
|
||||
|
||||
# Zapewnienie wezlow loop dla squashfs
|
||||
for i in 0 1 2 3 4 5 6 7; do
|
||||
[ ! -b /dev/loop$i ] && mknod -m 660 /dev/loop$i b 7 $i 2>/dev/null || true
|
||||
done
|
||||
[ ! -c /dev/loop-control ] && mknod -m 660 /dev/loop-control c 10 237 2>/dev/null || true
|
||||
|
||||
# Montowanie squashfs
|
||||
mkdir -p /mnt/squashfs
|
||||
mount -t squashfs -o ro,loop /mnt/cdrom/live/filesystem.squashfs /mnt/squashfs
|
||||
if ! mount -t squashfs -o ro,loop /mnt/cdrom/live/filesystem.squashfs /mnt/squashfs 2>/dev/null; then
|
||||
LOOP_DEV=$(losetup -f 2>/dev/null || echo "/dev/loop0")
|
||||
losetup -r "$LOOP_DEV" /mnt/cdrom/live/filesystem.squashfs 2>/dev/null || true
|
||||
mount -t squashfs -o ro "$LOOP_DEV" /mnt/squashfs || {
|
||||
echo "[BLAD KRYTYCZNY] Nie udalo sie zamontowac /mnt/cdrom/live/filesystem.squashfs!"
|
||||
exec /bin/sh
|
||||
}
|
||||
fi
|
||||
|
||||
# Warstwa OverlayFS na ramdysku tmpfs
|
||||
mkdir -p /mnt/tmpfs
|
||||
@@ -175,9 +443,9 @@ umount /proc /sys /dev/pts 2>/dev/null || true
|
||||
|
||||
exec switch_root /newroot /sbin/init
|
||||
|
||||
echo "[BLAD] switch_root nie powiodl sie!"
|
||||
echo "[BLAD KRYTYCZNY] switch_root nie powiodl sie!"
|
||||
exec /bin/sh
|
||||
EOF
|
||||
INIT_SCRIPT_EOF
|
||||
|
||||
chmod +x init
|
||||
|
||||
|
||||
+43
-2
@@ -8,10 +8,26 @@ mkdir -p "$ISODIR/boot/grub"
|
||||
mkdir -p "$ISODIR/live"
|
||||
mkdir -p "$OUTPUTDIR"
|
||||
|
||||
# Kopiowanie pakietow do obrazu ISO (tylko niezbedne do instalacji, reszta z serwera sieciowego)
|
||||
if [ -d "$BASEDIR/KhOS-packages/packages" ]; then
|
||||
echo "[INFO] Kopiowanie niezbednych pakietow instalacyjnych do ISO (/packages)..."
|
||||
mkdir -p "$ISODIR/packages"
|
||||
|
||||
# Kopiuj cala baze pakietow (indeks z serwera z informacja o wszystkich programach)
|
||||
[ -f "$BASEDIR/KhOS-packages/PACKAGES.db" ] && cp -a "$BASEDIR/KhOS-packages/PACKAGES.db" "$ISODIR/packages/" 2>/dev/null || true
|
||||
|
||||
# Kopiuj wylacznie pakiety scisle wymagane do instalatora i menedzera pakietow:
|
||||
for req_pkg in e2fsprogs wpkg khos-installer wlasnyos-installer dejavu-fonts terminfo xfce4; do
|
||||
cp -a "$BASEDIR/KhOS-packages/packages/${req_pkg}"*.wpkg "$ISODIR/packages/" 2>/dev/null || true
|
||||
done
|
||||
|
||||
echo "[INFO] Skopiowano podstawowe pakiety instalacyjne. Pakiety dodatkowe beda pobierane z https://git.kpgpmc.org/KhOS/KhOS-packages."
|
||||
fi
|
||||
|
||||
# Tworzenie squashfs
|
||||
echo "[INFO] Generowanie live/filesystem.squashfs..."
|
||||
rm -f "$ISODIR/live/filesystem.squashfs"
|
||||
mksquashfs "$ROOTFSDIR" "$ISODIR/live/filesystem.squashfs" -comp xz -e boot
|
||||
mksquashfs "$ROOTFSDIR" "$ISODIR/live/filesystem.squashfs" -comp zstd -Xcompression-level 19 -b 256K -e boot
|
||||
|
||||
echo "[INFO] Rozmiar squashfs:"
|
||||
du -sh "$ISODIR/live/filesystem.squashfs"
|
||||
@@ -25,8 +41,33 @@ serial --unit=0 --speed=115200
|
||||
terminal_input console serial
|
||||
terminal_output console serial
|
||||
|
||||
menuentry "${OS_NAME} ${OS_VERSION} - Uruchom system (Pulpit XFCE 4 - domyslny)" {
|
||||
linux /boot/vmlinuz console=tty0 console=ttyS0,115200 radeon.dpm=0 acpi_backlight=vendor quiet
|
||||
initrd /boot/initramfs.img
|
||||
}
|
||||
|
||||
menuentry "${OS_NAME} ${OS_VERSION} - HP ProBook 4545s / AMD Radeon (XFCE 4, DPM off, backlight fix)" {
|
||||
linux /boot/vmlinuz console=tty0 radeon.dpm=0 radeon.bapm=0 radeon.audio=0 acpi_backlight=vendor acpi_osi=Linux quiet
|
||||
initrd /boot/initramfs.img
|
||||
}
|
||||
|
||||
menuentry "${OS_NAME} ${OS_VERSION} - Uruchom system (Pulpit KDE Plasma)" {
|
||||
linux /boot/vmlinuz console=tty0 console=ttyS0,115200 quiet
|
||||
linux /boot/vmlinuz console=tty0 console=ttyS0,115200 desktop=plasma radeon.dpm=0 acpi_backlight=vendor quiet
|
||||
initrd /boot/initramfs.img
|
||||
}
|
||||
|
||||
menuentry "${OS_NAME} ${OS_VERSION} - Bezpieczna grafika (Safe Graphics / nomodeset / vesa)" {
|
||||
linux /boot/vmlinuz console=tty0 nomodeset radeon.modeset=0 swrender=1 quiet
|
||||
initrd /boot/initramfs.img
|
||||
}
|
||||
|
||||
menuentry "${OS_NAME} ${OS_VERSION} - Uruchom system (Pulpit Hyprland - Wayland)" {
|
||||
linux /boot/vmlinuz console=tty0 console=ttyS0,115200 desktop=hyprland radeon.dpm=0 acpi_backlight=vendor quiet
|
||||
initrd /boot/initramfs.img
|
||||
}
|
||||
|
||||
menuentry "${OS_NAME} ${OS_VERSION} - Aktualizacja istniejacego systemu z ISO" {
|
||||
linux /boot/vmlinuz console=tty0 console=ttyS0,115200 textmode
|
||||
initrd /boot/initramfs.img
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,372 @@
|
||||
/*
|
||||
* KhOS - Bezpieczna i zoptymalizowana implementacja polecenia sudo
|
||||
* Przeznaczona dla srodowiska musl libc + BusyBox w dystrybucji KhOS.
|
||||
*/
|
||||
|
||||
#define _GNU_SOURCE
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/stat.h>
|
||||
#include <pwd.h>
|
||||
#include <grp.h>
|
||||
#include <shadow.h>
|
||||
#include <errno.h>
|
||||
#include <ctype.h>
|
||||
|
||||
#define SUDOERS_FILE "/etc/sudoers"
|
||||
#define DEFAULT_SECURE_PATH "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
|
||||
|
||||
static const char *const dangerous_env[] = {
|
||||
"LD_PRELOAD", "LD_LIBRARY_PATH", "LD_AUDIT", "LD_DEBUG", "LD_DYNAMIC_WEAK",
|
||||
"LD_ORIGIN_PATH", "LD_SHOW_AUXV", "LD_PROFILE", "LD_BIND_NOW", "LD_AOUT_LIBRARY_PATH",
|
||||
"LD_AOUT_PRELOAD", "GCONV_PATH", "GETCONF_DIR", "HOSTALIASES", "IFS", "ENV",
|
||||
"BASH_ENV", "KRB5_CONFIG", "RESOLV_HOST_CONF", "RES_OPTIONS", "NLSPATH",
|
||||
"XFILESEARCHPATH", "PYTHONPATH", "PERLLIB", "PERL5LIB", "RUBYLIB", "TERMINFO",
|
||||
"TERMINFO_DIRS", NULL
|
||||
};
|
||||
|
||||
static void print_usage(const char *progname) {
|
||||
fprintf(stderr, "Uzycie: %s [opcje] polecenie [argumenty...]\n", progname);
|
||||
fprintf(stderr, "Opcje:\n");
|
||||
fprintf(stderr, " -h, --help Wyswietla te pomoc\n");
|
||||
fprintf(stderr, " -u <uzytkownik> Uruchom jako wskazany uzytkownik (domyslnie: root)\n");
|
||||
fprintf(stderr, " -g <grupa> Uruchom z dana grupa podstawowa\n");
|
||||
fprintf(stderr, " -i Powloka logowania z pelnym srodowiskiem roota\n");
|
||||
fprintf(stderr, " -s Uruchom powloke jako docelowy uzytkownik\n");
|
||||
fprintf(stderr, " -E, --preserve-env Zachowaj biezace zmienne srodowiskowe (z wyjatkiem LD_*)\n");
|
||||
fprintf(stderr, " -v, --validate Zaktualizuj uprawnienia (walidacja hasla)\n");
|
||||
fprintf(stderr, " -- Koniec opcji, nastepne to polecenie\n");
|
||||
}
|
||||
|
||||
static int is_user_in_group(const char *username, const char *groupname) {
|
||||
struct group *gr = getgrnam(groupname);
|
||||
if (!gr) return 0;
|
||||
gid_t target_gid = gr->gr_gid;
|
||||
|
||||
struct passwd *pw = getpwnam(username);
|
||||
if (!pw) return 0;
|
||||
if (pw->pw_gid == target_gid) return 1;
|
||||
|
||||
gid_t groups[64];
|
||||
int ngroups = 64;
|
||||
if (getgrouplist(username, pw->pw_gid, groups, &ngroups) >= 0) {
|
||||
for (int i = 0; i < ngroups; i++) {
|
||||
if (groups[i] == target_gid) return 1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int check_authorization(const char *caller, int *is_nopasswd) {
|
||||
*is_nopasswd = 0;
|
||||
|
||||
/* Root zawsze ma pelne uprawnienia */
|
||||
if (strcmp(caller, "root") == 0) {
|
||||
*is_nopasswd = 1;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Uzytkownik 'live' w trybie LiveCD ma uprawnienia NOPASSWD */
|
||||
if (strcmp(caller, "live") == 0) {
|
||||
*is_nopasswd = 1;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Czlonkowie grupy wheel maja domyslnie uprawnienia */
|
||||
if (is_user_in_group(caller, "wheel")) {
|
||||
*is_nopasswd = 1;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Parsowanie /etc/sudoers */
|
||||
FILE *f = fopen(SUDOERS_FILE, "r");
|
||||
if (!f) return 0;
|
||||
|
||||
char line[512];
|
||||
int authorized = 0;
|
||||
|
||||
while (fgets(line, sizeof(line), f)) {
|
||||
char *p = line;
|
||||
while (*p == ' ' || *p == '\t') p++;
|
||||
if (*p == '#' || *p == '\0' || *p == '\n') continue;
|
||||
|
||||
char *nl = strchr(p, '\n');
|
||||
if (nl) *nl = '\0';
|
||||
|
||||
char token[64];
|
||||
if (sscanf(p, "%63s", token) != 1) continue;
|
||||
|
||||
int match = 0;
|
||||
if (token[0] == '%') {
|
||||
if (is_user_in_group(caller, token + 1)) match = 1;
|
||||
} else if (strcmp(token, caller) == 0) {
|
||||
match = 1;
|
||||
}
|
||||
|
||||
if (match) {
|
||||
authorized = 1;
|
||||
if (strstr(p, "NOPASSWD") != NULL) {
|
||||
*is_nopasswd = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
fclose(f);
|
||||
|
||||
return authorized;
|
||||
}
|
||||
|
||||
static int verify_password(const char *username) {
|
||||
const char *hash = NULL;
|
||||
struct spwd *sp = getspnam(username);
|
||||
if (sp && sp->sp_pwdp && sp->sp_pwdp[0]) {
|
||||
hash = sp->sp_pwdp;
|
||||
} else {
|
||||
struct passwd *pw = getpwnam(username);
|
||||
if (pw && pw->pw_passwd && pw->pw_passwd[0] && strcmp(pw->pw_passwd, "x") != 0) {
|
||||
hash = pw->pw_passwd;
|
||||
}
|
||||
}
|
||||
|
||||
/* Puste haslo lub brak hasla */
|
||||
if (!hash || hash[0] == '\0') {
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Zablokowane konto */
|
||||
if (hash[0] == '!' || hash[0] == '*') {
|
||||
fprintf(stderr, "sudo: konto uzytkownika '%s' jest zablokowane.\n", username);
|
||||
return 0;
|
||||
}
|
||||
|
||||
char prompt[128];
|
||||
snprintf(prompt, sizeof(prompt), "[sudo] haslo dla uzytkownika %s: ", username);
|
||||
char *pass = getpass(prompt);
|
||||
if (!pass) return 0;
|
||||
|
||||
char *encrypted = crypt(pass, hash);
|
||||
if (encrypted && strcmp(encrypted, hash) == 0) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
fprintf(stderr, "sudo: niepoprawne haslo.\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void sanitize_environment(int preserve_env, const char *target_user, const char *target_dir, const char *target_shell) {
|
||||
/* Bezwzgledne usuwanie zmiennych dynamicznego linkera i loaderow */
|
||||
for (int i = 0; dangerous_env[i] != NULL; i++) {
|
||||
unsetenv(dangerous_env[i]);
|
||||
}
|
||||
|
||||
if (!preserve_env) {
|
||||
/* Zachowaj tylko scisle okreslone bezpieczne zmienne */
|
||||
char *term = getenv("TERM") ? strdup(getenv("TERM")) : NULL;
|
||||
char *disp = getenv("DISPLAY") ? strdup(getenv("DISPLAY")) : NULL;
|
||||
char *xauth = getenv("XAUTHORITY") ? strdup(getenv("XAUTHORITY")) : NULL;
|
||||
char *lang = getenv("LANG") ? strdup(getenv("LANG")) : NULL;
|
||||
char *color = getenv("COLORTERM") ? strdup(getenv("COLORTERM")) : NULL;
|
||||
|
||||
clearenv();
|
||||
|
||||
setenv("PATH", DEFAULT_SECURE_PATH, 1);
|
||||
setenv("USER", target_user, 1);
|
||||
setenv("LOGNAME", target_user, 1);
|
||||
setenv("HOME", target_dir, 1);
|
||||
setenv("SHELL", target_shell, 1);
|
||||
|
||||
if (term) { setenv("TERM", term, 1); free(term); }
|
||||
if (disp) { setenv("DISPLAY", disp, 1); free(disp); }
|
||||
if (xauth) { setenv("XAUTHORITY", xauth, 1); free(xauth); }
|
||||
if (lang) { setenv("LANG", lang, 1); free(lang); }
|
||||
if (color) { setenv("COLORTERM", color, 1); free(color); }
|
||||
} else {
|
||||
/* -E zachowuje zmienne, ale weryfikuje bezpieczenstwo PATH */
|
||||
const char *p = getenv("PATH");
|
||||
if (!p || strstr(p, "..") || strstr(p, "/tmp") || strstr(p, "./") || p[0] == ':' || p[0] == '.') {
|
||||
setenv("PATH", DEFAULT_SECURE_PATH, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
uid_t ruid = getuid();
|
||||
uid_t euid = geteuid();
|
||||
|
||||
if (euid != 0) {
|
||||
fprintf(stderr, "sudo: blad: plik wykonywalny musi posiadac bit SUID root (chmod 4755 %s)!\n", argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
struct passwd *caller_pw = getpwuid(ruid);
|
||||
char caller_name[64];
|
||||
if (caller_pw && caller_pw->pw_name) {
|
||||
strncpy(caller_name, caller_pw->pw_name, sizeof(caller_name) - 1);
|
||||
caller_name[sizeof(caller_name) - 1] = '\0';
|
||||
} else {
|
||||
snprintf(caller_name, sizeof(caller_name), "uid%u", (unsigned int)ruid);
|
||||
}
|
||||
|
||||
int is_nopasswd = 0;
|
||||
if (!check_authorization(caller_name, &is_nopasswd)) {
|
||||
fprintf(stderr, "sudo: uzytkownik '%s' nie znajduje sie w pliku %s. Zgloszenie zostanie zarejestrowane.\n",
|
||||
caller_name, SUDOERS_FILE);
|
||||
return 1;
|
||||
}
|
||||
|
||||
const char *target_user = "root";
|
||||
const char *target_group = NULL;
|
||||
int login_shell = 0;
|
||||
int run_shell = 0;
|
||||
int preserve_env = 0;
|
||||
int cmd_start = -1;
|
||||
|
||||
for (int i = 1; i < argc; i++) {
|
||||
if (strcmp(argv[i], "--") == 0) {
|
||||
cmd_start = i + 1;
|
||||
break;
|
||||
}
|
||||
if (argv[i][0] == '-' && cmd_start == -1) {
|
||||
if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) {
|
||||
print_usage(argv[0]);
|
||||
return 0;
|
||||
}
|
||||
if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--validate") == 0) {
|
||||
if (!is_nopasswd && !verify_password(caller_name)) return 1;
|
||||
return 0;
|
||||
}
|
||||
if (strcmp(argv[i], "-i") == 0) {
|
||||
login_shell = 1;
|
||||
continue;
|
||||
}
|
||||
if (strcmp(argv[i], "-s") == 0) {
|
||||
run_shell = 1;
|
||||
continue;
|
||||
}
|
||||
if (strcmp(argv[i], "-E") == 0 || strcmp(argv[i], "--preserve-env") == 0) {
|
||||
preserve_env = 1;
|
||||
continue;
|
||||
}
|
||||
if (strcmp(argv[i], "-u") == 0) {
|
||||
if (i + 1 < argc) {
|
||||
target_user = argv[++i];
|
||||
continue;
|
||||
} else {
|
||||
fprintf(stderr, "sudo: opcja '-u' wymaga podania nazwy uzytkownika\n");
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
if (strcmp(argv[i], "-g") == 0) {
|
||||
if (i + 1 < argc) {
|
||||
target_group = argv[++i];
|
||||
continue;
|
||||
} else {
|
||||
fprintf(stderr, "sudo: opcja '-g' wymaga podania nazwy grupy\n");
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
fprintf(stderr, "sudo: nieznana opcja: %s\n", argv[i]);
|
||||
print_usage(argv[0]);
|
||||
return 1;
|
||||
} else {
|
||||
cmd_start = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!is_nopasswd) {
|
||||
if (!verify_password(caller_name)) {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
struct passwd *target_pw = getpwnam(target_user);
|
||||
if (!target_pw) {
|
||||
fprintf(stderr, "sudo: nieznany uzytkownik docelowy: '%s'\n", target_user);
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Kopia pol target_pw poniewaz kolejne wywolania moga nadpisac strukture */
|
||||
uid_t target_uid = target_pw->pw_uid;
|
||||
gid_t target_gid = target_pw->pw_gid;
|
||||
char target_name[64];
|
||||
char target_dir[256];
|
||||
char target_shell[128];
|
||||
strncpy(target_name, target_pw->pw_name, sizeof(target_name) - 1);
|
||||
target_name[sizeof(target_name) - 1] = '\0';
|
||||
strncpy(target_dir, target_pw->pw_dir, sizeof(target_dir) - 1);
|
||||
target_dir[sizeof(target_dir) - 1] = '\0';
|
||||
strncpy(target_shell, target_pw->pw_shell, sizeof(target_shell) - 1);
|
||||
target_shell[sizeof(target_shell) - 1] = '\0';
|
||||
|
||||
if (target_group) {
|
||||
struct group *target_gr = getgrnam(target_group);
|
||||
if (!target_gr) {
|
||||
fprintf(stderr, "sudo: nieznana grupa docelowa: '%s'\n", target_group);
|
||||
return 1;
|
||||
}
|
||||
target_gid = target_gr->gr_gid;
|
||||
}
|
||||
|
||||
char *cmd_argv[512];
|
||||
int cmd_argc = 0;
|
||||
|
||||
if (login_shell || (run_shell && cmd_start == -1)) {
|
||||
const char *shell = target_shell;
|
||||
if (!shell || !shell[0]) shell = "/bin/sh";
|
||||
|
||||
cmd_argv[cmd_argc++] = (char *)shell;
|
||||
if (login_shell) {
|
||||
cmd_argv[cmd_argc++] = "-l";
|
||||
}
|
||||
cmd_argv[cmd_argc] = NULL;
|
||||
} else if (cmd_start != -1) {
|
||||
for (int i = cmd_start; i < argc && cmd_argc < 510; i++) {
|
||||
cmd_argv[cmd_argc++] = argv[i];
|
||||
}
|
||||
cmd_argv[cmd_argc] = NULL;
|
||||
} else {
|
||||
print_usage(argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Oczyszczanie i konfiguracja srodowiska przed exec */
|
||||
if (login_shell) {
|
||||
sanitize_environment(0, target_name, target_dir, target_shell);
|
||||
if (chdir(target_dir) != 0) {
|
||||
chdir("/");
|
||||
}
|
||||
} else {
|
||||
sanitize_environment(preserve_env, target_name, target_dir, target_shell);
|
||||
}
|
||||
|
||||
char uid_str[32], gid_str[32];
|
||||
snprintf(uid_str, sizeof(uid_str), "%u", (unsigned int)ruid);
|
||||
snprintf(gid_str, sizeof(gid_str), "%u", (unsigned int)(caller_pw ? caller_pw->pw_gid : 0));
|
||||
setenv("SUDO_USER", caller_name, 1);
|
||||
setenv("SUDO_UID", uid_str, 1);
|
||||
setenv("SUDO_GID", gid_str, 1);
|
||||
|
||||
/* Zmiana uprawnien i grup */
|
||||
if (initgroups(target_name, target_gid) != 0) {
|
||||
perror("sudo: nie mozna zainicjalizowac grup pomocniczych (initgroups)");
|
||||
return 1;
|
||||
}
|
||||
if (setgid(target_gid) != 0) {
|
||||
perror("sudo: nie mozna zmienic grupy (setgid)");
|
||||
return 1;
|
||||
}
|
||||
if (setuid(target_uid) != 0) {
|
||||
perror("sudo: nie mozna zmienic uzytkownika (setuid)");
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Bezposrednie wykonanie polecenia z prawami docelowego uzytkownika */
|
||||
execvp(cmd_argv[0], cmd_argv);
|
||||
|
||||
/* Jesli execvp zwrocilo blad */
|
||||
fprintf(stderr, "sudo: nie mozna uruchomic '%s': %s\n", cmd_argv[0], strerror(errno));
|
||||
return (errno == ENOENT) ? 127 : 126;
|
||||
}
|
||||
Reference in New Issue
Block a user