installer.py (40675B)
1 from glob import glob 2 import os 3 import subprocess 4 import time 5 import gettext 6 import parted 7 import partitioning 8 import alongside 9 import shlex 10 from functools import cmp_to_key 11 12 gettext.install("live-installer", "/usr/share/locale") 13 14 class InstallerEngine: 15 ''' This is central to the live installer ''' 16 17 def __init__(self, setup): 18 self.setup = setup 19 # the live system image, mounted there by the chamesle initramfs 20 self.source = "/run/chamesle/rootfs" 21 22 def set_progress_hook(self, progresshook): 23 ''' Set a callback to be called on progress updates ''' 24 ''' i.e. def my_callback(progress_type, message, current_progress, total) ''' 25 ''' Where progress_type is any off PROGRESS_START, PROGRESS_UPDATE, PROGRESS_COMPLETE, PROGRESS_ERROR ''' 26 self.update_progress = progresshook 27 28 def set_error_hook(self, errorhook): 29 ''' Set a callback to be called on errors ''' 30 self.set_critical_error = errorhook 31 32 def setup_user(self): 33 print(" --> Adding new user") 34 groups = [] 35 with open("/target/etc/group") as f: 36 existing = [line.split(":")[0] for line in f] 37 for group in 'wheel audio video input network storage optical scanner lp plugdev bluetooth users kvm'.split(): 38 if group in existing: 39 groups.append(group) 40 subprocess.run(["chroot", "/target", "useradd", "-m", "-s", "/bin/bash", "-c", self.setup.real_name, 41 "-G", ",".join(groups), self.setup.username]) 42 43 # through stdin: never in a file or on a command line. -c: hash it here, the pam setup for chpasswd 44 # doesn't store anything 45 subprocess.run(["chroot", "/target", "chpasswd", "-c", "SHA512"], 46 input="%s:%s\n" % (self.setup.username, self.setup.password1), text=True) 47 48 # the sign-in screen the edition uses (the build left it in /etc/chamesle/login): sddm is installed everywhere, 49 # but gnome signs in with gdm 50 try: 51 login = open("/target/etc/chamesle/login").read().strip() 52 except OSError: 53 login = "" 54 if self.setup.autologin and login == "gdm" and os.path.exists("/target/etc/gdm/custom.conf"): 55 os.system("sed -i 's/^\\[daemon\\]$/&\\nAutomaticLoginEnable=True\\nAutomaticLogin=%s/' /target/etc/gdm/custom.conf" 56 % self.setup.username) 57 elif self.setup.autologin and os.path.exists("/target/usr/bin/sddm"): 58 # sddm needs the session too: the edition's default, which the build left in /etc/chamesle/session 59 try: 60 session = open("/target/etc/chamesle/session").read().strip() 61 except OSError: 62 session = "" 63 if session and not session.endswith(".desktop"): 64 session += ".desktop" 65 os.makedirs("/target/etc/sddm.conf.d", exist_ok=True) 66 with open("/target/etc/sddm.conf.d/80-autologin.conf", "w") as f: 67 f.write("[Autologin]\nUser=%s\nSession=%s\n" % (self.setup.username, session)) 68 elif self.setup.autologin: 69 os.makedirs("/target/etc/lightdm/lightdm.conf.d", exist_ok=True) 70 with open("/target/etc/lightdm/lightdm.conf.d/80-autologin.conf", "w") as f: 71 f.write("[Seat:*]\nautologin-user=%s\n" % self.setup.username) 72 73 def setup_hostname(self): 74 print(" --> Writing hostname") 75 hostnamefh = open("/target/etc/hostname", "w") 76 hostnamefh.write("%s\n" % self.setup.hostname) 77 hostnamefh.close() 78 hostsfh = open("/target/etc/hosts", "w") 79 hostsfh.write("127.0.0.1\tlocalhost\n") 80 hostsfh.write("127.0.1.1\t%s\n" % self.setup.hostname) 81 hostsfh.write("# The following lines are desirable for IPv6 capable hosts\n") 82 hostsfh.write("::1 localhost ip6-localhost ip6-loopback\n") 83 hostsfh.write("fe00::0 ip6-localnet\n") 84 hostsfh.write("ff00::0 ip6-mcastprefix\n") 85 hostsfh.write("ff02::1 ip6-allnodes\n") 86 hostsfh.write("ff02::2 ip6-allrouters\n") 87 hostsfh.write("ff02::3 ip6-allhosts\n") 88 hostsfh.close() 89 90 def setup_locale(self): 91 print(" --> Setting the locale") 92 locale = "%s.UTF-8" % self.setup.language 93 path = "/target/etc/default/libc-locales" 94 lines = open(path).read().split("\n") if os.path.exists(path) else [] 95 wanted = "%s UTF-8" % locale 96 found = False 97 for i, line in enumerate(lines): 98 if line.lstrip("#").strip() == wanted: 99 lines[i] = wanted 100 found = True 101 if not found: 102 lines.append(wanted) 103 with open(path, "w") as f: 104 f.write("\n".join(lines).rstrip("\n") + "\n") 105 self.do_run_in_chroot("locale-gen") 106 with open("/target/etc/locale.conf", "w") as f: 107 f.write("LANG=%s\n" % locale) 108 109 def setup_timezone(self): 110 print(" --> Setting the timezone") 111 os.system("echo \"%s\" > /target/etc/timezone" % self.setup.timezone) 112 os.system("rm -f /target/etc/localtime") 113 os.system("ln -s /usr/share/zoneinfo/%s /target/etc/localtime" % self.setup.timezone) 114 115 def setup_localization(self): 116 # firefox in your language, if we're online 117 if self.setup.language.startswith("en"): 118 return 119 print(" --> Localizing packages") 120 lang = self.setup.language.split("_")[0] 121 for pkg in ("firefox-i18n-%s" % self.setup.language.replace("_", "-"), "firefox-i18n-%s" % lang): 122 if subprocess.run(["chroot", "/target", "apk", "add", "--quiet", pkg]).returncode == 0: 123 break 124 125 def setup_keyboard(self): 126 print(" --> Setting the keyboard") 127 os.makedirs("/target/etc/X11/xorg.conf.d", exist_ok=True) 128 with open("/target/etc/X11/xorg.conf.d/00-keyboard.conf", "w") as f: 129 f.write('Section "InputClass"\n' 130 ' Identifier "system-keyboard"\n' 131 ' MatchIsKeyboard "on"\n' 132 ' Option "XkbLayout" "%s"\n' 133 ' Option "XkbModel" "%s"\n' 134 ' Option "XkbVariant" "%s"\n' 135 ' Option "XkbOptions" "grp:win_space_toggle"\n' 136 'EndSection\n' % (self.setup.keyboard_layout, self.setup.keyboard_model, 137 self.setup.keyboard_variant or "")) 138 # the console takes the last layout (the one that isn't "us," for non-latin ones) 139 keymap = self.setup.keyboard_layout.split(",")[-1] 140 variant = (self.setup.keyboard_variant or "").split(",")[-1] 141 if variant and os.system("find /target/usr/share/kbd/keymaps -name '%s-%s.map*' | grep -q ." % (keymap, variant)) == 0: 142 keymap = "%s-%s" % (keymap, variant) 143 with open("/target/etc/vconsole.conf", "w") as f: 144 f.write("KEYMAP=%s\n" % keymap) 145 146 def start_installation(self): 147 148 # mount the media location. 149 print(" --> Installation started") 150 if(not os.path.exists("/target")): 151 if (self.setup.skip_mount): 152 self.set_critical_error(message=_("ERROR: You must first manually mount your target filesystem(s) at /target to do a custom install!")) 153 return 154 os.mkdir("/target") 155 156 os.system("umount --force /target/sys/firmware/efi/efivars") 157 os.system("umount --force /target/dev/shm") 158 os.system("umount --force /target/dev/pts") 159 os.system("umount --force /target/dev/") 160 os.system("umount --force /target/sys/") 161 os.system("umount --force /target/proc/") 162 os.system("umount --force /target/run/") 163 164 print(" --> Mounting partitions") 165 self.update_progress(50, False, False, _("Mounting partitions...")) 166 if not os.path.isdir(os.path.join(self.source, "usr")) and not __debug__: 167 print("Live system expected at %s" % self.source) 168 self.set_critical_error(message=_("Live medium not found!")) 169 return 170 171 def rootiest_first(parta, partb): 172 if parta.mount_as == None or parta.mount_as == "" or \ 173 partb.mount_as == None or partb.mount_as == "": 174 return 0 175 176 if len(parta.mount_as) > len(partb.mount_as): 177 return 1 178 elif len(partb.mount_as) > len(parta.mount_as): 179 return -1 180 else: 181 return 0 182 183 self.setup.partitions.sort(key=cmp_to_key(rootiest_first)) 184 185 print("********** Partition mount order ***") 186 for part in self.setup.partitions: 187 print(part.mount_as) 188 print("************************************") 189 190 if (not self.setup.skip_mount): 191 if self.setup.automated: 192 self.create_partitions() 193 else: 194 self.format_partitions() 195 self.mount_partitions() 196 197 # Transfer the files 198 SOURCE = self.source + "/" 199 DEST = "/target/" 200 EXCLUDE_DIRS = "home/* dev/* proc/* sys/* tmp/* run/* mnt/* media/* lost+found source target".split() 201 num_copied = 0 202 # (Valid) assumption: num-of-files-to-copy ~= num-of-used-inodes-on-/ 203 num_files = int(subprocess.getoutput("df --inodes {src} | awk 'END{{ print $3 }}'".format(src=SOURCE))) 204 print(f" --> Copying {num_files} files") 205 rsync_filter = ' '.join('--exclude=' + SOURCE + d for d in EXCLUDE_DIRS) 206 rsync = subprocess.Popen("rsync --verbose --archive --no-D --acls " 207 "--hard-links --xattrs {rsync_filter} " 208 "{src}* {dst}".format(src=SOURCE, dst=DEST, rsync_filter=rsync_filter), 209 shell=True, encoding='utf-8', errors='ignore', stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 210 while rsync.poll() is None: 211 line = rsync.stdout.readline() 212 if not line: # still copying the previous file, just wait 213 time.sleep(0.1) 214 else: 215 num_copied = min(num_copied + 1, num_files) 216 percentage = int(float(num_copied) / float(num_files) * 100) 217 self.update_progress(percentage, False, False, _("Copying files...")) 218 print("rsync exited with returncode: " + str(rsync.poll())) 219 220 # chroot 221 print(" --> Chrooting") 222 self.update_progress(10, False, False, _("Entering the system...")) 223 os.system("mount --bind /dev/ /target/dev/") 224 os.system("mount --bind /dev/shm /target/dev/shm") 225 os.system("mount --bind /dev/pts /target/dev/pts") 226 os.system("mount --bind /sys/ /target/sys/") 227 os.system("mount --bind /proc/ /target/proc/") 228 os.system("mount --bind /run/ /target/run/") 229 os.system("mv /target/etc/resolv.conf /target/etc/resolv.conf.bk") 230 os.system("cp -f /etc/resolv.conf /target/etc/resolv.conf") 231 232 if os.path.exists("/sys/firmware/efi/efivars"): 233 os.system("mkdir -p /target/sys/firmware/efi/efivars") 234 os.system("mount --bind /sys/firmware/efi/efivars /target/sys/firmware/efi/efivars/") 235 236 # remove what only the live session has 237 print(" --> Removing live configuration") 238 self.update_progress(20, False, False, _("Removing live configuration (packages)")) 239 for path in ("/etc/sudoers.d/live", "/etc/polkit-1/rules.d/49-live.rules", "/etc/lightdm/lightdm.conf.d/90-live.conf", 240 "/etc/sddm.conf.d/90-live.conf", 241 "/usr/share/applications/chamesle-install.desktop", "/usr/bin/chamesle-install", 242 "/usr/bin/live-installer", "/usr/lib/live-installer", "/usr/share/live-installer", 243 "/usr/share/icons/live-installer-progress-dot-on.png", 244 "/usr/share/icons/live-installer-progress-dot-off.png", "/var/lib/AccountsService/users/live"): 245 os.system("rm -rf /target%s" % path) 246 # gdm keeps the live autologin in its one config file 247 if os.path.exists("/target/etc/gdm/custom.conf"): 248 os.system("sed -i '/^# the live session only$/d; /^AutomaticLogin/d' /target/etc/gdm/custom.conf") 249 self.do_run_in_chroot("userdel -r live") 250 251 # add new user 252 self.update_progress(30, False, False, _("Adding new user to the system")) 253 self.setup_user() 254 255 # Lock and delete root password 256 self.do_run_in_chroot("passwd -dl root") 257 258 # Set LightDM to show user list by default 259 if os.path.exists("/target/etc/lightdm/lightdm.conf"): 260 self.do_run_in_chroot(r"sed -i -r 's/^#?(greeter-hide-users)\s*=.*/\1=false/' /etc/lightdm/lightdm.conf") 261 262 # /etc/fstab, mtab and crypttab 263 self.update_progress(40, False, False, _("Writing filesystem mount information to /etc/fstab")) 264 self.write_fstab() 265 self.write_mtab() 266 self.write_crypttab() 267 268 def create_partitions(self): 269 if self.setup.alongside: 270 return self.create_alongside() 271 # Create partitions on the selected disk (automated installation) 272 partition_prefix = partitioning.get_device_naming_scheme_prefix(self.setup.disk) 273 if self.setup.luks: 274 if self.setup.gptonefi: 275 # EFI+LUKS/LVM 276 # sdx1=EFI, sdx2=BOOT, sdx3=ROOT 277 self.auto_efi_partition = self.setup.disk + partition_prefix + "1" 278 self.auto_boot_partition = self.setup.disk + partition_prefix + "2" 279 self.auto_swap_partition = None 280 self.auto_root_partition = self.setup.disk + partition_prefix + "3" 281 else: 282 # BIOS+LUKS/LVM 283 # sdx1=BOOT, sdx2=ROOT 284 self.auto_efi_partition = None 285 self.auto_boot_partition = self.setup.disk + partition_prefix + "1" 286 self.auto_swap_partition = None 287 self.auto_root_partition = self.setup.disk + partition_prefix + "2" 288 elif self.setup.lvm: 289 if self.setup.gptonefi: 290 # EFI+LVM 291 # sdx1=EFI, sdx2=ROOT 292 self.auto_efi_partition = self.setup.disk + partition_prefix + "1" 293 self.auto_boot_partition = None 294 self.auto_swap_partition = None 295 self.auto_root_partition = self.setup.disk + partition_prefix + "2" 296 else: 297 # BIOS+LVM: 298 # sdx1=ROOT 299 self.auto_efi_partition = None 300 self.auto_boot_partition = None 301 self.auto_swap_partition = None 302 self.auto_root_partition = self.setup.disk + partition_prefix + "1" 303 else: 304 if self.setup.gptonefi: 305 # EFI 306 # sdx1=EFI, sdx2=SWAP, sdx3=ROOT 307 self.auto_efi_partition = self.setup.disk + partition_prefix + "1" 308 self.auto_boot_partition = None 309 self.auto_swap_partition = self.setup.disk + partition_prefix + "2" 310 self.auto_root_partition = self.setup.disk + partition_prefix + "3" 311 else: 312 # BIOS: 313 # sdx1=SWAP, sdx2=ROOT 314 self.auto_efi_partition = None 315 self.auto_boot_partition = None 316 self.auto_swap_partition = self.setup.disk + partition_prefix + "1" 317 self.auto_root_partition = self.setup.disk + partition_prefix + "2" 318 319 self.auto_root_physical_partition = self.auto_root_partition 320 321 # Wipe HDD 322 if self.setup.badblocks: 323 self.update_progress(25, False, False, _("Filling disk with random data (please be patient, this can take hours...)")) 324 print(" --> Filling %s with random data" % self.setup.disk) 325 os.system("badblocks -c 10240 -s -w -t random -v %s" % self.setup.disk) 326 327 # Create partitions 328 self.update_progress(25, False, False, _("Creating partitions on %s") % self.setup.disk) 329 print(" --> Creating partitions on %s" % self.setup.disk) 330 disk_device = parted.getDevice(self.setup.disk) 331 partitioning.full_disk_format(disk_device, create_boot=(self.auto_boot_partition is not None), create_swap=(self.auto_swap_partition is not None)) 332 333 # Encrypt root partition 334 if self.setup.luks: 335 print(" --> Encrypting root partition %s" % self.auto_root_partition) 336 # the passphrase goes in on stdin, where ps can't see it and echo can't eat a leading -n or -e 337 subprocess.run(["cryptsetup", "luksFormat", "--batch-mode", "-c", "aes-xts-plain64", "-h", "sha256", "-s", "512", 338 "--key-file=-", self.auto_root_partition], input=self.setup.passphrase1, text=True) 339 print(" --> Opening root partition %s" % self.auto_root_partition) 340 subprocess.run(["cryptsetup", "luksOpen", "--key-file=-", self.auto_root_partition, "chamesle"], 341 input=self.setup.passphrase1, text=True) 342 self.auto_root_partition = "/dev/mapper/chamesle" 343 344 # Setup LVM 345 if self.setup.lvm: 346 print(" --> LVM: Creating PV") 347 os.system("pvcreate -y %s" % self.auto_root_partition) 348 print(" --> LVM: Creating VG") 349 os.system("vgcreate -y chamesle %s" % self.auto_root_partition) 350 print(" --> LVM: Creating LV root") 351 os.system("lvcreate -y -n root -L 1GB chamesle") 352 print(" --> LVM: Creating LV swap") 353 os.system("lvcreate -y -n swap -L 2GB chamesle") 354 print(" --> LVM: Extending LV root") 355 os.system(r"lvextend -l 100%FREE /dev/chamesle/root") 356 print(" --> LVM: Formatting LV swap") 357 os.system("mkswap -f /dev/mapper/chamesle-swap") 358 print(" --> LVM: Enabling LV swap") 359 os.system("swapon /dev/mapper/chamesle-swap") 360 self.auto_root_partition = "/dev/mapper/chamesle-root" 361 self.auto_swap_partition = "/dev/mapper/chamesle-swap" 362 363 self.make_root_btrfs(self.auto_root_partition) 364 if (self.auto_boot_partition is not None): 365 os.system("mkdir -p /target/boot") 366 self.do_mount(self.auto_boot_partition, "/target/boot", "ext4", None) 367 if (self.auto_efi_partition is not None): 368 os.system("mkdir -p /target/boot/efi") 369 self.do_mount(self.auto_efi_partition, "/target/boot/efi", "vfat", None) 370 371 def make_root_btrfs(self, device): 372 # btrfs, with the system in @ and your files in @home: the system gets snapshotted before updates 373 # (chamesle-snapshot), your files never 374 print(" --> Formatting %s as btrfs (@ and @home)" % device) 375 self.exec_cmd("mkfs.btrfs -f %s" % device) 376 self.do_mount(device, "/target", "btrfs", None) 377 os.system("btrfs subvolume create /target/@ /target/@home") 378 os.system("umount /target") 379 self.do_mount(device, "/target", "btrfs", "subvol=@") 380 os.makedirs("/target/home", exist_ok=True) 381 self.do_mount(device, "/target/home", "btrfs", "subvol=@home") 382 383 def create_alongside(self): 384 win = self.setup.windows 385 self.update_progress(15, True, False, _("Shrinking Windows (this can take a while)")) 386 print(" --> Shrinking %s to make room for %d bytes" % (win["path"], self.setup.alongside_size)) 387 root = alongside.shrink_and_make_room(win, self.setup.alongside_size) 388 self.auto_root_partition = self.auto_root_physical_partition = root 389 self.auto_boot_partition = self.auto_swap_partition = None 390 self.auto_efi_partition = alongside.find_esp(win["disk"]) if self.setup.gptonefi else None 391 self.update_progress(25, False, False, _("Formatting partitions...")) 392 self.make_root_btrfs(root) 393 if self.auto_efi_partition is not None: 394 # windows' own EFI partition, shared, not formatted 395 os.system("mkdir -p /target/boot/efi") 396 self.do_mount(self.auto_efi_partition, "/target/boot/efi", "vfat", None) 397 398 def format_partitions(self): 399 for partition in self.setup.partitions: 400 if(partition.format_as is not None and partition.format_as != ""): 401 # report it. should grab the total count of filesystems to be formatted .. 402 self.update_progress(25, True, False, _("Formatting partitions...")) 403 404 #Format it 405 if partition.format_as == "swap": 406 cmd = "mkswap %s" % partition.path 407 else: 408 if (partition.format_as in ['ext2', 'ext3', 'ext4']): 409 cmd = "mkfs.%s -F %s" % (partition.format_as, partition.path) 410 elif (partition.format_as == "jfs"): 411 cmd = "mkfs.%s -q %s" % (partition.format_as, partition.path) 412 elif (partition.format_as in ["btrfs", "xfs"]): 413 cmd = "mkfs.%s -f %s" % (partition.format_as, partition.path) 414 elif (partition.format_as == "vfat"): 415 cmd = "mkfs.%s %s -F 32" % (partition.format_as, partition.path) 416 else: 417 cmd = "mkfs.%s %s" % (partition.format_as, partition.path) # works with bfs, minix, msdos, ntfs, vfat 418 419 print("EXECUTING: '%s'" % cmd) 420 self.exec_cmd(cmd) 421 partition.type = partition.format_as 422 423 def mount_partitions(self): 424 # Mount the target partition 425 for partition in self.setup.partitions: 426 if(partition.mount_as is not None and partition.mount_as != ""): 427 if partition.mount_as == "/": 428 self.update_progress(75, False, False, _("Mounting %(partition)s on %(mountpoint)s") % {'partition':partition.path, 'mountpoint':"/target/"}) 429 print(" ------ Mounting partition %s on %s" % (partition.path, "/target/")) 430 fs = partition.type 431 if fs == "fat32": 432 fs = "vfat" 433 self.do_mount(partition.path, "/target", fs, None) 434 if fs == "btrfs": 435 # Create subvolumes for Btrfs 436 os.system("btrfs subvolume create /target/@") 437 os.system("btrfs subvolume list -p /target") 438 print(" ------ Umount btrfs to remount subvolume @") 439 os.system("umount --force /target") 440 self.do_mount(partition.path, "/target", fs, "subvol=@") 441 if not self.setup_has_dedicated_home(): 442 # If there is no dedicated home partition, add a @home subvolume to / 443 os.system("mkdir -p /target/home") 444 self.do_mount(partition.path, "/target/home", fs, None) 445 os.system("btrfs subvolume create /target/home/@home") 446 os.system("btrfs subvolume list -p /target/home") 447 print(" ------- Umount btrfs to remount subvolume @home") 448 os.system("umount --force /target/home") 449 self.do_mount(partition.path, "/target/home", fs, "subvol=@home") 450 break 451 452 # Mount the other partitions 453 for partition in self.setup.partitions: 454 if(partition.mount_as is not None and partition.mount_as != "" and partition.mount_as != "/" and partition.mount_as != "swap"): 455 print(" ------ Mounting %s on %s" % (partition.path, "/target" + partition.mount_as)) 456 os.system("mkdir -p /target" + partition.mount_as) 457 fs = partition.type 458 if fs == "fat16" or fs == "fat32": 459 fs = "vfat" 460 self.do_mount(partition.path, "/target" + partition.mount_as, fs, None) 461 if partition.mount_as == "/home" and fs == "btrfs": 462 # Dedicated home partition with Btrfs, needs a @home subvolume 463 os.system("btrfs subvolume create /target/home/@home") 464 os.system("btrfs subvolume list -p /target/home") 465 print(" ------- Umount btrfs to remount subvolume @home") 466 os.system("umount --force /target/home") 467 self.do_mount(partition.path, "/target/home", fs, "subvol=@home") 468 469 def get_blkid(self, path): 470 uuid = path # If we can't find the UUID we use the path 471 blkid = subprocess.getoutput('blkid').split('\n') 472 for blkid_line in blkid: 473 blkid_elements = blkid_line.split(':') 474 if blkid_elements[0] == path: 475 blkid_mini_elements = blkid_line.split() 476 for blkid_mini_element in blkid_mini_elements: 477 if "UUID=" in blkid_mini_element: 478 uuid = blkid_mini_element.replace('"', '').strip() 479 break 480 break 481 return uuid 482 483 def setup_has_dedicated_home(self): 484 # Find out if there is a dedicated home partition 485 has_dedicated_home = False 486 for partition in self.setup.partitions: 487 if partition.mount_as == "/home": 488 has_dedicated_home = True 489 break 490 return has_dedicated_home 491 492 def write_fstab(self, path="/target/etc/fstab"): 493 # write the /etc/fstab 494 print(" --> Writing fstab") 495 # make sure fstab has default /proc and /sys entries 496 fstab = open(path, "w") 497 fstab.write("#### Static Filesystem Table File\n") 498 fstab.write("proc\t/proc\tproc\tdefaults\t0\t0\n") 499 if(not self.setup.skip_mount): 500 if self.setup.automated: 501 fstab.write("# %s\n" % self.auto_root_partition) 502 root_uuid = self.get_blkid(self.auto_root_partition) 503 fstab.write("%s / btrfs defaults,subvol=@ 0 0\n" % root_uuid) 504 fstab.write("%s /home btrfs defaults,subvol=@home 0 0\n" % root_uuid) 505 if self.auto_swap_partition is not None: 506 fstab.write("# %s\n" % self.auto_swap_partition) 507 fstab.write("%s none swap sw 0 0\n" % self.get_blkid(self.auto_swap_partition)) 508 if (self.auto_boot_partition is not None): 509 fstab.write("# %s\n" % self.auto_boot_partition) 510 fstab.write("%s /boot ext4 defaults 0 1\n" % self.get_blkid(self.auto_boot_partition)) 511 if (self.auto_efi_partition is not None): 512 fstab.write("# %s\n" % self.auto_efi_partition) 513 fstab.write("%s /boot/efi vfat defaults 0 1\n" % self.get_blkid(self.auto_efi_partition)) 514 else: 515 for partition in self.setup.partitions: 516 if (partition.mount_as is not None and partition.mount_as != "" and partition.mount_as != "None"): 517 fs = partition.type 518 if fs == "fat16" or fs == "fat32": 519 fs = "vfat" 520 fstab.write("# %s\n" % (partition.path)) 521 fstab_fsck_option = "0" 522 if fs != "btrfs" and partition.mount_as in ["/", "/boot", "/boot/efi"]: 523 fstab_fsck_option = "1" 524 if "ext" in fs: 525 fstab_mount_options = "rw,errors=remount-ro" 526 elif fs == "btrfs" and partition.mount_as == "/": 527 fstab_mount_options = "defaults,subvol=@" 528 elif fs == "btrfs" and partition.mount_as == "/home": 529 fstab_mount_options = "defaults,subvol=@home" 530 else: 531 fstab_mount_options = "defaults" 532 533 partition_uuid = self.get_blkid(partition.path) 534 if fs == "swap": 535 fstab.write("%s\tswap\tswap\tsw\t0\t0\n" % partition_uuid) 536 else: 537 fstab.write("%s\t%s\t%s\t%s\t%s\t%s\n" % (partition_uuid, partition.mount_as, fs, fstab_mount_options, "0", fstab_fsck_option)) 538 539 if fs == "btrfs" and partition.mount_as == "/" and not self.setup_has_dedicated_home(): 540 # Special case, if / is btrfs and there is no dedicated /home, add the @home subvolume to / 541 fstab.write("%s\t%s\t%s\t%s\t%s\t%s\n" % (partition_uuid, "/home", "btrfs", "defaults,subvol=@home", "0", "0")) 542 fstab.close() 543 544 def write_mtab(self, fstab="/target/etc/fstab", mtab="/target/etc/mtab"): 545 if self.setup.lvm: 546 os.system(f"grep -v swap {fstab} > {mtab}") 547 548 def write_crypttab(self, path="/target/etc/crypttab"): 549 if self.setup.luks: 550 os.system(f"echo 'chamesle {self.get_blkid(self.auto_root_physical_partition)} none luks,discard,tries=3' >> {path}") 551 552 def finish_installation(self): 553 554 self.update_progress(50, False, False, _("Setting hostname")) 555 self.setup_hostname() 556 557 self.update_progress(55, False, False, _("Setting locale")) 558 self.setup_locale() 559 560 self.update_progress(60, False, False, _("Setting timezone")) 561 self.setup_timezone() 562 563 self.update_progress(65, False, False, _("Localizing packages")) 564 self.setup_localization() 565 566 # set the keyboard options.. 567 self.update_progress(75, False, False, _("Setting keyboard options")) 568 self.setup_keyboard() 569 570 if self.setup.luks: 571 uuid = self.get_blkid(self.auto_root_physical_partition).replace("UUID=", "") 572 self.set_grub_option("GRUB_CMDLINE_LINUX", "rd.luks.uuid=%s rd.lvm.vg=chamesle" % uuid) 573 elif self.setup.lvm: 574 self.set_grub_option("GRUB_CMDLINE_LINUX", "rd.lvm.vg=chamesle") 575 576 # the initramfs the installed system boots with 577 print(" --> Configuring Initramfs") 578 self.update_progress(78, True, False, _("Configuring the initramfs")) 579 self.do_run_in_chroot("dracut --force --regenerate-all") 580 581 # boot menu 582 print(" --> Configuring Grub") 583 if(self.setup.grub_device is not None): 584 self.update_progress(80, False, False, _("Installing bootloader")) 585 self.set_grub_option("GRUB_DISTRIBUTOR", "Chamesle") 586 cmdline = "quiet splash loglevel=3 drm.panic_screen=qr_code" 587 # dinit with the blue screen when the system can't finish starting 588 if os.path.exists("/target/usr/lib/chamesle/init"): 589 cmdline += " init=/usr/lib/chamesle/init" 590 self.set_grub_option("GRUB_CMDLINE_LINUX_DEFAULT", cmdline) 591 self.set_grub_option("GRUB_DISABLE_OS_PROBER", "false") 592 # our kernel first, void's below it for when ours doesn't start 593 ours = sorted(glob("/target/boot/vmlinuz-*-cachyos-lts")) 594 if ours: 595 self.set_grub_option("GRUB_TOP_LEVEL", ours[-1][len("/target"):]) 596 self.set_grub_option("GRUB_GFXMODE", "auto") 597 self.set_grub_option("GRUB_GFXPAYLOAD_LINUX", "keep") 598 if os.path.exists("/target/usr/share/grub/themes/chamesle/theme.txt"): 599 self.set_grub_option("GRUB_THEME", "/usr/share/grub/themes/chamesle/theme.txt") 600 elif os.path.exists("/target/usr/share/backgrounds/chamesle/grub.png"): 601 self.set_grub_option("GRUB_BACKGROUND", "/usr/share/backgrounds/chamesle/grub.png") 602 print(" --> Running grub-install") 603 if os.path.exists("/sys/firmware/efi"): 604 self.do_run_in_chroot("grub-install --target=x86_64-efi --efi-directory=/boot/efi --bootloader-id=chamesle --recheck") 605 # also as the fallback loader, some firmware only boots that 606 self.do_run_in_chroot("grub-install --target=x86_64-efi --efi-directory=/boot/efi --removable --no-nvram") 607 else: 608 self.do_run_in_chroot("grub-install --target=i386-pc --force %s" % self.setup.grub_device) 609 self.do_configure_grub() 610 grub_retries = 0 611 while (not self.do_check_grub()): 612 self.do_configure_grub() 613 grub_retries = grub_retries + 1 614 if grub_retries >= 5: 615 self.set_critical_error(message=_("WARNING: The grub bootloader was not configured properly! You need to configure it manually.")) 616 break 617 618 # now unmount it 619 print(" --> Unmounting partitions") 620 621 if os.path.exists("/target/sys/firmware/efi/efivars"): 622 os.system("umount --force /target/sys/firmware/efi/efivars") 623 624 os.system("umount --force /target/dev/shm") 625 os.system("umount --force /target/dev/pts") 626 if self.setup.gptonefi: 627 os.system("umount --force /target/boot/efi") 628 os.system("umount --force /target/media/cdrom") 629 os.system("umount --force /target/boot") 630 os.system("umount --force /target/dev/") 631 os.system("umount --force /target/sys/") 632 os.system("umount --force /target/proc/") 633 os.system("umount --force /target/run/") 634 os.system("rm -f /target/etc/resolv.conf") 635 os.system("mv /target/etc/resolv.conf.bk /target/etc/resolv.conf") 636 if(not self.setup.skip_mount): 637 for partition in self.setup.partitions: 638 if(partition.mount_as is not None and partition.mount_as != "" and partition.mount_as != "/" and partition.mount_as != "swap"): 639 self.do_unmount("/target" + partition.mount_as) 640 641 # btrfs subvolumes are mounts, but will block unmounting /target. This will 642 # unmount the submounts also. 643 cmd = "umount -AR /target" 644 print("Unmounting the target root: '%s'" % cmd) 645 self.exec_cmd(cmd) 646 647 self.update_progress(100, False, True, _("Installation finished")) 648 print(" --> All done") 649 650 def set_grub_option(self, key, value): 651 path = "/target/etc/default/grub" 652 lines = open(path).read().split("\n") if os.path.exists(path) else [] 653 line = '%s="%s"' % (key, value) 654 for i, l in enumerate(lines): 655 if l.lstrip("#").startswith(key + "="): 656 lines[i] = line 657 break 658 else: 659 lines.append(line) 660 with open(path, "w") as f: 661 f.write("\n".join(lines).rstrip("\n") + "\n") 662 663 def do_run_in_chroot(self, command): 664 command = command.replace('"', "'").strip() 665 print("chroot /target/ /bin/sh -c \"%s\"" % command) 666 os.system("chroot /target/ /bin/sh -c \"%s\"" % command) 667 668 def do_configure_grub(self): 669 self.update_progress(85, True, False, _("Configuring bootloader")) 670 print(" --> Running grub-mkconfig") 671 self.do_run_in_chroot("grub-mkconfig -o /boot/grub/grub.cfg") 672 grub_output = subprocess.getoutput("chroot /target/ /bin/sh -c \"grub-mkconfig -o /boot/grub/grub.cfg\"") 673 grubfh = open("/var/log/live-installer-grub-output.log", "w") 674 grubfh.writelines(grub_output) 675 grubfh.close() 676 677 def do_check_grub(self): 678 self.update_progress(90, True, False, _("Checking bootloader")) 679 print(" --> Checking Grub configuration") 680 time.sleep(5) 681 found_entry = False 682 if os.path.exists("/target/boot/grub/grub.cfg"): 683 grubfh = open("/target/boot/grub/grub.cfg", "r") 684 for line in grubfh: 685 line = line.rstrip("\r\n") 686 if "menuentry" in line and "Chamesle" in line: 687 found_entry = True 688 print(" --> Found Grub entry: %s " % line) 689 grubfh.close() 690 return (found_entry) 691 else: 692 print("!No /target/boot/grub/grub.cfg file found!") 693 return False 694 695 def do_mount(self, device, dest, type, options=None): 696 ''' Mount a filesystem ''' 697 p = None 698 if(options is not None): 699 cmd = "mount -o %s -t %s %s %s" % (options, type, device, dest) 700 else: 701 cmd = "mount -t %s %s %s" % (type, device, dest) 702 print("EXECUTING: '%s'" % cmd) 703 self.exec_cmd(cmd) 704 705 def do_unmount(self, mountpoint): 706 ''' Unmount a filesystem ''' 707 cmd = "umount %s" % mountpoint 708 print("EXECUTING: '%s'" % cmd) 709 self.exec_cmd(cmd) 710 711 # Execute schell command and return output in a list 712 def exec_cmd(self, cmd): 713 p = subprocess.Popen(cmd, shell=True, encoding='utf-8', errors='ignore', stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 714 lstOut = [] 715 for line in p.stdout.readlines(): 716 # Strip the line, also from null spaces (strip() only strips white spaces) 717 line = line.strip().strip("\0") 718 if line != '': 719 lstOut.append(line) 720 return lstOut 721 722 # Represents the choices made by the user 723 class Setup(object): 724 is_mint = False 725 oem_mode = False 726 language = None 727 timezone = None 728 keyboard_model = None 729 keyboard_layout = None 730 keyboard_variant = None 731 partitions = [] #Array of PartitionSetup objects 732 username = None 733 hostname = None 734 autologin = False 735 ecryptfs = False 736 password1 = None 737 password2 = None 738 real_name = None 739 grub_device = None 740 disks = [] 741 automated = True 742 alongside = False 743 windows = None 744 alongside_size = 0 745 disk = None 746 diskname = None 747 passphrase1 = None 748 passphrase2 = None 749 lvm = False 750 luks = False 751 badblocks = False 752 target_disk = None 753 gptonefi = False 754 # Optionally skip all mouting/partitioning for advanced users with custom setups (raid/dmcrypt/etc) 755 # Make sure the user knows that they need to: 756 # * Mount their target directory structure at /target 757 # * NOT mount /target/dev, /target/dev/shm, /target/dev/pts, /target/proc, and /target/sys 758 # * Manually create /target/etc/fstab after start_installation has completed and before finish_installation is called 759 # * Install cryptsetup/dmraid/mdadm/etc in target environment (using chroot) between start_installation and finish_installation 760 # * Make sure target is mounted using the same block device as is used in /target/etc/fstab (eg if you change the name of a dm-crypt device between now and /target/etc/fstab, update-initramfs will likely fail) 761 skip_mount = False 762 763 #Descriptions (used by the summary screen) 764 keyboard_model_description = None 765 keyboard_layout_description = None 766 keyboard_variant_description = None 767 768 def print_setup(self): 769 if __debug__: 770 print("-------------------------------------------------------------------------") 771 print("Is Mint: %s" % self.is_mint) 772 print("OEM mode: %s" % self.oem_mode) 773 print("language: %s" % self.language) 774 print("timezone: %s" % self.timezone) 775 print("keyboard: %s - %s (%s) - %s - %s (%s)" % (self.keyboard_model, self.keyboard_layout, self.keyboard_variant, self.keyboard_model_description, self.keyboard_layout_description, self.keyboard_variant_description)) 776 print("user: %s (%s)" % (self.username, self.real_name)) 777 print("autologin: ", self.autologin) 778 print("ecryptfs: ", self.ecryptfs) 779 print("hostname: %s " % self.hostname) 780 print("password: %s" % ("set" if self.password1 else "none")) 781 print("grub_device: %s " % self.grub_device) 782 print("skip_mount: %s" % self.skip_mount) 783 print("automated: %s" % self.automated) 784 if self.automated: 785 print("disk: %s (%s)" % (self.disk, self.diskname)) 786 print("luks: %s" % self.luks) 787 print("badblocks: %s" % self.badblocks) 788 print("lvm: %s" % self.lvm) 789 print("passphrase: %s" % ("set" if self.passphrase1 else "none")) 790 if (not self.skip_mount): 791 print("target_disk: %s " % self.target_disk) 792 if self.gptonefi: 793 print("GPT partition table: True") 794 else: 795 print("GPT partition table: False") 796 print("disks: %s " % self.disks) 797 print("partitions:") 798 for partition in self.partitions: 799 partition.print_partition() 800 print("-------------------------------------------------------------------------")