diff --git a/build-scripts/.gitignore b/build-scripts/.gitignore new file mode 100644 index 0000000..89df10c --- /dev/null +++ b/build-scripts/.gitignore @@ -0,0 +1,23 @@ +build/ +out/ +dist/ +*.log +*.tmp +keys/ +*.key +*.crt +*.cer +*.pem +*.pfx +*.p12 +*.signed +*.efi +*.iso +*.img +*.wim +*.esd +*.pf +*.vhd +*.vmdk +*.exe +*.dll diff --git a/build-scripts/README.md b/build-scripts/README.md new file mode 100644 index 0000000..d757738 --- /dev/null +++ b/build-scripts/README.md @@ -0,0 +1,46 @@ +# Paravis Ventoy build scripts + +Scripts used to build, patch, theme and deploy Ventoy/GRUB2 for the PARAVIS +flash. This tree is meant to be added to the `Ventoy` repository under +`build-scripts/`. + +## Categories + +``` +build/ Ventoy/GRUB core and EFI build scripts +layout/ flash layout: partitions, deployment, relayout +theme-tools/ PSD/theme/font tooling (grub-mkfont, pf2 helpers) +integration/ third-party menus: Acronis, Super Grub2 Disk, KRD, XorBoot +config/ Ventoy F6 menu and VTOYEFI grub.cfg/grbp.cfg sources +experiments/ one-off debug/experiment scripts, kept for reference +``` + +`integration/signing/` contains signing **scripts** only. No keys or +certificates are included; supply your own in `keys/` if you need to sign +Secure Boot binaries. + +## Paths + +Absolute build paths were replaced with `/path/to/pf` (Linux) and `C:\PF` +(Windows). Adjust them to your checkout. Scripts that reference `keys/` expect +your own keys and are not runnable without them. + +## Requirements + +- Linux/WSL for the shell scripts (xorriso, mtools, grub tools, sbsign, + osslsigncode, Python 3, Pillow, fontTools); +- PowerShell 7+ for the layout scripts; +- Ventoy 1.1.18 source tree (`Ventoy-src/`). + +## What is not included + +- Secure Boot keys, certificates and signed EFI binaries; +- Microsoft font derivatives (`tahoma*.pf2`, `segoeui18.pf2`); +- bootable images (`*.iso`, `*.img`, `*.wim`, `*.esd`, `Data.pf`); +- third-party payloads (Acronis, KRD, Strelec, XorBoot, bootice). + +## License + +The Paravis scripts are MIT. Scripts that patch or build Ventoy/GRUB2 are +derived from GPLv3 projects; keep `Ventoy-src/COPYING` and the GPL terms when +redistributing them. diff --git a/build-scripts/config/VTOYEFI/checksum.cfg b/build-scripts/config/VTOYEFI/checksum.cfg new file mode 100644 index 0000000..df045ec --- /dev/null +++ b/build-scripts/config/VTOYEFI/checksum.cfg @@ -0,0 +1,96 @@ + +unset vtchkdef +vt_vtoychksum_exist "${VTOY_CHKSUM_FILE_PATH}" + +if [ "$VT_EXIST_MD5" = "1" ]; then + if [ -z "$vtchkdef" ]; then + set default=0 + set vtchkdef=1 + fi + menuentry "$VTLANG_CHKSUM_MD5_CALC_CHK" --class=checksum_md5 { + md5sum "${vtoy_iso_part}${VTOY_CHKSUM_FILE_PATH}" + vt_cmp_checksum 0 "${VTOY_CHKSUM_FILE_PATH}" + + echo -en "\n\n$VTLANG_ENTER_EXIT ..." + read vtInputKey + } +else + menuentry "$VTLANG_CHKSUM_MD5_CALC" --class=checksum_md5 { + md5sum "${vtoy_iso_part}${VTOY_CHKSUM_FILE_PATH}" + + echo -en "\n\n$VTLANG_ENTER_EXIT ..." + read vtInputKey + } +fi + +if [ "$VT_EXIST_SHA1" = "1" ]; then + if [ -z "$vtchkdef" ]; then + set default=1 + set vtchkdef=1 + fi + menuentry "$VTLANG_CHKSUM_SHA1_CALC_CHK" --class=checksum_sha1 { + sha1sum "${vtoy_iso_part}${VTOY_CHKSUM_FILE_PATH}" + vt_cmp_checksum 1 "${VTOY_CHKSUM_FILE_PATH}" + + echo -en "\n\n$VTLANG_ENTER_EXIT ..." + read vtInputKey + } +else + menuentry "$VTLANG_CHKSUM_SHA1_CALC" --class=checksum_sha1 { + sha1sum "${vtoy_iso_part}${VTOY_CHKSUM_FILE_PATH}" + + echo -en "\n\n$VTLANG_ENTER_EXIT ..." + read vtInputKey + } +fi + + + +if [ "$VT_EXIST_SHA256" = "1" ]; then + if [ -z "$vtchkdef" ]; then + set default=2 + set vtchkdef=1 + fi + menuentry "$VTLANG_CHKSUM_SHA256_CALC_CHK" --class=checksum_sha256 { + sha256sum "${vtoy_iso_part}${VTOY_CHKSUM_FILE_PATH}" + vt_cmp_checksum 2 "${VTOY_CHKSUM_FILE_PATH}" + + echo -en "\n\n$VTLANG_ENTER_EXIT ..." + read vtInputKey + } +else + menuentry "$VTLANG_CHKSUM_SHA256_CALC" --class=checksum_sha256 { + sha256sum "${vtoy_iso_part}${VTOY_CHKSUM_FILE_PATH}" + + echo -en "\n\n$VTLANG_ENTER_EXIT ..." + read vtInputKey + } +fi + + + +if [ "$VT_EXIST_SHA512" = "1" ]; then + if [ -z "$vtchkdef" ]; then + set default=3 + set vtchkdef=1 + fi + menuentry "$VTLANG_CHKSUM_SHA512_CALC_CHK" --class=checksum_sha512{ + sha512sum "${vtoy_iso_part}${VTOY_CHKSUM_FILE_PATH}" + vt_cmp_checksum 3 "${VTOY_CHKSUM_FILE_PATH}" + + echo -en "\n\n$VTLANG_ENTER_EXIT ..." + read vtInputKey + } +else + menuentry "$VTLANG_CHKSUM_SHA512_CALC" --class=checksum_sha512{ + sha512sum "${vtoy_iso_part}${VTOY_CHKSUM_FILE_PATH}" + + echo -en "\n\n$VTLANG_ENTER_EXIT ..." + read vtInputKey + } +fi + + +menuentry "$VTLANG_RETURN_PREVIOUS" --class=vtoyret VTOY_RET { + echo 'Return ...' +} diff --git a/build-scripts/config/VTOYEFI/debug.cfg b/build-scripts/config/VTOYEFI/debug.cfg new file mode 100644 index 0000000..10f3248 --- /dev/null +++ b/build-scripts/config/VTOYEFI/debug.cfg @@ -0,0 +1,294 @@ +# +# VTLANG_CTRL_TEMP_SET must be the first +# And the inside item order can not be changed +# +submenu "$VTLANG_CTRL_TEMP_SET" --class=debug_temp_set --class=F5tool { + menuentry "[ $VTOY_WIN11_BYPASS_CHECK ] $VTLANG_WIN11_BYPASS_CHECK" --class=debug_temp_win11_bypass --class=debug_temp_set --class=F5tool \ + VTOY_RUN_SET_0_0 { + if [ "$VTOY_WIN11_BYPASS_CHECK" = "0" ]; then + set VTOY_WIN11_BYPASS_CHECK=1 + else + set VTOY_WIN11_BYPASS_CHECK=0 + fi + } + + menuentry "[ $VTOY_WIN11_BYPASS_NRO ] $VTLANG_WIN11_BYPASS_NRO" --class=debug_temp_win11_nro --class=debug_temp_set --class=F5tool \ + VTOY_RUN_SET_1_0 { + if [ "$VTOY_WIN11_BYPASS_NRO" = "0" ]; then + set VTOY_WIN11_BYPASS_NRO=1 + else + set VTOY_WIN11_BYPASS_NRO=0 + fi + } + + menuentry "[ $VTOY_SECONDARY_BOOT_MENU ] $VTLANG_SECONDARY_BOOT_MENU" --class=debug_temp_second_menu --class=debug_temp_set --class=F5tool \ + VTOY_RUN_SET_2_0 { + if [ "$VTOY_SECONDARY_BOOT_MENU" = "0" ]; then + set VTOY_SECONDARY_BOOT_MENU=1 + else + set VTOY_SECONDARY_BOOT_MENU=0 + fi + } + + menuentry "$VTLANG_RETURN_PREVIOUS" --class=vtoyret VTOY_RET { + echo "Return ..." + } +} + + +if [ "$grub_platform" != "pc" ]; then + submenu "$VTLANG_WIN_UEFI_RES_LOCK" --class=debug_uefi_res_lock --class=F5tool { + set vtActive0="[ ]" + set vtActive1="[ ]" + set vtActive2="[ ]" + set vtActive3="[ ]" + if [ "$VTOY_WIN_UEFI_RES_LOCK" = "0" ]; then + set vtActive0="[*]" + elif [ "$VTOY_WIN_UEFI_RES_LOCK" = "1" ]; then + set vtActive1="[*]" + elif [ "$VTOY_WIN_UEFI_RES_LOCK" = "2" ]; then + set vtActive2="[*]" + elif [ "$VTOY_WIN_UEFI_RES_LOCK" = "3" ]; then + set vtActive3="[*]" + fi + + menuentry "$vtActive0 $VTLANG_UEFI_RES_LOCK_NONE" --class=debug_uefi_res_lock0 --class=F5tool VTOY_RUN_SET_0_1 { + set VTOY_WIN_UEFI_RES_LOCK=0 + } + menuentry "$vtActive1 $VTLANG_UEFI_RES_LOCK_MAX" --class=debug_uefi_res_lock1 --class=F5tool VTOY_RUN_SET_1_1 { + set VTOY_WIN_UEFI_RES_LOCK=1 + } + menuentry "$vtActive2 $VTLANG_UEFI_RES_LOCK_1024_768" --class=debug_uefi_res_lock2 --class=F5tool VTOY_RUN_SET_2_1 { + set VTOY_WIN_UEFI_RES_LOCK=2 + } + menuentry "$vtActive3 $VTLANG_UEFI_RES_LOCK_BE1024_768" --class=debug_uefi_res_lock3 --class=F5tool VTOY_RUN_SET_3_1 { + set VTOY_WIN_UEFI_RES_LOCK=3 + } + + menuentry "$VTLANG_RETURN_PREVIOUS" --class=vtoyret VTOY_RET { + echo "Return ..." + } + } +fi + + +submenu "$VTLANG_MENU_LANG" --class=debug_menu_lang --class=F5tool { + source $prefix/menulang.cfg +} + +source $prefix/power.cfg +source $prefix/hwinfo.cfg +source $prefix/keyboard.cfg + +submenu "$VTLANG_RESOLUTION_CFG" --class=debug_resolution --class=F5tool { + menuentry "$VTLANG_RETURN_PREVIOUS" --class=vtoyret VTOY_RET { + echo "Return ..." + } + + vt_update_cur_video_mode VT_CUR_MODE + set vdid=0 + while [ $vdid -lt $VTOY_VIDEO_MODE_NUM ]; do + vt_get_video_mode $vdid vtCurMode + + unset vtActive + if [ "$vtCurMode" = "$VT_CUR_MODE" ]; then + set vtActive="[*]" + fi + + menuentry "$vtCurMode $vtActive" --class=debug_videomode --class=debug_resolution --class=F5tool VTOY_RUN_RET { + terminal_output console + set gfxmode=$1 + terminal_output gfxterm + if [ "$vtoy_res_fit" = "1" ]; then + vt_set_theme switch + fi + } + + vt_incr vdid 1 + done +} + +submenu "$VTLANG_SCREEN_MODE" --class=debug_screen_mode --class=F5tool { + menuentry "$VTLANG_SCREEN_TEXT_MODE" --class=debug_text_mode --class=debug_screen_mode --class=F5tool { + vt_push_menu_lang en_US + terminal_output console + } + menuentry "$VTLANG_SCREEN_GUI_MODE" --class=debug_gui_mode --class=debug_screen_mode --class=F5tool { + terminal_output gfxterm + vt_pop_menu_lang + } + menuentry "$VTLANG_RETURN_PREVIOUS" --class=vtoyret VTOY_RET { + echo "Return ..." + } +} + +if [ -n "$VTOY_THEME_COUNT" -a $VTOY_THEME_COUNT -gt 1 ]; then + submenu "$VTLANG_THEME_SELECT" --class=debug_theme_select --class=F5tool { + vt_select_theme_cfg + } +fi + +if [ "$grub_platform" != "pc" ]; then + submenu "$VTLANG_UEFI_UTIL" --class=debug_util --class=F5tool { + menuentry "$VTLANG_UTIL_SHOW_EFI_DRV" --class=debug_util_efidrv --class=debug_util --class=F5tool { + vt_push_pager + chainloader ${vtoy_path}/vtoyutil_${VTOY_EFI_ARCH}.efi env_param=${env_param} ${vtdebug_flag} feature=show_efi_drivers + boot + vt_pop_pager + echo -en "\n$VTLANG_ENTER_EXIT ..." + read vtInputKey + } + + menuentry "$VTLANG_UTIL_FIX_BLINIT_FAIL" --class=debug_util_blinit --class=debug_util --class=F5tool { + chainloader ${vtoy_path}/vtoyutil_${VTOY_EFI_ARCH}.efi env_param=${env_param} ${vtdebug_flag} feature=fix_windows_mmap + boot + echo -en "\n$VTLANG_ENTER_EXIT ..." + read vtInputKey + } + + menuentry "$VTLANG_RETURN_PREVIOUS" --class=vtoyret VTOY_RET { + echo "Return ..." + } + } +fi + + +submenu "$VTLANG_JSON_CHK_JSON" --class=debug_json --class=F5tool { + menuentry "$VTLANG_JSON_CHK_CONTROL" --class=debug_control --class=debug_json --class=F5tool { + set pager=1 + vt_check_plugin_json $vt_plugin_path control $vtoy_iso_part + + echo -en "\n$VTLANG_ENTER_EXIT ..." + read vtInputKey + unset pager + } + + menuentry "$VTLANG_JSON_CHK_THEME" --class=debug_theme --class=debug_json --class=F5tool { + set pager=1 + vt_check_plugin_json $vt_plugin_path theme $vtoy_iso_part + + echo -en "\n$VTLANG_ENTER_EXIT ..." + read vtInputKey + unset pager + } + + menuentry "$VTLANG_JSON_CHK_AUTOINS" --class=debug_autoinstall --class=debug_json --class=F5tool { + set pager=1 + vt_check_plugin_json $vt_plugin_path auto_install $vtoy_iso_part + + echo -en "\n$VTLANG_ENTER_EXIT ..." + read vtInputKey + unset pager + } + + menuentry "$VTLANG_JSON_CHK_PERSIST" --class=debug_persistence --class=debug_json --class=F5tool { + set pager=1 + vt_check_plugin_json $vt_plugin_path persistence $vtoy_iso_part + + echo -e "\n############### dump persistence ###############" + vt_dump_persistence + + echo -en "\n$VTLANG_ENTER_EXIT ..." + read vtInputKey + unset pager + } + + menuentry "$VTLANG_JSON_CHK_MENU_ALIAS" --class=debug_menualias --class=debug_json --class=F5tool { + set pager=1 + vt_check_plugin_json $vt_plugin_path menu_alias $vtoy_iso_part + + echo -en "\n$VTLANG_ENTER_EXIT ..." + read vtInputKey + unset pager + } + + menuentry "$VTLANG_JSON_CHK_MENU_TIP" --class=debug_menutip --class=debug_json --class=F5tool { + set pager=1 + vt_check_plugin_json $vt_plugin_path menu_tip $vtoy_iso_part + + echo -en "\n$VTLANG_ENTER_EXIT ..." + read vtInputKey + unset pager + } + + menuentry "$VTLANG_JSON_CHK_MENU_CLASS" --class=debug_menuclass --class=debug_json --class=F5tool { + set pager=1 + vt_check_plugin_json $vt_plugin_path menu_class $vtoy_iso_part + + echo -en "\n$VTLANG_ENTER_EXIT ..." + read vtInputKey + unset pager + } + + menuentry "$VTLANG_JSON_CHK_INJECTION" --class=debug_injection --class=debug_json --class=F5tool { + set pager=1 + vt_check_plugin_json $vt_plugin_path injection $vtoy_iso_part + + echo -en "\n$VTLANG_ENTER_EXIT ..." + read vtInputKey + unset pager + } + + menuentry "$VTLANG_JSON_CHK_AUTO_MEMDISK" --class=debug_automemdisk --class=debug_json --class=F5tool { + set pager=1 + vt_check_plugin_json $vt_plugin_path auto_memdisk $vtoy_iso_part + + echo -en "\n$VTLANG_ENTER_EXIT ..." + read vtInputKey + unset pager + } + + menuentry "$VTLANG_JSON_CHK_IMG_LIST" --class=debug_imagelist --class=debug_json --class=F5tool { + set pager=1 + vt_check_plugin_json $vt_plugin_path image_list $vtoy_iso_part + + echo -en "\n$VTLANG_ENTER_EXIT ..." + read vtInputKey + unset pager + } + + menuentry "$VTLANG_JSON_CHK_IMG_BLIST" --class=debug_imageblacklist --class=debug_json --class=F5tool { + set pager=1 + vt_check_plugin_json $vt_plugin_path image_blacklist $vtoy_iso_part + + echo -en "\n$VTLANG_ENTER_EXIT ..." + read vtInputKey + unset pager + } + + menuentry "$VTLANG_JSON_CHK_CONF_REPLACE" --class=debug_bootconf_replace --class=debug_json --class=F5tool { + set pager=1 + vt_check_plugin_json $vt_plugin_path conf_replace $vtoy_iso_part + + echo -en "\n$VTLANG_ENTER_EXIT ..." + read vtInputKey + unset pager + } + + menuentry "$VTLANG_JSON_CHK_DUD" --class=debug_dud --class=debug_json --class=F5tool { + set pager=1 + vt_check_plugin_json $vt_plugin_path dud $vtoy_iso_part + + echo -en "\n$VTLANG_ENTER_EXIT ..." + read vtInputKey + unset pager + } + + menuentry "$VTLANG_JSON_CHK_PASSWORD" --class=debug_pwd --class=debug_json --class=F5tool { + set pager=1 + vt_check_plugin_json $vt_plugin_path password $vtoy_iso_part + + echo -en "\n$VTLANG_ENTER_EXIT ..." + read vtInputKey + unset pager + } + + menuentry "$VTLANG_RETURN_PREVIOUS" --class=vtoyret VTOY_RET { + echo "Return ..." + } +} + + +menuentry "$VTLANG_RETURN_PREVIOUS" --class=vtoyret VTOY_RET { + echo "Return ..." +} diff --git a/build-scripts/config/VTOYEFI/grbp.cfg b/build-scripts/config/VTOYEFI/grbp.cfg new file mode 100644 index 0000000..70e08ca --- /dev/null +++ b/build-scripts/config/VTOYEFI/grbp.cfg @@ -0,0 +1,2859 @@ +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +if [ "$grub_platform" = "pc" ]; then + insmod setkey + insmod regexp +fi + +function ventoy_pause { + echo "press Enter to continue ......" + read vtTmpPause +} + +function ventoy_debug_pause { + if [ -n "${vtdebug_flag}" ]; then + echo "press Enter to continue ......" + read vtTmpPause + fi +} + + +function ventoy_cli_console { + if [ -z "$vtoy_display_mode" ]; then + terminal_output console + elif [ "$vtoy_display_mode" = "GUI" ]; then + terminal_output console + fi +} + +function ventoy_gui_console { + if [ -z "$vtoy_display_mode" ]; then + terminal_output gfxterm + elif [ "$vtoy_display_mode" = "GUI" ]; then + terminal_output gfxterm + fi +} + +function ventoy_cfg_theme_lock { + vt_timeout_lock $1 + vt_theme_lock $1 + terminal_lock $1 + lockfont $1 +} + +function ventoy_acpi_param { + if [ "$VTOY_PARAM_NO_ACPI" != "1" ]; then + vt_acpi_param "$1" "$2" + fi +} + +function vt_vcfg_pre_proc { + vt_img_sector "${vtoy_iso_part}${vt_chosen_path}" + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=$ventoy_busybox_ver" + vt_trailer_cpio $vtoy_iso_part "$vt_chosen_path" +} + +function ventoy_vcfg_proc { + if vt_check_custom_boot "${1}" vt_vcfg; then + set vtoy_chosen_path="${1}" + vt_file_basefile "${vtoy_chosen_path}" vtoy_chosen_file + + export vtoy_chosen_path + export vtoy_chosen_file + ventoy_debug_pause + configfile "${vtoy_iso_part}${vt_vcfg}" + true + else + false + fi +} + +function ventoy_language { + configfile $prefix/menulang.cfg +} + +function ventoy_diagnosis { + vt_enum_video_mode + configfile $prefix/debug.cfg +} + +function ventoy_localboot { + configfile $prefix/localboot.cfg +} + +function paravis_return { + if [ "$grub_platform" = "efi" ]; then + search --no-floppy --file --set=root /efi/Paravis/Boot/grub2/grub.cfg + if [ "$grub_cpu" = "x86_64" ]; then + chainloader /efi/Paravis/Boot/grub2/grubx64.efi + else + chainloader /EFI/Boot/bootia32.efi + fi + else + chainloader (${vtoydev})+1 + fi + boot +} + +function ventoy_ext_menu { + if [ -e $vt_plugin_path/ISO/Ventoy/ventoy_grub.cfg ]; then + set ventoy_new_context=1 + configfile $vt_plugin_path/ISO/Ventoy/ventoy_grub.cfg + unset ventoy_new_context + else + echo "ventoy_grub.cfg NOT exist." + echo -en "\n$VTLANG_ENTER_EXIT ..." + read vtInputKey + fi +} + +function ventoy_checksum { + if [ -f "${vtoy_iso_part}${VTOY_CHKSUM_FILE_PATH}" ]; then + configfile $prefix/checksum.cfg + fi +} + +function ventoy_show_help { + if [ -f $prefix/help.tar.gz ]; then + if [ -z "$vtoy_help_txt_mem_addr" ]; then + vt_load_file_to_mem "auto" $prefix/help.tar.gz vtoy_help_txt_mem + fi + + loopback vt_help_tarfs mem:${vtoy_help_txt_mem_addr}:size:${vtoy_help_txt_mem_size} + vt_cur_menu_lang vtCurLang + if [ -f "(vt_help_tarfs)/help/${vtCurLang}.txt" ]; then + cat "(vt_help_tarfs)/help/${vtCurLang}.txt" + else + cat "(vt_help_tarfs)/help/en_US.txt" + fi + loopback -d vt_help_tarfs + fi +} + +function ventoy_load_menu_lang_file { + vt_load_file_to_mem "auto" $prefix/menu.tar.gz vtoy_menu_lang_mem + loopback vt_menu_tarfs mem:${vtoy_menu_lang_mem_addr}:size:${vtoy_menu_lang_mem_size} +} + +function get_os_type { + set vtoy_os=Linux + export vtoy_os + + if vt_str_begin "$vt_volume_id" "DLC Boot"; then + if [ -f (loop)/DLCBoot.exe ]; then + set vtoy_os=Windows + fi + else + for file in "efi/microsoft/boot/bcd" "sources/boot.wim" "boot/bcd" "bootmgr.efi" "boot/etfsboot.com" ; do + if vt_file_exist_nocase (loop)/$file; then + set vtoy_os=Windows + break + fi + done + fi + + if [ "$vtoy_os" = "Linux" ]; then + if vt_strstr "$vt_system_id" "FreeBSD"; then + set vtoy_os=Unix + set vt_unix_type=FreeBSD + elif [ -e (loop)/bin/freebsd-version ]; then + set vtoy_os=Unix + set vt_unix_type=FreeBSD + elif [ -e (loop)/boot/kernel/geom_ventoy.ko ]; then + set vtoy_os=Unix + set vt_unix_type=FreeBSD + elif vt_str_begin "$vt_system_id" "DragonFly"; then + set vtoy_os=Unix + set vt_unix_type=DragonFly + + + elif [ -e (loop)/boot/kernel/kernel ]; then + if file --is-x86-kfreebsd (loop)/boot/kernel/kernel; then + set vtoy_os=Unix + set vt_unix_type=FreeBSD + elif file --is-x86-knetbsd (loop)/boot/kernel/kernel; then + set vtoy_os=Unix + set vt_unix_type=NetBSD + fi + fi + fi + + if [ -n "${vtdebug_flag}" ]; then + echo ISO is "$vtoy_os" + fi +} + +function vt_check_compatible_pe { + #Check for PE without external tools + #set compatible if ISO file is less than 80MB + if [ $vt_chosen_size -GT 33554432 -a $vt_chosen_size -LE 83886080 ]; then + set ventoy_compatible=YES + fi + + return +} + +function vt_check_compatible_linux { + if vt_str_begin "$vt_volume_id" "embootkit"; then + set ventoy_compatible=YES + elif [ -e "$1/casper/tinycore.gz" ]; then + set ventoy_compatible=YES + fi + + return +} + +function locate_initrd { + vt_linux_locate_initrd + + if [ -n "${vtdebug_flag}" ]; then + vt_linux_dump_initrd + ventoy_debug_pause + fi +} + +function locate_wim { + vt_windows_locate_wim_patch (loop) "$1" + + if [ -n "${vtdebug_flag}" ]; then + echo '###############################################' + vt_dump_wim_patch + echo '###############################################' + ventoy_debug_pause + fi +} + +function distro_specify_wim_patch { + if [ -d (loop)/h3pe ]; then + vt_windows_collect_wim_patch wim /BOOT/H3_10PE.WIM + vt_windows_collect_wim_patch wim /BOOT/H3_7PE.WIM + vt_windows_collect_wim_patch wim /BOOT/H3_8PE.WIM + vt_windows_collect_wim_patch wim /BOOT/H3_81PE.WIM + elif [ -d (loop)/2k10/winpe ]; then + vt_windows_collect_wim_patch wim /2k10/winpe/w1086pe.wim + vt_windows_collect_wim_patch wim /2k10/winpe/w8x86pe.wim + vt_windows_collect_wim_patch wim /2k10/winpe/w7x86pe.wim + fi +} + +function distro_specify_wim_patch_phase2 { + if [ -f (loop)/boot/boot.wim ]; then + vt_windows_collect_wim_patch wim /boot/boot.wim + elif [ -f (loop)/sources/boot.wim ]; then + vt_windows_collect_wim_patch wim /sources/boot.wim + fi + + if vt_str_begin "$vt_volume_id" "DLC Boot"; then + for vwfile in "/DLC1/WinPE/W11x64.wim" "/DLC1/WinPE/W10x64.wim" "/DLC1/WinPE/W10x86.wim"; do + if [ -f (loop)/$vwfile ]; then + vt_windows_collect_wim_patch wim $vwfile + fi + done + fi + +} + + +function distro_specify_initrd_file { + if [ -e (loop)/boot/all.rdz ]; then + vt_linux_specify_initrd_file /boot/all.rdz + elif [ -e (loop)/boot/xen.gz ]; then + if [ -e (loop)/install.img ]; then + vt_linux_specify_initrd_file /install.img + fi + elif [ -d (loop)/casper ]; then + if [ -e (loop)/casper/initrd ]; then + vt_linux_specify_initrd_file /casper/initrd + fi + if [ -e (loop)/casper/initrd.gz ]; then + vt_linux_specify_initrd_file /casper/initrd.gz + fi + if [ -e (loop)/casper/initrd-oem ]; then + vt_linux_specify_initrd_file /casper/initrd-oem + fi + elif [ -e (loop)/boot/grub/initrd.xz ]; then + vt_linux_specify_initrd_file /boot/grub/initrd.xz + elif [ -e (loop)/initrd.gz ]; then + vt_linux_specify_initrd_file /initrd.gz + elif [ -e (loop)/slax/boot/initrfs.img ]; then + vt_linux_specify_initrd_file /slax/boot/initrfs.img + elif [ -e (loop)/minios/boot/initrfs.img ]; then + vt_linux_specify_initrd_file /minios/boot/initrfs.img + elif [ -e (loop)/pmagic/initrd.img ]; then + vt_linux_specify_initrd_file /pmagic/initrd.img + elif [ -e (loop)/boot/initrd.xz ]; then + vt_linux_specify_initrd_file /boot/initrd.xz + elif [ -e (loop)/boot/initrd.gz ]; then + vt_linux_specify_initrd_file /boot/initrd.gz + elif [ -f (loop)/boot/initrd ]; then + vt_linux_specify_initrd_file /boot/initrd + elif [ -f (loop)/boot/x86_64/loader/initrd ]; then + vt_linux_specify_initrd_file /boot/x86_64/loader/initrd + elif [ -f (loop)/boot/initramfs-x86_64.img ]; then + vt_linux_specify_initrd_file /boot/initramfs-x86_64.img + elif [ -f (loop)/boot/isolinux/initramfs_data64.cpio.gz ]; then + vt_linux_specify_initrd_file /boot/isolinux/initramfs_data64.cpio.gz + elif [ -f (loop)/boot/initrd.img ]; then + vt_linux_specify_initrd_file /boot/initrd.img + elif [ -f (loop)/boot/grmlfullamd64/initrd.img ]; then + vt_linux_specify_initrd_file /boot/grmlfullamd64/initrd.img + fi + + if [ -f (loop)/isolinux/initrd.gz ]; then + vt_linux_specify_initrd_file /isolinux/initrd.gz + fi + + if vt_str_begin "$vt_volume_id" "QUBES"; then + vt_linux_specify_initrd_file /images/pxeboot/initrd.img + fi + + if [ "$vt_chosen_size" = "1133375488" ]; then + if [ -d (loop)/boot/grub/x86_64-efi ]; then + vt_cpio_busybox64 "64h" + fi + fi +} + + +function distro_specify_initrd_file_phase2 { + if [ -f (loop)/boot/initrd.img ]; then + vt_linux_specify_initrd_file /boot/initrd.img + elif [ -f (loop)/Setup/initrd.gz ]; then + vt_linux_specify_initrd_file /Setup/initrd.gz + elif [ -f (loop)/isolinux/initramfs ]; then + vt_linux_specify_initrd_file /isolinux/initramfs + elif [ -f (loop)/boot/iniramfs.igz ]; then + vt_linux_specify_initrd_file /boot/iniramfs.igz + elif [ -f (loop)/initrd-x86_64 ]; then + vt_linux_specify_initrd_file /initrd-x86_64 + elif [ -f (loop)/live/initrd.img ]; then + vt_linux_specify_initrd_file /live/initrd.img + elif [ -f (loop)/initrd.img ]; then + vt_linux_specify_initrd_file /initrd.img + elif [ -f (loop)/sysresccd/boot/x86_64/sysresccd.img ]; then + vt_linux_specify_initrd_file /sysresccd/boot/x86_64/sysresccd.img + elif [ -f (loop)/CDlinux/initrd ]; then + vt_linux_specify_initrd_file /CDlinux/initrd + elif [ -f (loop)/parabola/boot/x86_64/parabolaiso.img ]; then + vt_linux_specify_initrd_file /parabola/boot/x86_64/parabolaiso.img + if [ -f (loop)/parabola/boot/i686/parabolaiso.img ]; then + vt_linux_specify_initrd_file /parabola/boot/i686/parabolaiso.img + fi + elif [ -f (loop)/parabola/boot/x86_64/initramfs-linux-libre.img ]; then + vt_linux_specify_initrd_file /parabola/boot/x86_64/initramfs-linux-libre.img + if [ -f (loop)/parabola/boot/i686/initramfs-linux-libre.img ]; then + vt_linux_specify_initrd_file /parabola/boot/i686/initramfs-linux-libre.img + fi + elif [ -f (loop)/hyperbola/boot/x86_64/hyperiso.img ]; then + vt_linux_specify_initrd_file /hyperbola/boot/x86_64/hyperiso.img + if [ -f (loop)/hyperbola/boot/i686/hyperiso.img ]; then + vt_linux_specify_initrd_file /hyperbola/boot/i686/hyperiso.img + fi + elif [ -f (loop)/EFI/BOOT/initrd.img ]; then + #Qubes + vt_linux_specify_initrd_file /EFI/BOOT/initrd.img + if [ "$grub_platform" != "pc" ]; then + vt_add_replace_file 0 "initrd.img" + fi + elif [ -f (loop)/initrd ]; then + vt_linux_specify_initrd_file /initrd + elif [ -f (loop)/live/initrd1 ]; then + vt_linux_specify_initrd_file /live/initrd1 + elif [ -f (loop)/isolinux/initrd.img ]; then + vt_linux_specify_initrd_file /isolinux/initrd.img + elif [ -f (loop)/isolinux/initrd.gz ]; then + vt_linux_specify_initrd_file /isolinux/initrd.gz + elif [ -f (loop)/syslinux/kernel/initramfs.gz ]; then + vt_linux_specify_initrd_file /syslinux/kernel/initramfs.gz + elif vt_strstr "$vt_volume_id" "Daphile"; then + vt_linux_parse_initrd_isolinux (loop)/isolinux/ + elif [ -f (loop)/boot/rootfs.xz ]; then + vt_linux_specify_initrd_file /boot/rootfs.xz + if [ "$grub_platform" != "pc" ]; then + vt_add_replace_file 0 "minimal\\x86_64\\rootfs.xz" + fi + elif [ -f (loop)/arch/boot/x86_64/archiso.img ]; then + vt_linux_specify_initrd_file /arch/boot/x86_64/archiso.img + if [ "$grub_platform" != "pc" ]; then + vt_add_replace_file 0 "EFI\\archiso\\archiso.img" + fi + elif [ -f (loop)/blackarch/boot/x86_64/archiso.img ]; then + vt_linux_specify_initrd_file /blackarch/boot/x86_64/archiso.img + elif [ -f (loop)/blackarch/boot/x86_64/initramfs-linux.img ]; then + vt_linux_specify_initrd_file /blackarch/boot/x86_64/initramfs-linux.img + + elif [ -f (loop)/install.amd/initrd.gz ]; then + vt_linux_specify_initrd_file /live/initrd2.img + vt_linux_specify_initrd_file /install.amd/initrd.gz + vt_linux_specify_initrd_file /install.amd/gtk/initrd.gz + elif [ -f (loop)/boot/grub/kernels.cfg ]; then + vt_linux_parse_initrd_grub file (loop)/boot/grub/kernels.cfg + elif [ -f (loop)/austrumi/initrd.gz ]; then + vt_linux_specify_initrd_file /austrumi/initrd.gz + if [ -f (loop)/EFI/BOOT/bootx64.efi ]; then + vt_cpio_busybox64 "64h" + fi + elif [ -f (loop)/boot/initfs.x86_64-efi ]; then + vt_linux_specify_initrd_file /boot/initfs.x86_64-efi + if [ -f (loop)/boot/initfs.i386-pc ]; then + vt_linux_specify_initrd_file /boot/initfs.i386-pc + fi + elif [ -f (loop)/antiX/initrd.gz ]; then + vt_linux_specify_initrd_file /antiX/initrd.gz + elif [ -f (loop)/360Disk/initrd.gz ]; then + vt_linux_specify_initrd_file /360Disk/initrd.gz + elif [ -f (loop)/porteus/initrd.xz ]; then + vt_linux_specify_initrd_file /porteus/initrd.xz + elif [ -f (loop)/pyabr/boot/initrfs.img ]; then + vt_linux_specify_initrd_file /pyabr/boot/initrfs.img + elif [ -f (loop)/initrd0.img ]; then + vt_linux_specify_initrd_file /initrd0.img + elif [ -f (loop)/sysresccd/boot/i686/sysresccd.img ]; then + vt_linux_specify_initrd_file /sysresccd/boot/i686/sysresccd.img + elif [ -f (loop)/boot/full.cz ]; then + vt_linux_specify_initrd_file /boot/full.cz + elif [ -f (loop)/images/pxeboot/initrd.img ]; then + vt_linux_specify_initrd_file /images/pxeboot/initrd.img + elif [ -f (loop)/live/initrd ]; then + vt_linux_specify_initrd_file /live/initrd + elif [ -f (loop)/initramfs-linux.img ]; then + vt_linux_specify_initrd_file /initramfs-linux.img + elif [ -f (loop)/boot/isolinux/initrd.gz ]; then + vt_linux_specify_initrd_file /boot/isolinux/initrd.gz + elif [ -f (loop)/tiny/initrd ]; then + vt_linux_specify_initrd_file /tiny/initrd + elif vt_str_begin "$vt_volume_id" "AERYNOS"; then + vt_vcfg_pre_proc + + loopback va "${vtoy_iso_part}${vt_chosen_path}" + loopback vb (va)/EFI/Boot/efiboot.img + + set root=(vb) + vt_systemd_menu (vb) vt_sys_menu_mem vt_linux_initrd + configfile "mem:${vt_sys_menu_mem_addr}:size:${vt_sys_menu_mem_size}" + + fi +} + + +function ventoy_get_ghostbsd_ver { + # fallback to parse version from elf /boot/kernel/kernel + set vt_freebsd_ver=xx +} + +function ventoy_get_furybsd_ver { + set vt_freebsd_ver=12.x + if regexp --set 1:vtFuryVer "(14|13)\.[0-9]" "$2"; then + set vt_freebsd_ver=${vtFuryVer}.x + fi +} + +function ventoy_get_freenas_ver { + set vt_freebsd_ver=11.x + + if [ -e (loop)/FreeNAS-MANIFEST ]; then + vt_parse_freenas_ver (loop)/FreeNAS-MANIFEST vt_freenas_ver + if regexp --set 1:vtNasVer "^(14|13|12|11)\.[0-9]" "$vt_freenas_ver"; then + set vt_freebsd_ver=${vtNasVer}.x + fi + fi +} + +function ventoy_get_truenas_ver { + set vt_freebsd_ver=12.x + + if [ -e (loop)/TrueNAS-MANIFEST ]; then + vt_parse_freenas_ver (loop)/TrueNAS-MANIFEST vt_truenas_ver + if regexp --set 1:vtTNasVer "^(14|13|12|11)\.[0-9]" "$vt_truenas_ver"; then + set vt_freebsd_ver=${vtTNasVer}.x + fi + fi +} + +function ventoy_get_midnightbsd_ver { + if vt_str_begin "$vt_volume_id" "1_"; then + set vt_freebsd_ver=11.x + elif vt_str_begin "$vt_volume_id" "2_"; then + set vt_freebsd_ver=2.x + elif vt_str_begin "$vt_volume_id" "3_"; then + set vt_freebsd_ver=3.x + fi +} + +function ventoy_freebsd_proc { + set vtFreeBsdDistro=FreeBSD + set vt_freebsd_ver=xx + + if [ -e (loop)/boot/kernel/geom_ventoy.ko ]; then + vt_unix_ko_fillmap /boot/kernel/geom_ventoy.ko + return + fi + + if vt_strstr "$vt_volume_id" "GHOSTBSD"; then + ventoy_get_ghostbsd_ver "$1" "${chosen_path}" + elif vt_strstr "$vt_volume_id" "FREENAS"; then + ventoy_get_freenas_ver "$1" "${chosen_path}" + elif vt_strstr "$vt_volume_id" "TRUENAS"; then + ventoy_get_truenas_ver "$1" "${chosen_path}" + elif vt_strstr "$vt_volume_id" "FURYBSD"; then + ventoy_get_furybsd_ver "$1" "${chosen_path}" + elif regexp --set 1:vtBsdVerNum "^(1[0-9]|9)_[0-9]" "$vt_volume_id"; then + set vt_freebsd_ver=${vtBsdVerNum}.x + elif [ -d (loop)/usr/midnightbsd-dist ]; then + ventoy_get_midnightbsd_ver "$1" "${chosen_path}" + set vtFreeBsdDistro=MidnightBSD + elif [ -e (loop)/bin/freebsd-version ]; then + vt_unix_parse_freebsd_ver (loop)/bin/freebsd-version vt_userland_ver + if regexp --set 1:vtBsdVerNum "\"(1[0-9]|9)\.[0-9]-" "$vt_userland_ver"; then + set vt_freebsd_ver=${vtBsdVerNum}.x + fi + elif [ -e (loop)/README.TXT ]; then + vt_1st_line (loop)/README.TXT vt_freebsd_line1 + if regexp --set 1:vtBsdVerNum "FreeBSD (1[0-9]|9)\.[0-9]-" "$vt_freebsd_line1"; then + set vt_freebsd_ver=${vtBsdVerNum}.x + fi + elif vt_strstr "${chosen_path}" "MidnightBSD"; then + set vt_freebsd_ver=9.x + fi + + + if [ -e (loop)/usr/freebsd-dist/cloninst.sh ]; then + set vtFreeBsdDistro=ClonOS + fi + + set vt_freebsd_bit=64 + for file in "/boot/kernel/kernel" "/boot/kernel/kernel.gz"; do + if [ -e (loop)/$file ]; then + if file --is-i386-kfreebsd (loop)/$file; then + set vt_freebsd_bit=32 + fi + break + fi + done + + if [ "$vt_freebsd_ver" = "xx" ]; then + if [ -e (loop)/boot/kernel/kernel ]; then + vt_unix_parse_freebsd_ver_elf (loop)/boot/kernel/kernel $vt_freebsd_bit vt_freebsd_ver + elif [ -e (loop)/boot/kernel/kernel.gz ]; then + vt_unix_parse_freebsd_ver_elf (loop)/boot/kernel/kernel.gz $vt_freebsd_bit vt_freebsd_ver + fi + + if [ "$vt_freebsd_ver" = "xx" ]; then + set vt_freebsd_ver=15.x + fi + fi + + if [ "$vt_freebsd_ver" = "14.x" ]; then + if [ -e (loop)/boot/lua/brand-pfSense.lua ]; then + set vtFreeBsdDistro=pfSense + fi + fi + + + if [ -n "${vtdebug_flag}" ]; then + echo "This is $vtFreeBsdDistro $vt_freebsd_ver ${vt_freebsd_bit}bit" + fi + + unset vt_unix_mod_path + for file in "/COPYRIGHT" "/FreeNAS-MANIFEST" "/TrueNAS-MANIFEST" "/version" "/etc/fstab"; do + if [ -e (loop)${file} ]; then + set vt_unix_mod_path=${file} + break + fi + done + + if [ -n "$vt_unix_mod_path" ]; then + vt_unix_replace_ko $vt_unix_mod_path (vtunix)/ventoy_unix/$vtFreeBsdDistro/geom_ventoy_ko/$vt_freebsd_ver/$vt_freebsd_bit/geom_ventoy.ko.xz + vt_unix_replace_conf FreeBSD "${1}${chosen_path}" + elif [ -e (loop)/easyre.ufs.uzip ]; then + vt_unix_replace_ko "/boot/grub/i386-pc/linux.mod" (vtunix)/ventoy_unix/$vtFreeBsdDistro/geom_ventoy_ko/$vt_freebsd_ver/$vt_freebsd_bit/geom_ventoy.ko.xz + if [ "$grub_platform" = "pc" ]; then + vt_unix_replace_grub_conf "/boot/grub/i386-pc/linux.mod" "cd9" + else + vt_unix_replace_conf FreeBSD "${1}${chosen_path}" "cd9" + fi + fi +} + +function ventoy_dragonfly_proc { + + unset vt_unix_mod_path + for file in "/boot/kernel/initrd.img.gz"; do + if [ -e (loop)${file} ]; then + set vt_unix_mod_path=${file} + break + fi + done + + vt_unix_replace_ko $vt_unix_mod_path ${vtoy_path}/dragonfly.mfs.xz + vt_unix_fill_image_desc + vt_unix_gzip_new_ko + vt_unix_replace_conf DragonFly "${1}${chosen_path}" +} + +function ventoy_unix_comm_proc { + vt_unix_reset + + vt_unix_check_vlnk "${1}${chosen_path}" + + if [ "$ventoy_compatible" = "NO" ]; then + loopback vtunix $vtoy_efi_part/ventoy/ventoy_unix.cpio + + if [ "$vt_unix_type" = "FreeBSD" ]; then + ventoy_freebsd_proc "$1" "${chosen_path}" + elif [ "$vt_unix_type" = "DragonFly" ]; then + ventoy_dragonfly_proc "$1" "${chosen_path}" + elif [ "$vt_unix_type" = "NetBSD" ]; then + echo "NetBSD not supported" + + + else + if [ -n "${vtdebug_flag}" ]; then + echo "Unknown unix type" + fi + fi + fi + + vt_unix_chain_data "${1}${chosen_path}" + ventoy_debug_pause +} + + +function uefi_windows_menu_func { + vt_windows_reset + + unset vt_cur_wimboot_mode + if vt_check_mode 4 "$vt_chosen_name"; then + set vt_cur_wimboot_mode=1 + fi + + if [ "$ventoy_compatible" = "NO" -o "$vt_cur_wimboot_mode" = "1" ]; then + if [ "$ventoy_fs_probe" = "iso9660" ]; then + loopback -d loop + vt_iso9660_nojoliet 1 + loopback loop "$1$2" + fi + + for file in "efi/microsoft/boot/bcd" "boot/bcd" "SSTR/BCD" "WEPE/B64" "WEPE/B32" "WEPE/BCD" "ISPE/BCD" "ISYL/BCD" "2K10/FONTS/BCD" "2K10/BCD" "boot/uqi/BCD"; do + vt_windows_collect_wim_patch bcd (loop)/$file + done + + vt_windows_count_wim_patch vt_wim_cnt + if [ $vt_wim_cnt -eq 0 ]; then + distro_specify_wim_patch_phase2 + fi + + ventoy_debug_pause + locate_wim "${chosen_path}" + fi + + vt_windows_chain_data "${1}${chosen_path}" + ventoy_debug_pause + + if [ "$vt_cur_wimboot_mode" = "1" ]; then + vtoy_wimboot_func + fi + + if [ -n "$vtoy_chain_mem_addr" ]; then + ventoy_acpi_param ${vtoy_chain_mem_addr} 2048 + chainloader ${vtoy_path}/ventoy_${VTOY_EFI_ARCH}.efi env_param=${env_param} isoefi=${LoadIsoEfiDriver} iso_${ventoy_fs_probe} ${vtdebug_flag} mem:${vtoy_chain_mem_addr}:size:${vtoy_chain_mem_size} + boot + else + echo "chain empty failed" + ventoy_pause + fi +} + +function uefi_find_replace_initrd { + if vt_get_efi_vdisk_offset "${1}${2}" vt_efivdisk_offset; then + loopback -s $vt_efivdisk_offset vtefivdisk "${1}${2}" + + unset vt_rp_initrd + vt_search_replace_initrd (vtefivdisk) vt_rp_initrd + + if [ -n "$vt_rp_initrd" ]; then + vt_add_replace_file $3 "$vt_rp_initrd" + fi + + loopback -d vtefivdisk + ventoy_debug_pause + fi +} + +function uefi_linux_menu_func { + + if [ "$ventoy_compatible" = "NO" ]; then + + if [ "$ventoy_fs_probe" = "udf" ]; then + loopback -d loop + set ventoy_fs_probe=iso9660 + loopback loop "$1$2" + fi + + vt_load_cpio $vtoy_path "$2" "$1" "busybox=$ventoy_busybox_ver" + + vt_linux_clear_initrd + + if [ -d (loop)/pmagic ]; then + vt_linux_specify_initrd_file /pmagic/initrd.img + else + for file in "boot/grub/grub.cfg" "EFI/BOOT/grub.cfg" "EFI/boot/grub.cfg" "efi/boot/grub.cfg" "EFI/BOOT/BOOTX64.conf" "/grub/grub.cfg" "EFI/BOOT/grub/grub.cfg"; do + if [ -e (loop)/$file ]; then + vt_linux_parse_initrd_grub file (loop)/$file + fi + done + fi + + # special process for special distros + if [ -d (loop)/loader/entries ]; then + vt_linux_parse_initrd_grub dir (loop)/loader/entries/ + elif [ -d (loop)/boot/grub ]; then + vt_linux_parse_initrd_grub dir (loop)/boot/grub/ + fi + + distro_specify_initrd_file + + vt_linux_initrd_count vtcount + + if [ $vtcount -eq 0 ]; then + if [ -e (loop)/EFI/boot/livegrub.cfg ]; then + vt_linux_parse_initrd_grub file (loop)/EFI/boot/livegrub.cfg + fi + distro_specify_initrd_file_phase2 + + if [ "$vt_efi_dir" = "NO" ]; then + if [ -f (loop)/efi.img ]; then + vt_add_replace_file 0 "initrd" + fi + fi + fi + + locate_initrd + + if [ -d (loop)/loader/entries ]; then + vt_linux_get_main_initrd_index vtindex + + if [ -d (loop)/arch ]; then + if [ -f (loop)/arch/boot/x86_64/archiso.img ]; then + vt_add_replace_file $vtindex "EFI\\archiso\\archiso.img" + elif [ -f (loop)/arch/boot/x86_64/initramfs-linux.img ]; then + vt_add_replace_file $vtindex "arch\\boot\\x86_64\\initramfs-linux.img" + elif [ -f (loop)/boot/initramfs_x86_64.img ]; then + vt_add_replace_file $vtindex "boot\\initramfs_x86_64.img" + elif [ -f (loop)/arch/boot/x86_64/initramfs-linux-aegis-offensive.img ]; then + vt_add_replace_file $vtindex "arch\\boot\\x86_64\\initramfs-linux-aegis-offensive.img" + fi + elif [ -d (loop)/blackarch ]; then + if [ -f (loop)/blackarch/boot/x86_64/archiso.img ]; then + vt_add_replace_file $vtindex "EFI\\archiso\\archiso.img" + elif [ -f (loop)/blackarch/boot/x86_64/initramfs-linux.img ]; then + vt_add_replace_file $vtindex "blackarch\\boot\\x86_64\\initramfs-linux.img" + fi + elif [ -d (loop)/anarchy ]; then + if [ -f (loop)/anarchy/boot/x86_64/initramfs-linux.img ]; then + vt_add_replace_file $vtindex "anarchy\\boot\\x86_64\\initramfs-linux.img" + fi + elif [ -d (loop)/parabola ]; then + if [ -f (loop)/parabola/boot/x86_64/parabolaiso.img ]; then + vt_add_replace_file $vtindex "EFI\\parabolaiso\\parabolaiso.img" + elif [ -f (loop)/parabola/boot/x86_64/initramfs-linux-libre.img ]; then + vt_add_replace_file $vtindex "parabola\\boot\\x86_64\\initramfs-linux-libre.img" + fi + elif [ -f (loop)/EFI/BOOT/initrd.gz ]; then + vt_add_replace_file $vtindex "EFI\\BOOT\\initrd.gz" + elif [ -f (loop)/loader/entries/thinstation.conf ]; then + vt_add_replace_file $vtindex "boot\\initrd" + elif [ -f (loop)/loader/entries/pisi-efi-x86_64.conf ]; then + vt_add_replace_file $vtindex "EFI\\pisi\\initrd.img" + fi + + vt_get_replace_file_cnt vt_replace_cnt + if [ $vt_replace_cnt -eq 0 ]; then + uefi_find_replace_initrd "$1" "$2" $vtindex + fi + elif [ -d (loop)/EFI/boot/entries ]; then + if [ -f (loop)/parabola/boot/x86_64/parabolaiso.img ]; then + vt_add_replace_file 0 "EFI\\parabolaiso\\parabolaiso.img" + elif [ -f (loop)/hyperbola/boot/x86_64/hyperiso.img ]; then + vt_add_replace_file 0 "EFI\\hyperiso\\hyperiso.img" + fi + elif [ -d (loop)/EFI/BOOT/entries ]; then + vt_linux_get_main_initrd_index vtindex + + if [ -f (loop)/parabola/boot/x86_64/parabolaiso.img ]; then + vt_add_replace_file 0 "EFI\\parabolaiso\\parabolaiso.img" + elif [ -f (loop)/parabola/boot/x86_64/initramfs-linux-libre.img ]; then + vt_add_replace_file $vtindex "parabola\\boot\\x86_64\\initramfs-linux-libre.img" + fi + elif [ -e (loop)/syslinux/alt0/full.cz ]; then + vt_add_replace_file 0 "EFI\\BOOT\\full.cz" + set FirstTryBootFile='@EFI@BOOT@grubx64.efi' + + elif vt_str_begin "$vt_volume_id" "SolusLive"; then + vt_add_replace_file 0 "initrd" + + fi + + fi + + vt_linux_chain_data "${1}${chosen_path}" + + if [ -n "$LoadIsoEfiDriver" -a $vt_chosen_size -LT 104857600 ]; then + if [ -f (loop)/efi/clover/cloverx64.efi ]; then + unset LoadIsoEfiDriver + fi + fi + + if [ -n "$vtoy_chain_mem_addr" ]; then + ventoy_acpi_param ${vtoy_chain_mem_addr} 2048 + ventoy_cli_console + + unset vtGrub2Mode + if vt_check_mode 3 "$vt_chosen_name"; then + set vtGrub2Mode=1 + elif vt_str_begin "$vt_volume_id" "HOLO_"; then + if [ -d (loop)/loader/entries ]; then + set vtGrub2Mode=1 + fi + elif vt_str_begin "$vt_volume_id" "KRD"; then + if [ -f (loop)/boot/grub/grub.cfg.sig ]; then + set vtGrub2Mode=1 + fi + fi + + if [ -n "$vtGrub2Mode" ]; then + ventoy_debug_pause + else + if [ "$VTOY_EFI_ARCH" != "mips" ]; then + chainloader ${vtoy_path}/ventoy_${VTOY_EFI_ARCH}.efi fallback env_param=${env_param} isoefi=${LoadIsoEfiDriver} FirstTry=${FirstTryBootFile} ${vtdebug_flag} mem:${vtoy_chain_mem_addr}:size:${vtoy_chain_mem_size} + boot + fi + fi + + # fallback + set vtback_root=$root + vt_push_last_entry + set vtback_theme=$theme + unset theme + + vt_trailer_cpio "$vtoy_iso_part" "$vt_chosen_path" noinit + vt_set_boot_opt rdinit=/vtoy/vtoy + + set root=(loop) + set vtback_cfg_find=0 + for cfg in "/boot/grub/grub.cfg" "/EFI/BOOT/grub.cfg" "/EFI/debian/grub.cfg" "EFI/boot/grub.cfg" "efi/boot/grub.cfg" "/grub/grub.cfg" "EFI/BOOT/BOOTX64.conf"; do + if [ -e "$cfg" ]; then + set vtback_cfg_find=1 + configfile "$cfg" + break + fi + done + if [ $vtback_cfg_find -eq 0 ]; then + if [ -f (loop)/loader/loader.conf -a -d (loop)/loader/entries ]; then + if vt_str_begin "$vt_volume_id" "HOLO_"; then + set root=(loop,2) + vt_systemd_menu (loop,2) vt_sys_menu_mem + else + vt_systemd_menu (loop) vt_sys_menu_mem + fi + set vtback_cfg_find=1 + configfile "mem:${vt_sys_menu_mem_addr}:size:${vt_sys_menu_mem_size}" + fi + fi + + if [ $vtback_cfg_find -eq 0 ]; then + if [ -f (loop)/boot/isolinux/syslnx64.cfg ]; then + syslinux_configfile (loop)/boot/isolinux/syslnx64.cfg + set vtback_cfg_find=1 + elif [ -f (loop)/boot/syslinux/porteus.cfg ]; then + syslinux_configfile (loop)/boot/syslinux/porteus.cfg + set vtback_cfg_find=1 + elif [ -f (loop)/syslinux.cfg ]; then + syslinux_configfile (loop)/syslinux.cfg + set vtback_cfg_find=1 + fi + fi + + if [ "$vtback_cfg_find" = "0" ]; then + echo " " + echo "No bootfile found for UEFI!" + echo "Maybe the image does not support $VTOY_EFI_ARCH UEFI" + echo " " + sleep 30 + fi + + vt_unset_boot_opt + set root=$vtback_root + set theme=$vtback_theme + vt_pop_last_entry + ventoy_gui_console + else + echo "chain empty failed" + ventoy_pause + fi +} + +function uefi_unix_menu_func { + ventoy_unix_comm_proc $1 "${chosen_path}" + + if [ -n "$vtoy_chain_mem_addr" ]; then + ventoy_acpi_param ${vtoy_chain_mem_addr} 2048 + ventoy_cli_console + chainloader ${vtoy_path}/ventoy_${VTOY_EFI_ARCH}.efi env_param=${env_param} isoefi=${LoadIsoEfiDriver} FirstTry=${FirstTryBootFile} ${vtdebug_flag} mem:${vtoy_chain_mem_addr}:size:${vtoy_chain_mem_size} + boot + else + echo "chain empty failed" + ventoy_pause + fi +} + +function ventoy_reset_nojoliet { + if vt_str_begin "$vt_volume_id" "ARCARESCUE"; then + vt_iso9660_nojoliet 1 + else + vt_iso9660_nojoliet 0 + fi + + vt_append_extra_sector 0 +} + +function uefi_iso_menu_func { + if [ -n "$vtisouefi" ]; then + set LoadIsoEfiDriver=on + unset vtisouefi + elif vt_check_mode 2 "$vt_chosen_name"; then + set LoadIsoEfiDriver=on + else + unset LoadIsoEfiDriver + fi + + set chosen_path="$2" + vt_select_auto_install "${chosen_path}" + vt_select_persistence "${chosen_path}" + + if ! vt_is_udf "${1}${chosen_path}"; then + # Lenovo EasyStartup need an addional sector for boundary check + if vt_str_begin "$vt_volume_id" "EasyStartup"; then + vt_skip_svd "${vtoy_iso_part}${vt_chosen_path}" + vt_append_extra_sector 1 + fi + fi + + if [ -d (loop)/EFI ]; then + set vt_efi_dir=YES + elif [ -d (loop)/efi ]; then + set vt_efi_dir=YES + else + set vt_efi_dir=NO + fi + + if [ -n "$vtcompat" ]; then + set ventoy_compatible=YES + unset vtcompat + elif vt_check_mode 1 "$vt_chosen_name"; then + set ventoy_compatible=YES + else + vt_check_compatible (loop) + fi + + vt_img_sector "${1}${chosen_path}" + + if [ "$ventoy_fs_probe" = "iso9660" ]; then + vt_select_conf_replace "${1}" "${chosen_path}" + fi + + if [ "$vtoy_os" = "Windows" ]; then + vt_check_compatible_pe (loop) + uefi_windows_menu_func "$1" "${chosen_path}" + elif [ "$vtoy_os" = "Unix" ]; then + uefi_unix_menu_func "$1" "${chosen_path}" + else + vt_check_compatible_linux (loop) + uefi_linux_menu_func "$1" "${chosen_path}" + fi + + ventoy_gui_console +} + +function uefi_iso_memdisk { + echo 'Loading ISO file to memory ...' + vt_load_img_memdisk "${1}${2}" vtoy_iso_buf + + ventoy_cli_console + chainloader ${vtoy_path}/ventoy_${VTOY_EFI_ARCH}.efi memdisk env_param=${env_param} isoefi=${LoadIsoEfiDriver} ${vtdebug_flag} mem:${vtoy_iso_buf_addr}:size:${vtoy_iso_buf_size} + boot + + ventoy_gui_console +} + +function vtoy_windows_wimboot { + if [ -f (loop)/x86/sources/boot.wim -a -f (loop)/x64/sources/boot.wim ]; then + vt_sel_wimboot vtoy_wimboot_bit + if [ "$vtoy_wimboot_bit" = "32" ]; then + set vtoy_wimboot_prefix=(loop)/x86 + else + set vtoy_wimboot_prefix=(loop)/x64 + fi + else + set vtoy_wimboot_prefix=(loop) + if vt_is_pe64 $vtoy_wimboot_prefix/setup.exe; then + set vtoy_wimboot_bit=64 + else + set vtoy_wimboot_bit=32 + fi + fi + + if [ -n "${vtdebug_flag}" ]; then + echo vtoy_wimboot_prefix=$vtoy_wimboot_prefix vtoy_wimboot_bit=$vtoy_wimboot_bit vt_wimkernel=$vt_wimkernel + fi + + vt_windows_wimboot_data "$vtoy_wimboot_prefix/sources/boot.wim" vtoy_init_exe vtoy_wim_bit + + if [ "$grub_platform" = "pc" ]; then + linux16 "$vtoy_path/$vt_wimkernel" quiet + ventoy_debug_pause + + vt_set_wim_load_prompt 1 "Loading files......" + initrd16 newc:winpeshl.exe:mem:${vtoy_wimboot_mem_addr}:size:${vtoy_wimboot_mem_size} \ + newc:vtoy_wimboot:$vtoy_wimboot_prefix/boot/bcd \ + newc:bcd:$vtoy_wimboot_prefix/boot/bcd \ + newc:boot.sdi:$vtoy_wimboot_prefix/boot/boot.sdi \ + newc:boot.wim:$vtoy_wimboot_prefix/sources/boot.wim + vt_set_wim_load_prompt 0 + boot + else + vt_set_wim_load_prompt 1 "Loading files......" + vt_load_file_to_mem "nodecompress" $vtoy_wimboot_prefix/sources/boot.wim vtoy_wimfile_mem + vt_set_wim_load_prompt 0 + + if [ $? -eq 0 ]; then + set vtoy_wimfile_path=mem:${vtoy_wimfile_mem_addr}:size:${vtoy_wimfile_mem_size} + else + set vtoy_wimfile_path=$vtoy_wimboot_prefix/sources/boot.wim + fi + + ventoy_cli_console + chainloader "$vtoy_path/$vt_wimkernel" quiet \ + "vf=winpeshl.exe:mem:${vtoy_wimboot_mem_addr}:size:${vtoy_wimboot_mem_size}" \ + "vf=vtoy_wimboot:$vtoy_wimboot_prefix/boot/bcd" \ + "vf=bcd:$vtoy_wimboot_prefix/boot/bcd" \ + "vf=boot.sdi:$vtoy_wimboot_prefix/boot/boot.sdi" \ + "vf=boot.wim:$vtoy_wimfile_path" \ + pfsize=$vtoy_chain_file_size \ + pfread=$vtoy_chain_file_read + boot + ventoy_gui_console + fi +} + +function vtoy_winpe_wimboot { + unset vtoy_boot_sdi_legacy + unset vtoy_boot_sdi_efi + + set vtoy_wimboot_prefix=(loop) + set vtoy_wim_path="$1" + + if [ -n "${vtdebug_flag}" ]; then + echo "winpe_wimboot $1 $2 $3" + fi + + if [ "$2" != "0" ]; then + set vtoy_boot_sdi_legacy="newc:boot.sdi:$vtoy_wimboot_prefix/$2" + set vtoy_boot_sdi_efi="vf=boot.sdi:$vtoy_wimboot_prefix/$2" + fi + + vt_windows_wimboot_data $vtoy_wimboot_prefix/$vtoy_wim_path vtoy_init_exe vtoy_wim_bit + + if [ "$grub_platform" = "pc" ]; then + linux16 "$vtoy_path/$vt_wimkernel" quiet + ventoy_debug_pause + + vt_set_wim_load_prompt 1 "Loading files......" + initrd16 newc:$vtoy_init_exe:mem:${vtoy_wimboot_mem_addr}:size:${vtoy_wimboot_mem_size} \ + newc:vtoy_wimboot:$vtoy_path/$vt_wimkernel \ + newc:bootmgr.exe:mem:${vtoy_pe_bootmgr_mem_addr}:size:${vtoy_pe_bootmgr_mem_size} \ + newc:bcd:mem:${vtoy_pe_bcd_mem_addr}:size:${vtoy_pe_bcd_mem_size} \ + $vtoy_boot_sdi_legacy \ + newc:boot.wim:$vtoy_wimboot_prefix/$vtoy_wim_path + vt_set_wim_load_prompt 0 + boot + else + if [ "$VTOY_EFI_ARCH" = "x64" -a "$vtoy_wim_bit" = "32" ]; then + echo -e "\nThis is 32bit Windows and does NOT support x86_64 UEFI firmware.\n" + echo -e "这是32位的 Windows 系统,不支持当前的64位 UEFI 环境。\n" + fi + + vt_set_wim_load_prompt 1 "Loading files......" + vt_load_file_to_mem "nodecompress" $vtoy_wimboot_prefix/$vtoy_wim_path vtoy_wimfile_mem + vt_set_wim_load_prompt 0 + + if [ $? -eq 0 ]; then + set vtoy_wimfile_path=mem:${vtoy_wimfile_mem_addr}:size:${vtoy_wimfile_mem_size} + else + set vtoy_wimfile_path=$vtoy_wimboot_prefix/$vtoy_wim_path + fi + + unset vtoy_boot_efi_path + if [ -F (loop)/efi/boot/boot${VTOY_EFI_ARCH}.efi ]; then + set vtoy_boot_efi_path="vf=bootx64.efi:(loop)/efi/boot/boot${VTOY_EFI_ARCH}.efi" + fi + + ventoy_cli_console + chainloader "$vtoy_path/$vt_wimkernel" quiet \ + "vf=$vtoy_init_exe:mem:${vtoy_wimboot_mem_addr}:size:${vtoy_wimboot_mem_size}" \ + "vf=vtoy_wimboot:$vtoy_path/$vt_wimkernel" \ + "vf=bcd:mem:${vtoy_pe_bcd_mem_addr}:size:${vtoy_pe_bcd_mem_size}" \ + "$vtoy_boot_sdi_efi" \ + "$vtoy_boot_efi_path" \ + "vf=boot.wim:$vtoy_wimfile_path" \ + pfsize=$vtoy_chain_file_size \ + pfread=$vtoy_chain_file_read + boot + ventoy_gui_console + fi +} + +function vtoy_wimboot_func { + if [ "$grub_platform" = "pc" ]; then + set vt_wimkernel=wimboot.x86_64.xz + else + if [ "$grub_cpu" = "i386" ]; then + set vt_wimkernel=wimboot.i386.efi.xz + else + set vt_wimkernel=wimboot.x86_64.xz + fi + fi + + if vt_is_standard_winiso (loop); then + echo -e "\n==================== VENTOY WIMBOOT ==================\n" + vtoy_windows_wimboot + else + vt_sel_winpe_wim (loop) + if [ -n "$vtoy_pe_wim_path" ]; then + echo -e "\n==================== VENTOY WIMBOOT ==================\n" + + vt_fs_ignore_case 1 + vt_load_file_to_mem "auto" $vtoy_path/common_bcd.xz vtoy_pe_bcd_mem + + set vt_sdi_path=0 + for vsdi in "boot/boot.sdi" "2K10/FONTS/boot.sdi" "SSTR/boot.sdi" "ISPE/BOOT.SDI" \ + "boot/uqi.sdi" "ISYL/boot.sdi" "WEPE/WEPE.SDI" ; do + if [ -F "(loop)/$vsdi" ]; then + set vt_sdi_path=$vsdi + break + fi + done + + if [ "$grub_platform" = "pc" ]; then + vt_load_file_to_mem "auto" $vtoy_path/common_bootmgr.xz vtoy_pe_bootmgr_mem + vtoy_winpe_wimboot "$vtoy_pe_wim_path" "$vt_sdi_path" 1 + else + vtoy_winpe_wimboot "$vtoy_pe_wim_path" "$vt_sdi_path" 0 + fi + + vt_fs_ignore_case 0 + fi + fi +} + +function legacy_windows_menu_func { + vt_windows_reset + + unset vt_cur_wimboot_mode + if vt_check_mode 4 "$vt_chosen_name"; then + set vt_cur_wimboot_mode=1 + fi + + if [ "$ventoy_compatible" = "NO" -o "$vt_cur_wimboot_mode" = "1" ]; then + if [ "$ventoy_fs_probe" = "iso9660" ]; then + loopback -d loop + vt_iso9660_nojoliet 1 + loopback loop "$1$2" + fi + + for file in "boot/bcd" "/efi/microsoft/boot/bcd" "SSTR/BCD" "WEPE/B64" "WEPE/B32" "WEPE/BCD" "ISPE/BCD" "ISYL/BCD" "2K10/FONTS/BCD" "2K10/BCD" "boot/uqi/BCD" "boot/bce"; do + vt_windows_collect_wim_patch bcd (loop)/$file + done + + distro_specify_wim_patch + + vt_windows_count_wim_patch vt_wim_cnt + if [ $vt_wim_cnt -eq 0 ]; then + distro_specify_wim_patch_phase2 + fi + + ventoy_debug_pause + if [ -z "$vt_cur_wimboot_mode" ]; then + locate_wim "${chosen_path}" + fi + fi + + vt_windows_chain_data "${1}${chosen_path}" + ventoy_debug_pause + + if [ "$vt_cur_wimboot_mode" = "1" ]; then + vtoy_wimboot_func + fi + + if [ -n "$vtoy_chain_mem_addr" ]; then + ventoy_acpi_param ${vtoy_chain_mem_addr} 2048 + if [ "$ventoy_compatible" = "NO" ]; then + linux16 $vtoy_path/ipxe.krn ${vtdebug_flag} mem:${vtoy_chain_mem_addr}:size:${vtoy_chain_mem_size} + else + linux16 $vtoy_path/ipxe.krn ${vtdebug_flag} ibft mem:${vtoy_chain_mem_addr}:size:${vtoy_chain_mem_size} + fi + boot + else + echo "chain empty failed" + ventoy_pause + fi +} + +function legacy_linux_menu_func { + if [ "$ventoy_compatible" = "NO" ]; then + + if [ "$ventoy_fs_probe" = "udf" ]; then + loopback -d loop + set ventoy_fs_probe=iso9660 + loopback loop "$1$2" + fi + + + if vt_syslinux_need_nojoliet "$1$2"; then + vt_iso9660_nojoliet 1 + loopback -d loop + loopback loop "$1$2" + fi + + vt_load_cpio $vtoy_path "$2" "$1" "busybox=$ventoy_busybox_ver" + + vt_linux_clear_initrd + + if [ -d (loop)/pmagic ]; then + vt_linux_specify_initrd_file /pmagic/initrd.img + else + for dir in "isolinux" "boot/isolinux" "boot/x86_64/loader" "syslinux" "boot/syslinux"; do + if [ -d (loop)/$dir ]; then + vt_linux_parse_initrd_isolinux (loop)/$dir/ + fi + done + fi + + # special process for special distros + #archlinux + if [ -d (loop)/arch/boot/syslinux ]; then + vt_linux_parse_initrd_isolinux (loop)/arch/boot/syslinux/ /arch/ + vt_linux_parse_initrd_isolinux (loop)/arch/boot/syslinux/ /arch/boot/syslinux/ + elif [ -d (loop)/anarchy/boot/syslinux ]; then + vt_linux_parse_initrd_isolinux (loop)/anarchy/boot/syslinux/ /anarchy/ + + #manjaro + elif [ -d (loop)/manjaro ]; then + if [ -e (loop)/boot/grub/kernels.cfg ]; then + vt_linux_parse_initrd_grub file (loop)/boot/grub/kernels.cfg + fi + elif [ -e (loop)/boot/grub/grub.cfg ]; then + vt_linux_parse_initrd_grub file (loop)/boot/grub/grub.cfg + fi + + distro_specify_initrd_file + + vt_linux_initrd_count vtcount + if [ $vtcount -eq 0 ]; then + if [ -d (loop)/rancheros ]; then + vt_linux_parse_initrd_isolinux (loop)/boot/ /boot/isolinux/ + fi + + distro_specify_initrd_file_phase2 + fi + + locate_initrd + fi + + vt_linux_chain_data "${1}${chosen_path}" + ventoy_debug_pause + + if [ -n "$vtoy_chain_mem_addr" ]; then + unset vtGrub2Mode + if vt_check_mode 3 "$vt_chosen_name"; then + set vtGrub2Mode=1 + elif vt_str_begin "$vt_volume_id" "HOLO_"; then + if [ -d (loop)/loader/entries ]; then + set vtGrub2Mode=1 + fi + fi + + if [ -n "$vtGrub2Mode" ]; then + ventoy_acpi_param ${vtoy_chain_mem_addr} 2048 + ventoy_cli_console + + # fallback + set vtback_root=$root + vt_push_last_entry + set vtback_theme=$theme + unset theme + + vt_trailer_cpio "$vtoy_iso_part" "$vt_chosen_path" noinit + vt_set_boot_opt rdinit=/vtoy/vtoy + + set root=(loop) + set vtback_cfg_find=0 + for cfg in "/boot/grub/grub.cfg" "/EFI/BOOT/grub.cfg" "/EFI/debian/grub.cfg" "EFI/boot/grub.cfg" "efi/boot/grub.cfg" "/grub/grub.cfg" "EFI/BOOT/BOOTX64.conf"; do + if [ -e "$cfg" ]; then + set vtback_cfg_find=1 + configfile "$cfg" + break + fi + done + if [ $vtback_cfg_find -eq 0 ]; then + if [ -f (loop)/loader/loader.conf -a -d (loop)/loader/entries ]; then + if vt_str_begin "$vt_volume_id" "HOLO_"; then + set root=(loop,2) + vt_systemd_menu (loop,2) vt_sys_menu_mem + else + vt_systemd_menu (loop) vt_sys_menu_mem + fi + set vtback_cfg_find=1 + configfile "mem:${vt_sys_menu_mem_addr}:size:${vt_sys_menu_mem_size}" + fi + fi + + if [ $vtback_cfg_find -eq 0 ]; then + if [ -f (loop)/boot/isolinux/syslnx64.cfg ]; then + syslinux_configfile (loop)/boot/isolinux/syslnx64.cfg + set vtback_cfg_find=1 + elif [ -f (loop)/boot/syslinux/porteus.cfg ]; then + syslinux_configfile (loop)/boot/syslinux/porteus.cfg + set vtback_cfg_find=1 + elif [ -f (loop)/syslinux.cfg ]; then + syslinux_configfile (loop)/syslinux.cfg + set vtback_cfg_find=1 + fi + fi + + vt_unset_boot_opt + set root=$vtback_root + set theme=$vtback_theme + vt_pop_last_entry + ventoy_gui_console + else + ventoy_acpi_param ${vtoy_chain_mem_addr} 2048 + linux16 $vtoy_path/ipxe.krn ${vtdebug_flag} mem:${vtoy_chain_mem_addr}:size:${vtoy_chain_mem_size} + boot + fi + else + echo "chain empty failed" + ventoy_pause + fi +} + + +function legacy_unix_menu_func { + ventoy_unix_comm_proc $1 "${chosen_path}" + + if [ -n "$vtoy_chain_mem_addr" ]; then + #ventoy_acpi_param ${vtoy_chain_mem_addr} 2048 + linux16 $vtoy_path/ipxe.krn ${vtdebug_flag} mem:${vtoy_chain_mem_addr}:size:${vtoy_chain_mem_size} + boot + else + echo "chain empty failed" + ventoy_pause + fi +} + + +function legacy_iso_menu_func { + set chosen_path="$2" + + vt_select_auto_install "${chosen_path}" + vt_select_persistence "${chosen_path}" + + if [ -n "$vtcompat" ]; then + set ventoy_compatible=YES + unset vtcompat + elif vt_check_mode 1 "$vt_chosen_name"; then + set ventoy_compatible=YES + else + vt_check_compatible (loop) + fi + + vt_img_sector "${1}${chosen_path}" + + if [ "$ventoy_fs_probe" = "iso9660" ]; then + vt_select_conf_replace "${1}" "${chosen_path}" + fi + + if [ "$vtoy_os" = "Windows" ]; then + vt_check_compatible_pe (loop) + legacy_windows_menu_func "$1" "${chosen_path}" + elif [ "$vtoy_os" = "Unix" ]; then + legacy_unix_menu_func "$1" "${chosen_path}" + else + vt_check_compatible_linux (loop) + legacy_linux_menu_func "$1" "${chosen_path}" + fi + vt_secondary_recover_mode +} + +function legacy_iso_memdisk { + + linux16 $vtoy_path/memdisk iso raw + echo "Loading ISO file to memory ..." + initrd16 "${1}${2}" + boot +} + + +function iso_endless_os_proc { + if [ -d (loop)/ ]; then + loopback -d loop + fi + + loopback loop "${1}${2}" + vt_img_sector "${1}${2}" + + vt_load_cpio $vtoy_path "$2" "$1" "busybox=$ventoy_busybox_ver" + vt_trailer_cpio "$1" "$2" noinit + + ventoy_debug_pause + + vt_set_boot_opt '@kparams' rdinit=/vtoy/vtoy + + set eosimage=loop + set ventoy_bls_bootdev=/boot + set ventoy_loading_tip="Loading files ......" + + export eosimage + configfile (loop)/endless/grub/grub.cfg + + unset eosimage + unset ventoy_bls_bootdev + unset ventoy_loading_tip + + vt_unset_boot_opt +} + + +function ventoy_iso_busybox_ver { + + if [ "$VTOY_EFI_ARCH" = "aa64" ]; then + set ventoy_busybox_ver=a64 + elif [ "$VTOY_EFI_ARCH" = "mips" ]; then + set ventoy_busybox_ver=m64 + else + set ventoy_busybox_ver=32 + + #special process for deepin-live iso + if [ "$vt_chosen_size" = "403701760" ]; then + if vt_strstr "$vt_chosen_path" "/deepin-live"; then + set ventoy_busybox_ver=64 + fi + elif vt_str_begin "$vt_volume_id" "PHOTON_"; then + set ventoy_busybox_ver=64 + elif vt_str_begin "$vt_volume_id" "smgl-test-quinq-x86_64"; then + set ventoy_busybox_ver=64 + elif vt_str_begin "$vt_volume_id" "LDiagBootable"; then + set ventoy_busybox_ver=64 + elif vt_str_begin "$vt_volume_id" "KAOS_"; then + set ventoy_busybox_ver=64 + elif vt_strstr "$vt_volume_id" "x86_64"; then + set ventoy_busybox_ver=64 + elif vt_istrstr "${vt_chosen_path}" "x86_64"; then + set ventoy_busybox_ver=64 + elif vt_istrstr "${vt_chosen_path}" "amd64"; then + set ventoy_busybox_ver=64 + fi + fi +} + + +function iso_common_menuentry { + unset vt_system_id + unset vt_volume_id + + vt_chosen_img_path vt_chosen_path vt_chosen_size vt_chosen_name + + vt_parse_iso_volume "${vtoy_iso_part}${vt_chosen_path}" vt_system_id vt_volume_id vt_volume_space + if [ $vt_volume_space -NE $vt_chosen_size ]; then + vt_mod $vt_chosen_size 2048 vt_chosen_size_mod + if [ $vt_chosen_size_mod -ne 0 ]; then + echo -e "\n $vt_volume_space $vt_chosen_size $vt_chosen_size_mod\n" + echo -e "\n The size of the iso file \"$vt_chosen_size\" is invalid. File corrupted ?\n" + echo -e " 此ISO文件的大小 \"$vt_chosen_size\" 有问题,请确认文件是否损坏。\n" + echo -en "\n$VTLANG_ENTER_CONTINUE ..." + read vtInputKey + fi + fi + + if vt_check_password "${vt_chosen_path}"; then + return + fi + + if ventoy_vcfg_proc "${vt_chosen_path}"; then + return + fi + + + + #secondary boot menu + if vt_is_udf "${vtoy_iso_part}${vt_chosen_path}"; then + set ventoy_fs_probe=udf + else + set ventoy_fs_probe=iso9660 + ventoy_reset_nojoliet + fi + + if [ -d (loop)/ ]; then + loopback -d loop + fi + loopback loop "${vtoy_iso_part}${vt_chosen_path}" + + get_os_type (loop) + + ventoy_debug_pause + + if vt_need_secondary_menu "$vt_chosen_name"; then + vt_show_secondary_menu "$vt_chosen_path" "$vtoy_os" $vt_chosen_size + if [ "$VTOY_SECOND_EXIT" = "1" ]; then + return + fi + fi + + + if vt_str_begin "$vt_volume_id" "Avira"; then + vt_skip_svd "${vtoy_iso_part}${vt_chosen_path}" + fi + + ventoy_iso_busybox_ver + + #special process for Endless OS + if vt_str_begin "$vt_volume_id" "Endless-OS"; then + iso_endless_os_proc $vtoy_iso_part "$vt_chosen_path" + elif vt_str_begin "$vt_volume_id" "TENS-Public"; then + set vtcompat=1 + fi + + + # auto memdisk mode for some special ISO files + vt_iso_vd_id_parse "${vtoy_iso_part}${vt_chosen_path}" + unset vtMemDiskBoot + if vt_check_mode 0 "$vt_chosen_name"; then + set vtMemDiskBoot=1 + else + if [ "$grub_platform" = "pc" ]; then + if vt_iso_vd_id_begin 1 0 "Memtest86+"; then + set vtMemDiskBoot=1 + elif vt_iso_vd_id_begin 0 1 "KolibriOS"; then + set vtMemDiskBoot=1 + fi + fi + + #For iKuai8 (<64MB) + if [ $vt_chosen_size -LE 67108864 ]; then + if vt_str_begin "$vt_chosen_name" "iKuai"; then + set vtMemDiskBoot=1 + fi + fi + fi + vt_iso_vd_id_clear + + + if [ "$grub_platform" = "pc" ]; then + if [ -n "$vtMemDiskBoot" ]; then + legacy_iso_memdisk $vtoy_iso_part "$vt_chosen_path" + else + legacy_iso_menu_func $vtoy_iso_part "$vt_chosen_path" + fi + else + if [ -n "$vtMemDiskBoot" ]; then + uefi_iso_memdisk $vtoy_iso_part "$vt_chosen_path" + else + uefi_iso_menu_func $vtoy_iso_part "$vt_chosen_path" + fi + fi + + vt_secondary_recover_mode +} + +function miso_common_menuentry { + vt_chosen_img_path vt_chosen_path vt_chosen_size vt_chosen_name + + if vt_check_password "${vt_chosen_path}"; then + return + fi + + echo "memdisk mode boot for $vt_chosen_path" + echo "" + ventoy_debug_pause + + if [ "$grub_platform" = "pc" ]; then + legacy_iso_memdisk $vtoy_iso_part "$vt_chosen_path" + else + uefi_iso_memdisk $vtoy_iso_part "$vt_chosen_path" + fi +} + + +function common_unsupport_menuentry { + echo -e "\n The name of the iso file could NOT contain space or non-ascii characters. \n" + echo -e " 文件名中不能有中文或空格 \n" + echo -en "\n$VTLANG_ENTER_EXIT ..." + read vtInputKey +} + +function miso_unsupport_menuentry { + common_unsupport_menuentry +} + +function iso_unsupport_menuentry { + common_unsupport_menuentry +} + +function wim_common_menuentry { + vt_chosen_img_path vt_chosen_path vt_chosen_size vt_chosen_name + + if vt_check_password "${vt_chosen_path}"; then + return + fi + + if ventoy_vcfg_proc "${vt_chosen_path}"; then + return + fi + + if vt_wim_check_bootable "${vtoy_iso_part}${vt_chosen_path}"; then + vt_wim_chain_data "${vtoy_iso_part}${vt_chosen_path}" + else + echo -e "\n This is NOT a bootable WIM file. \n" + echo -e " 这不是一个可启动的 WIM 文件。\n" + fi + + ventoy_debug_pause + + if [ -n "$vtoy_chain_mem_addr" ]; then + if [ "$grub_platform" = "pc" ]; then + linux16 $vtoy_path/ipxe.krn ${vtdebug_flag} mem:${vtoy_chain_mem_addr}:size:${vtoy_chain_mem_size} + else + ventoy_cli_console + chainloader ${vtoy_path}/ventoy_${VTOY_EFI_ARCH}.efi env_param=${env_param} isoefi=${LoadIsoEfiDriver} ${vtdebug_flag} mem:${vtoy_chain_mem_addr}:size:${vtoy_chain_mem_size} + ventoy_gui_console + fi + boot + else + echo "chain empty failed" + ventoy_pause + fi +} + +function wim_unsupport_menuentry { + common_unsupport_menuentry +} + +function efi_common_menuentry { + vt_chosen_img_path vt_chosen_path vt_chosen_size vt_chosen_name + + if vt_check_password "${vt_chosen_path}"; then + return + fi + + if ventoy_vcfg_proc "${vt_chosen_path}"; then + return + fi + + unset vt_vlnk_dst + if vt_is_vlnk_name "${vt_chosen_path}"; then + vt_get_vlnk_dst "${vtoy_iso_part}${vt_chosen_path}" vt_vlnk_dst + if [ -z "$vt_vlnk_dst" ]; then + echo -e "\n### VLNK FILE NOT FOUND ###\n### VLNK 文件不存在 ###\n" + ventoy_pause + return + fi + else + vt_vlnk_dst="${vtoy_iso_part}${vt_chosen_path}" + fi + + ventoy_debug_pause + + ventoy_cli_console + + #first try with chainload + set vtOldRoot=$root + set root=$vtoy_iso_part + chainloader "${vt_vlnk_dst}" + boot + + #retry with isoboot + set root=$vtOldRoot + vt_concat_efi_iso "${vt_vlnk_dst}" vtoy_iso_buf + chainloader ${vtoy_path}/ventoy_${VTOY_EFI_ARCH}.efi memdisk env_param=${env_param} dotefi isoefi=on ${vtdebug_flag} mem:${vtoy_iso_buf_addr}:size:${vtoy_iso_buf_size} + boot + + ventoy_gui_console +} + +function efi_unsupport_menuentry { + common_unsupport_menuentry +} + +function vhdboot_common_func { + vt_patch_vhdboot "$1" + + ventoy_debug_pause + + if [ -n "$vtoy_vhd_buf_addr" ]; then + if [ "$grub_platform" = "pc" ]; then + ventoy_cli_console + linux16 $vtoy_path/memdisk iso raw + initrd16 mem:${vtoy_vhd_buf_addr}:size:${vtoy_vhd_buf_size} + boot + ventoy_gui_console + else + ventoy_cli_console + chainloader ${vtoy_path}/ventoy_${VTOY_EFI_ARCH}.efi memdisk env_param=${env_param} isoefi=${LoadIsoEfiDriver} ${vtdebug_flag} mem:${vtoy_vhd_buf_addr}:size:${vtoy_vhd_buf_size} + boot + ventoy_gui_console + fi + else + echo "Please put ventoy_vhdboot.img to \ISO\Ventoy\ of the data partition" + ventoy_pause + fi +} + +function vhd_common_menuentry { + vt_chosen_img_path vt_chosen_path vt_chosen_size vt_chosen_name + + if vt_check_password "${vt_chosen_path}"; then + return + fi + + if ventoy_vcfg_proc "${vt_chosen_path}"; then + return + fi + + unset vt_vlnk_dst + if vt_is_vlnk_name "${vt_chosen_path}"; then + vt_get_vlnk_dst "${vtoy_iso_part}${vt_chosen_path}" vt_vlnk_dst + if [ -z "$vt_vlnk_dst" ]; then + echo -e "\n### VLNK FILE NOT FOUND ###\n### VLNK 文件不存在 ###\n" + ventoy_pause + return + fi + else + vt_vlnk_dst="${vt_chosen_path}" + if [ "$VTOY_VHD_NO_WARNING" != "1" ]; then + if [ "$vtoy_iso_fs" != "ntfs" ]; then + echo -e "!!! WARNING !!!\n" + echo -e "\nPartition1 ($vtoy_iso_fs) is NOT ntfs, the VHD(x) file may not boot normally \n" + echo -e "\nVHD(x) 文件所在分区不是 ntfs 格式, 可能无法正常启动 \n\n" + echo -en "\n$VTLANG_ENTER_CONTINUE ..." + read vtInputKey + fi + fi + fi + + vhdboot_common_func "${vt_vlnk_dst}" +} + +function vhd_unsupport_menuentry { + common_unsupport_menuentry +} + +function vtoyboot_common_func { + set AltBootPart=0 + set vtoysupport=0 + + vt_get_vtoy_type "${1}" vtoytype parttype AltBootPart + + if vt_str_begin $vtoytype vhd; then + set vtoysupport=1 + elif [ "$vtoytype" = "raw" ]; then + set vtoysupport=1 + elif [ "$vtoytype" = "vdi" ]; then + set vtoysupport=1 + fi + + if [ $vtoysupport -eq 1 ]; then + if [ "$grub_platform" = "pc" ]; then + if [ "$parttype" = "gpt" -a $AltBootPart -eq 0 ]; then + echo "The OS in the vdisk was created in UEFI mode, but current is Legacy BIOS mode." + echo "虚拟磁盘内的系统是在UEFI模式下创建的,而当前系统是Legacy BIOS模式,可能无法正常启动。" + ventoy_pause + fi + else + if [ "$parttype" = "mbr" -a $AltBootPart -eq 0 ]; then + echo "The OS in the vdisk was created in Legacy BIOS mode, but current is UEFI mode." + echo "虚拟磁盘内的系统是在Legacy BIOS模式下创建的,而当前系统是UEFI模式,可能无法正常启动。" + ventoy_pause + fi + fi + + vt_img_sector "${1}" + vt_raw_chain_data "${1}" + + ventoy_debug_pause + + if [ -n "$vtoy_chain_mem_addr" ]; then + if [ "$grub_platform" = "pc" ]; then + vt_acpi_param ${vtoy_chain_mem_addr} 512 + linux16 $vtoy_path/ipxe.krn ${vtdebug_flag} bios80 sector512 mem:${vtoy_chain_mem_addr}:size:${vtoy_chain_mem_size} + boot + else + if vt_check_secureboot_var; then + vt_acpi_param ${vtoy_chain_mem_addr} 512 + fi + ventoy_cli_console + chainloader ${vtoy_path}/ventoy_${VTOY_EFI_ARCH}.efi sector512 env_param=${ventoy_env_param} ${vtdebug_flag} mem:${vtoy_chain_mem_addr}:size:${vtoy_chain_mem_size} + boot + ventoy_gui_console + fi + else + echo "chain empty failed!" + ventoy_pause + fi + else + echo "Unsupported vtoy type $vtoytype" + ventoy_pause + fi +} + +function vtoy_common_menuentry { + vt_chosen_img_path vt_chosen_path vt_chosen_size vt_chosen_name + + if vt_check_password "${vt_chosen_path}"; then + return + fi + + if ventoy_vcfg_proc "${vt_chosen_path}"; then + return + fi + + unset vt_vlnk_dst + if vt_is_vlnk_name "${vt_chosen_path}"; then + vt_get_vlnk_dst "${vtoy_iso_part}${vt_chosen_path}" vt_vlnk_dst + if [ -z "$vt_vlnk_dst" ]; then + echo -e "\n### VLNK FILE NOT FOUND ###\n### VLNK 文件不存在 ###\n" + ventoy_pause + return + fi + else + vt_vlnk_dst="${vtoy_iso_part}${vt_chosen_path}" + fi + + vtoyboot_common_func "${vt_vlnk_dst}" +} + +function vtoy_unsupport_menuentry { + common_unsupport_menuentry +} + +# +#============================================================# +# IMG file boot process # +#============================================================# +# + +function only_uefi_tip { + echo -e "\n This IMG file is only supported in UEFI mode. \n" + echo -en "\n$VTLANG_ENTER_EXIT ..." + read vtInputKey +} + +function ventoy_img_easyos { + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=$ventoy_busybox_ver" + vt_trailer_cpio ${vtoy_iso_part} "${vt_chosen_path}" noinit + + loopback easysfs (vtimghd,1)/easy.sfs + vt_get_lib_module_ver (easysfs) /lib/modules/ vt_module_ver + + if [ -n "$vt_module_ver" ]; then + for mod in "kernel/drivers/md/dm-mod.ko" "kernel/drivers/dax/dax.ko"; do + if [ -e (easysfs)/lib/modules/$vt_module_ver/$mod ]; then + vt_img_extra_initrd_append (easysfs)/lib/modules/$vt_module_ver/$mod + fi + done + fi + + ventoy_debug_pause + + #boot image file + vt_set_boot_opt rdinit=/vtoy/vtoy + vt_img_hook_root + + syslinux_configfile (vtimghd,1)/syslinux.cfg + + vt_img_unhook_root + vt_unset_boot_opt + loopback -d easysfs +} + +function ventoy_img_easyos2 { + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=$ventoy_busybox_ver" + vt_trailer_cpio ${vtoy_iso_part} "${vt_chosen_path}" noinit + + if [ -e (vtimghd,2)/easyos/easy.sfs ]; then + loopback easysfs (vtimghd,2)/easyos/easy.sfs + elif [ -d (vtimghd,2)/easyos/releases ]; then + vt_fs_enum_1st_dir (vtimghd,2) /easyos/releases/ vt_dir_name + loopback easysfs (vtimghd,2)/easyos/releases/$vt_dir_name/easy.sfs + fi + + vt_get_lib_module_ver (easysfs) /lib/modules/ vt_module_ver + + if [ -n "$vt_module_ver" ]; then + for mod in "kernel/drivers/md/dm-mod.ko" "kernel/drivers/dax/dax.ko"; do + if [ -e (easysfs)/lib/modules/$vt_module_ver/$mod ]; then + vt_img_extra_initrd_append (easysfs)/lib/modules/$vt_module_ver/$mod + fi + done + fi + + ventoy_debug_pause + + #boot image file + vt_set_boot_opt rdinit=/vtoy/vtoy + vt_img_hook_root + + vt_limine_menu (vtimghd,1)/limine.cfg vt_sys_menu_mem + configfile "mem:${vt_sys_menu_mem_addr}:size:${vt_sys_menu_mem_size}" + + vt_img_unhook_root + vt_unset_boot_opt + loopback -d easysfs +} + +function ventoy_img_volumio { + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=$ventoy_busybox_ver" + vt_trailer_cpio ${vtoy_iso_part} "${vt_chosen_path}" noinit + + ventoy_debug_pause + + #boot image file + vt_set_boot_opt rdinit=/vtoy/vtoy imgpart=/dev/ventoy2 bootpart=/dev/ventoy1 + vt_img_hook_root + + syslinux_configfile (vtimghd,1)/syslinux.cfg + + vt_img_unhook_root + vt_unset_boot_opt +} + +function ventoy_img_openelec { + elec_ver=$1 + + if [ "$elec_ver" = "LibreELEC" ]; then + if vt_strstr "$vt_chosen_name" "x86_64"; then + set ventoy_busybox_ver=64 + fi + fi + + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=$ventoy_busybox_ver" + vt_trailer_cpio ${vtoy_iso_part} "${vt_chosen_path}" noinit + + loopback vtloopex $vtoy_efi_part/ventoy/vtloopex.cpio + vt_img_extra_initrd_append (vtloopex)/$elec_ver/vtloopex.tar.xz + + if [ "$elec_ver" = "LibreELEC" ]; then + if [ -f (vtimghd,1)/system ]; then + loopback elecsfs (vtimghd,1)/system + vt_get_lib_module_ver (elecsfs) /usr/lib/kernel-overlays/base/lib/modules/ vt_module_ver + if [ -n "$vt_module_ver" ]; then + for mod in "kernel/drivers/md/dm-mod.ko"; do + if [ -e (elecsfs)/usr/lib/kernel-overlays/base/lib/modules/$vt_module_ver/$mod ]; then + vt_img_extra_initrd_append (elecsfs)/usr/lib/kernel-overlays/base/lib/modules/$vt_module_ver/$mod + fi + done + fi + fi + fi + + ventoy_debug_pause + + #boot image file + vt_set_boot_opt rdinit=/vtoy/vtoy ventoyos=$elec_ver + vt_img_hook_root + + set root=(vtimghd,1) + syslinux_configfile (vtimghd,1)/syslinux.cfg + + vt_img_unhook_root + vt_unset_boot_opt + loopback -d vtloopex + loopback -d elecsfs +} + + +function ventoy_img_freedombox { + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=$ventoy_busybox_ver" + vt_trailer_cpio ${vtoy_iso_part} "${vt_chosen_path}" noinit + + vt_get_lib_module_ver (vtimghd,1) /lib/modules/ vt_module_ver + if [ -n "$vt_module_ver" ]; then + vt_img_extra_initrd_append (vtimghd,1)/lib/modules/$vt_module_ver/kernel/drivers/md/dm-mod.ko + fi + + ventoy_debug_pause + + #boot image file + vt_set_boot_opt rdinit=/vtoy/vtoy ventoyos=freedombox + vt_img_hook_root + + configfile (vtimghd,1)/boot/grub/grub.cfg + + vt_img_unhook_root + vt_unset_boot_opt +} + +function steamenv_init { + echo "dummy steamenv_boot" +} + +function steamenv_boot { + if [ -n "${vtdebug_flag}" ]; then + $1 $2 loglevel=7 + else + $@ + fi +} + + +function ventoy_img_steamos { + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=$ventoy_busybox_ver" + vt_trailer_cpio ${vtoy_iso_part} "${vt_chosen_path}" noinit + + vt_get_lib_module_ver (vtimghd,3) /lib/modules/ vt_module_ver + if [ -n "$vt_module_ver" ]; then + vt_img_extra_initrd_append (vtimghd,3)/lib/modules/$vt_module_ver/kernel/drivers/md/dm-mod + fi + + ventoy_debug_pause + + #boot image file + vt_set_boot_opt rdinit=/vtoy/vtoy ventoyos=steamos steamos.efi=/dev/steamos-media-efi + vt_img_hook_root + + set theme=$vtback_theme + ventoy_gui_console + ventoy_cfg_theme_lock 1 + + configfile (vtimghd,2)/EFI/steamos/grub.cfg + + ventoy_cfg_theme_lock 0 + + vt_img_unhook_root + vt_unset_boot_opt +} + + +function ventoy_img_paldo { + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=$ventoy_busybox_ver" + vt_trailer_cpio ${vtoy_iso_part} "${vt_chosen_path}" noinit + + ventoy_debug_pause + + #boot image file + vt_set_boot_opt rdinit=/vtoy/vtoy ventoyos=paldo + vt_img_hook_root + + vt_fs_enum_1st_file (vtimghd,1) /loader/entries/ vt_paldo_entry_conf + vt_file_basename $vt_paldo_entry_conf vtPaldoVer + + echo loading file... + linux (vtimghd,1)/linux-${vtPaldoVer} root=/dev/ventoy1 rootfstype=vfat + initrd (vtimghd,1)/initramfs-${vtPaldoVer} + boot + + vt_img_unhook_root + vt_unset_boot_opt +} + +function ventoy_img_ubos { + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=$ventoy_busybox_ver" + vt_trailer_cpio ${vtoy_iso_part} "${vt_chosen_path}" noinit + + vt_get_lib_module_ver (vtimghd,3) /lib/modules/ vt_module_ver + if [ -n "$vt_module_ver" ]; then + vt_img_extra_initrd_append (vtimghd,3)/lib/modules/$vt_module_ver/kernel/drivers/md/dm-mod.ko.xz + fi + + ventoy_debug_pause + + #boot image file + vt_set_boot_opt rdinit=/vtoy/vtoy ventoyos=ubos + vt_img_hook_root + + echo loading file... + linux (vtimghd,2)/vmlinuz-linux root=/dev/ventoy3 rw + initrd (vtimghd,2)/initramfs-linux.img + boot + + vt_img_unhook_root + vt_unset_boot_opt +} + +function ventoy_img_recalbox { + if [ $vtoy_img_max_part_end -GT $vt_chosen_size ]; then + echo -e "\nPlease extend the img file size before boot it. \n" + ventoy_pause + return + fi + + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=$ventoy_busybox_ver" + vt_trailer_cpio ${vtoy_iso_part} "${vt_chosen_path}" noinit + + if [ -e (vtimghd,1)/boot/recalbox ]; then + loopback recalbox (vtimghd,1)/boot/recalbox + vt_get_lib_module_ver (recalbox) /lib/modules/ vt_module_ver + if [ -n "$vt_module_ver" ]; then + vt_img_extra_initrd_append (recalbox)/lib/modules/$vt_module_ver/kernel/drivers/md/dm-mod.ko + fi + fi + + ventoy_debug_pause + + #boot image file + vt_set_boot_opt rdinit=/vtoy/vtoy ventoyos=recalbox + vt_img_hook_root + + set root=(vtimghd,1) + configfile (vtimghd,1)/boot/grub/grub.cfg + + vt_img_unhook_root + vt_unset_boot_opt +} + +function ventoy_img_esysrescue { + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=$ventoy_busybox_ver" + vt_trailer_cpio ${vtoy_iso_part} "${vt_chosen_path}" noinit + + ventoy_debug_pause + + #boot image file + vt_set_boot_opt rdinit=/vtoy/vtoy ventoyos=esysrescue + vt_img_hook_root + + set root=(vtimghd,1) + configfile (vtimghd,1)/boot/grub/grub.cfg + + vt_img_unhook_root + vt_unset_boot_opt +} + +function ventoy_img_batocera { + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=$ventoy_busybox_ver" + vt_trailer_cpio ${vtoy_iso_part} "${vt_chosen_path}" noinit + + ventoy_debug_pause + + #boot image file + vt_set_boot_opt rdinit=/vtoy/vtoy ventoyos=batocera + vt_img_hook_root + + set root=(vtimghd,1) + syslinux_configfile (vtimghd,1)/boot/syslinux/syslinux.cfg + + vt_img_unhook_root + vt_unset_boot_opt +} + +function ventoy_img_openwrt { + if [ -e (vtimghd,2)/lib64 ]; then + set ventoy_busybox_ver=64 + fi + + vt_fs_enum_1st_dir (vtimghd,2) /lib/modules/ vt_dir_name + + if [ -f (vtimghd,2)/lib/modules/$vt_dir_name/dm-mod.ko ]; then + set openwrt_plugin_need=0 + vt_img_extra_initrd_append (vtimghd,2)/lib/modules/$vt_dir_name/dm-mod.ko + if [ -f (vtimghd,2)/lib/modules/$vt_dir_name/dax.ko ]; then + vt_img_extra_initrd_append (vtimghd,2)/lib/modules/$vt_dir_name/dax.ko + fi + else + set openwrt_plugin_need=1 + if [ ! -f ${vtoy_iso_part}/ventoy/ventoy_openwrt.xz ]; then + ventoy_gui_console + echo -e "\n ventoy_openwrt.xz not found. Please refer https://www.ventoy.net/en/doc_openwrt.html.\n" + echo -e " 未找到 ventoy_openwrt.xz 文件。请参考 https://www.ventoy.net/cn/doc_openwrt.html\n" + echo -en "\n$VTLANG_ENTER_EXIT ..." + read vtInputKey + ventoy_cli_console + return + fi + fi + + if vt_img_check_range "${vtoy_iso_part}${vt_chosen_path}"; then + ventoy_debug_pause + else + ventoy_gui_console + echo -e "\n IMG file need processed. Please refer https://www.ventoy.net/en/doc_openwrt.html.\n" + echo -e " 此 IMG 文件必须处理之后才能支持。请参考 https://www.ventoy.net/cn/doc_openwrt.html\n" + echo -e "\n press ENTER to exit (请按 回车 键返回) ..." + read vtInputKey + ventoy_cli_console + return + fi + + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=$ventoy_busybox_ver" + vt_trailer_cpio ${vtoy_iso_part} "${vt_chosen_path}" noinit + + if [ $openwrt_plugin_need -eq 1 ]; then + if [ -f ${vtoy_iso_part}/ventoy/ventoy_openwrt.xz ]; then + vt_img_extra_initrd_append ${vtoy_iso_part}/ventoy/ventoy_openwrt.xz + fi + fi + + #boot image file + vt_set_boot_opt rdinit=/vtoy/vtoy ventoyos=openwrt + vt_img_hook_root + + set root=(vtimghd,1) + configfile (vtimghd,1)/boot/grub/grub.cfg + + vt_img_unhook_root + vt_unset_boot_opt +} + +function ventoy_img_tails { + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=$ventoy_busybox_ver" + vt_trailer_cpio ${vtoy_iso_part} "${vt_chosen_path}" noinit + + ventoy_debug_pause + + #boot image file + vt_set_boot_opt rdinit=/vtoy/vtoy live-media=/dev/dm-1 ventoyos=tails + vt_img_hook_root + + set root=(vtimghd,1) + configfile (vtimghd,1)/efi/debian/grub.cfg + + vt_img_unhook_root + vt_unset_boot_opt +} + +function ventoy_img_fydeos { + if [ "$grub_platform" = "pc" ]; then + only_uefi_tip + return + fi + + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=64" + vt_trailer_cpio ${vtoy_iso_part} "${vt_chosen_path}" noinit + + ventoy_debug_pause + + #boot image file + vt_set_boot_opt rdinit=/vtoy/vtoy ventoyos=fydeos + vt_img_hook_root + + set grubdisk=vtimghd + set grubpartA=(vtimghd,3) + set grubpartB=(vtimghd,5) + set linuxpartA=(sda,3) + set linuxpartB=(sda,5) + + set root=(vtimghd,12) + configfile (vtimghd,12)/efi/boot/grub.cfg + + vt_img_unhook_root + vt_unset_boot_opt + + unset grubdisk + unset grubpartA + unset grubpartB + unset linuxpartA + unset linuxpartB +} + +function ventoy_img_cloudready { + if [ "$grub_platform" = "pc" ]; then + only_uefi_tip + return + fi + + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=64" + vt_trailer_cpio ${vtoy_iso_part} "${vt_chosen_path}" noinit + + ventoy_debug_pause + + #boot image file + vt_set_boot_opt rdinit=/vtoy/vtoy ventoyos=cloudready + vt_img_hook_root + + set grubdisk=vtimghd + set grubpartA=(vtimghd,3) + set grubpartB=(vtimghd,5) + set linuxpartA=(sda,3) + set linuxpartB=(sda,5) + + set root=(vtimghd,12) + configfile (vtimghd,12)/efi/boot/grub.cfg + + vt_img_unhook_root + vt_unset_boot_opt + + unset grubdisk + unset grubpartA + unset grubpartB + unset linuxpartA + unset linuxpartB +} + + +function ventoy_img_fwts { + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=$ventoy_busybox_ver" + vt_trailer_cpio ${vtoy_iso_part} "${vt_chosen_path}" noinit + + ventoy_debug_pause + + #boot image file + vt_set_boot_opt rdinit=/vtoy/vtoy ventoyos=fwts + vt_img_hook_root + + configfile $prefix/distro/fwts.cfg + + vt_img_unhook_root + vt_unset_boot_opt +} + +function ventoy_img_memtest86 { + chainloader (vtimghd,1)/efi/boot/BOOTX64.efi + boot +} + +function img_unsupport_tip { + echo -e "\n This IMG file is NOT supported now. \n" + echo -e " 当前不支持启动此 IMG 文件 \n" + echo -en "\n$VTLANG_ENTER_EXIT ..." + read vtInputKey +} + +function legacy_img_memdisk { + linux16 $vtoy_path/memdisk + echo "Loading img file to memory ..." + initrd16 "${1}${2}" + + ventoy_cli_console + boot +} + +function img_common_menuentry { + set ventoy_compatible=YES + set ventoy_busybox_ver=32 + unset LoadIsoEfiDriver + + vt_chosen_img_path vt_chosen_path vt_chosen_size vt_chosen_name + + if vt_check_password "${vt_chosen_path}"; then + return + fi + + if ventoy_vcfg_proc "${vt_chosen_path}"; then + return + fi + + if [ "$grub_platform" = "pc" ]; then + if vt_check_mode 0 "$vt_chosen_name"; then + legacy_img_memdisk $vtoy_iso_part "$vt_chosen_path" + return + fi + fi + + loopback vtimghd "${vtoy_iso_part}${vt_chosen_path}" + vt_img_sector "${vtoy_iso_part}${vt_chosen_path}" + + vt_img_part_info (vtimghd) + + set vtback_root=$root + ventoy_cli_console + vt_push_last_entry + set vtback_theme=$theme + unset theme + + vt_img_extra_initrd_reset + + + vt_get_fs_label (vtimghd,1) vtImgHd1Label + + if [ "$vtImgHd1Label" = "STATE" ]; then + vt_get_fs_label (vtimghd,3) vtImgHd3Label + elif [ -d (vtimghd,2)/lib ]; then + vt_get_fs_label (vtimghd,2) vtImgHd2Label + fi + + if [ -z "$vtImgHd1Label" ]; then + if [ -d (vtimghd,2)/efi ]; then + vt_get_fs_label (vtimghd,3) vtImgHd3Label + elif [ -d (vtimghd,12)/efi ]; then + vt_get_fs_label (vtimghd,3) vtImgHd3Label + fi + fi + + if [ -e (vtimghd,1)/etc/hostname ]; then + vt_1st_line (vtimghd,1)/etc/hostname vtImgHostname + fi + + if vt_str_begin "$vtImgHd3Label" "ROOT-"; then + if [ -f (vtimghd,3)/etc/os-release.d/ID ]; then + vt_1st_line (vtimghd,3)/etc/os-release.d/ID vt_release_line1 + if vt_str_begin "$vt_release_line1" "FydeOS"; then + ventoy_img_fydeos + else + ventoy_img_cloudready + fi + elif [ -f (vtimghd,3)/etc/cloudready-release ]; then + ventoy_img_cloudready + elif [ -f (vtimghd,3)/etc/chrome_dev.conf ]; then + ventoy_img_cloudready + fi + elif vt_str_begin "$vtImgHd3Label" "fwts-result"; then + ventoy_img_fwts + elif vt_str_begin "$vtImgHd1Label" "LAKKA"; then + ventoy_img_openelec lakka + elif vt_str_begin "$vtImgHd1Label" "LIBREELEC"; then + ventoy_img_openelec LibreELEC + elif vt_str_begin "$vtImgHd1Label" "paldo-live"; then + ventoy_img_paldo + elif vt_str_begin "$vtImgHostname" "freedombox"; then + ventoy_img_freedombox + elif vt_str_begin "$vtImgHd1Label" "BATOCERA"; then + ventoy_img_batocera + elif vt_str_begin "$vtImgHd1Label" "Tails"; then + ventoy_img_tails + elif [ "$vtImgHd2Label" = "RECALBOX" -o "$vtImgHd1Label" = "RECALBOX" ]; then + ventoy_img_recalbox + elif [ "$vtImgHd1Label" = "ESYSRESCUE" ]; then + ventoy_img_esysrescue + elif [ -e (vtimghd,1)/SteamOS ]; then + ventoy_img_steamos + elif [ -e (vtimghd,1)/easy.sfs ]; then + ventoy_img_easyos + elif [ -d (vtimghd,2)/easyos ]; then + ventoy_img_easyos2 + elif [ -e (vtimghd,1)/volumio.initrd ]; then + ventoy_img_volumio + elif [ -f (vtimghd,2)/loader/entries/ubos.conf ]; then + ventoy_img_ubos + elif [ -f (vtimghd,2)/etc/openwrt_version ]; then + ventoy_img_openwrt + else + if [ -f (vtimghd,1)/efi/boot/mt86.png ]; then + if [ "$grub_platform" = "pc" ]; then + img_unsupport_tip + fi + fi + + #common chain + vt_linux_chain_data "${vtoy_iso_part}${vt_chosen_path}" + ventoy_acpi_param ${vtoy_chain_mem_addr} 512 + if [ "$grub_platform" = "pc" ]; then + linux16 $vtoy_path/ipxe.krn ${vtdebug_flag} sector512 mem:${vtoy_chain_mem_addr}:size:${vtoy_chain_mem_size} + boot + else + chainloader ${vtoy_path}/ventoy_${VTOY_EFI_ARCH}.efi sector512 env_param=${env_param} isoefi=${LoadIsoEfiDriver} FirstTry=${FirstTryBootFile} ${vtdebug_flag} mem:${vtoy_chain_mem_addr}:size:${vtoy_chain_mem_size} + boot + fi + fi + + loopback -d vtimghd + + set root=$vtback_root + vt_pop_last_entry + set theme=$vtback_theme + ventoy_gui_console + set ventoy_compatible=NO +} + +function img_unsupport_menuentry { + common_unsupport_menuentry +} + +function mimg_common_menuentry { + vt_chosen_img_path vt_chosen_path vt_chosen_size vt_chosen_name + + if vt_check_password "${vt_chosen_path}"; then + return + fi + + echo "memdisk mode boot for $vt_chosen_path" + echo "" + ventoy_debug_pause + + if [ "$grub_platform" = "pc" ]; then + legacy_img_memdisk $vtoy_iso_part "$vt_chosen_path" + else + vt_load_img_memdisk "$vtoy_iso_part$vt_chosen_path" vtoy_img_buf + ventoy_cli_console + chainloader ${vtoy_path}/ventoy_${VTOY_EFI_ARCH}.efi memdisk env_param=${env_param} isoefi=${LoadIsoEfiDriver} ${vtdebug_flag} mem:${vtoy_img_buf_addr}:size:${vtoy_img_buf_size} + boot + ventoy_gui_console + fi +} + +############################################################# +############################################################# +############################################################# +####### Main Process ########### +############################################################# +############################################################# +############################################################# + +set VENTOY_VERSION="1.1.18" + +#ACPI not compatible with Window7/8, so disable by default +set VTOY_PARAM_NO_ACPI=1 + +# Default menu display mode, you can change it as you want. +# 0: List mode +# 1: TreeView mode +set VTOY_DEFAULT_MENU_MODE=0 + +set VTOY_MEM_DISK_STR="[Memdisk]" +set VTOY_ISO_RAW_STR="Compatible Mode" +set VTOY_GRUB2_MODE_STR="GRUB2 Mode" +set VTOY_WIMBOOT_MODE_STR="WIMBOOT Mode" +set VTOY_ISO_UEFI_DRV_STR="UEFI FS" + +set VTOY_F2_CMD="vt_browser_disk" +set VTOY_F4_CMD="ventoy_localboot" +set VTOY_F5_CMD="ventoy_diagnosis" +set VTOY_F6_CMD="ventoy_ext_menu" +set VTOY_HELP_CMD="ventoy_show_help" +set VTOY_CHKSUM_CMD="ventoy_checksum" +set VTOY_HELP_TXT_LANGUAGE="en_US" +set VTOY_CHKSUM_FILE_PATH="X" +set VTOY_LANG_CMD="ventoy_language" + + +if [ "$grub_platform" = "pc" ]; then + set VTOY_TEXT_MENU_VER="Ventoy $VENTOY_VERSION BIOS www.ventoy.net" +else + if [ "$grub_cpu" = "i386" ]; then + set VTOY_EFI_ARCH=ia32 + set VTOY_TEXT_MENU_VER="Ventoy $VENTOY_VERSION IA32 www.ventoy.net" + elif [ "$grub_cpu" = "arm64" ]; then + set VTOY_EFI_ARCH=aa64 + set VTOY_TEXT_MENU_VER="Ventoy $VENTOY_VERSION AA64 www.ventoy.net" + elif [ "$grub_cpu" = "mips64el" ]; then + set VTOY_EFI_ARCH=mips + set VTOY_TEXT_MENU_VER="Ventoy $VENTOY_VERSION MIPS www.ventoy.net" + else + set VTOY_EFI_ARCH=x64 + set VTOY_TEXT_MENU_VER="Ventoy $VENTOY_VERSION UEFI www.ventoy.net" + fi +fi + +vt_device $root vtoy_dev + +if [ "$vtoy_dev" = "tftp" ]; then + set vtoy_path=($root) + for vtid in 0 1 2 3; do + if [ -f (hd$vtid,2)/ventoy/ventoy.cpio ]; then + set vtoy_iso_part=(hd$vtid,1) + set vtoy_efi_part=(hd$vtid,2) + set vtoydev=hd$vtid + break + fi + done + loadfont ascii + + if [ -n "$vtoy_efi_part" ]; then + vt_load_file_to_mem "auto" $vtoy_efi_part/grub/fonts/unicode.pf2 vtoy_font_mem + loadfont mem:${vtoy_font_mem_addr}:size:${vtoy_font_mem_size} + fi + + if [ -f $vtoy_iso_part/ISO/Ventoy/ventoy.json ]; then + set vt_plugin_path=$vtoy_iso_part + else + set vt_plugin_path=$prefix + vt_load_plugin $vt_plugin_path + fi +else + if [ "$prefix" = "(ventoydisk)/grub" ]; then + set vtoy_path=(ventoydisk)/ventoy + else + set vtoy_path=($root)/ventoy + fi + + set vtoydev=$vtoy_dev + set vtoy_iso_part=($vtoy_dev,1) + set VTOY_DATA_PART_IDX=1 + set vtoy_efi_part=($vtoy_dev,2) + set VTOY_EFI_PART_IDX=2 + + # VTOY-CUSTOM-LAYOUT: data (ISO) partition is the one that contains + # /ISO/Ventoy/NOT.DEL (fallback: partition 1). VTOYEFI stays partition 2. + for vt_part in 1 2 3 4; do + if [ -f ($vtoy_dev,$vt_part)/ISO/Ventoy/NOT.DEL ]; then + set vtoy_iso_part=($vtoy_dev,$vt_part) + set VTOY_DATA_PART_IDX=$vt_part + break + fi + done + export VTOY_DATA_PART_IDX + export VTOY_EFI_PART_IDX + + vt_load_file_to_mem "auto" $prefix/fonts/unicode.pf2 vtoy_font_mem + loadfont mem:${vtoy_font_mem_addr}:size:${vtoy_font_mem_size} + + set vt_plugin_path=$vtoy_iso_part +fi + +#Load Partition Table +vt_load_part_table $vtoydev + +#Load menu lang file +ventoy_load_menu_lang_file + +#Load Plugin +if [ -f $vtoy_iso_part/ISO/Ventoy/ventoy.json ]; then + clear + vt_load_plugin $vtoy_iso_part + clear +else + vt_check_json_path_case $vtoy_iso_part +fi + +#Update Secure Boot Policy +vt_update_sb_policy + + +if [ -n "$VTOY_MENU_LANGUAGE" ]; then + vt_init_menu_lang "$VTOY_MENU_LANGUAGE" +else + vt_init_menu_lang ru_RU +fi + +if [ -n "$VTOY_MENU_TIMEOUT" ]; then + set timeout=$VTOY_MENU_TIMEOUT +else + unset timeout +fi + +if [ -f $vtoy_iso_part/ISO/Ventoy/ventoy_wimboot.img ]; then + vt_load_wimboot $vtoy_iso_part/ISO/Ventoy/ventoy_wimboot.img +elif [ -f $vtoy_iso_part/ventoy/ventoy_wimboot.img ]; then + vt_load_wimboot $vtoy_iso_part/ventoy/ventoy_wimboot.img +elif [ -f $vtoy_efi_part/ventoy/ventoy_wimboot.img ]; then + vt_load_wimboot $vtoy_efi_part/ventoy/ventoy_wimboot.img +fi + +if [ -f $vtoy_iso_part/ISO/Ventoy/ventoy_vhdboot.img ]; then + vt_load_vhdboot $vtoy_iso_part/ISO/Ventoy/ventoy_vhdboot.img +elif [ -f $vtoy_iso_part/ventoy/ventoy_vhdboot.img ]; then + vt_load_vhdboot $vtoy_iso_part/ventoy/ventoy_vhdboot.img +elif [ -f $vtoy_efi_part/ventoy/ventoy_vhdboot.img ]; then + vt_load_vhdboot $vtoy_efi_part/ventoy/ventoy_vhdboot.img +fi + + +if [ $VTOY_DEFAULT_MENU_MODE -eq 0 ]; then + set VTOY_F3_CMD="vt_dynamic_menu 1 1" +else + set VTOY_F3_CMD="vt_dynamic_menu 1 0" +fi + +terminal_output console + +if [ -n "$vtoy_gfxmode" ]; then + set gfxmode=$vtoy_gfxmode + set gfxpayload=keep +else + set gfxmode=1024x768 + set gfxpayload=keep +fi + + +if [ "$vtoy_display_mode" = "CLI" ]; then + terminal_output console +elif [ "$vtoy_display_mode" = "serial" ]; then + if [ -n "$vtoy_serial_param" ]; then + serial $vtoy_serial_param + fi + terminal_input serial + terminal_output serial +elif [ "$vtoy_display_mode" = "serial_console" ]; then + if [ -n "$vtoy_serial_param" ]; then + serial $vtoy_serial_param + fi + terminal_input serial console + terminal_output serial console +else + if [ "$vtoy_gfxmode" = "max" ]; then + set gfxmode=1024x768 + terminal_output gfxterm + + vt_enum_video_mode + vt_get_video_mode 0 vtCurMode + terminal_output console + set gfxmode=$vtCurMode + terminal_output gfxterm + elif [ "$vtoy_res_fit" = "1" ]; then + terminal_output gfxterm + fi + + if [ -n "$vtoy_theme" ]; then + vt_set_theme + else + set theme=$prefix/themes/ventoy/theme.txt + fi + terminal_output gfxterm +fi + +if [ "$grub_platform" = "efi" ]; then + set mouse_delta=4000 + # terminal_input --append mouse +fi + +if [ -n "$VTOY_DEFAULT_KBD_LAYOUT" ]; then + set_keyboard_layout "$VTOY_DEFAULT_KBD_LAYOUT" +fi + +if [ -n "$VTOY_PLUGIN_PATH_CASE_MISMATCH" ]; then + clear + echo "$VTOY_PLUGIN_PATH_CASE_MISMATCH" + echo -e "\n\nPath case does not match! ventoy directory and ventoy.json MUST be all lowercase!" + echo -e "\n路径大小写不匹配!ventoy 目录和 ventoy.json 文件的名字必须是全部小写,请修正!" + echo -e "\n\npress ENTER to continue (请按回车键继续) ..." + read vtInputKey +fi + +if [ -n "$VTOY_PLUGIN_SYNTAX_ERROR" ]; then + clear + if [ -n "$VTOY_PLUGIN_ENCODE_ERROR" ]; then + echo -e "\n Encoding type for ventoy.json is not supported, please convert to UTF-8.\n" + echo -e " ventoy.json 文件编码格式不支持,请转换为 UTF-8 编码格式!\n" + else + echo -e "\n Syntax error detected in ventoy.json, please check! \n" + echo -e " ventoy.json 文件中有语法错误,所有配置都不会生效,请检查!\n" + fi + + echo -e "\n press ENTER to continue (请按 回车 键继续) ..." + read vtInputKey +fi + + +for vtTFile in ventoy.json ventoy_grub.cfg; do + if [ -f $vtoy_efi_part/ventoy/$vtTFile ]; then + clear + echo -e "\n You need to put $vtTFile in the 1st partition which hold the ISO files.\n" + echo -e " $vtTFile 放错分区了,请放到镜像分区里的 ventoy 目录下(此目录需要手动创建)!\n" + echo -e "\n press ENTER to continue (请按 回车 键继续) ..." + read vtInputKey + fi +done + +#clear all input key before show main menu +vt_clear_key + +#export necessary variable +export theme +export gfxmode +export gfxpayload +export vtoydev +export vtoy_path +export vtdebug_flag +export vtoy_iso_fs +export vtoy_iso_part +export vtoy_efi_part +export VENTOY_VERSION +export VTOY_CUR_VIDEO_MODE +export VTOY_EFI_ARCH +export VTOY_MEM_DISK_STR +export VTOY_ISO_RAW_STR +export VTOY_GRUB2_MODE_STR +export VTOY_WIMBOOT_MODE_STR +export VTOY_ISO_UEFI_DRV_STR +export VTOY_F2_CMD +export VTOY_F4_CMD +export VTOY_F5_CMD +export VTOY_F6_CMD +export VTOY_HELP_CMD +export VTOY_CHKSUM_CMD +export VTOY_HELP_TXT_LANGUAGE +export VTOY_CHKSUM_FILE_PATH +export VTOY_LANG_CMD + + +#colect all image files (iso files) +set ventoy_img_count=0 +vt_list_img $vtoy_iso_part ventoy_img_count + + + +#Main menu +if [ $ventoy_img_count -gt 0 ]; then + if [ $VTOY_DEFAULT_MENU_MODE -eq 0 ]; then + vt_dynamic_menu 0 0 + else + vt_dynamic_menu 0 1 + fi +else + if [ -n "$VTOY_NO_ISO_TIP" ]; then + NO_ISO_MENU="No ISO or supported IMG files found, $VTOY_NO_ISO_TIP" + elif [ -n "$VTOY_DEFAULT_SEARCH_ROOT" ]; then + NO_ISO_MENU="No ISO or supported IMG files found, please check VTOY_DEFAULT_SEARCH_ROOT" + else + NO_ISO_MENU="No ISO or supported IMG files found" + fi + menuentry "$NO_ISO_MENU (Press enter to reboot ...)" { + echo -e "\n Rebooting ... " + reboot + } +fi + + +menuentry "Возврат в главное меню Paravis Flash" --id="paravis_return" --class="vtoyret" { + paravis_return +} + +set default="paravis_return" + +#special VTOY_DEFAULT_IMAGE process +if [ -n "$VTOY_DEFAULT_IMAGE" ]; then + if regexp --set 1:vtHotkey --set 2:vtDefault "(F[2-9])>(.*)" "$VTOY_DEFAULT_IMAGE"; then + + set default="$vtDefault" + if [ -z "$VTOY_MENU_TIMEOUT" ]; then + set timeout=0 + else + set timeout=$VTOY_MENU_TIMEOUT + fi + + export timeout + export default + + vt_fn_mutex_lock 1 + + if [ "$vtHotkey" = "F2" ]; then + unset timeout + vt_browser_disk + elif [ "$vtHotkey" = "F4" ]; then + ventoy_localboot + elif [ "$vtHotkey" = "F5" ]; then + ventoy_diagnosis + elif [ "$vtHotkey" = "F6" ]; then + ventoy_ext_menu + fi + + vt_fn_mutex_lock 0 + + unset timeout + unset default + fi +fi + diff --git a/build-scripts/config/VTOYEFI/grub.cfg b/build-scripts/config/VTOYEFI/grub.cfg new file mode 100644 index 0000000..42a66b3 --- /dev/null +++ b/build-scripts/config/VTOYEFI/grub.cfg @@ -0,0 +1,2857 @@ +#************************************************************************************ +# Copyright (c) 2020, longpanda +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, see . +# +#************************************************************************************ + +if [ "$grub_platform" = "pc" ]; then + insmod setkey + insmod regexp +fi + +function ventoy_pause { + echo "press Enter to continue ......" + read vtTmpPause +} + +function ventoy_debug_pause { + if [ -n "${vtdebug_flag}" ]; then + echo "press Enter to continue ......" + read vtTmpPause + fi +} + + +function ventoy_cli_console { + if [ -z "$vtoy_display_mode" ]; then + terminal_output console + elif [ "$vtoy_display_mode" = "GUI" ]; then + terminal_output console + fi +} + +function ventoy_gui_console { + if [ -z "$vtoy_display_mode" ]; then + terminal_output gfxterm + elif [ "$vtoy_display_mode" = "GUI" ]; then + terminal_output gfxterm + fi +} + +function ventoy_cfg_theme_lock { + vt_timeout_lock $1 + vt_theme_lock $1 + terminal_lock $1 + lockfont $1 +} + +function ventoy_acpi_param { + if [ "$VTOY_PARAM_NO_ACPI" != "1" ]; then + vt_acpi_param "$1" "$2" + fi +} + +function vt_vcfg_pre_proc { + vt_img_sector "${vtoy_iso_part}${vt_chosen_path}" + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=$ventoy_busybox_ver" + vt_trailer_cpio $vtoy_iso_part "$vt_chosen_path" +} + +function ventoy_vcfg_proc { + if vt_check_custom_boot "${1}" vt_vcfg; then + set vtoy_chosen_path="${1}" + vt_file_basefile "${vtoy_chosen_path}" vtoy_chosen_file + + export vtoy_chosen_path + export vtoy_chosen_file + ventoy_debug_pause + configfile "${vtoy_iso_part}${vt_vcfg}" + true + else + false + fi +} + +function ventoy_language { + configfile $prefix/menulang.cfg +} + +function ventoy_diagnosis { + vt_enum_video_mode + configfile $prefix/debug.cfg +} + +function ventoy_localboot { + configfile $prefix/localboot.cfg +} + +function paravis_return { + if [ "$grub_platform" = "efi" ]; then + search --no-floppy --file --set=root /efi/Paravis/Boot/grub2/grub.cfg + if [ "$grub_cpu" = "x86_64" ]; then + chainloader /efi/Paravis/Boot/grub2/grubx64.efi + else + chainloader /EFI/Boot/bootia32.efi + fi + else + chainloader (${vtoydev})+1 + fi + boot +} + +function ventoy_ext_menu { + if [ -e $vt_plugin_path/ISO/Ventoy/ventoy_grub.cfg ]; then + set ventoy_new_context=1 + configfile $vt_plugin_path/ISO/Ventoy/ventoy_grub.cfg + unset ventoy_new_context + else + echo "ventoy_grub.cfg NOT exist." + echo -en "\n$VTLANG_ENTER_EXIT ..." + read vtInputKey + fi +} + +function ventoy_checksum { + if [ -f "${vtoy_iso_part}${VTOY_CHKSUM_FILE_PATH}" ]; then + configfile $prefix/checksum.cfg + fi +} + +function ventoy_show_help { + if [ -f $prefix/help.tar.gz ]; then + if [ -z "$vtoy_help_txt_mem_addr" ]; then + vt_load_file_to_mem "auto" $prefix/help.tar.gz vtoy_help_txt_mem + fi + + loopback vt_help_tarfs mem:${vtoy_help_txt_mem_addr}:size:${vtoy_help_txt_mem_size} + vt_cur_menu_lang vtCurLang + if [ -f "(vt_help_tarfs)/help/${vtCurLang}.txt" ]; then + cat "(vt_help_tarfs)/help/${vtCurLang}.txt" + else + cat "(vt_help_tarfs)/help/en_US.txt" + fi + loopback -d vt_help_tarfs + fi +} + +function ventoy_load_menu_lang_file { + vt_load_file_to_mem "auto" $prefix/menu.tar.gz vtoy_menu_lang_mem + loopback vt_menu_tarfs mem:${vtoy_menu_lang_mem_addr}:size:${vtoy_menu_lang_mem_size} +} + +function get_os_type { + set vtoy_os=Linux + export vtoy_os + + if vt_str_begin "$vt_volume_id" "DLC Boot"; then + if [ -f (loop)/DLCBoot.exe ]; then + set vtoy_os=Windows + fi + else + for file in "efi/microsoft/boot/bcd" "sources/boot.wim" "boot/bcd" "bootmgr.efi" "boot/etfsboot.com" ; do + if vt_file_exist_nocase (loop)/$file; then + set vtoy_os=Windows + break + fi + done + fi + + if [ "$vtoy_os" = "Linux" ]; then + if vt_strstr "$vt_system_id" "FreeBSD"; then + set vtoy_os=Unix + set vt_unix_type=FreeBSD + elif [ -e (loop)/bin/freebsd-version ]; then + set vtoy_os=Unix + set vt_unix_type=FreeBSD + elif [ -e (loop)/boot/kernel/geom_ventoy.ko ]; then + set vtoy_os=Unix + set vt_unix_type=FreeBSD + elif vt_str_begin "$vt_system_id" "DragonFly"; then + set vtoy_os=Unix + set vt_unix_type=DragonFly + + + elif [ -e (loop)/boot/kernel/kernel ]; then + if file --is-x86-kfreebsd (loop)/boot/kernel/kernel; then + set vtoy_os=Unix + set vt_unix_type=FreeBSD + elif file --is-x86-knetbsd (loop)/boot/kernel/kernel; then + set vtoy_os=Unix + set vt_unix_type=NetBSD + fi + fi + fi + + if [ -n "${vtdebug_flag}" ]; then + echo ISO is "$vtoy_os" + fi +} + +function vt_check_compatible_pe { + #Check for PE without external tools + #set compatible if ISO file is less than 80MB + if [ $vt_chosen_size -GT 33554432 -a $vt_chosen_size -LE 83886080 ]; then + set ventoy_compatible=YES + fi + + return +} + +function vt_check_compatible_linux { + if vt_str_begin "$vt_volume_id" "embootkit"; then + set ventoy_compatible=YES + elif [ -e "$1/casper/tinycore.gz" ]; then + set ventoy_compatible=YES + fi + + return +} + +function locate_initrd { + vt_linux_locate_initrd + + if [ -n "${vtdebug_flag}" ]; then + vt_linux_dump_initrd + ventoy_debug_pause + fi +} + +function locate_wim { + vt_windows_locate_wim_patch (loop) "$1" + + if [ -n "${vtdebug_flag}" ]; then + echo '###############################################' + vt_dump_wim_patch + echo '###############################################' + ventoy_debug_pause + fi +} + +function distro_specify_wim_patch { + if [ -d (loop)/h3pe ]; then + vt_windows_collect_wim_patch wim /BOOT/H3_10PE.WIM + vt_windows_collect_wim_patch wim /BOOT/H3_7PE.WIM + vt_windows_collect_wim_patch wim /BOOT/H3_8PE.WIM + vt_windows_collect_wim_patch wim /BOOT/H3_81PE.WIM + elif [ -d (loop)/2k10/winpe ]; then + vt_windows_collect_wim_patch wim /2k10/winpe/w1086pe.wim + vt_windows_collect_wim_patch wim /2k10/winpe/w8x86pe.wim + vt_windows_collect_wim_patch wim /2k10/winpe/w7x86pe.wim + fi +} + +function distro_specify_wim_patch_phase2 { + if [ -f (loop)/boot/boot.wim ]; then + vt_windows_collect_wim_patch wim /boot/boot.wim + elif [ -f (loop)/sources/boot.wim ]; then + vt_windows_collect_wim_patch wim /sources/boot.wim + fi + + if vt_str_begin "$vt_volume_id" "DLC Boot"; then + for vwfile in "/DLC1/WinPE/W11x64.wim" "/DLC1/WinPE/W10x64.wim" "/DLC1/WinPE/W10x86.wim"; do + if [ -f (loop)/$vwfile ]; then + vt_windows_collect_wim_patch wim $vwfile + fi + done + fi + +} + + +function distro_specify_initrd_file { + if [ -e (loop)/boot/all.rdz ]; then + vt_linux_specify_initrd_file /boot/all.rdz + elif [ -e (loop)/boot/xen.gz ]; then + if [ -e (loop)/install.img ]; then + vt_linux_specify_initrd_file /install.img + fi + elif [ -d (loop)/casper ]; then + if [ -e (loop)/casper/initrd ]; then + vt_linux_specify_initrd_file /casper/initrd + fi + if [ -e (loop)/casper/initrd.gz ]; then + vt_linux_specify_initrd_file /casper/initrd.gz + fi + if [ -e (loop)/casper/initrd-oem ]; then + vt_linux_specify_initrd_file /casper/initrd-oem + fi + elif [ -e (loop)/boot/grub/initrd.xz ]; then + vt_linux_specify_initrd_file /boot/grub/initrd.xz + elif [ -e (loop)/initrd.gz ]; then + vt_linux_specify_initrd_file /initrd.gz + elif [ -e (loop)/slax/boot/initrfs.img ]; then + vt_linux_specify_initrd_file /slax/boot/initrfs.img + elif [ -e (loop)/minios/boot/initrfs.img ]; then + vt_linux_specify_initrd_file /minios/boot/initrfs.img + elif [ -e (loop)/pmagic/initrd.img ]; then + vt_linux_specify_initrd_file /pmagic/initrd.img + elif [ -e (loop)/boot/initrd.xz ]; then + vt_linux_specify_initrd_file /boot/initrd.xz + elif [ -e (loop)/boot/initrd.gz ]; then + vt_linux_specify_initrd_file /boot/initrd.gz + elif [ -f (loop)/boot/initrd ]; then + vt_linux_specify_initrd_file /boot/initrd + elif [ -f (loop)/boot/x86_64/loader/initrd ]; then + vt_linux_specify_initrd_file /boot/x86_64/loader/initrd + elif [ -f (loop)/boot/initramfs-x86_64.img ]; then + vt_linux_specify_initrd_file /boot/initramfs-x86_64.img + elif [ -f (loop)/boot/isolinux/initramfs_data64.cpio.gz ]; then + vt_linux_specify_initrd_file /boot/isolinux/initramfs_data64.cpio.gz + elif [ -f (loop)/boot/initrd.img ]; then + vt_linux_specify_initrd_file /boot/initrd.img + elif [ -f (loop)/boot/grmlfullamd64/initrd.img ]; then + vt_linux_specify_initrd_file /boot/grmlfullamd64/initrd.img + fi + + if [ -f (loop)/isolinux/initrd.gz ]; then + vt_linux_specify_initrd_file /isolinux/initrd.gz + fi + + if vt_str_begin "$vt_volume_id" "QUBES"; then + vt_linux_specify_initrd_file /images/pxeboot/initrd.img + fi + + if [ "$vt_chosen_size" = "1133375488" ]; then + if [ -d (loop)/boot/grub/x86_64-efi ]; then + vt_cpio_busybox64 "64h" + fi + fi +} + + +function distro_specify_initrd_file_phase2 { + if [ -f (loop)/boot/initrd.img ]; then + vt_linux_specify_initrd_file /boot/initrd.img + elif [ -f (loop)/Setup/initrd.gz ]; then + vt_linux_specify_initrd_file /Setup/initrd.gz + elif [ -f (loop)/isolinux/initramfs ]; then + vt_linux_specify_initrd_file /isolinux/initramfs + elif [ -f (loop)/boot/iniramfs.igz ]; then + vt_linux_specify_initrd_file /boot/iniramfs.igz + elif [ -f (loop)/initrd-x86_64 ]; then + vt_linux_specify_initrd_file /initrd-x86_64 + elif [ -f (loop)/live/initrd.img ]; then + vt_linux_specify_initrd_file /live/initrd.img + elif [ -f (loop)/initrd.img ]; then + vt_linux_specify_initrd_file /initrd.img + elif [ -f (loop)/sysresccd/boot/x86_64/sysresccd.img ]; then + vt_linux_specify_initrd_file /sysresccd/boot/x86_64/sysresccd.img + elif [ -f (loop)/CDlinux/initrd ]; then + vt_linux_specify_initrd_file /CDlinux/initrd + elif [ -f (loop)/parabola/boot/x86_64/parabolaiso.img ]; then + vt_linux_specify_initrd_file /parabola/boot/x86_64/parabolaiso.img + if [ -f (loop)/parabola/boot/i686/parabolaiso.img ]; then + vt_linux_specify_initrd_file /parabola/boot/i686/parabolaiso.img + fi + elif [ -f (loop)/parabola/boot/x86_64/initramfs-linux-libre.img ]; then + vt_linux_specify_initrd_file /parabola/boot/x86_64/initramfs-linux-libre.img + if [ -f (loop)/parabola/boot/i686/initramfs-linux-libre.img ]; then + vt_linux_specify_initrd_file /parabola/boot/i686/initramfs-linux-libre.img + fi + elif [ -f (loop)/hyperbola/boot/x86_64/hyperiso.img ]; then + vt_linux_specify_initrd_file /hyperbola/boot/x86_64/hyperiso.img + if [ -f (loop)/hyperbola/boot/i686/hyperiso.img ]; then + vt_linux_specify_initrd_file /hyperbola/boot/i686/hyperiso.img + fi + elif [ -f (loop)/EFI/BOOT/initrd.img ]; then + #Qubes + vt_linux_specify_initrd_file /EFI/BOOT/initrd.img + if [ "$grub_platform" != "pc" ]; then + vt_add_replace_file 0 "initrd.img" + fi + elif [ -f (loop)/initrd ]; then + vt_linux_specify_initrd_file /initrd + elif [ -f (loop)/live/initrd1 ]; then + vt_linux_specify_initrd_file /live/initrd1 + elif [ -f (loop)/isolinux/initrd.img ]; then + vt_linux_specify_initrd_file /isolinux/initrd.img + elif [ -f (loop)/isolinux/initrd.gz ]; then + vt_linux_specify_initrd_file /isolinux/initrd.gz + elif [ -f (loop)/syslinux/kernel/initramfs.gz ]; then + vt_linux_specify_initrd_file /syslinux/kernel/initramfs.gz + elif vt_strstr "$vt_volume_id" "Daphile"; then + vt_linux_parse_initrd_isolinux (loop)/isolinux/ + elif [ -f (loop)/boot/rootfs.xz ]; then + vt_linux_specify_initrd_file /boot/rootfs.xz + if [ "$grub_platform" != "pc" ]; then + vt_add_replace_file 0 "minimal\\x86_64\\rootfs.xz" + fi + elif [ -f (loop)/arch/boot/x86_64/archiso.img ]; then + vt_linux_specify_initrd_file /arch/boot/x86_64/archiso.img + if [ "$grub_platform" != "pc" ]; then + vt_add_replace_file 0 "EFI\\archiso\\archiso.img" + fi + elif [ -f (loop)/blackarch/boot/x86_64/archiso.img ]; then + vt_linux_specify_initrd_file /blackarch/boot/x86_64/archiso.img + elif [ -f (loop)/blackarch/boot/x86_64/initramfs-linux.img ]; then + vt_linux_specify_initrd_file /blackarch/boot/x86_64/initramfs-linux.img + + elif [ -f (loop)/install.amd/initrd.gz ]; then + vt_linux_specify_initrd_file /live/initrd2.img + vt_linux_specify_initrd_file /install.amd/initrd.gz + vt_linux_specify_initrd_file /install.amd/gtk/initrd.gz + elif [ -f (loop)/boot/grub/kernels.cfg ]; then + vt_linux_parse_initrd_grub file (loop)/boot/grub/kernels.cfg + elif [ -f (loop)/austrumi/initrd.gz ]; then + vt_linux_specify_initrd_file /austrumi/initrd.gz + if [ -f (loop)/EFI/BOOT/bootx64.efi ]; then + vt_cpio_busybox64 "64h" + fi + elif [ -f (loop)/boot/initfs.x86_64-efi ]; then + vt_linux_specify_initrd_file /boot/initfs.x86_64-efi + if [ -f (loop)/boot/initfs.i386-pc ]; then + vt_linux_specify_initrd_file /boot/initfs.i386-pc + fi + elif [ -f (loop)/antiX/initrd.gz ]; then + vt_linux_specify_initrd_file /antiX/initrd.gz + elif [ -f (loop)/360Disk/initrd.gz ]; then + vt_linux_specify_initrd_file /360Disk/initrd.gz + elif [ -f (loop)/porteus/initrd.xz ]; then + vt_linux_specify_initrd_file /porteus/initrd.xz + elif [ -f (loop)/pyabr/boot/initrfs.img ]; then + vt_linux_specify_initrd_file /pyabr/boot/initrfs.img + elif [ -f (loop)/initrd0.img ]; then + vt_linux_specify_initrd_file /initrd0.img + elif [ -f (loop)/sysresccd/boot/i686/sysresccd.img ]; then + vt_linux_specify_initrd_file /sysresccd/boot/i686/sysresccd.img + elif [ -f (loop)/boot/full.cz ]; then + vt_linux_specify_initrd_file /boot/full.cz + elif [ -f (loop)/images/pxeboot/initrd.img ]; then + vt_linux_specify_initrd_file /images/pxeboot/initrd.img + elif [ -f (loop)/live/initrd ]; then + vt_linux_specify_initrd_file /live/initrd + elif [ -f (loop)/initramfs-linux.img ]; then + vt_linux_specify_initrd_file /initramfs-linux.img + elif [ -f (loop)/boot/isolinux/initrd.gz ]; then + vt_linux_specify_initrd_file /boot/isolinux/initrd.gz + elif [ -f (loop)/tiny/initrd ]; then + vt_linux_specify_initrd_file /tiny/initrd + elif vt_str_begin "$vt_volume_id" "AERYNOS"; then + vt_vcfg_pre_proc + + loopback va "${vtoy_iso_part}${vt_chosen_path}" + loopback vb (va)/EFI/Boot/efiboot.img + + set root=(vb) + vt_systemd_menu (vb) vt_sys_menu_mem vt_linux_initrd + configfile "mem:${vt_sys_menu_mem_addr}:size:${vt_sys_menu_mem_size}" + + fi +} + + +function ventoy_get_ghostbsd_ver { + # fallback to parse version from elf /boot/kernel/kernel + set vt_freebsd_ver=xx +} + +function ventoy_get_furybsd_ver { + set vt_freebsd_ver=12.x + if regexp --set 1:vtFuryVer "(14|13)\.[0-9]" "$2"; then + set vt_freebsd_ver=${vtFuryVer}.x + fi +} + +function ventoy_get_freenas_ver { + set vt_freebsd_ver=11.x + + if [ -e (loop)/FreeNAS-MANIFEST ]; then + vt_parse_freenas_ver (loop)/FreeNAS-MANIFEST vt_freenas_ver + if regexp --set 1:vtNasVer "^(14|13|12|11)\.[0-9]" "$vt_freenas_ver"; then + set vt_freebsd_ver=${vtNasVer}.x + fi + fi +} + +function ventoy_get_truenas_ver { + set vt_freebsd_ver=12.x + + if [ -e (loop)/TrueNAS-MANIFEST ]; then + vt_parse_freenas_ver (loop)/TrueNAS-MANIFEST vt_truenas_ver + if regexp --set 1:vtTNasVer "^(14|13|12|11)\.[0-9]" "$vt_truenas_ver"; then + set vt_freebsd_ver=${vtTNasVer}.x + fi + fi +} + +function ventoy_get_midnightbsd_ver { + if vt_str_begin "$vt_volume_id" "1_"; then + set vt_freebsd_ver=11.x + elif vt_str_begin "$vt_volume_id" "2_"; then + set vt_freebsd_ver=2.x + elif vt_str_begin "$vt_volume_id" "3_"; then + set vt_freebsd_ver=3.x + fi +} + +function ventoy_freebsd_proc { + set vtFreeBsdDistro=FreeBSD + set vt_freebsd_ver=xx + + if [ -e (loop)/boot/kernel/geom_ventoy.ko ]; then + vt_unix_ko_fillmap /boot/kernel/geom_ventoy.ko + return + fi + + if vt_strstr "$vt_volume_id" "GHOSTBSD"; then + ventoy_get_ghostbsd_ver "$1" "${chosen_path}" + elif vt_strstr "$vt_volume_id" "FREENAS"; then + ventoy_get_freenas_ver "$1" "${chosen_path}" + elif vt_strstr "$vt_volume_id" "TRUENAS"; then + ventoy_get_truenas_ver "$1" "${chosen_path}" + elif vt_strstr "$vt_volume_id" "FURYBSD"; then + ventoy_get_furybsd_ver "$1" "${chosen_path}" + elif regexp --set 1:vtBsdVerNum "^(1[0-9]|9)_[0-9]" "$vt_volume_id"; then + set vt_freebsd_ver=${vtBsdVerNum}.x + elif [ -d (loop)/usr/midnightbsd-dist ]; then + ventoy_get_midnightbsd_ver "$1" "${chosen_path}" + set vtFreeBsdDistro=MidnightBSD + elif [ -e (loop)/bin/freebsd-version ]; then + vt_unix_parse_freebsd_ver (loop)/bin/freebsd-version vt_userland_ver + if regexp --set 1:vtBsdVerNum "\"(1[0-9]|9)\.[0-9]-" "$vt_userland_ver"; then + set vt_freebsd_ver=${vtBsdVerNum}.x + fi + elif [ -e (loop)/README.TXT ]; then + vt_1st_line (loop)/README.TXT vt_freebsd_line1 + if regexp --set 1:vtBsdVerNum "FreeBSD (1[0-9]|9)\.[0-9]-" "$vt_freebsd_line1"; then + set vt_freebsd_ver=${vtBsdVerNum}.x + fi + elif vt_strstr "${chosen_path}" "MidnightBSD"; then + set vt_freebsd_ver=9.x + fi + + + if [ -e (loop)/usr/freebsd-dist/cloninst.sh ]; then + set vtFreeBsdDistro=ClonOS + fi + + set vt_freebsd_bit=64 + for file in "/boot/kernel/kernel" "/boot/kernel/kernel.gz"; do + if [ -e (loop)/$file ]; then + if file --is-i386-kfreebsd (loop)/$file; then + set vt_freebsd_bit=32 + fi + break + fi + done + + if [ "$vt_freebsd_ver" = "xx" ]; then + if [ -e (loop)/boot/kernel/kernel ]; then + vt_unix_parse_freebsd_ver_elf (loop)/boot/kernel/kernel $vt_freebsd_bit vt_freebsd_ver + elif [ -e (loop)/boot/kernel/kernel.gz ]; then + vt_unix_parse_freebsd_ver_elf (loop)/boot/kernel/kernel.gz $vt_freebsd_bit vt_freebsd_ver + fi + + if [ "$vt_freebsd_ver" = "xx" ]; then + set vt_freebsd_ver=15.x + fi + fi + + if [ "$vt_freebsd_ver" = "14.x" ]; then + if [ -e (loop)/boot/lua/brand-pfSense.lua ]; then + set vtFreeBsdDistro=pfSense + fi + fi + + + if [ -n "${vtdebug_flag}" ]; then + echo "This is $vtFreeBsdDistro $vt_freebsd_ver ${vt_freebsd_bit}bit" + fi + + unset vt_unix_mod_path + for file in "/COPYRIGHT" "/FreeNAS-MANIFEST" "/TrueNAS-MANIFEST" "/version" "/etc/fstab"; do + if [ -e (loop)${file} ]; then + set vt_unix_mod_path=${file} + break + fi + done + + if [ -n "$vt_unix_mod_path" ]; then + vt_unix_replace_ko $vt_unix_mod_path (vtunix)/ventoy_unix/$vtFreeBsdDistro/geom_ventoy_ko/$vt_freebsd_ver/$vt_freebsd_bit/geom_ventoy.ko.xz + vt_unix_replace_conf FreeBSD "${1}${chosen_path}" + elif [ -e (loop)/easyre.ufs.uzip ]; then + vt_unix_replace_ko "/boot/grub/i386-pc/linux.mod" (vtunix)/ventoy_unix/$vtFreeBsdDistro/geom_ventoy_ko/$vt_freebsd_ver/$vt_freebsd_bit/geom_ventoy.ko.xz + if [ "$grub_platform" = "pc" ]; then + vt_unix_replace_grub_conf "/boot/grub/i386-pc/linux.mod" "cd9" + else + vt_unix_replace_conf FreeBSD "${1}${chosen_path}" "cd9" + fi + fi +} + +function ventoy_dragonfly_proc { + + unset vt_unix_mod_path + for file in "/boot/kernel/initrd.img.gz"; do + if [ -e (loop)${file} ]; then + set vt_unix_mod_path=${file} + break + fi + done + + vt_unix_replace_ko $vt_unix_mod_path ${vtoy_path}/dragonfly.mfs.xz + vt_unix_fill_image_desc + vt_unix_gzip_new_ko + vt_unix_replace_conf DragonFly "${1}${chosen_path}" +} + +function ventoy_unix_comm_proc { + vt_unix_reset + + vt_unix_check_vlnk "${1}${chosen_path}" + + if [ "$ventoy_compatible" = "NO" ]; then + loopback vtunix $vtoy_efi_part/ventoy/ventoy_unix.cpio + + if [ "$vt_unix_type" = "FreeBSD" ]; then + ventoy_freebsd_proc "$1" "${chosen_path}" + elif [ "$vt_unix_type" = "DragonFly" ]; then + ventoy_dragonfly_proc "$1" "${chosen_path}" + elif [ "$vt_unix_type" = "NetBSD" ]; then + echo "NetBSD not supported" + + + else + if [ -n "${vtdebug_flag}" ]; then + echo "Unknown unix type" + fi + fi + fi + + vt_unix_chain_data "${1}${chosen_path}" + ventoy_debug_pause +} + + +function uefi_windows_menu_func { + vt_windows_reset + + unset vt_cur_wimboot_mode + if vt_check_mode 4 "$vt_chosen_name"; then + set vt_cur_wimboot_mode=1 + fi + + if [ "$ventoy_compatible" = "NO" -o "$vt_cur_wimboot_mode" = "1" ]; then + if [ "$ventoy_fs_probe" = "iso9660" ]; then + loopback -d loop + vt_iso9660_nojoliet 1 + loopback loop "$1$2" + fi + + for file in "efi/microsoft/boot/bcd" "boot/bcd" "SSTR/BCD" "WEPE/B64" "WEPE/B32" "WEPE/BCD" "ISPE/BCD" "ISYL/BCD" "2K10/FONTS/BCD" "2K10/BCD" "boot/uqi/BCD"; do + vt_windows_collect_wim_patch bcd (loop)/$file + done + + vt_windows_count_wim_patch vt_wim_cnt + if [ $vt_wim_cnt -eq 0 ]; then + distro_specify_wim_patch_phase2 + fi + + ventoy_debug_pause + locate_wim "${chosen_path}" + fi + + vt_windows_chain_data "${1}${chosen_path}" + ventoy_debug_pause + + if [ "$vt_cur_wimboot_mode" = "1" ]; then + vtoy_wimboot_func + fi + + if [ -n "$vtoy_chain_mem_addr" ]; then + ventoy_acpi_param ${vtoy_chain_mem_addr} 2048 + chainloader ${vtoy_path}/ventoy_${VTOY_EFI_ARCH}.efi env_param=${env_param} isoefi=${LoadIsoEfiDriver} iso_${ventoy_fs_probe} ${vtdebug_flag} mem:${vtoy_chain_mem_addr}:size:${vtoy_chain_mem_size} + boot + else + echo "chain empty failed" + ventoy_pause + fi +} + +function uefi_find_replace_initrd { + if vt_get_efi_vdisk_offset "${1}${2}" vt_efivdisk_offset; then + loopback -s $vt_efivdisk_offset vtefivdisk "${1}${2}" + + unset vt_rp_initrd + vt_search_replace_initrd (vtefivdisk) vt_rp_initrd + + if [ -n "$vt_rp_initrd" ]; then + vt_add_replace_file $3 "$vt_rp_initrd" + fi + + loopback -d vtefivdisk + ventoy_debug_pause + fi +} + +function uefi_linux_menu_func { + + if [ "$ventoy_compatible" = "NO" ]; then + + if [ "$ventoy_fs_probe" = "udf" ]; then + loopback -d loop + set ventoy_fs_probe=iso9660 + loopback loop "$1$2" + fi + + vt_load_cpio $vtoy_path "$2" "$1" "busybox=$ventoy_busybox_ver" + + vt_linux_clear_initrd + + if [ -d (loop)/pmagic ]; then + vt_linux_specify_initrd_file /pmagic/initrd.img + else + for file in "boot/grub/grub.cfg" "EFI/BOOT/grub.cfg" "EFI/boot/grub.cfg" "efi/boot/grub.cfg" "EFI/BOOT/BOOTX64.conf" "/grub/grub.cfg" "EFI/BOOT/grub/grub.cfg"; do + if [ -e (loop)/$file ]; then + vt_linux_parse_initrd_grub file (loop)/$file + fi + done + fi + + # special process for special distros + if [ -d (loop)/loader/entries ]; then + vt_linux_parse_initrd_grub dir (loop)/loader/entries/ + elif [ -d (loop)/boot/grub ]; then + vt_linux_parse_initrd_grub dir (loop)/boot/grub/ + fi + + distro_specify_initrd_file + + vt_linux_initrd_count vtcount + + if [ $vtcount -eq 0 ]; then + if [ -e (loop)/EFI/boot/livegrub.cfg ]; then + vt_linux_parse_initrd_grub file (loop)/EFI/boot/livegrub.cfg + fi + distro_specify_initrd_file_phase2 + + if [ "$vt_efi_dir" = "NO" ]; then + if [ -f (loop)/efi.img ]; then + vt_add_replace_file 0 "initrd" + fi + fi + fi + + locate_initrd + + if [ -d (loop)/loader/entries ]; then + vt_linux_get_main_initrd_index vtindex + + if [ -d (loop)/arch ]; then + if [ -f (loop)/arch/boot/x86_64/archiso.img ]; then + vt_add_replace_file $vtindex "EFI\\archiso\\archiso.img" + elif [ -f (loop)/arch/boot/x86_64/initramfs-linux.img ]; then + vt_add_replace_file $vtindex "arch\\boot\\x86_64\\initramfs-linux.img" + elif [ -f (loop)/boot/initramfs_x86_64.img ]; then + vt_add_replace_file $vtindex "boot\\initramfs_x86_64.img" + elif [ -f (loop)/arch/boot/x86_64/initramfs-linux-aegis-offensive.img ]; then + vt_add_replace_file $vtindex "arch\\boot\\x86_64\\initramfs-linux-aegis-offensive.img" + fi + elif [ -d (loop)/blackarch ]; then + if [ -f (loop)/blackarch/boot/x86_64/archiso.img ]; then + vt_add_replace_file $vtindex "EFI\\archiso\\archiso.img" + elif [ -f (loop)/blackarch/boot/x86_64/initramfs-linux.img ]; then + vt_add_replace_file $vtindex "blackarch\\boot\\x86_64\\initramfs-linux.img" + fi + elif [ -d (loop)/anarchy ]; then + if [ -f (loop)/anarchy/boot/x86_64/initramfs-linux.img ]; then + vt_add_replace_file $vtindex "anarchy\\boot\\x86_64\\initramfs-linux.img" + fi + elif [ -d (loop)/parabola ]; then + if [ -f (loop)/parabola/boot/x86_64/parabolaiso.img ]; then + vt_add_replace_file $vtindex "EFI\\parabolaiso\\parabolaiso.img" + elif [ -f (loop)/parabola/boot/x86_64/initramfs-linux-libre.img ]; then + vt_add_replace_file $vtindex "parabola\\boot\\x86_64\\initramfs-linux-libre.img" + fi + elif [ -f (loop)/EFI/BOOT/initrd.gz ]; then + vt_add_replace_file $vtindex "EFI\\BOOT\\initrd.gz" + elif [ -f (loop)/loader/entries/thinstation.conf ]; then + vt_add_replace_file $vtindex "boot\\initrd" + elif [ -f (loop)/loader/entries/pisi-efi-x86_64.conf ]; then + vt_add_replace_file $vtindex "EFI\\pisi\\initrd.img" + fi + + vt_get_replace_file_cnt vt_replace_cnt + if [ $vt_replace_cnt -eq 0 ]; then + uefi_find_replace_initrd "$1" "$2" $vtindex + fi + elif [ -d (loop)/EFI/boot/entries ]; then + if [ -f (loop)/parabola/boot/x86_64/parabolaiso.img ]; then + vt_add_replace_file 0 "EFI\\parabolaiso\\parabolaiso.img" + elif [ -f (loop)/hyperbola/boot/x86_64/hyperiso.img ]; then + vt_add_replace_file 0 "EFI\\hyperiso\\hyperiso.img" + fi + elif [ -d (loop)/EFI/BOOT/entries ]; then + vt_linux_get_main_initrd_index vtindex + + if [ -f (loop)/parabola/boot/x86_64/parabolaiso.img ]; then + vt_add_replace_file 0 "EFI\\parabolaiso\\parabolaiso.img" + elif [ -f (loop)/parabola/boot/x86_64/initramfs-linux-libre.img ]; then + vt_add_replace_file $vtindex "parabola\\boot\\x86_64\\initramfs-linux-libre.img" + fi + elif [ -e (loop)/syslinux/alt0/full.cz ]; then + vt_add_replace_file 0 "EFI\\BOOT\\full.cz" + set FirstTryBootFile='@EFI@BOOT@grubx64.efi' + + elif vt_str_begin "$vt_volume_id" "SolusLive"; then + vt_add_replace_file 0 "initrd" + + fi + + fi + + vt_linux_chain_data "${1}${chosen_path}" + + if [ -n "$LoadIsoEfiDriver" -a $vt_chosen_size -LT 104857600 ]; then + if [ -f (loop)/efi/clover/cloverx64.efi ]; then + unset LoadIsoEfiDriver + fi + fi + + if [ -n "$vtoy_chain_mem_addr" ]; then + ventoy_acpi_param ${vtoy_chain_mem_addr} 2048 + ventoy_cli_console + + unset vtGrub2Mode + if vt_check_mode 3 "$vt_chosen_name"; then + set vtGrub2Mode=1 + elif vt_str_begin "$vt_volume_id" "HOLO_"; then + if [ -d (loop)/loader/entries ]; then + set vtGrub2Mode=1 + fi + elif vt_str_begin "$vt_volume_id" "KRD"; then + if [ -f (loop)/boot/grub/grub.cfg.sig ]; then + set vtGrub2Mode=1 + fi + fi + + if [ -n "$vtGrub2Mode" ]; then + ventoy_debug_pause + else + if [ "$VTOY_EFI_ARCH" != "mips" ]; then + chainloader ${vtoy_path}/ventoy_${VTOY_EFI_ARCH}.efi fallback env_param=${env_param} isoefi=${LoadIsoEfiDriver} FirstTry=${FirstTryBootFile} ${vtdebug_flag} mem:${vtoy_chain_mem_addr}:size:${vtoy_chain_mem_size} + boot + fi + fi + + # fallback + set vtback_root=$root + vt_push_last_entry + set vtback_theme=$theme + unset theme + + vt_trailer_cpio "$vtoy_iso_part" "$vt_chosen_path" noinit + vt_set_boot_opt rdinit=/vtoy/vtoy + + set root=(loop) + set vtback_cfg_find=0 + for cfg in "/boot/grub/grub.cfg" "/EFI/BOOT/grub.cfg" "/EFI/debian/grub.cfg" "EFI/boot/grub.cfg" "efi/boot/grub.cfg" "/grub/grub.cfg" "EFI/BOOT/BOOTX64.conf"; do + if [ -e "$cfg" ]; then + set vtback_cfg_find=1 + configfile "$cfg" + break + fi + done + if [ $vtback_cfg_find -eq 0 ]; then + if [ -f (loop)/loader/loader.conf -a -d (loop)/loader/entries ]; then + if vt_str_begin "$vt_volume_id" "HOLO_"; then + set root=(loop,2) + vt_systemd_menu (loop,2) vt_sys_menu_mem + else + vt_systemd_menu (loop) vt_sys_menu_mem + fi + set vtback_cfg_find=1 + configfile "mem:${vt_sys_menu_mem_addr}:size:${vt_sys_menu_mem_size}" + fi + fi + + if [ $vtback_cfg_find -eq 0 ]; then + if [ -f (loop)/boot/isolinux/syslnx64.cfg ]; then + syslinux_configfile (loop)/boot/isolinux/syslnx64.cfg + set vtback_cfg_find=1 + elif [ -f (loop)/boot/syslinux/porteus.cfg ]; then + syslinux_configfile (loop)/boot/syslinux/porteus.cfg + set vtback_cfg_find=1 + elif [ -f (loop)/syslinux.cfg ]; then + syslinux_configfile (loop)/syslinux.cfg + set vtback_cfg_find=1 + fi + fi + + if [ "$vtback_cfg_find" = "0" ]; then + echo " " + echo "No bootfile found for UEFI!" + echo "Maybe the image does not support $VTOY_EFI_ARCH UEFI" + echo " " + sleep 30 + fi + + vt_unset_boot_opt + set root=$vtback_root + set theme=$vtback_theme + vt_pop_last_entry + ventoy_gui_console + else + echo "chain empty failed" + ventoy_pause + fi +} + +function uefi_unix_menu_func { + ventoy_unix_comm_proc $1 "${chosen_path}" + + if [ -n "$vtoy_chain_mem_addr" ]; then + ventoy_acpi_param ${vtoy_chain_mem_addr} 2048 + ventoy_cli_console + chainloader ${vtoy_path}/ventoy_${VTOY_EFI_ARCH}.efi env_param=${env_param} isoefi=${LoadIsoEfiDriver} FirstTry=${FirstTryBootFile} ${vtdebug_flag} mem:${vtoy_chain_mem_addr}:size:${vtoy_chain_mem_size} + boot + else + echo "chain empty failed" + ventoy_pause + fi +} + +function ventoy_reset_nojoliet { + if vt_str_begin "$vt_volume_id" "ARCARESCUE"; then + vt_iso9660_nojoliet 1 + else + vt_iso9660_nojoliet 0 + fi + + vt_append_extra_sector 0 +} + +function uefi_iso_menu_func { + if [ -n "$vtisouefi" ]; then + set LoadIsoEfiDriver=on + unset vtisouefi + elif vt_check_mode 2 "$vt_chosen_name"; then + set LoadIsoEfiDriver=on + else + unset LoadIsoEfiDriver + fi + + set chosen_path="$2" + vt_select_auto_install "${chosen_path}" + vt_select_persistence "${chosen_path}" + + if ! vt_is_udf "${1}${chosen_path}"; then + # Lenovo EasyStartup need an addional sector for boundary check + if vt_str_begin "$vt_volume_id" "EasyStartup"; then + vt_skip_svd "${vtoy_iso_part}${vt_chosen_path}" + vt_append_extra_sector 1 + fi + fi + + if [ -d (loop)/EFI ]; then + set vt_efi_dir=YES + elif [ -d (loop)/efi ]; then + set vt_efi_dir=YES + else + set vt_efi_dir=NO + fi + + if [ -n "$vtcompat" ]; then + set ventoy_compatible=YES + unset vtcompat + elif vt_check_mode 1 "$vt_chosen_name"; then + set ventoy_compatible=YES + else + vt_check_compatible (loop) + fi + + vt_img_sector "${1}${chosen_path}" + + if [ "$ventoy_fs_probe" = "iso9660" ]; then + vt_select_conf_replace "${1}" "${chosen_path}" + fi + + if [ "$vtoy_os" = "Windows" ]; then + vt_check_compatible_pe (loop) + uefi_windows_menu_func "$1" "${chosen_path}" + elif [ "$vtoy_os" = "Unix" ]; then + uefi_unix_menu_func "$1" "${chosen_path}" + else + vt_check_compatible_linux (loop) + uefi_linux_menu_func "$1" "${chosen_path}" + fi + + ventoy_gui_console +} + +function uefi_iso_memdisk { + echo 'Loading ISO file to memory ...' + vt_load_img_memdisk "${1}${2}" vtoy_iso_buf + + ventoy_cli_console + chainloader ${vtoy_path}/ventoy_${VTOY_EFI_ARCH}.efi memdisk env_param=${env_param} isoefi=${LoadIsoEfiDriver} ${vtdebug_flag} mem:${vtoy_iso_buf_addr}:size:${vtoy_iso_buf_size} + boot + + ventoy_gui_console +} + +function vtoy_windows_wimboot { + if [ -f (loop)/x86/sources/boot.wim -a -f (loop)/x64/sources/boot.wim ]; then + vt_sel_wimboot vtoy_wimboot_bit + if [ "$vtoy_wimboot_bit" = "32" ]; then + set vtoy_wimboot_prefix=(loop)/x86 + else + set vtoy_wimboot_prefix=(loop)/x64 + fi + else + set vtoy_wimboot_prefix=(loop) + if vt_is_pe64 $vtoy_wimboot_prefix/setup.exe; then + set vtoy_wimboot_bit=64 + else + set vtoy_wimboot_bit=32 + fi + fi + + if [ -n "${vtdebug_flag}" ]; then + echo vtoy_wimboot_prefix=$vtoy_wimboot_prefix vtoy_wimboot_bit=$vtoy_wimboot_bit vt_wimkernel=$vt_wimkernel + fi + + vt_windows_wimboot_data "$vtoy_wimboot_prefix/sources/boot.wim" vtoy_init_exe vtoy_wim_bit + + if [ "$grub_platform" = "pc" ]; then + linux16 "$vtoy_path/$vt_wimkernel" quiet + ventoy_debug_pause + + vt_set_wim_load_prompt 1 "Loading files......" + initrd16 newc:winpeshl.exe:mem:${vtoy_wimboot_mem_addr}:size:${vtoy_wimboot_mem_size} \ + newc:vtoy_wimboot:$vtoy_wimboot_prefix/boot/bcd \ + newc:bcd:$vtoy_wimboot_prefix/boot/bcd \ + newc:boot.sdi:$vtoy_wimboot_prefix/boot/boot.sdi \ + newc:boot.wim:$vtoy_wimboot_prefix/sources/boot.wim + vt_set_wim_load_prompt 0 + boot + else + vt_set_wim_load_prompt 1 "Loading files......" + vt_load_file_to_mem "nodecompress" $vtoy_wimboot_prefix/sources/boot.wim vtoy_wimfile_mem + vt_set_wim_load_prompt 0 + + if [ $? -eq 0 ]; then + set vtoy_wimfile_path=mem:${vtoy_wimfile_mem_addr}:size:${vtoy_wimfile_mem_size} + else + set vtoy_wimfile_path=$vtoy_wimboot_prefix/sources/boot.wim + fi + + ventoy_cli_console + chainloader "$vtoy_path/$vt_wimkernel" quiet \ + "vf=winpeshl.exe:mem:${vtoy_wimboot_mem_addr}:size:${vtoy_wimboot_mem_size}" \ + "vf=vtoy_wimboot:$vtoy_wimboot_prefix/boot/bcd" \ + "vf=bcd:$vtoy_wimboot_prefix/boot/bcd" \ + "vf=boot.sdi:$vtoy_wimboot_prefix/boot/boot.sdi" \ + "vf=boot.wim:$vtoy_wimfile_path" \ + pfsize=$vtoy_chain_file_size \ + pfread=$vtoy_chain_file_read + boot + ventoy_gui_console + fi +} + +function vtoy_winpe_wimboot { + unset vtoy_boot_sdi_legacy + unset vtoy_boot_sdi_efi + + set vtoy_wimboot_prefix=(loop) + set vtoy_wim_path="$1" + + if [ -n "${vtdebug_flag}" ]; then + echo "winpe_wimboot $1 $2 $3" + fi + + if [ "$2" != "0" ]; then + set vtoy_boot_sdi_legacy="newc:boot.sdi:$vtoy_wimboot_prefix/$2" + set vtoy_boot_sdi_efi="vf=boot.sdi:$vtoy_wimboot_prefix/$2" + fi + + vt_windows_wimboot_data $vtoy_wimboot_prefix/$vtoy_wim_path vtoy_init_exe vtoy_wim_bit + + if [ "$grub_platform" = "pc" ]; then + linux16 "$vtoy_path/$vt_wimkernel" quiet + ventoy_debug_pause + + vt_set_wim_load_prompt 1 "Loading files......" + initrd16 newc:$vtoy_init_exe:mem:${vtoy_wimboot_mem_addr}:size:${vtoy_wimboot_mem_size} \ + newc:vtoy_wimboot:$vtoy_path/$vt_wimkernel \ + newc:bootmgr.exe:mem:${vtoy_pe_bootmgr_mem_addr}:size:${vtoy_pe_bootmgr_mem_size} \ + newc:bcd:mem:${vtoy_pe_bcd_mem_addr}:size:${vtoy_pe_bcd_mem_size} \ + $vtoy_boot_sdi_legacy \ + newc:boot.wim:$vtoy_wimboot_prefix/$vtoy_wim_path + vt_set_wim_load_prompt 0 + boot + else + if [ "$VTOY_EFI_ARCH" = "x64" -a "$vtoy_wim_bit" = "32" ]; then + echo -e "\nThis is 32bit Windows and does NOT support x86_64 UEFI firmware.\n" + echo -e "这是32位的 Windows 系统,不支持当前的64位 UEFI 环境。\n" + fi + + vt_set_wim_load_prompt 1 "Loading files......" + vt_load_file_to_mem "nodecompress" $vtoy_wimboot_prefix/$vtoy_wim_path vtoy_wimfile_mem + vt_set_wim_load_prompt 0 + + if [ $? -eq 0 ]; then + set vtoy_wimfile_path=mem:${vtoy_wimfile_mem_addr}:size:${vtoy_wimfile_mem_size} + else + set vtoy_wimfile_path=$vtoy_wimboot_prefix/$vtoy_wim_path + fi + + unset vtoy_boot_efi_path + if [ -F (loop)/efi/boot/boot${VTOY_EFI_ARCH}.efi ]; then + set vtoy_boot_efi_path="vf=bootx64.efi:(loop)/efi/boot/boot${VTOY_EFI_ARCH}.efi" + fi + + ventoy_cli_console + chainloader "$vtoy_path/$vt_wimkernel" quiet \ + "vf=$vtoy_init_exe:mem:${vtoy_wimboot_mem_addr}:size:${vtoy_wimboot_mem_size}" \ + "vf=vtoy_wimboot:$vtoy_path/$vt_wimkernel" \ + "vf=bcd:mem:${vtoy_pe_bcd_mem_addr}:size:${vtoy_pe_bcd_mem_size}" \ + "$vtoy_boot_sdi_efi" \ + "$vtoy_boot_efi_path" \ + "vf=boot.wim:$vtoy_wimfile_path" \ + pfsize=$vtoy_chain_file_size \ + pfread=$vtoy_chain_file_read + boot + ventoy_gui_console + fi +} + +function vtoy_wimboot_func { + if [ "$grub_platform" = "pc" ]; then + set vt_wimkernel=wimboot.x86_64.xz + else + if [ "$grub_cpu" = "i386" ]; then + set vt_wimkernel=wimboot.i386.efi.xz + else + set vt_wimkernel=wimboot.x86_64.xz + fi + fi + + if vt_is_standard_winiso (loop); then + echo -e "\n==================== VENTOY WIMBOOT ==================\n" + vtoy_windows_wimboot + else + vt_sel_winpe_wim (loop) + if [ -n "$vtoy_pe_wim_path" ]; then + echo -e "\n==================== VENTOY WIMBOOT ==================\n" + + vt_fs_ignore_case 1 + vt_load_file_to_mem "auto" $vtoy_path/common_bcd.xz vtoy_pe_bcd_mem + + set vt_sdi_path=0 + for vsdi in "boot/boot.sdi" "2K10/FONTS/boot.sdi" "SSTR/boot.sdi" "ISPE/BOOT.SDI" \ + "boot/uqi.sdi" "ISYL/boot.sdi" "WEPE/WEPE.SDI" ; do + if [ -F "(loop)/$vsdi" ]; then + set vt_sdi_path=$vsdi + break + fi + done + + if [ "$grub_platform" = "pc" ]; then + vt_load_file_to_mem "auto" $vtoy_path/common_bootmgr.xz vtoy_pe_bootmgr_mem + vtoy_winpe_wimboot "$vtoy_pe_wim_path" "$vt_sdi_path" 1 + else + vtoy_winpe_wimboot "$vtoy_pe_wim_path" "$vt_sdi_path" 0 + fi + + vt_fs_ignore_case 0 + fi + fi +} + +function legacy_windows_menu_func { + vt_windows_reset + + unset vt_cur_wimboot_mode + if vt_check_mode 4 "$vt_chosen_name"; then + set vt_cur_wimboot_mode=1 + fi + + if [ "$ventoy_compatible" = "NO" -o "$vt_cur_wimboot_mode" = "1" ]; then + if [ "$ventoy_fs_probe" = "iso9660" ]; then + loopback -d loop + vt_iso9660_nojoliet 1 + loopback loop "$1$2" + fi + + for file in "boot/bcd" "/efi/microsoft/boot/bcd" "SSTR/BCD" "WEPE/B64" "WEPE/B32" "WEPE/BCD" "ISPE/BCD" "ISYL/BCD" "2K10/FONTS/BCD" "2K10/BCD" "boot/uqi/BCD" "boot/bce"; do + vt_windows_collect_wim_patch bcd (loop)/$file + done + + distro_specify_wim_patch + + vt_windows_count_wim_patch vt_wim_cnt + if [ $vt_wim_cnt -eq 0 ]; then + distro_specify_wim_patch_phase2 + fi + + ventoy_debug_pause + if [ -z "$vt_cur_wimboot_mode" ]; then + locate_wim "${chosen_path}" + fi + fi + + vt_windows_chain_data "${1}${chosen_path}" + ventoy_debug_pause + + if [ "$vt_cur_wimboot_mode" = "1" ]; then + vtoy_wimboot_func + fi + + if [ -n "$vtoy_chain_mem_addr" ]; then + ventoy_acpi_param ${vtoy_chain_mem_addr} 2048 + if [ "$ventoy_compatible" = "NO" ]; then + linux16 $vtoy_path/ipxe.krn ${vtdebug_flag} mem:${vtoy_chain_mem_addr}:size:${vtoy_chain_mem_size} + else + linux16 $vtoy_path/ipxe.krn ${vtdebug_flag} ibft mem:${vtoy_chain_mem_addr}:size:${vtoy_chain_mem_size} + fi + boot + else + echo "chain empty failed" + ventoy_pause + fi +} + +function legacy_linux_menu_func { + if [ "$ventoy_compatible" = "NO" ]; then + + if [ "$ventoy_fs_probe" = "udf" ]; then + loopback -d loop + set ventoy_fs_probe=iso9660 + loopback loop "$1$2" + fi + + + if vt_syslinux_need_nojoliet "$1$2"; then + vt_iso9660_nojoliet 1 + loopback -d loop + loopback loop "$1$2" + fi + + vt_load_cpio $vtoy_path "$2" "$1" "busybox=$ventoy_busybox_ver" + + vt_linux_clear_initrd + + if [ -d (loop)/pmagic ]; then + vt_linux_specify_initrd_file /pmagic/initrd.img + else + for dir in "isolinux" "boot/isolinux" "boot/x86_64/loader" "syslinux" "boot/syslinux"; do + if [ -d (loop)/$dir ]; then + vt_linux_parse_initrd_isolinux (loop)/$dir/ + fi + done + fi + + # special process for special distros + #archlinux + if [ -d (loop)/arch/boot/syslinux ]; then + vt_linux_parse_initrd_isolinux (loop)/arch/boot/syslinux/ /arch/ + vt_linux_parse_initrd_isolinux (loop)/arch/boot/syslinux/ /arch/boot/syslinux/ + elif [ -d (loop)/anarchy/boot/syslinux ]; then + vt_linux_parse_initrd_isolinux (loop)/anarchy/boot/syslinux/ /anarchy/ + + #manjaro + elif [ -d (loop)/manjaro ]; then + if [ -e (loop)/boot/grub/kernels.cfg ]; then + vt_linux_parse_initrd_grub file (loop)/boot/grub/kernels.cfg + fi + elif [ -e (loop)/boot/grub/grub.cfg ]; then + vt_linux_parse_initrd_grub file (loop)/boot/grub/grub.cfg + fi + + distro_specify_initrd_file + + vt_linux_initrd_count vtcount + if [ $vtcount -eq 0 ]; then + if [ -d (loop)/rancheros ]; then + vt_linux_parse_initrd_isolinux (loop)/boot/ /boot/isolinux/ + fi + + distro_specify_initrd_file_phase2 + fi + + locate_initrd + fi + + vt_linux_chain_data "${1}${chosen_path}" + ventoy_debug_pause + + if [ -n "$vtoy_chain_mem_addr" ]; then + unset vtGrub2Mode + if vt_check_mode 3 "$vt_chosen_name"; then + set vtGrub2Mode=1 + elif vt_str_begin "$vt_volume_id" "HOLO_"; then + if [ -d (loop)/loader/entries ]; then + set vtGrub2Mode=1 + fi + fi + + if [ -n "$vtGrub2Mode" ]; then + ventoy_acpi_param ${vtoy_chain_mem_addr} 2048 + ventoy_cli_console + + # fallback + set vtback_root=$root + vt_push_last_entry + set vtback_theme=$theme + unset theme + + vt_trailer_cpio "$vtoy_iso_part" "$vt_chosen_path" noinit + vt_set_boot_opt rdinit=/vtoy/vtoy + + set root=(loop) + set vtback_cfg_find=0 + for cfg in "/boot/grub/grub.cfg" "/EFI/BOOT/grub.cfg" "/EFI/debian/grub.cfg" "EFI/boot/grub.cfg" "efi/boot/grub.cfg" "/grub/grub.cfg" "EFI/BOOT/BOOTX64.conf"; do + if [ -e "$cfg" ]; then + set vtback_cfg_find=1 + configfile "$cfg" + break + fi + done + if [ $vtback_cfg_find -eq 0 ]; then + if [ -f (loop)/loader/loader.conf -a -d (loop)/loader/entries ]; then + if vt_str_begin "$vt_volume_id" "HOLO_"; then + set root=(loop,2) + vt_systemd_menu (loop,2) vt_sys_menu_mem + else + vt_systemd_menu (loop) vt_sys_menu_mem + fi + set vtback_cfg_find=1 + configfile "mem:${vt_sys_menu_mem_addr}:size:${vt_sys_menu_mem_size}" + fi + fi + + if [ $vtback_cfg_find -eq 0 ]; then + if [ -f (loop)/boot/isolinux/syslnx64.cfg ]; then + syslinux_configfile (loop)/boot/isolinux/syslnx64.cfg + set vtback_cfg_find=1 + elif [ -f (loop)/boot/syslinux/porteus.cfg ]; then + syslinux_configfile (loop)/boot/syslinux/porteus.cfg + set vtback_cfg_find=1 + elif [ -f (loop)/syslinux.cfg ]; then + syslinux_configfile (loop)/syslinux.cfg + set vtback_cfg_find=1 + fi + fi + + vt_unset_boot_opt + set root=$vtback_root + set theme=$vtback_theme + vt_pop_last_entry + ventoy_gui_console + else + ventoy_acpi_param ${vtoy_chain_mem_addr} 2048 + linux16 $vtoy_path/ipxe.krn ${vtdebug_flag} mem:${vtoy_chain_mem_addr}:size:${vtoy_chain_mem_size} + boot + fi + else + echo "chain empty failed" + ventoy_pause + fi +} + + +function legacy_unix_menu_func { + ventoy_unix_comm_proc $1 "${chosen_path}" + + if [ -n "$vtoy_chain_mem_addr" ]; then + #ventoy_acpi_param ${vtoy_chain_mem_addr} 2048 + linux16 $vtoy_path/ipxe.krn ${vtdebug_flag} mem:${vtoy_chain_mem_addr}:size:${vtoy_chain_mem_size} + boot + else + echo "chain empty failed" + ventoy_pause + fi +} + + +function legacy_iso_menu_func { + set chosen_path="$2" + + vt_select_auto_install "${chosen_path}" + vt_select_persistence "${chosen_path}" + + if [ -n "$vtcompat" ]; then + set ventoy_compatible=YES + unset vtcompat + elif vt_check_mode 1 "$vt_chosen_name"; then + set ventoy_compatible=YES + else + vt_check_compatible (loop) + fi + + vt_img_sector "${1}${chosen_path}" + + if [ "$ventoy_fs_probe" = "iso9660" ]; then + vt_select_conf_replace "${1}" "${chosen_path}" + fi + + if [ "$vtoy_os" = "Windows" ]; then + vt_check_compatible_pe (loop) + legacy_windows_menu_func "$1" "${chosen_path}" + elif [ "$vtoy_os" = "Unix" ]; then + legacy_unix_menu_func "$1" "${chosen_path}" + else + vt_check_compatible_linux (loop) + legacy_linux_menu_func "$1" "${chosen_path}" + fi + vt_secondary_recover_mode +} + +function legacy_iso_memdisk { + + linux16 $vtoy_path/memdisk iso raw + echo "Loading ISO file to memory ..." + initrd16 "${1}${2}" + boot +} + + +function iso_endless_os_proc { + if [ -d (loop)/ ]; then + loopback -d loop + fi + + loopback loop "${1}${2}" + vt_img_sector "${1}${2}" + + vt_load_cpio $vtoy_path "$2" "$1" "busybox=$ventoy_busybox_ver" + vt_trailer_cpio "$1" "$2" noinit + + ventoy_debug_pause + + vt_set_boot_opt '@kparams' rdinit=/vtoy/vtoy + + set eosimage=loop + set ventoy_bls_bootdev=/boot + set ventoy_loading_tip="Loading files ......" + + export eosimage + configfile (loop)/endless/grub/grub.cfg + + unset eosimage + unset ventoy_bls_bootdev + unset ventoy_loading_tip + + vt_unset_boot_opt +} + + +function ventoy_iso_busybox_ver { + + if [ "$VTOY_EFI_ARCH" = "aa64" ]; then + set ventoy_busybox_ver=a64 + elif [ "$VTOY_EFI_ARCH" = "mips" ]; then + set ventoy_busybox_ver=m64 + else + set ventoy_busybox_ver=32 + + #special process for deepin-live iso + if [ "$vt_chosen_size" = "403701760" ]; then + if vt_strstr "$vt_chosen_path" "/deepin-live"; then + set ventoy_busybox_ver=64 + fi + elif vt_str_begin "$vt_volume_id" "PHOTON_"; then + set ventoy_busybox_ver=64 + elif vt_str_begin "$vt_volume_id" "smgl-test-quinq-x86_64"; then + set ventoy_busybox_ver=64 + elif vt_str_begin "$vt_volume_id" "LDiagBootable"; then + set ventoy_busybox_ver=64 + elif vt_str_begin "$vt_volume_id" "KAOS_"; then + set ventoy_busybox_ver=64 + elif vt_strstr "$vt_volume_id" "x86_64"; then + set ventoy_busybox_ver=64 + elif vt_istrstr "${vt_chosen_path}" "x86_64"; then + set ventoy_busybox_ver=64 + elif vt_istrstr "${vt_chosen_path}" "amd64"; then + set ventoy_busybox_ver=64 + fi + fi +} + + +function iso_common_menuentry { + unset vt_system_id + unset vt_volume_id + + vt_chosen_img_path vt_chosen_path vt_chosen_size vt_chosen_name + + vt_parse_iso_volume "${vtoy_iso_part}${vt_chosen_path}" vt_system_id vt_volume_id vt_volume_space + if [ $vt_volume_space -NE $vt_chosen_size ]; then + vt_mod $vt_chosen_size 2048 vt_chosen_size_mod + if [ $vt_chosen_size_mod -ne 0 ]; then + echo -e "\n $vt_volume_space $vt_chosen_size $vt_chosen_size_mod\n" + echo -e "\n The size of the iso file \"$vt_chosen_size\" is invalid. File corrupted ?\n" + echo -e " 此ISO文件的大小 \"$vt_chosen_size\" 有问题,请确认文件是否损坏。\n" + echo -en "\n$VTLANG_ENTER_CONTINUE ..." + read vtInputKey + fi + fi + + if vt_check_password "${vt_chosen_path}"; then + return + fi + + if ventoy_vcfg_proc "${vt_chosen_path}"; then + return + fi + + + + #secondary boot menu + if vt_is_udf "${vtoy_iso_part}${vt_chosen_path}"; then + set ventoy_fs_probe=udf + else + set ventoy_fs_probe=iso9660 + ventoy_reset_nojoliet + fi + + if [ -d (loop)/ ]; then + loopback -d loop + fi + loopback loop "${vtoy_iso_part}${vt_chosen_path}" + + get_os_type (loop) + + ventoy_debug_pause + + if vt_need_secondary_menu "$vt_chosen_name"; then + vt_show_secondary_menu "$vt_chosen_path" "$vtoy_os" $vt_chosen_size + if [ "$VTOY_SECOND_EXIT" = "1" ]; then + return + fi + fi + + + if vt_str_begin "$vt_volume_id" "Avira"; then + vt_skip_svd "${vtoy_iso_part}${vt_chosen_path}" + fi + + ventoy_iso_busybox_ver + + #special process for Endless OS + if vt_str_begin "$vt_volume_id" "Endless-OS"; then + iso_endless_os_proc $vtoy_iso_part "$vt_chosen_path" + elif vt_str_begin "$vt_volume_id" "TENS-Public"; then + set vtcompat=1 + fi + + + # auto memdisk mode for some special ISO files + vt_iso_vd_id_parse "${vtoy_iso_part}${vt_chosen_path}" + unset vtMemDiskBoot + if vt_check_mode 0 "$vt_chosen_name"; then + set vtMemDiskBoot=1 + else + if [ "$grub_platform" = "pc" ]; then + if vt_iso_vd_id_begin 1 0 "Memtest86+"; then + set vtMemDiskBoot=1 + elif vt_iso_vd_id_begin 0 1 "KolibriOS"; then + set vtMemDiskBoot=1 + fi + fi + + #For iKuai8 (<64MB) + if [ $vt_chosen_size -LE 67108864 ]; then + if vt_str_begin "$vt_chosen_name" "iKuai"; then + set vtMemDiskBoot=1 + fi + fi + fi + vt_iso_vd_id_clear + + + if [ "$grub_platform" = "pc" ]; then + if [ -n "$vtMemDiskBoot" ]; then + legacy_iso_memdisk $vtoy_iso_part "$vt_chosen_path" + else + legacy_iso_menu_func $vtoy_iso_part "$vt_chosen_path" + fi + else + if [ -n "$vtMemDiskBoot" ]; then + uefi_iso_memdisk $vtoy_iso_part "$vt_chosen_path" + else + uefi_iso_menu_func $vtoy_iso_part "$vt_chosen_path" + fi + fi + + vt_secondary_recover_mode +} + +function miso_common_menuentry { + vt_chosen_img_path vt_chosen_path vt_chosen_size vt_chosen_name + + if vt_check_password "${vt_chosen_path}"; then + return + fi + + echo "memdisk mode boot for $vt_chosen_path" + echo "" + ventoy_debug_pause + + if [ "$grub_platform" = "pc" ]; then + legacy_iso_memdisk $vtoy_iso_part "$vt_chosen_path" + else + uefi_iso_memdisk $vtoy_iso_part "$vt_chosen_path" + fi +} + + +function common_unsupport_menuentry { + echo -e "\n The name of the iso file could NOT contain space or non-ascii characters. \n" + echo -e " 文件名中不能有中文或空格 \n" + echo -en "\n$VTLANG_ENTER_EXIT ..." + read vtInputKey +} + +function miso_unsupport_menuentry { + common_unsupport_menuentry +} + +function iso_unsupport_menuentry { + common_unsupport_menuentry +} + +function wim_common_menuentry { + vt_chosen_img_path vt_chosen_path vt_chosen_size vt_chosen_name + + if vt_check_password "${vt_chosen_path}"; then + return + fi + + if ventoy_vcfg_proc "${vt_chosen_path}"; then + return + fi + + if vt_wim_check_bootable "${vtoy_iso_part}${vt_chosen_path}"; then + vt_wim_chain_data "${vtoy_iso_part}${vt_chosen_path}" + else + echo -e "\n This is NOT a bootable WIM file. \n" + echo -e " 这不是一个可启动的 WIM 文件。\n" + fi + + ventoy_debug_pause + + if [ -n "$vtoy_chain_mem_addr" ]; then + if [ "$grub_platform" = "pc" ]; then + linux16 $vtoy_path/ipxe.krn ${vtdebug_flag} mem:${vtoy_chain_mem_addr}:size:${vtoy_chain_mem_size} + else + ventoy_cli_console + chainloader ${vtoy_path}/ventoy_${VTOY_EFI_ARCH}.efi env_param=${env_param} isoefi=${LoadIsoEfiDriver} ${vtdebug_flag} mem:${vtoy_chain_mem_addr}:size:${vtoy_chain_mem_size} + ventoy_gui_console + fi + boot + else + echo "chain empty failed" + ventoy_pause + fi +} + +function wim_unsupport_menuentry { + common_unsupport_menuentry +} + +function efi_common_menuentry { + vt_chosen_img_path vt_chosen_path vt_chosen_size vt_chosen_name + + if vt_check_password "${vt_chosen_path}"; then + return + fi + + if ventoy_vcfg_proc "${vt_chosen_path}"; then + return + fi + + unset vt_vlnk_dst + if vt_is_vlnk_name "${vt_chosen_path}"; then + vt_get_vlnk_dst "${vtoy_iso_part}${vt_chosen_path}" vt_vlnk_dst + if [ -z "$vt_vlnk_dst" ]; then + echo -e "\n### VLNK FILE NOT FOUND ###\n### VLNK 文件不存在 ###\n" + ventoy_pause + return + fi + else + vt_vlnk_dst="${vtoy_iso_part}${vt_chosen_path}" + fi + + ventoy_debug_pause + + ventoy_cli_console + + #first try with chainload + set vtOldRoot=$root + set root=$vtoy_iso_part + chainloader "${vt_vlnk_dst}" + boot + + #retry with isoboot + set root=$vtOldRoot + vt_concat_efi_iso "${vt_vlnk_dst}" vtoy_iso_buf + chainloader ${vtoy_path}/ventoy_${VTOY_EFI_ARCH}.efi memdisk env_param=${env_param} dotefi isoefi=on ${vtdebug_flag} mem:${vtoy_iso_buf_addr}:size:${vtoy_iso_buf_size} + boot + + ventoy_gui_console +} + +function efi_unsupport_menuentry { + common_unsupport_menuentry +} + +function vhdboot_common_func { + vt_patch_vhdboot "$1" + + ventoy_debug_pause + + if [ -n "$vtoy_vhd_buf_addr" ]; then + if [ "$grub_platform" = "pc" ]; then + ventoy_cli_console + linux16 $vtoy_path/memdisk iso raw + initrd16 mem:${vtoy_vhd_buf_addr}:size:${vtoy_vhd_buf_size} + boot + ventoy_gui_console + else + ventoy_cli_console + chainloader ${vtoy_path}/ventoy_${VTOY_EFI_ARCH}.efi memdisk env_param=${env_param} isoefi=${LoadIsoEfiDriver} ${vtdebug_flag} mem:${vtoy_vhd_buf_addr}:size:${vtoy_vhd_buf_size} + boot + ventoy_gui_console + fi + else + echo "Please put ventoy_vhdboot.img to \ISO\Ventoy\ of the data partition" + ventoy_pause + fi +} + +function vhd_common_menuentry { + vt_chosen_img_path vt_chosen_path vt_chosen_size vt_chosen_name + + if vt_check_password "${vt_chosen_path}"; then + return + fi + + if ventoy_vcfg_proc "${vt_chosen_path}"; then + return + fi + + unset vt_vlnk_dst + if vt_is_vlnk_name "${vt_chosen_path}"; then + vt_get_vlnk_dst "${vtoy_iso_part}${vt_chosen_path}" vt_vlnk_dst + if [ -z "$vt_vlnk_dst" ]; then + echo -e "\n### VLNK FILE NOT FOUND ###\n### VLNK 文件不存在 ###\n" + ventoy_pause + return + fi + else + vt_vlnk_dst="${vt_chosen_path}" + if [ "$VTOY_VHD_NO_WARNING" != "1" ]; then + if [ "$vtoy_iso_fs" != "ntfs" ]; then + echo -e "!!! WARNING !!!\n" + echo -e "\nPartition1 ($vtoy_iso_fs) is NOT ntfs, the VHD(x) file may not boot normally \n" + echo -e "\nVHD(x) 文件所在分区不是 ntfs 格式, 可能无法正常启动 \n\n" + echo -en "\n$VTLANG_ENTER_CONTINUE ..." + read vtInputKey + fi + fi + fi + + vhdboot_common_func "${vt_vlnk_dst}" +} + +function vhd_unsupport_menuentry { + common_unsupport_menuentry +} + +function vtoyboot_common_func { + set AltBootPart=0 + set vtoysupport=0 + + vt_get_vtoy_type "${1}" vtoytype parttype AltBootPart + + if vt_str_begin $vtoytype vhd; then + set vtoysupport=1 + elif [ "$vtoytype" = "raw" ]; then + set vtoysupport=1 + elif [ "$vtoytype" = "vdi" ]; then + set vtoysupport=1 + fi + + if [ $vtoysupport -eq 1 ]; then + if [ "$grub_platform" = "pc" ]; then + if [ "$parttype" = "gpt" -a $AltBootPart -eq 0 ]; then + echo "The OS in the vdisk was created in UEFI mode, but current is Legacy BIOS mode." + echo "虚拟磁盘内的系统是在UEFI模式下创建的,而当前系统是Legacy BIOS模式,可能无法正常启动。" + ventoy_pause + fi + else + if [ "$parttype" = "mbr" -a $AltBootPart -eq 0 ]; then + echo "The OS in the vdisk was created in Legacy BIOS mode, but current is UEFI mode." + echo "虚拟磁盘内的系统是在Legacy BIOS模式下创建的,而当前系统是UEFI模式,可能无法正常启动。" + ventoy_pause + fi + fi + + vt_img_sector "${1}" + vt_raw_chain_data "${1}" + + ventoy_debug_pause + + if [ -n "$vtoy_chain_mem_addr" ]; then + if [ "$grub_platform" = "pc" ]; then + vt_acpi_param ${vtoy_chain_mem_addr} 512 + linux16 $vtoy_path/ipxe.krn ${vtdebug_flag} bios80 sector512 mem:${vtoy_chain_mem_addr}:size:${vtoy_chain_mem_size} + boot + else + if vt_check_secureboot_var; then + vt_acpi_param ${vtoy_chain_mem_addr} 512 + fi + ventoy_cli_console + chainloader ${vtoy_path}/ventoy_${VTOY_EFI_ARCH}.efi sector512 env_param=${ventoy_env_param} ${vtdebug_flag} mem:${vtoy_chain_mem_addr}:size:${vtoy_chain_mem_size} + boot + ventoy_gui_console + fi + else + echo "chain empty failed!" + ventoy_pause + fi + else + echo "Unsupported vtoy type $vtoytype" + ventoy_pause + fi +} + +function vtoy_common_menuentry { + vt_chosen_img_path vt_chosen_path vt_chosen_size vt_chosen_name + + if vt_check_password "${vt_chosen_path}"; then + return + fi + + if ventoy_vcfg_proc "${vt_chosen_path}"; then + return + fi + + unset vt_vlnk_dst + if vt_is_vlnk_name "${vt_chosen_path}"; then + vt_get_vlnk_dst "${vtoy_iso_part}${vt_chosen_path}" vt_vlnk_dst + if [ -z "$vt_vlnk_dst" ]; then + echo -e "\n### VLNK FILE NOT FOUND ###\n### VLNK 文件不存在 ###\n" + ventoy_pause + return + fi + else + vt_vlnk_dst="${vtoy_iso_part}${vt_chosen_path}" + fi + + vtoyboot_common_func "${vt_vlnk_dst}" +} + +function vtoy_unsupport_menuentry { + common_unsupport_menuentry +} + +# +#============================================================# +# IMG file boot process # +#============================================================# +# + +function only_uefi_tip { + echo -e "\n This IMG file is only supported in UEFI mode. \n" + echo -en "\n$VTLANG_ENTER_EXIT ..." + read vtInputKey +} + +function ventoy_img_easyos { + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=$ventoy_busybox_ver" + vt_trailer_cpio ${vtoy_iso_part} "${vt_chosen_path}" noinit + + loopback easysfs (vtimghd,1)/easy.sfs + vt_get_lib_module_ver (easysfs) /lib/modules/ vt_module_ver + + if [ -n "$vt_module_ver" ]; then + for mod in "kernel/drivers/md/dm-mod.ko" "kernel/drivers/dax/dax.ko"; do + if [ -e (easysfs)/lib/modules/$vt_module_ver/$mod ]; then + vt_img_extra_initrd_append (easysfs)/lib/modules/$vt_module_ver/$mod + fi + done + fi + + ventoy_debug_pause + + #boot image file + vt_set_boot_opt rdinit=/vtoy/vtoy + vt_img_hook_root + + syslinux_configfile (vtimghd,1)/syslinux.cfg + + vt_img_unhook_root + vt_unset_boot_opt + loopback -d easysfs +} + +function ventoy_img_easyos2 { + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=$ventoy_busybox_ver" + vt_trailer_cpio ${vtoy_iso_part} "${vt_chosen_path}" noinit + + if [ -e (vtimghd,2)/easyos/easy.sfs ]; then + loopback easysfs (vtimghd,2)/easyos/easy.sfs + elif [ -d (vtimghd,2)/easyos/releases ]; then + vt_fs_enum_1st_dir (vtimghd,2) /easyos/releases/ vt_dir_name + loopback easysfs (vtimghd,2)/easyos/releases/$vt_dir_name/easy.sfs + fi + + vt_get_lib_module_ver (easysfs) /lib/modules/ vt_module_ver + + if [ -n "$vt_module_ver" ]; then + for mod in "kernel/drivers/md/dm-mod.ko" "kernel/drivers/dax/dax.ko"; do + if [ -e (easysfs)/lib/modules/$vt_module_ver/$mod ]; then + vt_img_extra_initrd_append (easysfs)/lib/modules/$vt_module_ver/$mod + fi + done + fi + + ventoy_debug_pause + + #boot image file + vt_set_boot_opt rdinit=/vtoy/vtoy + vt_img_hook_root + + vt_limine_menu (vtimghd,1)/limine.cfg vt_sys_menu_mem + configfile "mem:${vt_sys_menu_mem_addr}:size:${vt_sys_menu_mem_size}" + + vt_img_unhook_root + vt_unset_boot_opt + loopback -d easysfs +} + +function ventoy_img_volumio { + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=$ventoy_busybox_ver" + vt_trailer_cpio ${vtoy_iso_part} "${vt_chosen_path}" noinit + + ventoy_debug_pause + + #boot image file + vt_set_boot_opt rdinit=/vtoy/vtoy imgpart=/dev/ventoy2 bootpart=/dev/ventoy1 + vt_img_hook_root + + syslinux_configfile (vtimghd,1)/syslinux.cfg + + vt_img_unhook_root + vt_unset_boot_opt +} + +function ventoy_img_openelec { + elec_ver=$1 + + if [ "$elec_ver" = "LibreELEC" ]; then + if vt_strstr "$vt_chosen_name" "x86_64"; then + set ventoy_busybox_ver=64 + fi + fi + + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=$ventoy_busybox_ver" + vt_trailer_cpio ${vtoy_iso_part} "${vt_chosen_path}" noinit + + loopback vtloopex $vtoy_efi_part/ventoy/vtloopex.cpio + vt_img_extra_initrd_append (vtloopex)/$elec_ver/vtloopex.tar.xz + + if [ "$elec_ver" = "LibreELEC" ]; then + if [ -f (vtimghd,1)/system ]; then + loopback elecsfs (vtimghd,1)/system + vt_get_lib_module_ver (elecsfs) /usr/lib/kernel-overlays/base/lib/modules/ vt_module_ver + if [ -n "$vt_module_ver" ]; then + for mod in "kernel/drivers/md/dm-mod.ko"; do + if [ -e (elecsfs)/usr/lib/kernel-overlays/base/lib/modules/$vt_module_ver/$mod ]; then + vt_img_extra_initrd_append (elecsfs)/usr/lib/kernel-overlays/base/lib/modules/$vt_module_ver/$mod + fi + done + fi + fi + fi + + ventoy_debug_pause + + #boot image file + vt_set_boot_opt rdinit=/vtoy/vtoy ventoyos=$elec_ver + vt_img_hook_root + + set root=(vtimghd,1) + syslinux_configfile (vtimghd,1)/syslinux.cfg + + vt_img_unhook_root + vt_unset_boot_opt + loopback -d vtloopex + loopback -d elecsfs +} + + +function ventoy_img_freedombox { + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=$ventoy_busybox_ver" + vt_trailer_cpio ${vtoy_iso_part} "${vt_chosen_path}" noinit + + vt_get_lib_module_ver (vtimghd,1) /lib/modules/ vt_module_ver + if [ -n "$vt_module_ver" ]; then + vt_img_extra_initrd_append (vtimghd,1)/lib/modules/$vt_module_ver/kernel/drivers/md/dm-mod.ko + fi + + ventoy_debug_pause + + #boot image file + vt_set_boot_opt rdinit=/vtoy/vtoy ventoyos=freedombox + vt_img_hook_root + + configfile (vtimghd,1)/boot/grub/grub.cfg + + vt_img_unhook_root + vt_unset_boot_opt +} + +function steamenv_init { + echo "dummy steamenv_boot" +} + +function steamenv_boot { + if [ -n "${vtdebug_flag}" ]; then + $1 $2 loglevel=7 + else + $@ + fi +} + + +function ventoy_img_steamos { + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=$ventoy_busybox_ver" + vt_trailer_cpio ${vtoy_iso_part} "${vt_chosen_path}" noinit + + vt_get_lib_module_ver (vtimghd,3) /lib/modules/ vt_module_ver + if [ -n "$vt_module_ver" ]; then + vt_img_extra_initrd_append (vtimghd,3)/lib/modules/$vt_module_ver/kernel/drivers/md/dm-mod + fi + + ventoy_debug_pause + + #boot image file + vt_set_boot_opt rdinit=/vtoy/vtoy ventoyos=steamos steamos.efi=/dev/steamos-media-efi + vt_img_hook_root + + set theme=$vtback_theme + ventoy_gui_console + ventoy_cfg_theme_lock 1 + + configfile (vtimghd,2)/EFI/steamos/grub.cfg + + ventoy_cfg_theme_lock 0 + + vt_img_unhook_root + vt_unset_boot_opt +} + + +function ventoy_img_paldo { + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=$ventoy_busybox_ver" + vt_trailer_cpio ${vtoy_iso_part} "${vt_chosen_path}" noinit + + ventoy_debug_pause + + #boot image file + vt_set_boot_opt rdinit=/vtoy/vtoy ventoyos=paldo + vt_img_hook_root + + vt_fs_enum_1st_file (vtimghd,1) /loader/entries/ vt_paldo_entry_conf + vt_file_basename $vt_paldo_entry_conf vtPaldoVer + + echo loading file... + linux (vtimghd,1)/linux-${vtPaldoVer} root=/dev/ventoy1 rootfstype=vfat + initrd (vtimghd,1)/initramfs-${vtPaldoVer} + boot + + vt_img_unhook_root + vt_unset_boot_opt +} + +function ventoy_img_ubos { + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=$ventoy_busybox_ver" + vt_trailer_cpio ${vtoy_iso_part} "${vt_chosen_path}" noinit + + vt_get_lib_module_ver (vtimghd,3) /lib/modules/ vt_module_ver + if [ -n "$vt_module_ver" ]; then + vt_img_extra_initrd_append (vtimghd,3)/lib/modules/$vt_module_ver/kernel/drivers/md/dm-mod.ko.xz + fi + + ventoy_debug_pause + + #boot image file + vt_set_boot_opt rdinit=/vtoy/vtoy ventoyos=ubos + vt_img_hook_root + + echo loading file... + linux (vtimghd,2)/vmlinuz-linux root=/dev/ventoy3 rw + initrd (vtimghd,2)/initramfs-linux.img + boot + + vt_img_unhook_root + vt_unset_boot_opt +} + +function ventoy_img_recalbox { + if [ $vtoy_img_max_part_end -GT $vt_chosen_size ]; then + echo -e "\nPlease extend the img file size before boot it. \n" + ventoy_pause + return + fi + + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=$ventoy_busybox_ver" + vt_trailer_cpio ${vtoy_iso_part} "${vt_chosen_path}" noinit + + if [ -e (vtimghd,1)/boot/recalbox ]; then + loopback recalbox (vtimghd,1)/boot/recalbox + vt_get_lib_module_ver (recalbox) /lib/modules/ vt_module_ver + if [ -n "$vt_module_ver" ]; then + vt_img_extra_initrd_append (recalbox)/lib/modules/$vt_module_ver/kernel/drivers/md/dm-mod.ko + fi + fi + + ventoy_debug_pause + + #boot image file + vt_set_boot_opt rdinit=/vtoy/vtoy ventoyos=recalbox + vt_img_hook_root + + set root=(vtimghd,1) + configfile (vtimghd,1)/boot/grub/grub.cfg + + vt_img_unhook_root + vt_unset_boot_opt +} + +function ventoy_img_esysrescue { + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=$ventoy_busybox_ver" + vt_trailer_cpio ${vtoy_iso_part} "${vt_chosen_path}" noinit + + ventoy_debug_pause + + #boot image file + vt_set_boot_opt rdinit=/vtoy/vtoy ventoyos=esysrescue + vt_img_hook_root + + set root=(vtimghd,1) + configfile (vtimghd,1)/boot/grub/grub.cfg + + vt_img_unhook_root + vt_unset_boot_opt +} + +function ventoy_img_batocera { + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=$ventoy_busybox_ver" + vt_trailer_cpio ${vtoy_iso_part} "${vt_chosen_path}" noinit + + ventoy_debug_pause + + #boot image file + vt_set_boot_opt rdinit=/vtoy/vtoy ventoyos=batocera + vt_img_hook_root + + set root=(vtimghd,1) + syslinux_configfile (vtimghd,1)/boot/syslinux/syslinux.cfg + + vt_img_unhook_root + vt_unset_boot_opt +} + +function ventoy_img_openwrt { + if [ -e (vtimghd,2)/lib64 ]; then + set ventoy_busybox_ver=64 + fi + + vt_fs_enum_1st_dir (vtimghd,2) /lib/modules/ vt_dir_name + + if [ -f (vtimghd,2)/lib/modules/$vt_dir_name/dm-mod.ko ]; then + set openwrt_plugin_need=0 + vt_img_extra_initrd_append (vtimghd,2)/lib/modules/$vt_dir_name/dm-mod.ko + if [ -f (vtimghd,2)/lib/modules/$vt_dir_name/dax.ko ]; then + vt_img_extra_initrd_append (vtimghd,2)/lib/modules/$vt_dir_name/dax.ko + fi + else + set openwrt_plugin_need=1 + if [ ! -f ${vtoy_iso_part}/ventoy/ventoy_openwrt.xz ]; then + ventoy_gui_console + echo -e "\n ventoy_openwrt.xz not found. Please refer https://www.ventoy.net/en/doc_openwrt.html.\n" + echo -e " 未找到 ventoy_openwrt.xz 文件。请参考 https://www.ventoy.net/cn/doc_openwrt.html\n" + echo -en "\n$VTLANG_ENTER_EXIT ..." + read vtInputKey + ventoy_cli_console + return + fi + fi + + if vt_img_check_range "${vtoy_iso_part}${vt_chosen_path}"; then + ventoy_debug_pause + else + ventoy_gui_console + echo -e "\n IMG file need processed. Please refer https://www.ventoy.net/en/doc_openwrt.html.\n" + echo -e " 此 IMG 文件必须处理之后才能支持。请参考 https://www.ventoy.net/cn/doc_openwrt.html\n" + echo -e "\n press ENTER to exit (请按 回车 键返回) ..." + read vtInputKey + ventoy_cli_console + return + fi + + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=$ventoy_busybox_ver" + vt_trailer_cpio ${vtoy_iso_part} "${vt_chosen_path}" noinit + + if [ $openwrt_plugin_need -eq 1 ]; then + if [ -f ${vtoy_iso_part}/ventoy/ventoy_openwrt.xz ]; then + vt_img_extra_initrd_append ${vtoy_iso_part}/ventoy/ventoy_openwrt.xz + fi + fi + + #boot image file + vt_set_boot_opt rdinit=/vtoy/vtoy ventoyos=openwrt + vt_img_hook_root + + set root=(vtimghd,1) + configfile (vtimghd,1)/boot/grub/grub.cfg + + vt_img_unhook_root + vt_unset_boot_opt +} + +function ventoy_img_tails { + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=$ventoy_busybox_ver" + vt_trailer_cpio ${vtoy_iso_part} "${vt_chosen_path}" noinit + + ventoy_debug_pause + + #boot image file + vt_set_boot_opt rdinit=/vtoy/vtoy live-media=/dev/dm-1 ventoyos=tails + vt_img_hook_root + + set root=(vtimghd,1) + configfile (vtimghd,1)/efi/debian/grub.cfg + + vt_img_unhook_root + vt_unset_boot_opt +} + +function ventoy_img_fydeos { + if [ "$grub_platform" = "pc" ]; then + only_uefi_tip + return + fi + + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=64" + vt_trailer_cpio ${vtoy_iso_part} "${vt_chosen_path}" noinit + + ventoy_debug_pause + + #boot image file + vt_set_boot_opt rdinit=/vtoy/vtoy ventoyos=fydeos + vt_img_hook_root + + set grubdisk=vtimghd + set grubpartA=(vtimghd,3) + set grubpartB=(vtimghd,5) + set linuxpartA=(sda,3) + set linuxpartB=(sda,5) + + set root=(vtimghd,12) + configfile (vtimghd,12)/efi/boot/grub.cfg + + vt_img_unhook_root + vt_unset_boot_opt + + unset grubdisk + unset grubpartA + unset grubpartB + unset linuxpartA + unset linuxpartB +} + +function ventoy_img_cloudready { + if [ "$grub_platform" = "pc" ]; then + only_uefi_tip + return + fi + + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=64" + vt_trailer_cpio ${vtoy_iso_part} "${vt_chosen_path}" noinit + + ventoy_debug_pause + + #boot image file + vt_set_boot_opt rdinit=/vtoy/vtoy ventoyos=cloudready + vt_img_hook_root + + set grubdisk=vtimghd + set grubpartA=(vtimghd,3) + set grubpartB=(vtimghd,5) + set linuxpartA=(sda,3) + set linuxpartB=(sda,5) + + set root=(vtimghd,12) + configfile (vtimghd,12)/efi/boot/grub.cfg + + vt_img_unhook_root + vt_unset_boot_opt + + unset grubdisk + unset grubpartA + unset grubpartB + unset linuxpartA + unset linuxpartB +} + + +function ventoy_img_fwts { + vt_load_cpio $vtoy_path "${vt_chosen_path}" ${vtoy_iso_part} "busybox=$ventoy_busybox_ver" + vt_trailer_cpio ${vtoy_iso_part} "${vt_chosen_path}" noinit + + ventoy_debug_pause + + #boot image file + vt_set_boot_opt rdinit=/vtoy/vtoy ventoyos=fwts + vt_img_hook_root + + configfile $prefix/distro/fwts.cfg + + vt_img_unhook_root + vt_unset_boot_opt +} + +function ventoy_img_memtest86 { + chainloader (vtimghd,1)/efi/boot/BOOTX64.efi + boot +} + +function img_unsupport_tip { + echo -e "\n This IMG file is NOT supported now. \n" + echo -e " 当前不支持启动此 IMG 文件 \n" + echo -en "\n$VTLANG_ENTER_EXIT ..." + read vtInputKey +} + +function legacy_img_memdisk { + linux16 $vtoy_path/memdisk + echo "Loading img file to memory ..." + initrd16 "${1}${2}" + + ventoy_cli_console + boot +} + +function img_common_menuentry { + set ventoy_compatible=YES + set ventoy_busybox_ver=32 + unset LoadIsoEfiDriver + + vt_chosen_img_path vt_chosen_path vt_chosen_size vt_chosen_name + + if vt_check_password "${vt_chosen_path}"; then + return + fi + + if ventoy_vcfg_proc "${vt_chosen_path}"; then + return + fi + + if [ "$grub_platform" = "pc" ]; then + if vt_check_mode 0 "$vt_chosen_name"; then + legacy_img_memdisk $vtoy_iso_part "$vt_chosen_path" + return + fi + fi + + loopback vtimghd "${vtoy_iso_part}${vt_chosen_path}" + vt_img_sector "${vtoy_iso_part}${vt_chosen_path}" + + vt_img_part_info (vtimghd) + + set vtback_root=$root + ventoy_cli_console + vt_push_last_entry + set vtback_theme=$theme + unset theme + + vt_img_extra_initrd_reset + + + vt_get_fs_label (vtimghd,1) vtImgHd1Label + + if [ "$vtImgHd1Label" = "STATE" ]; then + vt_get_fs_label (vtimghd,3) vtImgHd3Label + elif [ -d (vtimghd,2)/lib ]; then + vt_get_fs_label (vtimghd,2) vtImgHd2Label + fi + + if [ -z "$vtImgHd1Label" ]; then + if [ -d (vtimghd,2)/efi ]; then + vt_get_fs_label (vtimghd,3) vtImgHd3Label + elif [ -d (vtimghd,12)/efi ]; then + vt_get_fs_label (vtimghd,3) vtImgHd3Label + fi + fi + + if [ -e (vtimghd,1)/etc/hostname ]; then + vt_1st_line (vtimghd,1)/etc/hostname vtImgHostname + fi + + if vt_str_begin "$vtImgHd3Label" "ROOT-"; then + if [ -f (vtimghd,3)/etc/os-release.d/ID ]; then + vt_1st_line (vtimghd,3)/etc/os-release.d/ID vt_release_line1 + if vt_str_begin "$vt_release_line1" "FydeOS"; then + ventoy_img_fydeos + else + ventoy_img_cloudready + fi + elif [ -f (vtimghd,3)/etc/cloudready-release ]; then + ventoy_img_cloudready + elif [ -f (vtimghd,3)/etc/chrome_dev.conf ]; then + ventoy_img_cloudready + fi + elif vt_str_begin "$vtImgHd3Label" "fwts-result"; then + ventoy_img_fwts + elif vt_str_begin "$vtImgHd1Label" "LAKKA"; then + ventoy_img_openelec lakka + elif vt_str_begin "$vtImgHd1Label" "LIBREELEC"; then + ventoy_img_openelec LibreELEC + elif vt_str_begin "$vtImgHd1Label" "paldo-live"; then + ventoy_img_paldo + elif vt_str_begin "$vtImgHostname" "freedombox"; then + ventoy_img_freedombox + elif vt_str_begin "$vtImgHd1Label" "BATOCERA"; then + ventoy_img_batocera + elif vt_str_begin "$vtImgHd1Label" "Tails"; then + ventoy_img_tails + elif [ "$vtImgHd2Label" = "RECALBOX" -o "$vtImgHd1Label" = "RECALBOX" ]; then + ventoy_img_recalbox + elif [ "$vtImgHd1Label" = "ESYSRESCUE" ]; then + ventoy_img_esysrescue + elif [ -e (vtimghd,1)/SteamOS ]; then + ventoy_img_steamos + elif [ -e (vtimghd,1)/easy.sfs ]; then + ventoy_img_easyos + elif [ -d (vtimghd,2)/easyos ]; then + ventoy_img_easyos2 + elif [ -e (vtimghd,1)/volumio.initrd ]; then + ventoy_img_volumio + elif [ -f (vtimghd,2)/loader/entries/ubos.conf ]; then + ventoy_img_ubos + elif [ -f (vtimghd,2)/etc/openwrt_version ]; then + ventoy_img_openwrt + else + if [ -f (vtimghd,1)/efi/boot/mt86.png ]; then + if [ "$grub_platform" = "pc" ]; then + img_unsupport_tip + fi + fi + + #common chain + vt_linux_chain_data "${vtoy_iso_part}${vt_chosen_path}" + ventoy_acpi_param ${vtoy_chain_mem_addr} 512 + if [ "$grub_platform" = "pc" ]; then + linux16 $vtoy_path/ipxe.krn ${vtdebug_flag} sector512 mem:${vtoy_chain_mem_addr}:size:${vtoy_chain_mem_size} + boot + else + chainloader ${vtoy_path}/ventoy_${VTOY_EFI_ARCH}.efi sector512 env_param=${env_param} isoefi=${LoadIsoEfiDriver} FirstTry=${FirstTryBootFile} ${vtdebug_flag} mem:${vtoy_chain_mem_addr}:size:${vtoy_chain_mem_size} + boot + fi + fi + + loopback -d vtimghd + + set root=$vtback_root + vt_pop_last_entry + set theme=$vtback_theme + ventoy_gui_console + set ventoy_compatible=NO +} + +function img_unsupport_menuentry { + common_unsupport_menuentry +} + +function mimg_common_menuentry { + vt_chosen_img_path vt_chosen_path vt_chosen_size vt_chosen_name + + if vt_check_password "${vt_chosen_path}"; then + return + fi + + echo "memdisk mode boot for $vt_chosen_path" + echo "" + ventoy_debug_pause + + if [ "$grub_platform" = "pc" ]; then + legacy_img_memdisk $vtoy_iso_part "$vt_chosen_path" + else + vt_load_img_memdisk "$vtoy_iso_part$vt_chosen_path" vtoy_img_buf + ventoy_cli_console + chainloader ${vtoy_path}/ventoy_${VTOY_EFI_ARCH}.efi memdisk env_param=${env_param} isoefi=${LoadIsoEfiDriver} ${vtdebug_flag} mem:${vtoy_img_buf_addr}:size:${vtoy_img_buf_size} + boot + ventoy_gui_console + fi +} + +############################################################# +############################################################# +############################################################# +####### Main Process ########### +############################################################# +############################################################# +############################################################# + +set VENTOY_VERSION="1.1.18" + +#ACPI not compatible with Window7/8, so disable by default +set VTOY_PARAM_NO_ACPI=1 + +# Default menu display mode, you can change it as you want. +# 0: List mode +# 1: TreeView mode +set VTOY_DEFAULT_MENU_MODE=0 + +set VTOY_MEM_DISK_STR="[Memdisk]" +set VTOY_ISO_RAW_STR="Compatible Mode" +set VTOY_GRUB2_MODE_STR="GRUB2 Mode" +set VTOY_WIMBOOT_MODE_STR="WIMBOOT Mode" +set VTOY_ISO_UEFI_DRV_STR="UEFI FS" + +set VTOY_F2_CMD="vt_browser_disk" +set VTOY_F4_CMD="ventoy_localboot" +set VTOY_F5_CMD="ventoy_diagnosis" +set VTOY_F6_CMD="ventoy_ext_menu" +set VTOY_HELP_CMD="ventoy_show_help" +set VTOY_CHKSUM_CMD="ventoy_checksum" +set VTOY_HELP_TXT_LANGUAGE="en_US" +set VTOY_CHKSUM_FILE_PATH="X" +set VTOY_LANG_CMD="ventoy_language" + + +if [ "$grub_platform" = "pc" ]; then + set VTOY_TEXT_MENU_VER="Ventoy $VENTOY_VERSION BIOS www.ventoy.net" +else + if [ "$grub_cpu" = "i386" ]; then + set VTOY_EFI_ARCH=ia32 + set VTOY_TEXT_MENU_VER="Ventoy $VENTOY_VERSION IA32 www.ventoy.net" + elif [ "$grub_cpu" = "arm64" ]; then + set VTOY_EFI_ARCH=aa64 + set VTOY_TEXT_MENU_VER="Ventoy $VENTOY_VERSION AA64 www.ventoy.net" + elif [ "$grub_cpu" = "mips64el" ]; then + set VTOY_EFI_ARCH=mips + set VTOY_TEXT_MENU_VER="Ventoy $VENTOY_VERSION MIPS www.ventoy.net" + else + set VTOY_EFI_ARCH=x64 + set VTOY_TEXT_MENU_VER="Ventoy $VENTOY_VERSION UEFI www.ventoy.net" + fi +fi + +vt_device $root vtoy_dev + +if [ "$vtoy_dev" = "tftp" ]; then + set vtoy_path=($root) + for vtid in 0 1 2 3; do + if [ -f (hd$vtid,2)/ventoy/ventoy.cpio ]; then + set vtoy_iso_part=(hd$vtid,1) + set vtoy_efi_part=(hd$vtid,2) + set vtoydev=hd$vtid + break + fi + done + loadfont ascii + + if [ -n "$vtoy_efi_part" ]; then + vt_load_file_to_mem "auto" $vtoy_efi_part/grub/fonts/unicode.pf2 vtoy_font_mem + loadfont mem:${vtoy_font_mem_addr}:size:${vtoy_font_mem_size} + fi + + if [ -f $vtoy_iso_part/ISO/Ventoy/ventoy.json ]; then + set vt_plugin_path=$vtoy_iso_part + else + set vt_plugin_path=$prefix + vt_load_plugin $vt_plugin_path + fi +else + if [ "$prefix" = "(ventoydisk)/grub" ]; then + set vtoy_path=(ventoydisk)/ventoy + else + set vtoy_path=($root)/ventoy + fi + + set vtoydev=$vtoy_dev + set vtoy_iso_part=($vtoy_dev,1) + set VTOY_DATA_PART_IDX=1 + set vtoy_efi_part=($vtoy_dev,2) + set VTOY_EFI_PART_IDX=2 + + # VTOY-CUSTOM-LAYOUT: data (ISO) partition is the one that contains + # /ISO/Ventoy/NOT.DEL (fallback: partition 1). VTOYEFI stays partition 2. + for vt_part in 1 2 3 4; do + if [ -f ($vtoy_dev,$vt_part)/ISO/Ventoy/NOT.DEL ]; then + set vtoy_iso_part=($vtoy_dev,$vt_part) + set VTOY_DATA_PART_IDX=$vt_part + break + fi + done + export VTOY_DATA_PART_IDX + export VTOY_EFI_PART_IDX + + vt_load_file_to_mem "auto" $prefix/fonts/unicode.pf2 vtoy_font_mem + loadfont mem:${vtoy_font_mem_addr}:size:${vtoy_font_mem_size} + + set vt_plugin_path=$vtoy_iso_part +fi + +#Load Partition Table +vt_load_part_table $vtoydev + +#Load menu lang file +ventoy_load_menu_lang_file + +#Load Plugin +if [ -f $vtoy_iso_part/ISO/Ventoy/ventoy.json ]; then + clear + vt_load_plugin $vtoy_iso_part + clear +else + vt_check_json_path_case $vtoy_iso_part +fi + +#Update Secure Boot Policy +vt_update_sb_policy + + +if [ -n "$VTOY_MENU_LANGUAGE" ]; then + vt_init_menu_lang "$VTOY_MENU_LANGUAGE" +else + vt_init_menu_lang ru_RU +fi + +if [ -n "$VTOY_MENU_TIMEOUT" ]; then + set timeout=$VTOY_MENU_TIMEOUT +else + unset timeout +fi + +if [ -f $vtoy_iso_part/ISO/Ventoy/ventoy_wimboot.img ]; then + vt_load_wimboot $vtoy_iso_part/ISO/Ventoy/ventoy_wimboot.img +elif [ -f $vtoy_iso_part/ventoy/ventoy_wimboot.img ]; then + vt_load_wimboot $vtoy_iso_part/ventoy/ventoy_wimboot.img +elif [ -f $vtoy_efi_part/ventoy/ventoy_wimboot.img ]; then + vt_load_wimboot $vtoy_efi_part/ventoy/ventoy_wimboot.img +fi + +if [ -f $vtoy_iso_part/ISO/Ventoy/ventoy_vhdboot.img ]; then + vt_load_vhdboot $vtoy_iso_part/ISO/Ventoy/ventoy_vhdboot.img +elif [ -f $vtoy_iso_part/ventoy/ventoy_vhdboot.img ]; then + vt_load_vhdboot $vtoy_iso_part/ventoy/ventoy_vhdboot.img +elif [ -f $vtoy_efi_part/ventoy/ventoy_vhdboot.img ]; then + vt_load_vhdboot $vtoy_efi_part/ventoy/ventoy_vhdboot.img +fi + + +if [ $VTOY_DEFAULT_MENU_MODE -eq 0 ]; then + set VTOY_F3_CMD="vt_dynamic_menu 1 1" +else + set VTOY_F3_CMD="vt_dynamic_menu 1 0" +fi + +terminal_output console + +if [ -n "$vtoy_gfxmode" ]; then + set gfxmode=$vtoy_gfxmode + set gfxpayload=keep +else + set gfxmode=1024x768 + set gfxpayload=keep +fi + + +if [ "$vtoy_display_mode" = "CLI" ]; then + terminal_output console +elif [ "$vtoy_display_mode" = "serial" ]; then + if [ -n "$vtoy_serial_param" ]; then + serial $vtoy_serial_param + fi + terminal_input serial + terminal_output serial +elif [ "$vtoy_display_mode" = "serial_console" ]; then + if [ -n "$vtoy_serial_param" ]; then + serial $vtoy_serial_param + fi + terminal_input serial console + terminal_output serial console +else + if [ "$vtoy_gfxmode" = "max" ]; then + set gfxmode=1024x768 + terminal_output gfxterm + + vt_enum_video_mode + vt_get_video_mode 0 vtCurMode + terminal_output console + set gfxmode=$vtCurMode + terminal_output gfxterm + elif [ "$vtoy_res_fit" = "1" ]; then + terminal_output gfxterm + fi + + if [ -n "$vtoy_theme" ]; then + vt_set_theme + else + set theme=$prefix/themes/ventoy/theme.txt + fi + terminal_output gfxterm +fi + +if [ "$grub_platform" = "efi" ]; then + set mouse_delta=4000 + # terminal_input --append mouse +fi + +if [ -n "$VTOY_DEFAULT_KBD_LAYOUT" ]; then + set_keyboard_layout "$VTOY_DEFAULT_KBD_LAYOUT" +fi + +if [ -n "$VTOY_PLUGIN_PATH_CASE_MISMATCH" ]; then + clear + echo "$VTOY_PLUGIN_PATH_CASE_MISMATCH" + echo -e "\n\nPath case does not match! ventoy directory and ventoy.json MUST be all lowercase!" + echo -e "\n路径大小写不匹配!ventoy 目录和 ventoy.json 文件的名字必须是全部小写,请修正!" + echo -e "\n\npress ENTER to continue (请按回车键继续) ..." + read vtInputKey +fi + +if [ -n "$VTOY_PLUGIN_SYNTAX_ERROR" ]; then + clear + if [ -n "$VTOY_PLUGIN_ENCODE_ERROR" ]; then + echo -e "\n Encoding type for ventoy.json is not supported, please convert to UTF-8.\n" + echo -e " ventoy.json 文件编码格式不支持,请转换为 UTF-8 编码格式!\n" + else + echo -e "\n Syntax error detected in ventoy.json, please check! \n" + echo -e " ventoy.json 文件中有语法错误,所有配置都不会生效,请检查!\n" + fi + + echo -e "\n press ENTER to continue (请按 回车 键继续) ..." + read vtInputKey +fi + + +for vtTFile in ventoy.json ventoy_grub.cfg; do + if [ -f $vtoy_efi_part/ventoy/$vtTFile ]; then + clear + echo -e "\n You need to put $vtTFile in the 1st partition which hold the ISO files.\n" + echo -e " $vtTFile 放错分区了,请放到镜像分区里的 ventoy 目录下(此目录需要手动创建)!\n" + echo -e "\n press ENTER to continue (请按 回车 键继续) ..." + read vtInputKey + fi +done + +#clear all input key before show main menu +vt_clear_key + +#export necessary variable +export theme +export gfxmode +export gfxpayload +export vtoydev +export vtoy_path +export vtdebug_flag +export vtoy_iso_fs +export vtoy_iso_part +export vtoy_efi_part +export VENTOY_VERSION +export VTOY_CUR_VIDEO_MODE +export VTOY_EFI_ARCH +export VTOY_MEM_DISK_STR +export VTOY_ISO_RAW_STR +export VTOY_GRUB2_MODE_STR +export VTOY_WIMBOOT_MODE_STR +export VTOY_ISO_UEFI_DRV_STR +export VTOY_F2_CMD +export VTOY_F4_CMD +export VTOY_F5_CMD +export VTOY_F6_CMD +export VTOY_HELP_CMD +export VTOY_CHKSUM_CMD +export VTOY_HELP_TXT_LANGUAGE +export VTOY_CHKSUM_FILE_PATH +export VTOY_LANG_CMD + + +#colect all image files (iso files) +set ventoy_img_count=0 +vt_list_img $vtoy_iso_part ventoy_img_count + +#Main menu +if [ $ventoy_img_count -gt 0 ]; then + if [ $VTOY_DEFAULT_MENU_MODE -eq 0 ]; then + vt_dynamic_menu 0 0 + else + vt_dynamic_menu 0 1 + fi +else + if [ -n "$VTOY_NO_ISO_TIP" ]; then + NO_ISO_MENU="No ISO or supported IMG files found, $VTOY_NO_ISO_TIP" + elif [ -n "$VTOY_DEFAULT_SEARCH_ROOT" ]; then + NO_ISO_MENU="No ISO or supported IMG files found, please check VTOY_DEFAULT_SEARCH_ROOT" + else + NO_ISO_MENU="No ISO or supported IMG files found" + fi + menuentry "$NO_ISO_MENU (Press enter to reboot ...)" { + echo -e "\n Rebooting ... " + reboot + } +fi + + +menuentry "Возврат в главное меню Paravis Flash" --id="paravis_return" --class="vtoyret" { + paravis_return +} + +set default="paravis_return" + +#special VTOY_DEFAULT_IMAGE process +if [ -n "$VTOY_DEFAULT_IMAGE" ]; then + if regexp --set 1:vtHotkey --set 2:vtDefault "(F[2-9])>(.*)" "$VTOY_DEFAULT_IMAGE"; then + + set default="$vtDefault" + if [ -z "$VTOY_MENU_TIMEOUT" ]; then + set timeout=0 + else + set timeout=$VTOY_MENU_TIMEOUT + fi + + export timeout + export default + + vt_fn_mutex_lock 1 + + if [ "$vtHotkey" = "F2" ]; then + unset timeout + vt_browser_disk + elif [ "$vtHotkey" = "F4" ]; then + ventoy_localboot + elif [ "$vtHotkey" = "F5" ]; then + ventoy_diagnosis + elif [ "$vtHotkey" = "F6" ]; then + ventoy_ext_menu + fi + + vt_fn_mutex_lock 0 + + unset timeout + unset default + fi +fi + diff --git a/build-scripts/config/VTOYEFI/hwinfo.cfg b/build-scripts/config/VTOYEFI/hwinfo.cfg new file mode 100644 index 0000000..4bb3057 --- /dev/null +++ b/build-scripts/config/VTOYEFI/hwinfo.cfg @@ -0,0 +1,64 @@ +menuentry "$VTLANG_HWINFO" --class=debug_hwinfo --class=F5tool { + smbios -t 4 -s 0x10 --set=cpu_brand + + set system_vendor="-"; + smbios -t 1 -s 0x04 --set=system_vendor; + set system_product="-"; + smbios -t 1 -s 0x05 --set=system_product; + set system_version="-"; + smbios -t 1 -s 0x06 --set=system_version; + + set board_vendor="-"; + smbios -t 2 -s 0x04 --set=board_vendor; + set board_product="-"; + smbios -t 2 -s 0x05 --set=board_product; + set board_version="-"; + smbios -t 2 -s 0x06 --set=board_version; + + set bios_vendor="-"; + smbios -t 0 -s 0x04 --set=bios_vendor; + set bios_version="-"; + smbios -t 0 -s 0x05 --set=bios_ver; + set bios_date="-"; + smbios -t 0 -s 0x08 --set=bios_date; + set bios_size="-"; + smbios -t 0 -b 0x09 --set=bios_size; + + + echo "Platform $grub_cpu-$grub_platform" + if [ "$grub_platform" != "pc" ]; then + echo "UEFI Version $grub_uefi_version" + echo "PI Version $grub_pi_version" + if vt_check_secureboot_var; then + echo "Secure Boot Enabled" + else + echo "Secure Boot Disabled" + fi + + vt_sbinfo + fi + + echo "" + echo "CPU Model $cpu_brand" + echo "Physical RAM $grub_total_ram MB" + + echo "" + echo "Manufacturer $system_vendor" + echo "Product Name $system_product" + echo "Version $system_version" + + echo "" + echo "Board Manufacturer $board_vendor" + echo "Board Name $board_product" + echo "Board Version $board_version" + + echo "" + echo "BIOS Manufacturer $bios_vendor" + echo "BIOS Version $bios_ver" + echo "BIOS Date $bios_date" + echo "BIOS ROM Size $bios_size" + + + echo -en "\n\n\n$VTLANG_ENTER_EXIT ..." + read vtInputKey +} diff --git a/build-scripts/config/VTOYEFI/keyboard.cfg b/build-scripts/config/VTOYEFI/keyboard.cfg new file mode 100644 index 0000000..41caba9 --- /dev/null +++ b/build-scripts/config/VTOYEFI/keyboard.cfg @@ -0,0 +1,62 @@ +submenu "$VTLANG_KEYBRD_LAYOUT" --class=debug_krdlayout --class=F5tool { + menuentry QWERTY_USA --class=debug_kbd --class=debug_krdlayout --class=F5tool { + set_keyboard_layout QWERTY_USA + } + menuentry AZERTY --class=debug_kbd --class=debug_krdlayout --class=F5tool { + set_keyboard_layout AZERTY + } + menuentry CZECH_QWERTY --class=debug_kbd --class=debug_krdlayout --class=F5tool { + set_keyboard_layout CZECH_QWERTY + } + menuentry CZECH_QWERTZ --class=debug_kbd --class=debug_krdlayout --class=F5tool { + set_keyboard_layout CZECH_QWERTZ + } + menuentry DANISH --class=debug_kbd --class=debug_krdlayout --class=F5tool { + set_keyboard_layout DANISH + } + menuentry DVORAK_USA --class=debug_kbd --class=debug_krdlayout --class=F5tool { + set_keyboard_layout DVORAK_USA + } + menuentry FRENCH --class=debug_kbd --class=debug_krdlayout --class=F5tool { + set_keyboard_layout FRENCH + } + menuentry GERMAN --class=debug_kbd --class=debug_krdlayout --class=F5tool { + set_keyboard_layout GERMAN + } + menuentry ITALIANO --class=debug_kbd --class=debug_krdlayout --class=F5tool { + set_keyboard_layout ITALIANO + } + menuentry JAPAN_106 --class=debug_kbd --class=debug_krdlayout --class=F5tool { + set_keyboard_layout JAPAN_106 + } + menuentry LATIN_USA --class=debug_kbd --class=debug_krdlayout --class=F5tool { + set_keyboard_layout LATIN_USA + } + menuentry PORTU_BRAZIL --class=debug_kbd --class=debug_krdlayout --class=F5tool { + set_keyboard_layout PORTU_BRAZIL + } + menuentry QWERTY_UK --class=debug_kbd --class=debug_krdlayout --class=F5tool { + set_keyboard_layout QWERTY_UK + } + menuentry QWERTZ --class=debug_kbd --class=debug_krdlayout --class=F5tool { + set_keyboard_layout QWERTZ + } + menuentry QWERTZ_HUN --class=debug_kbd --class=debug_krdlayout --class=F5tool { + set_keyboard_layout QWERTZ_HUN + } + menuentry QWERTZ_SLOV_CROAT --class=debug_kbd --class=debug_krdlayout --class=F5tool { + set_keyboard_layout QWERTZ_SLOV_CROAT + } + menuentry SPANISH --class=debug_kbd --class=debug_krdlayout --class=F5tool { + set_keyboard_layout SPANISH + } + menuentry SWEDISH --class=debug_kbd --class=debug_krdlayout --class=F5tool { + set_keyboard_layout SWEDISH + } + menuentry TURKISH_Q --class=debug_kbd --class=debug_krdlayout --class=F5tool { + set_keyboard_layout TURKISH_Q + } + menuentry VIETNAMESE --class=debug_kbd --class=debug_krdlayout --class=F5tool { + set_keyboard_layout VIETNAMESE + } +} diff --git a/build-scripts/config/VTOYEFI/localboot.cfg b/build-scripts/config/VTOYEFI/localboot.cfg new file mode 100644 index 0000000..e746f1a --- /dev/null +++ b/build-scripts/config/VTOYEFI/localboot.cfg @@ -0,0 +1,222 @@ + +if [ "$grub_platform" = "pc" ]; then + menuentry "$VTLANG_LB_SBOOT_WINDOWS" --class=boot_windows --class=F4boot { + + set partid=3 + while [ $partid -le 128 ]; do + if vt_check_part_exist $partid; then + for bt in bootmgr BOOTMGR Bootmgr BootMGR; do + if [ -f ($vtoydev,$partid)/$bt ]; then + set root=($vtoydev,$partid) + ntldr /$bt + boot + fi + done + else + break + fi + vt_incr partid 1 + done + + if search -n -s -f /Boot/BCD; then + for bt in bootmgr BOOTMGR Bootmgr BootMGR; do + if [ -f /$bt ]; then + if regexp '^hd0' $root; then + ntldr /$bt + else + drivemap -s hd0 $root + ntldr /$bt + fi + break + fi + done + elif search -n -s -f /NTDETECT.COM; then + drivemap -s hd0 $root + ntldr /ntldr + else + echo "Windows NOT found ..." + fi + } + + menuentry "$VTLANG_LB_SBOOT_G4D" --class=boot_g4d --class=F4boot { + if search -n -s -f /grldr; then + ntldr /grldr + else + echo "Grub4dos NOT found ..." + fi + } + + menuentry "$VTLANG_LB_SBOOT_HDD1" --class=boot_disk --class=F4boot { + set root=(hd0,1) + chainloader +1 + boot + } + + menuentry "$VTLANG_LB_SBOOT_HDD2" --class=boot_disk --class=F4boot { + set root=(hd1,1) + chainloader +1 + boot + } + + menuentry "$VTLANG_LB_SBOOT_HDD3" --class=boot_disk --class=F4boot { + set root=(hd2,1) + chainloader +1 + boot + } + +else + + menuentry "$VTLANG_LB_SBOOT_WINDOWS" --class=boot_windows --class=F4boot { + + set partid=3 + while [ $partid -le 128 ]; do + if vt_check_part_exist $partid; then + if [ -f ($vtoydev,$partid)/EFI/Microsoft/Boot/bootmgfw.efi ]; then + set root=($vtoydev,$partid) + terminal_output console + chainloader /EFI/Microsoft/Boot/bootmgfw.efi + boot + elif [ -f ($vtoydev,$partid)/efi/Microsoft/Boot/bootmgfw.efi ]; then + set root=($vtoydev,$partid) + terminal_output console + chainloader /efi/Microsoft/Boot/bootmgfw.efi + boot + elif [ -f ($vtoydev,$partid)/VTEFI/Microsoft/Boot/bootmgfw.efi ]; then + set root=($vtoydev,$partid) + terminal_output console + chainloader /VTEFI/Microsoft/Boot/bootmgfw.efi + boot + fi + else + break + fi + vt_incr partid 1 + done + + if search -n -s -f /EFI/Microsoft/Boot/bootmgfw.efi; then + terminal_output console + chainloader /EFI/Microsoft/Boot/bootmgfw.efi + boot + elif search -n -s -f /efi/Microsoft/Boot/bootmgfw.efi; then + terminal_output console + chainloader /efi/Microsoft/Boot/bootmgfw.efi + boot + else + echo "Windows NOT found ..." + fi + } + + if [ "$grub_cpu" = "i386" ]; then + menuentry "$VTLANG_LB_SBOOT_IA32EFI" --class=boot_uefi --class=F4boot { + set VTOY_SEARCH_NO_VTOYEFI=1 + if search -n -s -f /efi/boot/bootia32.efi; then + unset VTOY_SEARCH_NO_VTOYEFI + terminal_output console + chainloader /efi/boot/bootia32.efi + boot + elif search -n -s -f /vtefi/boot/bootia32.efi; then + unset VTOY_SEARCH_NO_VTOYEFI + terminal_output console + chainloader /vtefi/boot/bootia32.efi + boot + else + unset VTOY_SEARCH_NO_VTOYEFI + echo "BOOTIA32.EFI NOT found ..." + fi + } + + menuentry "$VTLANG_LB_SBOOT_XORBOOT" --class=boot_xorboot --class=F4boot { + set VTOY_SEARCH_NO_VTOYEFI=1 + if search -n -s -f /efi/xorboot/xorboot32.xor; then + unset VTOY_SEARCH_NO_VTOYEFI + terminal_output console + if [ -f /efi/xorboot/bootia32.efi ]; then + chainloader /efi/xorboot/bootia32.efi + elif [ -f /efi/xorboot/xorboot.efi ]; then + chainloader /efi/xorboot/xorboot.efi + fi + boot + elif search -n -s -f /vtefi/xorboot/xorboot32.xor; then + unset VTOY_SEARCH_NO_VTOYEFI + terminal_output console + if [ -f /vtefi/xorboot/bootia32.efi ]; then + chainloader /vtefi/xorboot/bootia32.efi + elif [ -f /vtefi/xorboot/xorboot.efi ]; then + chainloader /vtefi/xorboot/xorboot.efi + fi + boot + else + unset VTOY_SEARCH_NO_VTOYEFI + echo "xorboot NOT found ..." + fi + } + elif [ "$grub_cpu" = "arm64" ]; then + menuentry "$VTLANG_LB_SBOOT_AA64EFI" --class=boot_uefi --class=F4boot { + set VTOY_SEARCH_NO_VTOYEFI=1 + if search -n -s -f /efi/boot/bootaa64.efi; then + unset VTOY_SEARCH_NO_VTOYEFI + terminal_output console + chainloader /efi/boot/bootaa64.efi + boot + elif search -n -s -f /vtefi/boot/bootaa64.efi; then + unset VTOY_SEARCH_NO_VTOYEFI + terminal_output console + chainloader /vtefi/boot/bootaa64.efi + boot + else + unset VTOY_SEARCH_NO_VTOYEFI + echo "BOOTAA64.EFI NOT found ..." + fi + } + else + menuentry "$VTLANG_LB_SBOOT_X64EFI" --class=boot_uefi --class=F4boot { + set VTOY_SEARCH_NO_VTOYEFI=1 + if search -n -s -f /efi/boot/bootx64.efi; then + unset VTOY_SEARCH_NO_VTOYEFI + terminal_output console + chainloader /efi/boot/bootx64.efi + boot + elif search -n -s -f /vtefi/boot/bootx64.efi; then + unset VTOY_SEARCH_NO_VTOYEFI + terminal_output console + chainloader /vtefi/boot/bootx64.efi + boot + else + unset VTOY_SEARCH_NO_VTOYEFI + echo "BOOTX64.EFI NOT found ..." + fi + } + + menuentry "$VTLANG_LB_SBOOT_XORBOOT" --class=boot_xorboot --class=F4boot { + set VTOY_SEARCH_NO_VTOYEFI=1 + if search -n -s -f /efi/xorboot/xorboot.xor; then + unset VTOY_SEARCH_NO_VTOYEFI + terminal_output console + if [ -f /efi/xorboot/bootx64.efi ]; then + chainloader /efi/xorboot/bootx64.efi + elif [ -f /efi/xorboot/xorboot.efi ]; then + chainloader /efi/xorboot/xorboot.efi + fi + boot + elif search -n -s -f /vtefi/xorboot/xorboot.xor; then + unset VTOY_SEARCH_NO_VTOYEFI + terminal_output console + if [ -f /vtefi/xorboot/bootx64.efi ]; then + chainloader /vtefi/xorboot/bootx64.efi + elif [ -f /vtefi/xorboot/xorboot.efi ]; then + chainloader /vtefi/xorboot/xorboot.efi + fi + boot + else + unset VTOY_SEARCH_NO_VTOYEFI + echo "xorboot NOT found ..." + fi + } + fi + + +fi + +menuentry "$VTLANG_RETURN_PREVIOUS" --class=vtoyret VTOY_RET { + echo "Return ..." +} diff --git a/build-scripts/config/VTOYEFI/menulang.cfg b/build-scripts/config/VTOYEFI/menulang.cfg new file mode 100644 index 0000000..a03e663 --- /dev/null +++ b/build-scripts/config/VTOYEFI/menulang.cfg @@ -0,0 +1,94 @@ +#ventoy_pack.sh will generate menuentry here +menuentry "zh_CN - Chinese Simplified (简体中文)" --class=menu_lang_item --class=debug_menu_lang --class=F5tool { + vt_load_menu_lang zh_CN +} +menuentry "ar_AR - Arabic (العربية)" --class=menu_lang_item --class=debug_menu_lang --class=F5tool { + vt_load_menu_lang ar_AR +} +menuentry "bn_BN - Bengali (বাংলা)" --class=menu_lang_item --class=debug_menu_lang --class=F5tool { + vt_load_menu_lang bn_BN +} +menuentry "cs_CZ - Czech (Čeština)" --class=menu_lang_item --class=debug_menu_lang --class=F5tool { + vt_load_menu_lang cs_CZ +} +menuentry "de_DE - German (Deutsch)" --class=menu_lang_item --class=debug_menu_lang --class=F5tool { + vt_load_menu_lang de_DE +} +menuentry "el_GR - Greek (Ελληνικά)" --class=menu_lang_item --class=debug_menu_lang --class=F5tool { + vt_load_menu_lang el_GR +} +menuentry "en_US - English (English)" --class=menu_lang_item --class=debug_menu_lang --class=F5tool { + vt_load_menu_lang en_US +} +menuentry "es_ES - Spanish (Español)" --class=menu_lang_item --class=debug_menu_lang --class=F5tool { + vt_load_menu_lang es_ES +} +menuentry "fa_IR - Persian (فارسی)" --class=menu_lang_item --class=debug_menu_lang --class=F5tool { + vt_load_menu_lang fa_IR +} +menuentry "fr_FR - French (Français)" --class=menu_lang_item --class=debug_menu_lang --class=F5tool { + vt_load_menu_lang fr_FR +} +menuentry "hi_HI - Hindi (हिन्दी)" --class=menu_lang_item --class=debug_menu_lang --class=F5tool { + vt_load_menu_lang hi_HI +} +menuentry "hr_HR - Croatian (Hrvatski)" --class=menu_lang_item --class=debug_menu_lang --class=F5tool { + vt_load_menu_lang hr_HR +} +menuentry "hu_HU - Magyar (Hungarian)" --class=menu_lang_item --class=debug_menu_lang --class=F5tool { + vt_load_menu_lang hu_HU +} +menuentry "id_ID - Indonesian (Bahasa Indonesia)" --class=menu_lang_item --class=debug_menu_lang --class=F5tool { + vt_load_menu_lang id_ID +} +menuentry "it_IT - Italiano (Italian)" --class=menu_lang_item --class=debug_menu_lang --class=F5tool { + vt_load_menu_lang it_IT +} +menuentry "ja_JP - Japanese (日本語)" --class=menu_lang_item --class=debug_menu_lang --class=F5tool { + vt_load_menu_lang ja_JP +} +menuentry "ka_GE - Georgian (ქართული)" --class=menu_lang_item --class=debug_menu_lang --class=F5tool { + vt_load_menu_lang ka_GE +} +menuentry "ko_KR - Korean (한국어)" --class=menu_lang_item --class=debug_menu_lang --class=F5tool { + vt_load_menu_lang ko_KR +} +menuentry "lg_UG - English (English)" --class=menu_lang_item --class=debug_menu_lang --class=F5tool { + vt_load_menu_lang lg_UG +} +menuentry "pl_PL - Polish (Poland)" --class=menu_lang_item --class=debug_menu_lang --class=F5tool { + vt_load_menu_lang pl_PL +} +menuentry "pt_BR - Brazilian Portuguese (Portugues Brasileiro)" --class=menu_lang_item --class=debug_menu_lang --class=F5tool { + vt_load_menu_lang pt_BR +} +menuentry "pt_PT - Portuguese (Português de Portugal)" --class=menu_lang_item --class=debug_menu_lang --class=F5tool { + vt_load_menu_lang pt_PT +} +menuentry "ru_RU - Russian (Русский)" --class=menu_lang_item --class=debug_menu_lang --class=F5tool { + vt_load_menu_lang ru_RU +} +menuentry "sl_SI - Slovenija (Slovenski)" --class=menu_lang_item --class=debug_menu_lang --class=F5tool { + vt_load_menu_lang sl_SI +} +menuentry "sr_RS - Serbian Latin (Srpski)" --class=menu_lang_item --class=debug_menu_lang --class=F5tool { + vt_load_menu_lang sr_RS +} +menuentry "ta_IN - Tamil (தமிழ்)" --class=menu_lang_item --class=debug_menu_lang --class=F5tool { + vt_load_menu_lang ta_IN +} +menuentry "tr_TR - Turkish (Türkçe)" --class=menu_lang_item --class=debug_menu_lang --class=F5tool { + vt_load_menu_lang tr_TR +} +menuentry "uk_UA - Ukrainian (Українська)" --class=menu_lang_item --class=debug_menu_lang --class=F5tool { + vt_load_menu_lang uk_UA +} +menuentry "vi_VN - Vietnamese (Tiếng Việt)" --class=menu_lang_item --class=debug_menu_lang --class=F5tool { + vt_load_menu_lang vi_VN +} +menuentry "zh_TW - Chinese Traditional (正體中文)" --class=menu_lang_item --class=debug_menu_lang --class=F5tool { + vt_load_menu_lang zh_TW +} +menuentry "$VTLANG_RETURN_PREVIOUS" --class=vtoyret VTOY_RET { + echo "Return ..." +} diff --git a/build-scripts/config/VTOYEFI/power.cfg b/build-scripts/config/VTOYEFI/power.cfg new file mode 100644 index 0000000..293151c --- /dev/null +++ b/build-scripts/config/VTOYEFI/power.cfg @@ -0,0 +1,25 @@ +submenu "$VTLANG_POWER" --class=debug_power --class=F5tool { + menuentry "$VTLANG_POWER_REBOOT" --class=debug_reboot --class=debug_power --class=F5tool { + echo -e '\n\nSystem is rebooting ... \n' + sleep 1 + reboot + } + + menuentry "$VTLANG_POWER_HALT" --class=debug_halt --class=debug_power --class=F5tool { + echo -e '\n\nSystem is halting ... \n' + sleep 1 + halt + } + + if [ "$grub_platform" != "pc" ]; then + menuentry "$VTLANG_POWER_BOOT_EFIFW" --class=debug_efisetup --class=debug_power --class=F5tool { + echo -e '\n\nRebooting to enter UEFI firmware setup ... \n' + sleep 1 + fwsetup + } + fi + + menuentry "$VTLANG_RETURN_PREVIOUS" --class=vtoyret VTOY_RET { + echo "Return ..." + } +} diff --git a/build-scripts/config/ventoy_grub-f7.cfg b/build-scripts/config/ventoy_grub-f7.cfg new file mode 100644 index 0000000..6bbc241 --- /dev/null +++ b/build-scripts/config/ventoy_grub-f7.cfg @@ -0,0 +1,17 @@ +menuentry "Возврат в главное меню сборки [F7]" --hotkey=f7 --class=vtoyret { + if [ "$grub_platform" = "efi" ]; then + search --no-floppy --file --set=root /efi/Paravis/Boot/grub2/grub.cfg + if [ "$grub_cpu" = "x86_64" ]; then + chainloader /efi/Paravis/Boot/grub2/grubx64.efi + else + chainloader /EFI/Boot/bootia32.efi + fi + else + chainloader (${vtoydev})+1 + fi + boot +} + +menuentry "← Назад в меню Ventoy [Esc]" --class=vtoyret VTOY_RET { + echo "Return ..." +} diff --git a/build-scripts/config/ventoy_grub.cfg b/build-scripts/config/ventoy_grub.cfg new file mode 100644 index 0000000..301f827 --- /dev/null +++ b/build-scripts/config/ventoy_grub.cfg @@ -0,0 +1,3 @@ +menuentry "← Назад в меню Ventoy [Esc]" --class=vtoyret VTOY_RET { + echo "Return ..." +} diff --git a/build-scripts/experiments/build-arm64-a.sh b/build-scripts/experiments/build-arm64-a.sh new file mode 100644 index 0000000..612e24e --- /dev/null +++ b/build-scripts/experiments/build-arm64-a.sh @@ -0,0 +1,50 @@ +#!/bin/bash +set -e + +echo "=== install cross compiler" +apt-get install -y gcc-aarch64-linux-gnu binutils-aarch64-linux-gnu >/tmp/apt_aarch64.log 2>&1 +which aarch64-linux-gnu-gcc + +ROOT=/root/vtbuild-arm64 +SRC=$ROOT/GRUB2/SRC/grub-2.04 +rm -rf $ROOT +mkdir -p $ROOT/GRUB2/SRC +cp -a /root/vtbuild-efi/GRUB2/SRC/grub-2.04 $SRC + +cd $SRC +make distclean >/tmp/arm_distclean.log 2>&1 || true +echo "=== configure aarch64-efi" +./configure --prefix=$ROOT/GRUB2/INSTALL/ \ + --target=aarch64 --with-platform=efi \ + --host=x86_64-linux-gnu \ + HOST_CC=x86_64-linux-gnu-gcc BUILD_CC=gcc \ + TARGET_CC=aarch64-linux-gnu-gcc \ + TARGET_OBJCOPY=aarch64-linux-gnu-objcopy \ + TARGET_STRIP=aarch64-linux-gnu-strip \ + TARGET_NM=aarch64-linux-gnu-nm \ + TARGET_RANLIB=aarch64-linux-gnu-ranlib \ + --disable-werror CFLAGS="-Os" >/tmp/arm_configure.log 2>&1 + +echo "=== make" +make -j16 >/tmp/arm_make.log 2>&1 +echo "=== install" +make install >/tmp/arm_install.log 2>&1 + +LIB=$ROOT/GRUB2/INSTALL/lib/grub/arm64-efi +echo "=== lib: $(ls $LIB | wc -l) files" + +echo "=== extract official aarch64 modules" +mkdir -p /tmp/efimods_arm +python3 /path/to/pf/Ventoy/extract-efi-mods.py /path/to/pf/Ventoy/tmp_arm/BOOTAA64.EFI /tmp/efimods_arm \ + crypto gcry_crc gcry_sha1 gcry_sha256 gcry_md5 gcry_sha512 gzio 2>&1 | tail -10 + +for m in crypto gcry_crc gcry_sha1 gcry_md5 gcry_sha512 gzio; do + [ -f /tmp/efimods_arm/$m.mod ] && cp -f /tmp/efimods_arm/$m.mod "$LIB/$m.mod" +done +[ -f /tmp/efimods_arm/gcry_sha256.mod ] && cp -f /tmp/efimods_arm/gcry_sha256.mod "$LIB/gcry_sha256.mod" + +echo "=== classes:" +for m in crypto gcry_crc gcry_sha1 gcry_sha256 gcry_md5 gcry_sha512 gzio ventoy; do + f="$LIB/$m.mod" + if [ -f "$f" ]; then printf " %-12s %s\n" "$m" "$(readelf -h "$f" | awk '/Class:/{print $2}')"; else echo " $m MISSING"; fi +done diff --git a/build-scripts/experiments/build-arm64-c.sh b/build-scripts/experiments/build-arm64-c.sh new file mode 100644 index 0000000..77c4f19 --- /dev/null +++ b/build-scripts/experiments/build-arm64-c.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -e +ROOT=/root/vtbuild-arm64 +SRC=$ROOT/GRUB2/SRC/grub-2.04 +LIB=$ROOT/GRUB2/INSTALL/lib/grub/arm64-efi +cd "$SRC" + +rm -f "$LIB/gcry_sha256.mod" +net_modules_uefi="efinet net tftp http" +arm64_modules=$(sed -n 's/^all_modules_arm64_uefi="\(.*\)"$/\1/p' install.sh) +mods="crypto gcry_crc gcry_sha1 gcry_md5 gcry_sha512" +for m in $net_modules_uefi $arm64_modules; do + [ "$m" = "gcry_sha256" ] && continue + case " $mods " in *" $m "*) ;; *) mods="$mods $m" ;; esac +done +echo "modules: $(echo $mods | wc -w)" + +echo "--- machines of crypto modules:" +for m in crypto gcry_crc gcry_sha1 gcry_md5 gcry_sha512 gzio ventoy; do + printf " %-12s %s\n" "$m" "$(readelf -h "$LIB/$m.mod" | awk -F: '/Machine:/{print $2}')" +done + +./grub-mkimage -O arm64-efi -o /tmp/BOOTAA64_new.EFI -p '(,2)/grub' -d "$LIB" --compression auto $mods +echo "image: $(stat -c %s /tmp/BOOTAA64_new.EFI)" +file /tmp/BOOTAA64_new.EFI +for s in '(,2)/grub' 'VTOY_DATA_PART_IDX' 'ISO/Ventoy/ventoy.json'; do + echo " $s : $(grep -c -a -F "$s" /tmp/BOOTAA64_new.EFI)" +done diff --git a/build-scripts/experiments/build-sg2d-all.sh b/build-scripts/experiments/build-sg2d-all.sh new file mode 100644 index 0000000..40ed50c --- /dev/null +++ b/build-scripts/experiments/build-sg2d-all.sh @@ -0,0 +1,73 @@ +#!/bin/bash +# Super GRUB2: Russian + "Detect and show boot methods" as default (by menuentry id). +# Builds x64.efi / x86.efi (signed) and super.iso -> D:/PF2026/super +set -e +K=/path/to/pf/Ventoy/keys +OUT=/path/to/pf/super +W=/root/sg2dwork +rm -rf "$W"; mkdir -p "$W" "$OUT" +cp -a /root/sg2d/. "$W/sg2d/" +cd "$W/sg2d" + +echo "=== patch menus" +python3 - <<'EOF' +import io +# 1) Russian language in the top-level config +p = 'menus/grub.cfg' +s = io.open(p, encoding='utf-8').read() +if 'set lang=ru' not in s: + s = s.replace('insmod datehook\n', 'insmod datehook\n\nset lang=ru\nexport lang\n', 1) + io.open(p, 'w', encoding='utf-8').write(s) + print(' grub.cfg: lang=ru') + +# 2) default entry = "Detect and show boot methods" (id-based, immune to index shifts) +p = 'menus/sgd/main.cfg' +s = io.open(p, encoding='utf-8').read() +old_block = '''if [ "$sb_vendor" = "" ] ; then + set default=2 +else + set default=3 +fi''' +if old_block in s: + s = s.replace(old_block, 'set default=detect', 1) + print(' main.cfg: default=detect') +else: + print(' main.cfg: default block not found (already patched?)') + +old_entry = 'menuentry $"Detect and show boot methods" {' +if old_entry in s: + s = s.replace(old_entry, 'menuentry $"Detect and show boot methods" --id=detect {', 1) + print(' main.cfg: --id=detect') +else: + print(' main.cfg: detect entry not found (already patched?)') +io.open(p, 'w', encoding='utf-8').write(s) +EOF +grep -n 'set default' menus/sgd/main.cfg | head -3 +grep -n 'id=detect' menus/sgd/main.cfg | head -3 + +apt-get install -y grub-common grub-pc-bin grub-efi-amd64-bin grub-efi-ia32-bin mtools xorriso gettext unifont >/tmp/apt8.log 2>&1 || true + +echo "=== build x86_64 EFI" +./supergrub-mkstandalone -O=x86_64-efi -o="$W/super-x64.efi" \ + --grub-mkstandalone-binary=/usr/bin/grub-mkstandalone \ + --grub-mkfont-binary=/usr/bin/grub-mkfont >/tmp/sg_x64.log 2>&1 || { tail -8 /tmp/sg_x64.log; exit 1; } +ls -l "$W/super-x64.efi" + +echo "=== build i386 EFI" +./supergrub-mkstandalone -O=i386-efi -o="$W/super-x86.efi" \ + --grub-mkstandalone-binary=/usr/bin/grub-mkstandalone \ + --grub-mkfont-binary=/usr/bin/grub-mkfont >/tmp/sg_x86.log 2>&1 || { tail -8 /tmp/sg_x86.log; exit 1; } +ls -l "$W/super-x86.efi" + +echo "=== sign" +sbsign --key "$K/ventoy.key" --cert "$K/ventoy.crt" --output "$OUT/x64.efi" "$W/super-x64.efi" +sbsign --key "$K/ventoy.key" --cert "$K/ventoy.crt" --output "$OUT/x86.efi" "$W/super-x86.efi" +sbverify --cert "$K/ventoy.crt" "$OUT/x64.efi" +sbverify --cert "$K/ventoy.crt" "$OUT/x86.efi" + +echo "=== build ISO" +./supergrub-mkrescue -o="$W/super.iso" \ + --grub-mkrescue-binary=/usr/bin/grub-mkrescue \ + --grub-mkfont-binary=/usr/bin/grub-mkfont >/tmp/sg_iso.log 2>&1 || { tail -12 /tmp/sg_iso.log; exit 1; } +cp -f "$W/super.iso" "$OUT/super.iso" +ls -l "$OUT" diff --git a/build-scripts/experiments/build-sg2d-ru.sh b/build-scripts/experiments/build-sg2d-ru.sh new file mode 100644 index 0000000..67b170f --- /dev/null +++ b/build-scripts/experiments/build-sg2d-ru.sh @@ -0,0 +1,35 @@ +#!/bin/bash +set -e +echo "=== deps" +apt-get install -y grub-common grub-efi-amd64-bin gettext unifont >/tmp/apt_sg2d.log 2>&1 || true +which grub-mkstandalone grub-mkfont msgfmt +ls /usr/lib/grub/x86_64-efi/*.mod >/dev/null && echo " modules ok" + +cd /tmp/sg2d +echo "=== patch default language -> ru" +python3 - <<'EOF' +import io +p='menus/grub.cfg' +s=io.open(p, encoding='utf-8').read() +if 'set lang=ru' not in s: + marker='insmod datehook\n' + s=s.replace(marker, marker+'\n# Paravis: default language\nset lang=ru\nexport lang\n',1) + io.open(p,'w',encoding='utf-8').write(s) + print(' patched menus/grub.cfg') +else: + print(' already patched') +EOF +grep -n -A3 'Paravis' menus/grub.cfg + +echo "=== build standalone EFI" +rm -f /tmp/sg2d_ru.efi +./supergrub-mkstandalone -O=x86_64-efi -o=/tmp/sg2d_ru.efi \ + --grub-mkstandalone-binary=/usr/bin/grub-mkstandalone \ + --grub-mkfont-binary=/usr/bin/grub-mkfont 2>&1 | tail -15 || true + +if [ -f /tmp/sg2d_ru.efi ]; then + ls -l /tmp/sg2d_ru.efi + file /tmp/sg2d_ru.efi +else + echo " !! build failed" +fi diff --git a/build-scripts/experiments/check-iso-memtest.sh b/build-scripts/experiments/check-iso-memtest.sh new file mode 100644 index 0000000..31a234f --- /dev/null +++ b/build-scripts/experiments/check-iso-memtest.sh @@ -0,0 +1,26 @@ +#!/bin/bash +echo "=== how grubfm boots a generic ISO (UEFI):" +find /tmp/gfm/boot/grubfm/rules/iso -name '*.sh' -o -name '*.lua' 2>/dev/null | head +for f in /tmp/gfm/boot/grubfm/rules/iso/*.sh; do + echo "--- $f"; sed -n '1,40p' "$f"; echo +done 2>/dev/null | head -80 + +echo +echo "=== memtest binaries:" +python3 - <<'EOF' +import struct +for p in ('/mnt/f/EFI/Boot/memtest.efi','/mnt/f/EFI/Boot/mtest32.efi', + '/mnt/f/efi/Paravis/Boot/mem/memtest64.efi','/mnt/f/efi/Paravis/Boot/mem/memtest32.efi'): + try: + d=open(p,'rb').read() + except Exception as e: + print(p, 'ERR', e); continue + pe=struct.unpack_from('/dev/null +python3 - <<'EOF' +import struct, glob +for p in sorted(glob.glob('/tmp/kchk/*.dat')): + d = open(p, 'rb').read() + if d[0x1FE:0x1FF] == b'\x00': + pass + setup_sects = d[0x1FE] + xload = struct.unpack_from('/dev/null 2>&1 && sig=OK + sbat=$(python3 - "$dst" <<'EOF' +import struct,sys +d=open(sys.argv[1],'rb').read() +try: + pe=struct.unpack_from('/dev/null || true +for f in old.exe new.exe; do + echo "== $f" + icotool -l "$f" 2>/dev/null | sed 's/^/ /' | head -10 +done diff --git a/build-scripts/experiments/cmp-icons2.sh b/build-scripts/experiments/cmp-icons2.sh new file mode 100644 index 0000000..ca1b69a --- /dev/null +++ b/build-scripts/experiments/cmp-icons2.sh @@ -0,0 +1,12 @@ +#!/bin/bash +cd /tmp/icmp || exit 1 +for f in old.exe new.exe; do + echo "== $f" + if [ -f "$f" ]; then + wrestool -l "$f" 2>/dev/null | grep -E 'type=14|type=3' | sed 's/^/ /' | head -12 + printf ' icon images: ' + wrestool -l "$f" 2>/dev/null | grep -c 'type=3' + else + echo " (missing)" + fi +done diff --git a/build-scripts/experiments/cmp-icons3.sh b/build-scripts/experiments/cmp-icons3.sh new file mode 100644 index 0000000..3ac7773 --- /dev/null +++ b/build-scripts/experiments/cmp-icons3.sh @@ -0,0 +1,14 @@ +#!/bin/bash +W=/root/icmp +rm -rf "$W"; mkdir -p "$W"; cd "$W" +cp -f "/mnt/f/Change_bootLoader.exe" new.exe +cp -f "/path/to/pf/Change_bootloader/Change_bootLoader.old-3.0.1.exe" old.exe +for f in old.exe new.exe; do + echo "== $f" + if [ ! -f "$f" ]; then echo " missing"; continue; fi + printf ' icon groups (type=14): ' + wrestool -l "$f" 2>/dev/null | grep -c 'type=14' || true + printf ' icon images (type=3): ' + wrestool -l "$f" 2>/dev/null | grep -c 'type=3' || true + wrestool -l "$f" 2>/dev/null | grep 'type=3' | head -6 | sed 's/^/ /' +done diff --git a/build-scripts/experiments/deploy-menu.sh b/build-scripts/experiments/deploy-menu.sh new file mode 100644 index 0000000..52fcf0e --- /dev/null +++ b/build-scripts/experiments/deploy-menu.sh @@ -0,0 +1,23 @@ +#!/bin/bash +set -e +K=/path/to/pf/Ventoy/keys +D=/path/to/pf/ParavisGrub +G=/mnt/f/efi/Paravis/Boot/grub2 + +echo "=== 1. memtest86+ 9.10 (built from git) -> signed" +if [ -f /tmp/mt86p/build/x86_64/mt86plus ]; then + cp -f /tmp/mt86p/build/x86_64/mt86plus /tmp/mt86p/mt86plus.efi + sbsign --key "$K/ventoy.key" --cert "$K/ventoy.crt" --output "$G/apps/memtest86p.efi" /tmp/mt86p/mt86plus.efi >/dev/null + sbverify --cert "$K/ventoy.crt" "$G/apps/memtest86p.efi" + ls -l "$G/apps/memtest86p.efi" +else + echo " !! build missing" +fi +rm -f "$G/apps/memtest86.efi" + +echo "=== 2. generate menu files" +python3 "$D/gen_menu.py" "$D" +cp -f "$D/grub.cfg" "$G/grub.cfg" +mkdir -p "$G/menu" +cp -f "$D"/menu/*.cfg "$G/menu/" +ls -l "$G" "$G/menu" "$G/apps" diff --git a/build-scripts/experiments/deploy-paravis-grub.sh b/build-scripts/experiments/deploy-paravis-grub.sh new file mode 100644 index 0000000..aa46561 --- /dev/null +++ b/build-scripts/experiments/deploy-paravis-grub.sh @@ -0,0 +1,31 @@ +#!/bin/bash +set -e +K=/path/to/pf/Ventoy/keys +G=/path/to/pf/ParavisGrub +D=/mnt/f/efi/Paravis/Boot/grub2 +APPS="$D/apps" +mkdir -p "$APPS" + +echo "=== grub core" +cp -f "$G/grubx64.efi" "$D/grubx64.efi" + +echo "=== sign helper EFI apps for chainloading under Secure Boot" +sign_app() { + local src="$1" dst="$2" + rm -f /tmp/a.efi /tmp/a2.efi + python3 /path/to/pf/Ventoy/add-sbat.py "$src" /tmp/a.efi >/dev/null + if sbattach --detach /tmp/old.p7 /tmp/a.efi >/dev/null 2>&1; then sbattach --remove /tmp/a.efi; fi + sbsign --key "$K/ventoy.key" --cert "$K/ventoy.crt" --output /tmp/a2.efi /tmp/a.efi >/dev/null + sbverify --cert "$K/ventoy.crt" /tmp/a2.efi >/dev/null + cp -f /tmp/a2.efi "$dst" + printf " %-16s %s\n" "$(basename "$dst")" "$(stat -c %s "$dst")" +} +sign_app /mnt/f/efi/Paravis/Boot/super/x64.efi "$APPS/super.efi" +sign_app /mnt/f/efi/Paravis/Boot/gfm/x64.efi "$APPS/gfm.efi" +sign_app /mnt/f/EFI/Boot/memtest.efi "$APPS/memtest.efi" + +echo "=== font (for later theme)" +cp -f /path/to/pf/Ventoy/vtoyefi/grub/fonts/unicode.pf2 "$D/unicode.pf2" + +echo "=== done, tree:" +ls -l "$D" "$APPS" diff --git a/build-scripts/experiments/dump-iso-cfg.sh b/build-scripts/experiments/dump-iso-cfg.sh new file mode 100644 index 0000000..e7d3687 --- /dev/null +++ b/build-scripts/experiments/dump-iso-cfg.sh @@ -0,0 +1,7 @@ +#!/bin/bash +for f in ADD ABA; do + echo "== $f /boot/grub/grub.cfg" + 7z e -y -o/tmp/cfgchk "/mnt/f/efi/Paravis/Utilities/$f" 'boot/grub/grub.cfg' >/dev/null 2>&1 + sed 's/^/ /' /tmp/cfgchk/grub.cfg 2>/dev/null + rm -f /tmp/cfgchk/grub.cfg +done diff --git a/build-scripts/experiments/fetch-cb.sh b/build-scripts/experiments/fetch-cb.sh new file mode 100644 index 0000000..4211d83 --- /dev/null +++ b/build-scripts/experiments/fetch-cb.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -e +OUT=/path/to/pf/Change_bootloader +rm -rf /tmp/cb /tmp/cb.tgz +mkdir -p /tmp/cb "$OUT" +curl -sSL --max-time 180 "https://git.paravis.ru/Paravis_Flash/Change_bootloader/archive/master.tar.gz" -o /tmp/cb.tgz +tar -xzf /tmp/cb.tgz -C /tmp/cb +echo "--- repo files:" +find /tmp/cb -type f -printf '%P %s\n' | sort +echo "--- copying to $OUT" +cp -r /tmp/cb/change_bootloader/. "$OUT"/ +ls -la "$OUT" diff --git a/build-scripts/experiments/find-src.sh b/build-scripts/experiments/find-src.sh new file mode 100644 index 0000000..d01ad1f --- /dev/null +++ b/build-scripts/experiments/find-src.sh @@ -0,0 +1,6 @@ +#!/bin/bash +echo "=== PSD 2023:" +find "/mnt/d/NEED/my_project/PSD 2023" -maxdepth 3 | head -40 +echo +echo "=== кандидаты-шрифты в vcpkg:" +ls /mnt/d/GIT/aspia_no2fa-3.0/vcpkg4aspia/buildtrees/harfbuzz/src/*/test/subset/data/fonts/ 2>/dev/null | grep -iE 'roboto|notosans|sourcesans|ubuntu|opensans|inter' | head -20 diff --git a/build-scripts/experiments/fix-menu.sh b/build-scripts/experiments/fix-menu.sh new file mode 100644 index 0000000..0f3e0cb --- /dev/null +++ b/build-scripts/experiments/fix-menu.sh @@ -0,0 +1,18 @@ +#!/bin/bash +set -e +K=/path/to/pf/Ventoy/keys +G=/mnt/f/efi/Paravis/Boot/grub2 + +echo "=== PassMark MemTest86 (memtest.org) -> signed copy, NO .sbat" +cp -f /mnt/f/EFI/Boot/memtest.efi /tmp/mt.efi +sbsign --key "$K/ventoy.key" --cert "$K/ventoy.crt" --output "$G/apps/memtest86.efi" /tmp/mt.efi >/dev/null +sbverify --cert "$K/ventoy.crt" "$G/apps/memtest86.efi" +ls -l "$G/apps/memtest86.efi" +rm -f "$G/apps/memtest86p.efi" "$G/apps/memtest.efi" + +echo "=== regenerate menu" +sed -i 's|apps/memtest86p.efi|apps/memtest86.efi|' /path/to/pf/ParavisGrub/gen_menu.py +python3 /path/to/pf/ParavisGrub/gen_menu.py > /path/to/pf/ParavisGrub/grub.cfg +cp -f /path/to/pf/ParavisGrub/grub.cfg "$G/grub.cfg" +echo "--- key lines:" +grep -nE 'subdir=|live-media-path=|Возврат|memtest|map --type' /path/to/pf/ParavisGrub/grub.cfg diff --git a/build-scripts/experiments/g2-inspect.sh b/build-scripts/experiments/g2-inspect.sh new file mode 100644 index 0000000..bf1b7e6 --- /dev/null +++ b/build-scripts/experiments/g2-inspect.sh @@ -0,0 +1,21 @@ +#!/bin/bash +# persist the a1ive grub tree on D: and inspect wimboot/ntboot usage +set -e +SRC=/tmp/g2/grub +OUT=/path/to/pf/grub2-a1ive +if [ -d "$SRC" ]; then + echo "--- copying release tree to $OUT" + rm -rf "$OUT"; mkdir -p "$OUT" + cp -a "$SRC" "$OUT/grub" +fi +G="$OUT/grub" +ls "$G" | head + +for m in wimboot ntboot chain linux; do + echo "=== $m.mod" + if [ -f "$G/x86_64-efi/$m.mod" ]; then + strings -a -n 4 "$G/x86_64-efi/$m.mod" | head -40 + else + echo " (no such module)" + fi +done diff --git a/build-scripts/experiments/g2-wimboot-strings.sh b/build-scripts/experiments/g2-wimboot-strings.sh new file mode 100644 index 0000000..d853600 --- /dev/null +++ b/build-scripts/experiments/g2-wimboot-strings.sh @@ -0,0 +1,10 @@ +#!/bin/bash +G=/path/to/pf/grub2-a1ive/grub +echo "=== wimboot.mod readable strings:" +strings -a -n 6 "$G/x86_64-efi/wimboot.mod" | grep -avE '^[A-Za-z0-9_]{0,5}$' | head -60 +echo +echo "=== full moddep entries for wimboot/ntboot:" +grep -aE '^wimboot|^ntboot' "$G/x86_64-efi/moddep.lst" 2>/dev/null +echo +echo "=== command.lst:" +grep -aE 'wimboot|ntboot' "$G/x86_64-efi/command.lst" 2>/dev/null diff --git a/build-scripts/experiments/g4d-around.py b/build-scripts/experiments/g4d-around.py new file mode 100644 index 0000000..195efab --- /dev/null +++ b/build-scripts/experiments/g4d-around.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 +import sys, re + +def around(path, needle, before=300, after=700): + d = open(path, 'rb').read() + i = d.find(needle) + if i < 0: + print(' (not found)') + return + chunk = d[max(0, i-before): i+after] + txt = re.sub(rb'[^\x09\x0a\x0d\x20-\x7e]+', b'\n', chunk).decode('latin1') + for line in txt.splitlines(): + line = line.strip() + if line: + print(' ', line) + +for path, needle in ( + ('/mnt/f/efi/Paravis/Boot/g4d/antiv', b'/efi/Paravis/KRD'), + ('/mnt/f/efi/Paravis/Boot/g4d/acroDD', b'/efi/Paravis/Utilities/ADD'), + ('/mnt/f/efi/Paravis/Boot/g4d/acroBA', b'/efi/Paravis/Utilities/ABA'), + ('/mnt/f/efi/Paravis/Boot/g4d/phdm', b'/efi/Paravis/Utilities/phdm.krn'), + ('/mnt/f/efi/Paravis/Boot/g4d/mint64r', b'/efi/Paravis/Linux/x64/vmlinuz'), +): + print('=====================', path.split('/')[-1]) + around(path, needle) + print() diff --git a/build-scripts/experiments/g4d-dump.sh b/build-scripts/experiments/g4d-dump.sh new file mode 100644 index 0000000..336f160 --- /dev/null +++ b/build-scripts/experiments/g4d-dump.sh @@ -0,0 +1,11 @@ +#!/bin/bash +D=/mnt/f/efi/Paravis/Boot/g4d +for f in mint64r mint64i phdm acroDD acroBA antiv Ventoy super mt dart linux; do + p="$D/$f" + [ -f "$p" ] || continue + echo "===================== $f" + echo "--- ascii hits:" + strings -a -n 5 "$p" | grep -aiE 'vmlinuz|initrd|squash|casper|k-x86|\.srm|kaspersky|acronis|paragon|phdm|memtest|ventoy|\.wim|\.iso|/efi|efi/|chainloader|ntboot|wimboot|bootmgr' | head -20 + echo "--- utf16 hits:" + strings -a -e l -n 5 "$p" | grep -aiE 'vmlinuz|initrd|squash|casper|k-x86|\.srm|kaspersky|acronis|paragon|phdm|memtest|ventoy|\.wim|\.iso|/efi|efi/|chainloader|ntboot|bootmgr' | head -20 +done diff --git a/build-scripts/experiments/g4d-krd.sh b/build-scripts/experiments/g4d-krd.sh new file mode 100644 index 0000000..3649962 --- /dev/null +++ b/build-scripts/experiments/g4d-krd.sh @@ -0,0 +1,13 @@ +#!/bin/bash +D=/mnt/f/efi/Paravis/Boot/g4d +echo "=== antiv (KRD) full menu lines:" +strings -a -n 4 "$D/antiv" | grep -aiE 'krd|kernel|initrd|srm|ksl|base|root|lang|:' | grep -aivE 'initrd_start|Create INITRD|Linux kernel must|initrd \[@name|initrdfs' | head -25 +echo +echo "=== acroDD map/menu lines:" +strings -a -n 4 "$D/acroDD" | grep -aiE 'map|iso=|chainloader|root|find' | grep -aivE 'table not recognized|map %s|initrd' | head -20 +echo +echo "=== ISO magic check (offset 0x8001):" +for f in ADD ABA; do + printf " %-6s " "$f" + dd if="$D/../Utilities/$f" bs=1 skip=32769 count=5 2>/dev/null | od -c | head -1 +done diff --git a/build-scripts/experiments/g4d-menu.sh b/build-scripts/experiments/g4d-menu.sh new file mode 100644 index 0000000..08d220d --- /dev/null +++ b/build-scripts/experiments/g4d-menu.sh @@ -0,0 +1,7 @@ +#!/bin/bash +D=/mnt/f/efi/Paravis/Boot/g4d +for f in acroDD acroBA antiv util str nix off gfm UBCD mt super Ventoy dart; do + p="$D/$f"; [ -f "$p" ] || continue + echo "===================== $f" + strings -a -n 4 "$p" | grep -aE '^(set |map |kernel |initrd |chainloader|find |root |checkrange|default |title |if |echo |ls |cat )' | head -30 +done diff --git a/build-scripts/experiments/g4d-raw.py b/build-scripts/experiments/g4d-raw.py new file mode 100644 index 0000000..9606428 --- /dev/null +++ b/build-scripts/experiments/g4d-raw.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 +import sys, re + +def dump_menu(path, needle=b'set ', span=1200): + d = open(path, 'rb').read() + i = d.find(needle) + if i < 0: + print(' (no marker)') + return + chunk = d[max(0, i-200): i+span] + txt = re.sub(rb'[^\x09\x0a\x0d\x20-\x7e]+', b'\n', chunk).decode('latin1') + for line in txt.splitlines(): + line = line.strip() + if line: + print(' ', line) + +for path in sys.argv[1:]: + print('=====================', path.split('/')[-1]) + dump_menu(path) + print() + +print('=== ISO magic at 0x8001:') +for p in ('/mnt/f/efi/Paravis/Utilities/ADD', '/mnt/f/efi/Paravis/Utilities/ABA'): + with open(p, 'rb') as f: + f.seek(32769); b = f.read(8) + print(' %-4s %r' % (p.split('/')[-1], b)) diff --git a/build-scripts/experiments/get-a1ive-grub.sh b/build-scripts/experiments/get-a1ive-grub.sh new file mode 100644 index 0000000..ecef8ad --- /dev/null +++ b/build-scripts/experiments/get-a1ive-grub.sh @@ -0,0 +1,15 @@ +#!/bin/bash +set -e +OUT=/path/to/pf/grub2-a1ive +rm -rf "$OUT" /tmp/g2; mkdir -p "$OUT" /tmp/g2 +curl -sSL --max-time 600 "https://github.com/a1ive/grub/releases/download/latest/grub2-latest.tar.gz" -o /tmp/g2.tgz +echo "size: $(stat -c %s /tmp/g2.tgz)" +file /tmp/g2.tgz +tar -xzf /tmp/g2.tgz -C /tmp/g2 +echo "=== top level:" +find /tmp/g2 -maxdepth 2 -type d | head -20 +echo "=== efi builds:" +find /tmp/g2 -maxdepth 2 -iname '*x86_64*' -o -maxdepth 2 -iname '*efi*' | head -20 +echo "=== grub-mkimage / .mod presence:" +find /tmp/g2 -name 'grub-mkimage*' | head -5 +find /tmp/g2 -name 'wimboot.mod' -o -name 'ntboot.mod' | head -5 diff --git a/build-scripts/experiments/get-a1ive-src.sh b/build-scripts/experiments/get-a1ive-src.sh new file mode 100644 index 0000000..9f98cb1 --- /dev/null +++ b/build-scripts/experiments/get-a1ive-src.sh @@ -0,0 +1,13 @@ +#!/bin/bash +set -e +cd /tmp +rm -rf ag ag.tgz +curl -sSL --max-time 600 "https://github.com/a1ive/grub/archive/refs/heads/master.tar.gz" -o ag.tgz +echo "size: $(stat -c %s ag.tgz)" +tar -xzf ag.tgz +D=$(find /tmp -maxdepth 1 -type d -name 'grub-*' | head -1) +echo "src dir: $D" +echo "=== wimboot command definition:" +grep -rn 'grub_register_extcmd.*wimboot\|"wimboot"' "$D/grub-core" | head -10 +echo "=== files:" +find "$D/grub-core" -name '*wimboot*' -o -name '*wim*' | head -20 diff --git a/build-scripts/experiments/get-grub-fontc.sh b/build-scripts/experiments/get-grub-fontc.sh new file mode 100644 index 0000000..38ee563 --- /dev/null +++ b/build-scripts/experiments/get-grub-fontc.sh @@ -0,0 +1,8 @@ +#!/bin/bash +cd /tmp +rm -f font.c +curl -sSL --max-time 120 "https://raw.githubusercontent.com/rhboot/grub2/master/grub-core/font/font.c" -o font.c || true +[ -s font.c ] || curl -sSL --max-time 120 "https://git.savannah.gnu.org/cgit/grub.git/plain/grub-core/font/font.c" -o font.c +echo "size: $(stat -c %s font.c)" +echo "=== CHIX / DATA parsing:" +grep -n -A25 'CHIX' font.c | head -60 diff --git a/build-scripts/experiments/gfm-examples.sh b/build-scripts/experiments/gfm-examples.sh new file mode 100644 index 0000000..bd03cf1 --- /dev/null +++ b/build-scripts/experiments/gfm-examples.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -e +cd /tmp +rm -rf gfm gfm.tgz +curl -sSL --max-time 300 "https://github.com/a1ive/grub2-filemanager/archive/refs/heads/master.tar.gz" -o gfm.tgz +mkdir -p gfm && tar -xzf gfm.tgz -C gfm --strip-components=1 +echo "=== ntboot usages:" +grep -rn 'ntboot' gfm --include='*.cfg' --include='*.lua' --include='*.sh' | head -15 +echo "=== wimboot usages:" +grep -rn 'wimboot' gfm --include='*.cfg' --include='*.lua' | head -15 +echo "=== efi chain examples:" +grep -rn 'chainloader' gfm --include='*.cfg' --include='*.lua' | head -10 diff --git a/build-scripts/experiments/gh-check.sh b/build-scripts/experiments/gh-check.sh new file mode 100644 index 0000000..7ca1696 --- /dev/null +++ b/build-scripts/experiments/gh-check.sh @@ -0,0 +1,9 @@ +#!/bin/bash +for repo in a1ive/grub2-filemanager a1ive/grub; do + echo "=== $repo" + curl -sL --max-time 60 "https://api.github.com/repos/$repo/releases/latest" \ + | python3 -c "import sys,json; +d=json.load(sys.stdin) +print('tag:', d.get('tag_name'), '|', d.get('name')) +for a in d.get('assets',[]): print(' ', a['name'], a['size'], a['browser_download_url'])" 2>&1 | head -20 +done diff --git a/build-scripts/experiments/gh-memtest.sh b/build-scripts/experiments/gh-memtest.sh new file mode 100644 index 0000000..c04578e --- /dev/null +++ b/build-scripts/experiments/gh-memtest.sh @@ -0,0 +1,9 @@ +#!/bin/bash +curl -sL --max-time 60 "https://api.github.com/repos/memtest86plus/memtest86plus/releases/latest" \ + | python3 -c " +import sys,json +d=json.load(sys.stdin) +print('tag:', d.get('tag_name')) +for a in d.get('assets',[]): + print(' %-40s %10d %s' % (a['name'], a['size'], a['browser_download_url'])) +" diff --git a/build-scripts/experiments/gh-memtest2.sh b/build-scripts/experiments/gh-memtest2.sh new file mode 100644 index 0000000..8db1fdf --- /dev/null +++ b/build-scripts/experiments/gh-memtest2.sh @@ -0,0 +1,18 @@ +#!/bin/bash +echo "=== releases (with assets):" +curl -sL --max-time 60 "https://api.github.com/repos/memtest86plus/memtest86plus/releases?per_page=10" \ + | python3 -c " +import sys,json +for r in json.load(sys.stdin): + print('tag:', r.get('tag_name'), '| assets:', len(r.get('assets',[]))) + for a in r.get('assets',[]): + print(' %-44s %10d' % (a['name'], a['size'])) + print() +" +echo "=== repo tree (top):" +curl -sL --max-time 60 "https://api.github.com/repos/memtest86plus/memtest86plus/contents/" \ + | python3 -c " +import sys,json +for e in json.load(sys.stdin): + print(' %-30s %s' % (e['name'], e['type'])) +" diff --git a/build-scripts/experiments/gh-sg2d.sh b/build-scripts/experiments/gh-sg2d.sh new file mode 100644 index 0000000..ebeeac9 --- /dev/null +++ b/build-scripts/experiments/gh-sg2d.sh @@ -0,0 +1,13 @@ +#!/bin/bash +echo "=== supergrub releases:" +curl -sL --max-time 60 "https://api.github.com/repos/supergrub/supergrub/releases?per_page=5" \ + | python3 -c " +import sys,json +for r in json.load(sys.stdin): + print('tag:', r.get('tag_name'), '|', r.get('name')) + for a in r.get('assets',[]): + print(' %-52s %10d' % (a['name'], a['size'])) + print() +" +echo "=== ventoy language handling in grub.cfg:" +grep -n 'lang' /path/to/pf/Ventoy/vtoyefi/grub/grub.cfg | head -25 diff --git a/build-scripts/experiments/grub-theme-src.sh b/build-scripts/experiments/grub-theme-src.sh new file mode 100644 index 0000000..ea9e4f7 --- /dev/null +++ b/build-scripts/experiments/grub-theme-src.sh @@ -0,0 +1,12 @@ +#!/bin/bash +cd /tmp +for f in grub-core/gfxmenu/gui_progress_bar.c grub-core/gfxmenu/gui_label.c grub-core/gfxmenu/gui_circular_progress.c grub-core/gfxmenu/view.c grub-core/font/font.c; do + out=$(echo "$f" | tr '/' '_') + [ -s "$out" ] || curl -sSL --max-time 120 "https://raw.githubusercontent.com/rhboot/grub2/master/$f" -o "$out" || true +done +echo "=== __timeout__ usage:" +grep -n '__timeout__\|timeout' grub-core_gfxmenu_gui_progress_bar.c grub-core_gfxmenu_view.c 2>/dev/null | head -20 +echo "=== label text handling:" +grep -n 'text\|@' grub-core_gfxmenu_gui_label.c | head -30 +echo "=== antialias in font.c:" +grep -in 'antialias\|alpha\|8-bit' grub-core_font_font.c | head -10 diff --git a/build-scripts/experiments/inspect-initrd.sh b/build-scripts/experiments/inspect-initrd.sh new file mode 100644 index 0000000..ebccc8a --- /dev/null +++ b/build-scripts/experiments/inspect-initrd.sh @@ -0,0 +1,26 @@ +#!/bin/bash +W=/tmp/insp +rm -rf "$W"; mkdir -p "$W" + +echo "=== memtest.efi:" +python3 - <<'EOF' +import struct +d=open('/mnt/f/EFI/Boot/memtest.efi','rb').read() +pe=struct.unpack_from(' krd.cpio 2>/dev/null || cp /mnt/f/efi/Paravis/KRD/initrd.xz krd.cpio +file krd.cpio +mkdir -p krd && ( cd krd && cpio -idm --quiet < ../krd.cpio 2>/dev/null || true ) +ls krd | head -20 +echo "--- init (first 80 lines):" +sed -n '1,80p' krd/init 2>/dev/null diff --git a/build-scripts/experiments/inspect-psd-acr.sh b/build-scripts/experiments/inspect-psd-acr.sh new file mode 100644 index 0000000..c956a12 --- /dev/null +++ b/build-scripts/experiments/inspect-psd-acr.sh @@ -0,0 +1,23 @@ +#!/bin/bash +set -e +echo "=== deps" +apt-get install -y python3-pip python3-venv >/tmp/apt_pip.log 2>&1 || true +python3 -m pip install --quiet --break-system-packages psd-tools 2>/dev/null || true + +echo "=== PSD layers (UEFI x64 main)" +python3 - <<'EOF' +from psd_tools import PSDImage +p = PSDImage.open('/path/to/pf/PSD/UEFI/x64/main/main.psd') +print('canvas: %dx%d mode=%s' % (p.width, p.height, p.color_mode)) +for i, l in enumerate(p): + print(' %2d %-28s type=%-10s vis=%-5s bbox=%-24s op=%s' % ( + i, (l.name or '')[:28], l.kind, l.visible, str(l.bbox), l.opacity)) +EOF + +echo +echo "=== Acronis 2024 ISO" +ISO=/path/to/pf/acronis/Acronis_Boot_Disk_2024.iso +ls -l "$ISO" +xorriso -indev "$ISO" -report_el_torito plain 2>&1 | grep -E 'El Torito|Boot record|Volume id' | head -12 +echo "--- EFI boot files:" +7z l -ba "$ISO" 2>/dev/null | grep -iE 'efi/boot/|bootx64|bootia32|shim|grub' | head -20 diff --git a/build-scripts/experiments/iso-el-torito.sh b/build-scripts/experiments/iso-el-torito.sh new file mode 100644 index 0000000..153fd85 --- /dev/null +++ b/build-scripts/experiments/iso-el-torito.sh @@ -0,0 +1,7 @@ +#!/bin/bash +for iso in /mnt/f/efi/Paravis/Utilities/ADD /mnt/f/efi/Paravis/Utilities/ABA; do + echo "===================== $(basename "$iso")" + xorriso -indev "$iso" -report_el_torito as_mkisofs 2>&1 | sed -n '1,40p' + echo "--- boot images:" + xorriso -indev "$iso" -report_el_torito plain 2>&1 | grep -iE 'El Torito|Boot record|boot image|platform|efi' | head -20 +done diff --git a/build-scripts/experiments/kernel-ver.sh b/build-scripts/experiments/kernel-ver.sh new file mode 100644 index 0000000..bb0a83f --- /dev/null +++ b/build-scripts/experiments/kernel-ver.sh @@ -0,0 +1,36 @@ +#!/bin/bash +# Identify kernels by decompressing the bzImage payload and grepping "Linux version" +python3 - <<'EOF' +import glob, gzip, io, lzma, os, re, struct, zlib + +def payload(d): + ss = d[0x1FE] or 4 + return d[(ss + 1) * 512:] + +def try_decompress(b): + for name, fn in (('gzip', lambda x: gzip.decompress(x)), + ('xz', lambda x: lzma.decompress(x)), + ('zlib', lambda x: zlib.decompress(x))): + try: + return fn(b), name + except Exception: + pass + return None, None + +paths = [] +for pat in ('ATI2025/dat10.dat', 'ATI2025/dat2.dat', 'ADDH12/dat14.dat', 'ADDH12/dat10.dat'): + paths.append('/path/to/pf/acronis/acr/ACR/' + pat) + +for p in paths: + if not os.path.exists(p): + print(p, 'missing'); continue + d = open(p, 'rb').read() + body = payload(d) + out, kind = try_decompress(body) + ver = '?' + if out: + m = re.search(rb'Linux version ([0-9][^ \x00]{0,40})', out[:6_000_000]) + if m: + ver = m.group(1).decode('latin1') + print('%-42s %-6s %s' % (p.split('ACR/')[-1], kind or 'raw', ver)) +EOF diff --git a/build-scripts/experiments/ls-iso.sh b/build-scripts/experiments/ls-iso.sh new file mode 100644 index 0000000..47c7786 --- /dev/null +++ b/build-scripts/experiments/ls-iso.sh @@ -0,0 +1,6 @@ +#!/bin/bash +ISO=/mnt/f/efi/Paravis/Utilities/ADD +echo "=== all entries:" +7z l -ba "$ISO" 2>/dev/null | awk '{print $NF}' | head -30 +echo "=== xorriso listing:" +xorriso -indev "$ISO" -find / 2>/dev/null | head -30 diff --git a/build-scripts/experiments/ppm-k18.sh b/build-scripts/experiments/ppm-k18.sh new file mode 100644 index 0000000..9cbb314 --- /dev/null +++ b/build-scripts/experiments/ppm-k18.sh @@ -0,0 +1,20 @@ +#!/bin/bash +python3 - <<'EOF' +import zlib, struct +src='/tmp/k18a.ppm'; dst='/path/to/pf/KRD/krd18-test.png' +d = open(src, 'rb').read() +parts = []; i = 0 +while len(parts) < 4: + while d[i:i+1].isspace(): i += 1 + j = i + while not d[j:j+1].isspace(): j += 1 + parts.append(d[i:j]); i = j +i += 1 +w=int(parts[1]); h=int(parts[2]); px=d[i:i+w*h*3] +raw=b''.join(b'\x00'+px[y*w*3:(y+1)*w*3] for y in range(h)) +def ch(t,dd): + c=t+dd + return struct.pack('>I',len(dd))+c+struct.pack('>I',zlib.crc32(c)&0xffffffff) +png=b'\x89PNG\r\n\x1a\n'+ch(b'IHDR',struct.pack('>IIBBBBB',w,h,8,2,0,0,0))+ch(b'IDAT',zlib.compress(raw,9))+ch(b'IEND',b'') +open(dst,'wb').write(png); print(dst,w,h) +EOF diff --git a/build-scripts/experiments/ppm-k32.sh b/build-scripts/experiments/ppm-k32.sh new file mode 100644 index 0000000..fd94122 --- /dev/null +++ b/build-scripts/experiments/ppm-k32.sh @@ -0,0 +1,20 @@ +#!/bin/bash +python3 - <<'EOF' +import zlib, struct +src='/tmp/k32.ppm'; dst='/path/to/pf/KRD/xor32-krd-direct.png' +d = open(src, 'rb').read() +parts = []; i = 0 +while len(parts) < 4: + while d[i:i+1].isspace(): i += 1 + j = i + while not d[j:j+1].isspace(): j += 1 + parts.append(d[i:j]); i = j +i += 1 +w=int(parts[1]); h=int(parts[2]); px=d[i:i+w*h*3] +raw=b''.join(b'\x00'+px[y*w*3:(y+1)*w*3] for y in range(h)) +def ch(t,dd): + c=t+dd + return struct.pack('>I',len(dd))+c+struct.pack('>I',zlib.crc32(c)&0xffffffff) +png=b'\x89PNG\r\n\x1a\n'+ch(b'IHDR',struct.pack('>IIBBBBB',w,h,8,2,0,0,0))+ch(b'IDAT',zlib.compress(raw,9))+ch(b'IEND',b'') +open(dst,'wb').write(png); print(dst,w,h) +EOF diff --git a/build-scripts/experiments/ppm-k32b.sh b/build-scripts/experiments/ppm-k32b.sh new file mode 100644 index 0000000..9e52301 --- /dev/null +++ b/build-scripts/experiments/ppm-k32b.sh @@ -0,0 +1,20 @@ +#!/bin/bash +python3 - <<'EOF' +import zlib, struct +src='/tmp/k32b.ppm'; dst='/path/to/pf/KRD/xor32-krd-direct2.png' +d = open(src, 'rb').read() +parts = []; i = 0 +while len(parts) < 4: + while d[i:i+1].isspace(): i += 1 + j = i + while not d[j:j+1].isspace(): j += 1 + parts.append(d[i:j]); i = j +i += 1 +w=int(parts[1]); h=int(parts[2]); px=d[i:i+w*h*3] +raw=b''.join(b'\x00'+px[y*w*3:(y+1)*w*3] for y in range(h)) +def ch(t,dd): + c=t+dd + return struct.pack('>I',len(dd))+c+struct.pack('>I',zlib.crc32(c)&0xffffffff) +png=b'\x89PNG\r\n\x1a\n'+ch(b'IHDR',struct.pack('>IIBBBBB',w,h,8,2,0,0,0))+ch(b'IDAT',zlib.compress(raw,9))+ch(b'IEND',b'') +open(dst,'wb').write(png); print(dst,w,h) +EOF diff --git a/build-scripts/experiments/ppm-k32c.sh b/build-scripts/experiments/ppm-k32c.sh new file mode 100644 index 0000000..7d45195 --- /dev/null +++ b/build-scripts/experiments/ppm-k32c.sh @@ -0,0 +1,20 @@ +#!/bin/bash +python3 - <<'EOF' +import zlib, struct +src='/tmp/k32b.ppm'; dst='/path/to/pf/KRD/xor32-krd-text.png' +d = open(src, 'rb').read() +parts = []; i = 0 +while len(parts) < 4: + while d[i:i+1].isspace(): i += 1 + j = i + while not d[j:j+1].isspace(): j += 1 + parts.append(d[i:j]); i = j +i += 1 +w=int(parts[1]); h=int(parts[2]); px=d[i:i+w*h*3] +raw=b''.join(b'\x00'+px[y*w*3:(y+1)*w*3] for y in range(h)) +def ch(t,dd): + c=t+dd + return struct.pack('>I',len(dd))+c+struct.pack('>I',zlib.crc32(c)&0xffffffff) +png=b'\x89PNG\r\n\x1a\n'+ch(b'IHDR',struct.pack('>IIBBBBB',w,h,8,2,0,0,0))+ch(b'IDAT',zlib.compress(raw,9))+ch(b'IEND',b'') +open(dst,'wb').write(png); print(dst,w,h) +EOF diff --git a/build-scripts/experiments/ppm-k32v.sh b/build-scripts/experiments/ppm-k32v.sh new file mode 100644 index 0000000..d1b2e09 --- /dev/null +++ b/build-scripts/experiments/ppm-k32v.sh @@ -0,0 +1,20 @@ +#!/bin/bash +python3 - <<'EOF' +import zlib, struct +src='/tmp/k32b.ppm'; dst='/path/to/pf/KRD/xor32-krd-video.png' +d = open(src, 'rb').read() +parts = []; i = 0 +while len(parts) < 4: + while d[i:i+1].isspace(): i += 1 + j = i + while not d[j:j+1].isspace(): j += 1 + parts.append(d[i:j]); i = j +i += 1 +w=int(parts[1]); h=int(parts[2]); px=d[i:i+w*h*3] +raw=b''.join(b'\x00'+px[y*w*3:(y+1)*w*3] for y in range(h)) +def ch(t,dd): + c=t+dd + return struct.pack('>I',len(dd))+c+struct.pack('>I',zlib.crc32(c)&0xffffffff) +png=b'\x89PNG\r\n\x1a\n'+ch(b'IHDR',struct.pack('>IIBBBBB',w,h,8,2,0,0,0))+ch(b'IDAT',zlib.compress(raw,9))+ch(b'IEND',b'') +open(dst,'wb').write(png); print(dst,w,h) +EOF diff --git a/build-scripts/experiments/ppm-k64.sh b/build-scripts/experiments/ppm-k64.sh new file mode 100644 index 0000000..1e07a58 --- /dev/null +++ b/build-scripts/experiments/ppm-k64.sh @@ -0,0 +1,20 @@ +#!/bin/bash +python3 - <<'EOF' +import zlib, struct +src='/tmp/k64a.ppm'; dst='/path/to/pf/KRD/krd64-test.png' +d = open(src, 'rb').read() +parts = []; i = 0 +while len(parts) < 4: + while d[i:i+1].isspace(): i += 1 + j = i + while not d[j:j+1].isspace(): j += 1 + parts.append(d[i:j]); i = j +i += 1 +w=int(parts[1]); h=int(parts[2]); px=d[i:i+w*h*3] +raw=b''.join(b'\x00'+px[y*w*3:(y+1)*w*3] for y in range(h)) +def ch(t,dd): + c=t+dd + return struct.pack('>I',len(dd))+c+struct.pack('>I',zlib.crc32(c)&0xffffffff) +png=b'\x89PNG\r\n\x1a\n'+ch(b'IHDR',struct.pack('>IIBBBBB',w,h,8,2,0,0,0))+ch(b'IDAT',zlib.compress(raw,9))+ch(b'IEND',b'') +open(dst,'wb').write(png); print(dst,w,h) +EOF diff --git a/build-scripts/experiments/ppm-x32.sh b/build-scripts/experiments/ppm-x32.sh new file mode 100644 index 0000000..863a932 --- /dev/null +++ b/build-scripts/experiments/ppm-x32.sh @@ -0,0 +1,22 @@ +#!/bin/bash +python3 - <<'EOF' +import zlib, struct +def ppm2png(src, dst): + d = open(src, 'rb').read() + parts = []; i = 0 + while len(parts) < 4: + while d[i:i+1].isspace(): i += 1 + j = i + while not d[j:j+1].isspace(): j += 1 + parts.append(d[i:j]); i = j + i += 1 + w = int(parts[1]); h = int(parts[2]); px = d[i:i+w*h*3] + raw = b''.join(b'\x00' + px[y*w*3:(y+1)*w*3] for y in range(h)) + def chunk(t, dd): + c = t + dd + return struct.pack('>I', len(dd)) + c + struct.pack('>I', zlib.crc32(c) & 0xffffffff) + png = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', w, h, 8, 2, 0, 0, 0)) + chunk(b'IDAT', zlib.compress(raw, 9)) + chunk(b'IEND', b'') + open(dst, 'wb').write(png) + print(dst, w, h) +ppm2png('/tmp/x32-krd.ppm', '/path/to/pf/KRD/xor32-krd.png') +EOF diff --git a/build-scripts/experiments/ppm-xnk.sh b/build-scripts/experiments/ppm-xnk.sh new file mode 100644 index 0000000..8319604 --- /dev/null +++ b/build-scripts/experiments/ppm-xnk.sh @@ -0,0 +1,20 @@ +#!/bin/bash +python3 - <<'EOF' +import zlib, struct +src='/tmp/xnk.ppm'; dst='/path/to/pf/KRD/x86nokrd.png' +d = open(src, 'rb').read() +parts = []; i = 0 +while len(parts) < 4: + while d[i:i+1].isspace(): i += 1 + j = i + while not d[j:j+1].isspace(): j += 1 + parts.append(d[i:j]); i = j +i += 1 +w=int(parts[1]); h=int(parts[2]); px=d[i:i+w*h*3] +raw=b''.join(b'\x00'+px[y*w*3:(y+1)*w*3] for y in range(h)) +def ch(t,dd): + c=t+dd + return struct.pack('>I',len(dd))+c+struct.pack('>I',zlib.crc32(c)&0xffffffff) +png=b'\x89PNG\r\n\x1a\n'+ch(b'IHDR',struct.pack('>IIBBBBB',w,h,8,2,0,0,0))+ch(b'IDAT',zlib.compress(raw,9))+ch(b'IEND',b'') +open(dst,'wb').write(png); print(dst,w,h) +EOF diff --git a/build-scripts/experiments/ppm-xnk2.sh b/build-scripts/experiments/ppm-xnk2.sh new file mode 100644 index 0000000..08b02ec --- /dev/null +++ b/build-scripts/experiments/ppm-xnk2.sh @@ -0,0 +1,20 @@ +#!/bin/bash +python3 - <<'EOF' +import zlib, struct +src='/tmp/xnk2.ppm'; dst='/path/to/pf/KRD/x86nokrd-nav.png' +d = open(src, 'rb').read() +parts = []; i = 0 +while len(parts) < 4: + while d[i:i+1].isspace(): i += 1 + j = i + while not d[j:j+1].isspace(): j += 1 + parts.append(d[i:j]); i = j +i += 1 +w=int(parts[1]); h=int(parts[2]); px=d[i:i+w*h*3] +raw=b''.join(b'\x00'+px[y*w*3:(y+1)*w*3] for y in range(h)) +def ch(t,dd): + c=t+dd + return struct.pack('>I',len(dd))+c+struct.pack('>I',zlib.crc32(c)&0xffffffff) +png=b'\x89PNG\r\n\x1a\n'+ch(b'IHDR',struct.pack('>IIBBBBB',w,h,8,2,0,0,0))+ch(b'IDAT',zlib.compress(raw,9))+ch(b'IEND',b'') +open(dst,'wb').write(png); print(dst,w,h) +EOF diff --git a/build-scripts/experiments/ppm2png-qx.sh b/build-scripts/experiments/ppm2png-qx.sh new file mode 100644 index 0000000..ab0fa1b --- /dev/null +++ b/build-scripts/experiments/ppm2png-qx.sh @@ -0,0 +1,22 @@ +#!/bin/bash +python3 - <<'EOF' +import zlib, struct +def ppm2png(src, dst): + d = open(src, 'rb').read() + parts = []; i = 0 + while len(parts) < 4: + while d[i:i+1].isspace(): i += 1 + j = i + while not d[j:j+1].isspace(): j += 1 + parts.append(d[i:j]); i = j + i += 1 + w = int(parts[1]); h = int(parts[2]); px = d[i:i+w*h*3] + raw = b''.join(b'\x00' + px[y*w*3:(y+1)*w*3] for y in range(h)) + def chunk(t, dd): + c = t + dd + return struct.pack('>I', len(dd)) + c + struct.pack('>I', zlib.crc32(c) & 0xffffffff) + png = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', w, h, 8, 2, 0, 0, 0)) + chunk(b'IDAT', zlib.compress(raw, 9)) + chunk(b'IEND', b'') + open(dst, 'wb').write(png) + print(dst, w, h) +ppm2png('/tmp/qx2.ppm', '/path/to/pf/KRD/xor-uefi-1.png') +EOF diff --git a/build-scripts/experiments/ppm2png3.sh b/build-scripts/experiments/ppm2png3.sh new file mode 100644 index 0000000..bc83576 --- /dev/null +++ b/build-scripts/experiments/ppm2png3.sh @@ -0,0 +1,22 @@ +#!/bin/bash +python3 - <<'EOF' +import zlib, struct +def ppm2png(src, dst): + d = open(src, 'rb').read() + parts = []; i = 0 + while len(parts) < 4: + while d[i:i+1].isspace(): i += 1 + j = i + while not d[j:j+1].isspace(): j += 1 + parts.append(d[i:j]); i = j + i += 1 + w = int(parts[1]); h = int(parts[2]); px = d[i:i+w*h*3] + raw = b''.join(b'\x00' + px[y*w*3:(y+1)*w*3] for y in range(h)) + def chunk(t, dd): + c = t + dd + return struct.pack('>I', len(dd)) + c + struct.pack('>I', zlib.crc32(c) & 0xffffffff) + png = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', w, h, 8, 2, 0, 0, 0)) + chunk(b'IDAT', zlib.compress(raw, 9)) + chunk(b'IEND', b'') + open(dst, 'wb').write(png) + print(dst, w, h) +ppm2png('/tmp/qx3.ppm', '/path/to/pf/KRD/xor-uefi-3.png') +EOF diff --git a/build-scripts/experiments/test-arm64.sh b/build-scripts/experiments/test-arm64.sh new file mode 100644 index 0000000..611ec15 --- /dev/null +++ b/build-scripts/experiments/test-arm64.sh @@ -0,0 +1,37 @@ +#!/bin/bash +set -e +W=/tmp/armtest +rm -rf $W && mkdir -p $W && cd $W + +dd if=/dev/zero of=p1.img bs=1M count=48 status=none +dd if=/dev/zero of=p2.img bs=1M count=128 status=none +mkfs.vfat -F 32 -n ESP p1.img >/dev/null +mkfs.vfat -F 32 -n GRUB p2.img >/dev/null + +mkdir -p t1/EFI/BOOT +cp /path/to/pf/Ventoy/grubia32.efi.signed /dev/null 2>/dev/null || true +cp "$(ls -1 /path/to/pf/Ventoy/BOOTAA64* 2>/dev/null | head -1)" t1/EFI/BOOT/BOOTAA64.EFI 2>/dev/null || true +if [ ! -f t1/EFI/BOOT/BOOTAA64.EFI ]; then + echo "no BOOTAA64 source; abort" + exit 1 +fi +mcopy -i p1.img -s t1/EFI ::/ + +mkdir -p t2 +cp -a /path/to/pf/Ventoy/vtoyefi/grub t2/grub +printf 'echo HELLO-ARM64-OK\nsleep 5\n' > t2/grub/grub.cfg +mcopy -i p2.img -s t2/grub ::/ + +dd if=/dev/zero of=disk.img bs=1M count=192 status=none +parted -s disk.img mklabel msdos +parted -s disk.img mkpart primary fat32 1MiB 49MiB +parted -s disk.img mkpart primary fat32 49MiB 177MiB +parted -s disk.img set 1 boot on +dd if=p1.img of=disk.img bs=1M seek=1 conv=notrunc status=none +dd if=p2.img of=disk.img bs=1M seek=49 conv=notrunc status=none + +echo "=== boot aarch64:" +timeout 60 qemu-system-aarch64 -M virt -cpu cortex-a57 -m 1024 -nographic -no-reboot \ + -bios /usr/share/qemu-efi-aarch64/QEMU_EFI.fd \ + -drive file=disk.img,format=raw,if=none,id=hd0 \ + -device virtio-blk-device,drive=hd0 2>&1 | tail -30 diff --git a/build-scripts/experiments/verify-deployed.sh b/build-scripts/experiments/verify-deployed.sh new file mode 100644 index 0000000..c37861d --- /dev/null +++ b/build-scripts/experiments/verify-deployed.sh @@ -0,0 +1,13 @@ +#!/bin/bash +C=/path/to/pf/Ventoy/keys/ventoy.crt +echo "=== deployed files on p1:" +for f in /mnt/f/EFI/Boot/fbx64.efi /mnt/f/EFI/Boot/bootx64.efi /mnt/f/efi/Paravis/Boot/xor/UEFI/bootx64.efi; do + printf '%-46s ' "${f#/mnt/f/}" + if sbverify --cert "$C" "$f" >/dev/null 2>&1; then echo "our signature OK"; else echo "FAIL"; fi +done +echo +echo "=== sha256 (deployed vs staging):" +sha256sum /mnt/f/EFI/Boot/fbx64.efi /path/to/pf/Ventoy/xorboot/fbx64-xor.efi +echo +echo "=== cert: subject / key usage / basic constraints / validity" +openssl x509 -in "$C" -noout -subject -dates -ext keyUsage,extendedKeyUsage,basicConstraints diff --git a/build-scripts/experiments/verify-fat12.sh b/build-scripts/experiments/verify-fat12.sh new file mode 100644 index 0000000..fb7bd56 --- /dev/null +++ b/build-scripts/experiments/verify-fat12.sh @@ -0,0 +1,8 @@ +#!/bin/bash +for f in ADD ABA; do + rm -f /tmp/e.img + xorriso -osirrox on -indev "/mnt/f/efi/Paravis/Utilities/$f" -extract /efi.img /tmp/e.img >/dev/null 2>&1 + printf ' %-4s %-28s ' "$f" "$(file -b /tmp/e.img)" + mdir -i /tmp/e.img ::/EFI/BOOT 2>/dev/null | grep -oE 'BOOT(IA32|X64) +EFI' | tr '\n' ' ' + echo +done diff --git a/build-scripts/experiments/verify-tree.sh b/build-scripts/experiments/verify-tree.sh new file mode 100644 index 0000000..49a50a0 --- /dev/null +++ b/build-scripts/experiments/verify-tree.sh @@ -0,0 +1,6 @@ +#!/bin/bash +for f in ADD ABA; do + printf ' %-4s tree: ' "$f" + 7z l -ba "/mnt/f/efi/Paravis/Utilities/$f" 2>/dev/null | grep -oE 'EFI/BOOT/BOOT(IA32|X64)\.EFI' | tr '\n' ' ' + echo +done diff --git a/build-scripts/experiments/verify-xor.sh b/build-scripts/experiments/verify-xor.sh new file mode 100644 index 0000000..76d2f74 --- /dev/null +++ b/build-scripts/experiments/verify-xor.sh @@ -0,0 +1,6 @@ +#!/bin/bash +C=/path/to/pf/Ventoy/keys/ventoy.crt +for f in /mnt/f/efi/Paravis/Boot/gfm/x86.efi /mnt/f/efi/Paravis/Boot/super/x86.efi /mnt/f/efi/Paravis/Boot/gfm/x64.efi /mnt/f/efi/Paravis/Boot/super/x64.efi; do + printf '%-46s ' "${f#/mnt/f/}" + if sbverify --cert "$C" "$f" >/dev/null 2>&1; then echo OK; else echo FAIL; fi +done diff --git a/build-scripts/integration/acronis/acr-menulst.sh b/build-scripts/integration/acronis/acr-menulst.sh new file mode 100644 index 0000000..d2afe99 --- /dev/null +++ b/build-scripts/integration/acronis/acr-menulst.sh @@ -0,0 +1,7 @@ +#!/bin/bash +SRC=/path/to/pf/acronis/Acronis_Boot_Disk_2024.iso +W=/tmp/menulst +rm -rf $W; mkdir -p $W +7z e -y -o$W "$SRC" 'boot/grub/menu.lst' 'boot/grub/grub.cfg' >/dev/null 2>&1 +echo "=== ATI2025 / ADDH12 / ACPH entries in menu.lst:" +grep -n -i -A6 -E 'ATI2025|ADDH12|ACPH|True Image 2025|Disk Director' $W/menu.lst | head -80 diff --git a/build-scripts/integration/acronis/acr2024-inspect.sh b/build-scripts/integration/acronis/acr2024-inspect.sh new file mode 100644 index 0000000..e0d1c2b --- /dev/null +++ b/build-scripts/integration/acronis/acr2024-inspect.sh @@ -0,0 +1,22 @@ +#!/bin/bash +ISO=/path/to/pf/acronis/Acronis_Boot_Disk_2024.iso +W=/tmp/acr +rm -rf $W; mkdir -p $W + +echo "=== top level:" +7z l -ba "$ISO" 2>/dev/null | awk '{print $NF}' | cut -d/ -f1 | sort -u | head -20 + +echo "=== ACR products:" +7z l -ba "$ISO" 2>/dev/null | awk '{print $NF}' | grep -i '^ACR/' | cut -d/ -f1-2 | sort -u | head -40 + +echo "=== boot/grub/grub.cfg:" +7z e -y -o$W "$ISO" 'boot/grub/grub.cfg' >/dev/null 2>&1 +sed -n '1,120p' $W/grub.cfg 2>/dev/null + +echo "=== efi loaders:" +7z e -y -o$W "$ISO" 'efi/boot/bootx64.efi' 'efi/boot/grubx64.efi' >/dev/null 2>&1 +ls -l $W/*.efi 2>/dev/null +for f in $W/*.efi; do + printf ' %-14s ' "$(basename "$f")" + sbverify --list "$f" 2>/dev/null | tr '\n' ' ' | cut -c1-140; echo +done diff --git a/build-scripts/integration/acronis/acr2024-more.sh b/build-scripts/integration/acronis/acr2024-more.sh new file mode 100644 index 0000000..75a8fe9 --- /dev/null +++ b/build-scripts/integration/acronis/acr2024-more.sh @@ -0,0 +1,14 @@ +#!/bin/bash +ISO=/path/to/pf/acronis/Acronis_Boot_Disk_2024.iso +W=/tmp/acr +echo "=== rest of grub.cfg (120+):" +sed -n '120,260p' $W/grub.cfg + +echo +echo "=== ATI2025 / DD dirs content:" +for d in ATI2025 ADDH12 ADD12; do + echo "--- ACR/$d" + 7z l -ba "$ISO" 2>/dev/null | awk -v p="ACR/$d/" '$NF ~ "^"p {printf " %-40s %10d\n", $NF, $4}' | head -12 + tot=$(7z l -ba "$ISO" 2>/dev/null | awk -v p="ACR/$d/" '$NF ~ "^"p {s+=$4} END{print s}') + echo " total: $((tot/1024/1024)) MB" +done diff --git a/build-scripts/integration/acronis/acronis-bootimg.sh b/build-scripts/integration/acronis/acronis-bootimg.sh new file mode 100644 index 0000000..93136d6 --- /dev/null +++ b/build-scripts/integration/acronis/acronis-bootimg.sh @@ -0,0 +1,11 @@ +#!/bin/bash +set -e +W=/path/to/pf/acronis +for d in ADD ABA; do + iso="/mnt/f/efi/Paravis/Utilities/$d" + out="$W/$d.boot" + rm -rf "$out"; mkdir -p "$out" + echo "===================== $d" + xorriso -indev "$iso" -osirrox on -extract_boot_images "$out" 2>&1 | grep -viE 'update|note|warning|sorry|sorry' | head -10 + ls -l "$out" +done diff --git a/build-scripts/integration/acronis/acronis-deploy.sh b/build-scripts/integration/acronis/acronis-deploy.sh new file mode 100644 index 0000000..c18feb4 --- /dev/null +++ b/build-scripts/integration/acronis/acronis-deploy.sh @@ -0,0 +1,20 @@ +#!/bin/bash +set -e +W=/path/to/pf/acronis +O="$W/orig" +mkdir -p "$O" + +for d in ADD ABA; do + dst="/mnt/f/efi/Paravis/Utilities/$d" + [ -f "$O/$d" ] || cp -f "$dst" "$O/$d" + cp -f "$W/$d.rebuilt.iso" "$dst" + printf "%-4s %s bytes\n" "$d" "$(stat -c %s "$dst")" +done + +echo "--- signatures inside the new ISOs:" +for d in ADD ABA; do + rm -rf /tmp/chk; mkdir -p /tmp/chk + 7z e -y -o/tmp/chk "/mnt/f/efi/Paravis/Utilities/$d" 'efi/boot/bootx64.efi' >/dev/null + printf " %-4s " "$d" + sbverify --cert /path/to/pf/Ventoy/keys/ventoy.crt /tmp/chk/bootx64.efi >/dev/null 2>&1 && echo "our signature OK" || echo "SIGNATURE PROBLEM" +done diff --git a/build-scripts/integration/acronis/acronis-efi-list.sh b/build-scripts/integration/acronis/acronis-efi-list.sh new file mode 100644 index 0000000..0eb7a3c --- /dev/null +++ b/build-scripts/integration/acronis/acronis-efi-list.sh @@ -0,0 +1,8 @@ +#!/bin/bash +W=/path/to/pf/acronis +for d in ADD ABA; do + echo "===================== $d : efi files" + find "$W/$d" -iname '*.efi' -printf ' %-46P %10s\n' | sort + echo "--- cfg/xml next to loader:" + find "$W/$d" -maxdepth 2 -iname '*.xml' -o -maxdepth 2 -iname '*.cfg' | sed 's/^/ /' +done diff --git a/build-scripts/integration/acronis/acronis-extract.sh b/build-scripts/integration/acronis/acronis-extract.sh new file mode 100644 index 0000000..c59219c --- /dev/null +++ b/build-scripts/integration/acronis/acronis-extract.sh @@ -0,0 +1,16 @@ +#!/bin/bash +set -e +W=/path/to/pf/acronis +rm -rf "$W"; mkdir -p "$W/ADD" "$W/ABA" + +echo "=== extracting" +7z x -y -o"$W/ADD" "/mnt/f/efi/Paravis/Utilities/ADD" >/dev/null +7z x -y -o"$W/ABA" "/mnt/f/efi/Paravis/Utilities/ABA" >/dev/null + +for d in ADD ABA; do + echo "===================== $d" + echo "--- size of tree:"; du -sh "$W/$d" | cut -f1 + echo "--- [BOOT] and efi:"; ls -l "$W/$d/[BOOT]" 2>/dev/null; ls -l "$W/$d/efi/boot" 2>/dev/null + echo "--- hashes:" + ( cd "$W/$d" && sha256sum efi/boot/bootx64.efi 2>/dev/null; sha256sum "Recovery Manager/bootwiz64.efi" 2>/dev/null || true ) +done diff --git a/build-scripts/integration/acronis/acronis-repack.sh b/build-scripts/integration/acronis/acronis-repack.sh new file mode 100644 index 0000000..99210dd --- /dev/null +++ b/build-scripts/integration/acronis/acronis-repack.sh @@ -0,0 +1,37 @@ +#!/bin/bash +set -e +W=/path/to/pf/acronis +K=/path/to/pf/Ventoy/keys + +for d in ADD ABA; do + echo "===================== $d" + T="$W/$d" + + # 1. BIOS el-torito image goes into the tree so xorriso can reference it + cp -f "$W/$d.boot/eltorito_img1_bios.img" "$T/[BOOT]/bios.img" + + # 2. sign the UEFI loader(s) in place + sign() { + local f="$1" + rm -f /tmp/s.efi + sbsign --key "$K/ventoy.key" --cert "$K/ventoy.crt" --output /tmp/s.efi "$f" >/dev/null 2>&1 \ + || { echo " sign failed: $f"; return; } + sbverify --cert "$K/ventoy.crt" /tmp/s.efi >/dev/null 2>&1 \ + || { echo " verify failed: $f"; return; } + cp -f /tmp/s.efi "$f" + printf " signed %-40s %s\n" "${f#$T/}" "$(stat -c %s "$f")" + } + sign "$T/efi/boot/bootx64.efi" + [ -f "$T/Recovery Manager/bootwiz64.efi" ] && sign "$T/Recovery Manager/bootwiz64.efi" + sign "$T/efi/boot/bootia32.efi" + + # 3. rebuild + out="$W/$d.rebuilt.iso" + rm -f "$out" + xorriso -as mkisofs -V ACRONIS_MEDIA -R -J -joliet-long \ + -b '[BOOT]/bios.img' -no-emul-boot -boot-load-size 4 \ + -eltorito-alt-boot -e 'efi/boot/bootx64.efi' -no-emul-boot \ + -o "$out" "$T" 2>&1 | tail -5 + echo " result: $(stat -c %s "$out") bytes" + xorriso -indev "$out" -report_el_torito plain 2>&1 | grep -E 'El Torito (boot img|img blks)' | sed 's/^/ /' +done diff --git a/build-scripts/integration/acronis/build-acronis-hybrid.sh b/build-scripts/integration/acronis/build-acronis-hybrid.sh new file mode 100644 index 0000000..b1c58f2 --- /dev/null +++ b/build-scripts/integration/acronis/build-acronis-hybrid.sh @@ -0,0 +1,76 @@ +#!/bin/bash +# Hybrid Acronis images: x64 set (our GRUB2 menu) + x86 set (xorboot/ia32). +# EFI boot image carries an i386 GRUB that boots the 32-bit kernel, so +# 32-bit UEFI firmware works too. BIOS El Torito is kept for legacy. +set -e +SRC=/path/to/pf/acronis/Acronis_Boot_Disk_2024.iso +OUT=/path/to/pf/acronis/hybrid +W=/root/hybrid +rm -rf "$W"; mkdir -p "$W" "$OUT" + +apt-get install -y grub-pc-bin grub-efi-amd64-bin grub-efi-ia32-bin mtools xorriso >/tmp/apt4.log 2>&1 || true + +build_one() { + local name="$1" dir="$2" k64="$3" i64="$4" k32="$5" i32="$6" + local tree="$W/$name" + mkdir -p "$tree/$dir" "$tree/efi/boot" "$tree/EFI/BOOT" "$tree/boot/grub" + + echo "=== $name : $dir" + 7z e -y -o"$tree/$dir" "$SRC" \ + "ACR/$dir/$k64" $(for i in $i64; do echo "ACR/$dir/$i"; done) \ + "ACR/$dir/$k32" $(for i in $i32; do echo "ACR/$dir/$i"; done) >/dev/null + du -sh "$tree/$dir" + + # ---- configs + cat > "$W/$name.32.cfg" < "$W/$name.64.cfg" </dev/null + mmd -i "$tree/efi.img" ::/EFI ::/EFI/BOOT + mcopy -i "$tree/efi.img" "$W/BOOTIA32.EFI" ::/EFI/BOOT/BOOTIA32.EFI + mcopy -i "$tree/efi.img" "$W/BOOTIA32.EFI" ::/EFI/BOOT/BOOTX64.EFI # xorboot looks for this name + mcopy -i "$tree/efi.img" "$W/BOOTX64.EFI" ::/EFI/BOOT/BOOTX64X.EFI >/dev/null 2>&1 || true + + # ---- base image (BIOS El Torito comes from grub-mkrescue) + grub-mkrescue -o "$W/$name.base.iso" "$tree" >/tmp/mk_$name.log 2>&1 + xorriso -osirrox on -indev "$W/$name.base.iso" \ + -extract /boot/grub/i386-pc/eltorito.img "$tree/boot/grub/i386-pc/eltorito.img" >/dev/null 2>&1 + + # ---- final ISO (Rock Ridge + Joliet so lowercase paths are visible) + xorriso -as mkisofs -R -J -joliet-long -V PARAVIS_ACRONIS -o "$OUT/$name.iso" \ + -b boot/grub/i386-pc/eltorito.img -no-emul-boot -boot-load-size 4 -boot-info-table \ + -eltorito-alt-boot -e efi.img -no-emul-boot \ + "$tree" >/tmp/xor_$name.log 2>&1 + + printf " -> %s: %s bytes\n" "$name" "$(stat -c %s "$OUT/$name.iso")" + xorriso -indev "$OUT/$name.iso" -report_el_torito plain 2>&1 | grep -E 'El Torito boot img' | sed 's/^/ /' + printf " tree: "; 7z l -ba "$OUT/$name.iso" 2>/dev/null | grep -oE '(efi|EFI)/boot/[Bb][Oo][Oo][Tt](IA32|X64|ia32|x64)\.efi' | tr '\n' ' '; echo +} + +# ADD = True Image 2025 : x64 dat10/11/12, x86 dat2/3/4 +build_one ADD ATI2025 dat10.dat "dat11.dat dat12.dat" dat2.dat "dat3.dat dat4.dat" +# ABA = Disk Director 12.5 : x64 dat14/15/16, x86 dat10/11/12 +build_one ABA ADDH12 dat14.dat "dat15.dat dat16.dat" dat10.dat "dat11.dat dat12.dat" +ls -l "$OUT" diff --git a/build-scripts/integration/acronis/build-acronis-ia32.sh b/build-scripts/integration/acronis/build-acronis-ia32.sh new file mode 100644 index 0000000..1202cdd --- /dev/null +++ b/build-scripts/integration/acronis/build-acronis-ia32.sh @@ -0,0 +1,59 @@ +#!/bin/bash +# Rebuild ADD/ABA images with a dual-arch EFI boot image (x64 + ia32). +set -e +W=/tmp/acrbuild2 +OLD=/path/to/pf/acronis/prev # previous images (mkrescue, BIOS+boot x64) +rm -rf "$W"; mkdir -p "$W" + +apt-get install -y grub-efi-ia32-bin grub-efi-amd64-bin grub-pc-bin mtools xorriso >/tmp/apt2.log 2>&1 || true + +build_one() { + local name="$1" srcdir="$2" kernel="$3" initrds="$4" + local tree="$W/$name" + mkdir -p "$tree/boot/grub/i386-pc" "$tree/$srcdir" + + echo "=== $name ($srcdir)" + # source files: take from the existing image to avoid re-extracting from the 4.4G ISO + xorriso -osirrox on -indev "/tmp/acrbuild/$name.iso" \ + -extract "/$srcdir" "$tree/$srcdir" >/dev/null 2>&1 + xorriso -osirrox on -indev "/tmp/acrbuild/$name.iso" \ + -extract /boot/grub/i386-pc/eltorito.img "$tree/boot/grub/i386-pc/eltorito.img" >/dev/null 2>&1 + + cat > "$W/$name.cfg" </dev/null + mmd -i "$W/efi.img" ::/EFI ::/EFI/BOOT + mcopy -i "$W/efi.img" "$W/BOOTX64.EFI" ::/EFI/BOOT/BOOTX64.EFI + mcopy -i "$W/efi.img" "$W/BOOTIA32.EFI" ::/EFI/BOOT/BOOTIA32.EFI + mdir -i "$W/efi.img" ::/EFI/BOOT + + cp -f "$W/efi.img" "$tree/efi.img" + xorriso -as mkisofs -o "$W/$name.iso" \ + -b boot/grub/i386-pc/eltorito.img -no-emul-boot -boot-load-size 4 -boot-info-table \ + -eltorito-alt-boot -e efi.img -no-emul-boot \ + "$tree" >/tmp/xorriso_$name.log 2>&1 || { tail -10 /tmp/xorriso_$name.log; return 1; } + + printf " -> %s.iso : %s bytes\n" "$name" "$(stat -c %s "$W/$name.iso")" + xorriso -indev "$W/$name.iso" -report_el_torito plain 2>&1 | grep -E 'El Torito boot img' | sed 's/^/ /' + echo -n " efi.img contents: " + xorriso -osirrox on -indev "$W/$name.iso" -extract /efi.img /tmp/chk_efi.img >/dev/null 2>&1 + mdir -i /tmp/chk_efi.img ::/EFI/BOOT | tr '\n' ' '; echo +} + +build_one ADD ATI2025 dat10.dat "dat11.dat dat12.dat" +build_one ABA ADDH12 dat14.dat "dat15.dat dat16.dat" diff --git a/build-scripts/integration/acronis/build-acronis-images.sh b/build-scripts/integration/acronis/build-acronis-images.sh new file mode 100644 index 0000000..a233559 --- /dev/null +++ b/build-scripts/integration/acronis/build-acronis-images.sh @@ -0,0 +1,37 @@ +#!/bin/bash +# Build new single-file bootable images for Acronis TI 2025 (ADD) and +# Disk Director 12.5 (ABA), keeping the old file names/paths so that the +# legacy (grub4dos/xorboot) menu keeps working unchanged. +set -e +ISO=/path/to/pf/acronis/Acronis_Boot_Disk_2024.iso +W=/tmp/acrbuild +rm -rf "$W"; mkdir -p "$W" + +apt-get install -y grub-pc-bin grub-efi-amd64-bin mtools xorriso >/tmp/apt_grubiso.log 2>&1 || true + +build_one() { + local name="$1" srcdir="$2" kernel="$3" initrds="$4" + local tree="$W/$name" + mkdir -p "$tree/boot/grub" "$tree/$srcdir" + echo "=== $name: extracting $srcdir" + 7z e -y -o"$tree/$srcdir" "$ISO" "ACR/$srcdir/$kernel" $(for i in $initrds; do echo "ACR/$srcdir/$i"; done) >/dev/null + ls -l "$tree/$srcdir" | tail -3 + + cat > "$tree/boot/grub/grub.cfg" </tmp/mkrescue_$name.log 2>&1 || { tail -5 /tmp/mkrescue_$name.log; return 1; } + printf " -> %s : %s bytes\n" "$name" "$(stat -c %s "$W/$name.iso")" + xorriso -indev "$W/$name.iso" -report_el_torito plain 2>&1 | grep -E 'El Torito boot img' | sed 's/^/ /' +} + +build_one ADD ATI2025 dat10.dat "dat11.dat dat12.dat" +build_one ABA ADDH12 dat14.dat "dat15.dat dat16.dat" + +ls -l "$W"/*.iso diff --git a/build-scripts/integration/acronis/build-acronis-images2.sh b/build-scripts/integration/acronis/build-acronis-images2.sh new file mode 100644 index 0000000..4cf2556 --- /dev/null +++ b/build-scripts/integration/acronis/build-acronis-images2.sh @@ -0,0 +1,77 @@ +#!/bin/bash +# Rebuild Acronis component images (self-contained: source ISO on D:). +# Result: D:/PF2026/acronis/new/{ADD,ABA}.iso with BIOS + dual-arch EFI. +set -e +SRC=/path/to/pf/acronis/Acronis_Boot_Disk_2024.iso +OUT=/path/to/pf/acronis/new +W=/root/acrbuild +rm -rf "$W"; mkdir -p "$W" "$OUT" + +apt-get install -y grub-pc-bin grub-efi-amd64-bin grub-efi-ia32-bin mtools xorriso >/tmp/apt3.log 2>&1 || true + +build_one() { + local name="$1" srcdir="$2" kernel="$3" initrds="$4" + local tree="$W/$name" + mkdir -p "$tree/$srcdir" + + echo "=== $name : ACR/$srcdir" + 7z e -y -o"$tree/$srcdir" "$SRC" "ACR/$srcdir/$kernel" $(for i in $initrds; do echo "ACR/$srcdir/$i"; done) >/dev/null + ls -l "$tree/$srcdir" | tail -4 + + mkdir -p "$tree/boot/grub" + cat > "$tree/boot/grub/grub.cfg" </tmp/mk_$name.log 2>&1 + xorriso -osirrox on -indev "$W/$name.base.iso" \ + -extract /boot/grub/i386-pc/eltorito.img "$tree/boot/grub/i386-pc/eltorito.img" >/dev/null 2>&1 + + # 2. our own EFI boot image with BOTH loaders + cat > "$W/$name.cfg" </dev/null + mmd -i "$tree/efi.img" ::/EFI ::/EFI/BOOT + mcopy -i "$tree/efi.img" "$W/BOOTIA32.EFI" ::/EFI/BOOT/BOOTIA32.EFI + mcopy -i "$tree/efi.img" "$W/BOOTIA32.EFI" ::/EFI/BOOT/BOOTX64.EFI + + # 3. final ISO: BIOS from grub-pc + our dual EFI image + xorriso -as mkisofs -o "$OUT/$name.iso" \ + -b boot/grub/i386-pc/eltorito.img -no-emul-boot -boot-load-size 4 -boot-info-table \ + -eltorito-alt-boot -e efi.img -no-emul-boot \ + "$tree" >/tmp/xor_$name.log 2>&1 + + printf " -> %s.iso %s bytes\n" "$name" "$(stat -c %s "$OUT/$name.iso")" + xorriso -indev "$OUT/$name.iso" -report_el_torito plain 2>&1 | grep -E 'El Torito boot img' | sed 's/^/ /' + rm -f /tmp/e.img + xorriso -osirrox on -indev "$OUT/$name.iso" -extract /efi.img /tmp/e.img >/dev/null 2>&1 + printf " efi.img: "; mdir -i /tmp/e.img ::/EFI/BOOT | grep -oE 'BOOT(IA32|X64) +EFI' | tr '\n' ' '; echo +} + +build_one ADD ATI2025 dat10.dat "dat11.dat dat12.dat" +build_one ABA ADDH12 dat14.dat "dat15.dat dat16.dat" +ls -l "$OUT" diff --git a/build-scripts/integration/acronis/build-acronis-merged.sh b/build-scripts/integration/acronis/build-acronis-merged.sh new file mode 100644 index 0000000..52f9088 --- /dev/null +++ b/build-scripts/integration/acronis/build-acronis-merged.sh @@ -0,0 +1,66 @@ +#!/bin/bash +# Merged Acronis images: one file per product. +# tree : old Acronis ISO content + new Acronis kernel sets +# BIOS : grub-pc image -> new Acronis (32-bit kernel, like their own menu) +# UEFI : ORIGINAL old Acronis EFI image -> ia32/xorboot boots old Acronis +set -e +SRC=/path/to/pf/acronis/Acronis_Boot_Disk_2024.iso +OLD=/path/to/pf/acronis/orig +OUT=/path/to/pf/acronis/merged +W=/root/merged +rm -rf "$W"; mkdir -p "$W" "$OUT" + +apt-get install -y grub-pc-bin grub-efi-amd64-bin grub-efi-ia32-bin mtools xorriso >/tmp/apt5.log 2>&1 || true + +build_one() { + local name="$1" dir="$2" k32="$3" i32="$4" k64="$5" i64="$6" + local tree="$W/$name" + + echo "=== $name" + mkdir -p "$tree" "$tree/$dir" "$W/$name.boot" "$tree/boot/grub/i386-pc" + + # 1. old ISO content (this is what ia32 boots through its own loader) + xorriso -osirrox on -indev "$OLD/$name" -extract / "$tree" >/dev/null 2>&1 + + # 2. new kernel sets from the 2024 collection + 7z e -y -o"$tree/$dir" "$SRC" \ + "ACR/$dir/$k32" $(for i in $i32; do echo "ACR/$dir/$i"; done) \ + "ACR/$dir/$k64" $(for i in $i64; do echo "ACR/$dir/$i"; done) >/dev/null + + echo " old tree files: $(find "$tree" -type f | wc -l)" + # 3. BIOS menu -> new Acronis (same cmdline as their grub4dos menu) + cat > "$tree/boot/grub/grub.cfg" </tmp/mk_$name.log 2>&1 + xorriso -osirrox on -indev "$W/$name.base.iso" \ + -extract /boot/grub/i386-pc/eltorito.img "$tree/boot/grub/i386-pc/eltorito.img" >/dev/null 2>&1 + + # 5. ORIGINAL EFI image of the old ISO (acronis bootwiz) -> ia32 path stays intact + xorriso -osirrox on -indev "$OLD/$name" -extract_boot_images "$W/$name.boot" >/dev/null 2>&1 + local efiimg + efiimg=$(ls "$W/$name.boot"/*uefi*.img 2>/dev/null | head -1) + cp -f "$efiimg" "$tree/efi_old.img" + + # 6. final ISO + xorriso -as mkisofs -R -J -joliet-long -V PARAVIS_ACRONIS -o "$OUT/$name.iso" \ + -b boot/grub/i386-pc/eltorito.img -no-emul-boot -boot-load-size 4 -boot-info-table \ + -eltorito-alt-boot -e efi_old.img -no-emul-boot \ + "$tree" >/tmp/xor_$name.log 2>&1 || { tail -8 /tmp/xor_$name.log; return 1; } + + printf " -> %s: %s bytes (%s MB)\n" "$name" \ + "$(stat -c %s "$OUT/$name.iso")" "$(( $(stat -c %s "$OUT/$name.iso") / 1048576 ))" + xorriso -indev "$OUT/$name.iso" -report_el_torito plain 2>&1 | grep -E 'El Torito boot img' | sed 's/^/ /' + echo -n " old loader present: "; 7z l -ba "$OUT/$name.iso" 2>/dev/null | grep -c -iE 'efi/boot/bootia32\.efi' || true +} + +build_one ADD ATI2025 dat2.dat "dat3.dat dat4.dat" dat10.dat "dat11.dat dat12.dat" +build_one ABA ADDH12 dat10.dat "dat11.dat dat12.dat" dat14.dat "dat15.dat dat16.dat" +ls -l "$OUT" diff --git a/build-scripts/integration/acronis/build-acronis-new2.sh b/build-scripts/integration/acronis/build-acronis-new2.sh new file mode 100644 index 0000000..955184d --- /dev/null +++ b/build-scripts/integration/acronis/build-acronis-new2.sh @@ -0,0 +1,67 @@ +#!/bin/bash +# Rebuild the new Acronis images so that the BIOS (grub-pc) boot works: +# the modules must be present on the ISO, otherwise GRUB drops to rescue. +set -e +SRC=/path/to/pf/acronis/Acronis_Boot_Disk_2024.iso +OUT=/path/to/pf/acronis/new +W=/root/new2 +rm -rf "$W"; mkdir -p "$W" "$OUT" + +apt-get install -y grub-pc-bin grub-efi-amd64-bin grub-efi-ia32-bin mtools xorriso >/tmp/apt6.log 2>&1 || true + +build_one() { + local name="$1" dir="$2" kernel="$3" initrds="$4" + local tree="$W/$name" + mkdir -p "$tree/$dir" "$tree/boot/grub/i386-pc" + + echo "=== $name ($dir)" + 7z e -y -o"$tree/$dir" "$SRC" "ACR/$dir/$kernel" $(for i in $initrds; do echo "ACR/$dir/$i"; done) >/dev/null + + # BIOS menu + cat > "$tree/boot/grub/grub.cfg" </dev/null || true + + # BIOS El Torito image + grub-mkrescue -o "$W/$name.base.iso" "$tree" >/tmp/mk2_$name.log 2>&1 + xorriso -osirrox on -indev "$W/$name.base.iso" \ + -extract /boot/grub/i386-pc/eltorito.img "$tree/boot/grub/i386-pc/eltorito.img" >/dev/null 2>&1 + + # UEFI image: our x64 GRUB (standalone, embedded config) — only used if someone + # boots the ISO straight from firmware; our menu uses loopback instead. + cat > "$W/$name.efi.cfg" </dev/null + mmd -i "$tree/efi.img" ::/EFI ::/EFI/BOOT + mcopy -i "$tree/efi.img" "$W/BOOTX64.EFI" ::/EFI/BOOT/BOOTX64.EFI + mkdir -p "$tree/EFI/BOOT" + cp -f "$W/BOOTX64.EFI" "$tree/EFI/BOOT/BOOTX64.EFI" + + xorriso -as mkisofs -R -J -joliet-long -V PARAVIS_ACRONIS -o "$OUT/$name.iso" \ + -b boot/grub/i386-pc/eltorito.img -no-emul-boot -boot-load-size 4 -boot-info-table \ + -eltorito-alt-boot -e efi.img -no-emul-boot \ + "$tree" >/tmp/xor2_$name.log 2>&1 + + printf " -> %s: %s MB\n" "$name" "$(( $(stat -c %s "$OUT/$name.iso") / 1048576 ))" + printf " modules in ISO: " + 7z l -ba "$OUT/$name.iso" 2>/dev/null | grep -c 'boot/grub/i386-pc/.*\.mod' || true +} + +build_one ADD ATI2025 dat10.dat "dat11.dat dat12.dat" +build_one ABA ADDH12 dat14.dat "dat15.dat dat16.dat" +ls -l "$OUT" diff --git a/build-scripts/integration/acronis/cmp-acronis.sh b/build-scripts/integration/acronis/cmp-acronis.sh new file mode 100644 index 0000000..d4bc879 --- /dev/null +++ b/build-scripts/integration/acronis/cmp-acronis.sh @@ -0,0 +1,31 @@ +#!/bin/bash +W=/tmp/cmp +rm -rf $W; mkdir -p $W +OLD=/path/to/pf/acronis/orig +NEW=/path/to/pf/acronis/new + +for tag in old new; do + if [ $tag = old ]; then ISO="$OLD/ADD"; else ISO="$NEW/ADD.iso"; fi + echo "===================== $tag : $ISO" + echo "--- file:" + file -b "$ISO" + echo "--- el torito:" + xorriso -indev "$ISO" -report_el_torito plain 2>&1 | grep -E 'Boot record|El Torito|Volume id' | sed 's/^/ /' + echo "--- boot images extract:" + rm -rf $W/$tag; mkdir -p $W/$tag + xorriso -indev "$ISO" -osirrox on -extract_boot_images "$W/$tag" >/dev/null 2>&1 + ls -l "$W/$tag" | sed 's/^/ /' + for img in "$W/$tag"/*uefi*.img; do + [ -f "$img" ] || continue + echo " uefi img: $(file -b "$img")" + echo " contents:" + mdir -i "$img" ::/ 2>/dev/null | head -8 | sed 's/^/ /' + mdir -i "$img" ::/EFI/BOOT 2>/dev/null | head -8 | sed 's/^/ /' + # boot sector details + echo " boot sector:" + dd if="$img" bs=1 count=64 status=none | od -An -tx1 | head -4 | sed 's/^/ /' + done + echo "--- catalog bytes:" + cat_img="$W/$tag"/eltorito_catalog.img + [ -f "$cat_img" ] && od -An -tx1 "$cat_img" | head -8 | sed 's/^/ /' +done diff --git a/build-scripts/integration/acronis/deploy-acronis-ia32.sh b/build-scripts/integration/acronis/deploy-acronis-ia32.sh new file mode 100644 index 0000000..8720572 --- /dev/null +++ b/build-scripts/integration/acronis/deploy-acronis-ia32.sh @@ -0,0 +1,18 @@ +#!/bin/bash +set -e +U=/mnt/f/efi/Paravis/Utilities +B=/path/to/pf/acronis/prev +mkdir -p "$B" +for f in ADD ABA; do + [ -f "$B/$f.mkrescue" ] || cp -f "$U/$f" "$B/$f.mkrescue" + cp -f "/tmp/acrbuild2/$f.iso" "$U/$f" + printf " %-4s %s bytes\n" "$f" "$(stat -c %s "$U/$f")" +done +echo "--- EFI image inside each (what xorboot will load):" +for f in ADD ABA; do + rm -f /tmp/e.img + xorriso -osirrox on -indev "$U/$f" -extract /efi.img /tmp/e.img >/dev/null 2>&1 + printf " %-4s " "$f" + mdir -i /tmp/e.img ::/EFI/BOOT | grep -oE 'BOOT(IA32|X64) +EFI +[0-9]+' | tr '\n' ' ' + echo +done diff --git a/build-scripts/integration/acronis/deploy-acronis-images.sh b/build-scripts/integration/acronis/deploy-acronis-images.sh new file mode 100644 index 0000000..782b923 --- /dev/null +++ b/build-scripts/integration/acronis/deploy-acronis-images.sh @@ -0,0 +1,18 @@ +#!/bin/bash +set -e +K=/path/to/pf/Ventoy/keys +U=/mnt/f/efi/Paravis/Utilities +B=/path/to/pf/acronis/prev + +mkdir -p "$B" +for f in ADD ABA; do + [ -f "$B/$f" ] || cp -f "$U/$f" "$B/$f" + cp -f "/tmp/acrbuild/$f.iso" "$U/$f" + printf " %-4s %s bytes\n" "$f" "$(stat -c %s "$U/$f")" +done + +echo "--- El Torito of deployed images:" +for f in ADD ABA; do + echo " $f:" + xorriso -indev "$U/$f" -report_el_torito plain 2>&1 | grep -E 'El Torito boot img' | sed 's/^/ /' +done diff --git a/build-scripts/integration/acronis/extract-acronis-parts.sh b/build-scripts/integration/acronis/extract-acronis-parts.sh new file mode 100644 index 0000000..4ee287f --- /dev/null +++ b/build-scripts/integration/acronis/extract-acronis-parts.sh @@ -0,0 +1,14 @@ +#!/bin/bash +set -e +ISO=/path/to/pf/acronis/Acronis_Boot_Disk_2024.iso +U=/mnt/f/efi/Paravis/Utilities + +mkdir -p "$U/ATI2025" "$U/ADDH12" + +echo "=== Acronis True Image 2025 (ACR/ATI2025)" +7z e -y -o"$U/ATI2025" "$ISO" 'ACR/ATI2025/dat10.dat' 'ACR/ATI2025/dat11.dat' 'ACR/ATI2025/dat12.dat' >/dev/null +ls -l "$U/ATI2025" + +echo "=== Acronis Disk Director 12.5 (ACR/ADDH12)" +7z e -y -o"$U/ADDH12" "$ISO" 'ACR/ADDH12/dat14.dat' 'ACR/ADDH12/dat15.dat' 'ACR/ADDH12/dat16.dat' >/dev/null +ls -l "$U/ADDH12" diff --git a/build-scripts/integration/acronis/ls-old-acronis.sh b/build-scripts/integration/acronis/ls-old-acronis.sh new file mode 100644 index 0000000..886b2c6 --- /dev/null +++ b/build-scripts/integration/acronis/ls-old-acronis.sh @@ -0,0 +1,5 @@ +#!/bin/bash +for f in ADD ABA; do + echo "===================== $f" + 7z l -ba "/path/to/pf/acronis/orig/$f" 2>/dev/null | awk '{printf " %-56s %10d\n", $NF, $4}' | sort -k1 | head -40 +done diff --git a/build-scripts/integration/acronis/old-acronis-cfg.sh b/build-scripts/integration/acronis/old-acronis-cfg.sh new file mode 100644 index 0000000..88fd412 --- /dev/null +++ b/build-scripts/integration/acronis/old-acronis-cfg.sh @@ -0,0 +1,16 @@ +#!/bin/bash +W=/tmp/oldcfg +rm -rf $W; mkdir -p $W +echo "=== ADD: bootwiz.cfg / bootmenu.xml" +7z e -y -o$W "/path/to/pf/acronis/orig/ADD" 'bootwiz.cfg' 'bootmenu.xml' >/dev/null 2>&1 +echo "--- bootwiz.cfg:"; cat $W/bootwiz.cfg 2>/dev/null +echo "--- bootmenu.xml (head):"; head -40 $W/bootmenu.xml 2>/dev/null +rm -f $W/bootwiz.cfg $W/bootmenu.xml + +echo +echo "=== ABA: bootwiz.cfg / bootmenu.xml / Manager/f11-grub.cfg / Manager/f11.cfg" +7z e -y -o$W "/path/to/pf/acronis/orig/ABA" 'bootwiz.cfg' 'bootmenu.xml' 'Manager/f11-grub.cfg' 'Manager/f11.cfg' >/dev/null 2>&1 +echo "--- bootwiz.cfg:"; cat $W/bootwiz.cfg 2>/dev/null +echo "--- f11-grub.cfg:"; cat $W/f11-grub.cfg 2>/dev/null +echo "--- f11.cfg:"; cat $W/f11.cfg 2>/dev/null +echo "--- bootmenu.xml (head):"; head -30 $W/bootmenu.xml 2>/dev/null diff --git a/build-scripts/integration/acronis/scan-acr-kernels.sh b/build-scripts/integration/acronis/scan-acr-kernels.sh new file mode 100644 index 0000000..2abb348 --- /dev/null +++ b/build-scripts/integration/acronis/scan-acr-kernels.sh @@ -0,0 +1,42 @@ +#!/bin/bash +set -e +SRC=/path/to/pf/acronis/Acronis_Boot_Disk_2024.iso +OUT=/path/to/pf/acronis/acr + +if [ ! -d "$OUT" ]; then + echo "=== extracting ACR (once, ~4.4 GB)..." + mkdir -p "$OUT" + 7z x -y -o"$OUT" "$SRC" 'ACR/*' >/dev/null +fi +echo "=== scanning kernels" +python3 - <<'EOF' +import glob, os, struct + +rows = [] +for p in sorted(glob.glob('/path/to/pf/acronis/acr/ACR/*/*')): + if not os.path.isfile(p) or os.path.getsize(p) < 1024 * 1024: + continue + try: + with open(p, 'rb') as f: + head = f.read(0x300) + except OSError: + continue + # bzImage: 'HdrS' at 0x202 + if head[0x202:0x206] != b'HdrS': + continue + flags = struct.unpack_from('/dev/null +cp -f /usr/lib/grub/i386-pc/*.mod /usr/lib/grub/i386-pc/*.lst "$W/tree/boot/grub/i386-pc/" 2>/dev/null || true + +cat > "$W/tree/boot/grub/grub.cfg" <<'EOF' +set timeout=0 +set default=0 +menuentry "Acronis" { + linux /ATI2025/dat10.dat vga=791 mbrcrcs=on force_modules=usbhid lang=ru quiet console=ttyS0,115200 + initrd /ATI2025/dat11.dat /ATI2025/dat12.dat +} +EOF + +grub-mkrescue -o "$W/test.iso" "$W/tree" >/tmp/mk_test.log 2>&1 +xorriso -osirrox on -indev "$W/test.iso" -extract /boot/grub/i386-pc/eltorito.img "$W/tree/boot/grub/i386-pc/eltorito.img" >/dev/null 2>&1 +xorriso -as mkisofs -o "$W/final.iso" \ + -b boot/grub/i386-pc/eltorito.img -no-emul-boot -boot-load-size 4 -boot-info-table \ + "$W/tree" >/tmp/xor_test.log 2>&1 +ls -l "$W/final.iso" + +echo "=== booting in QEMU (BIOS), 90s max" +timeout 90 qemu-system-x86_64 -m 4096 -cdrom "$W/final.iso" -boot d \ + -display none -serial stdio -no-reboot 2>&1 | tail -60 || true diff --git a/build-scripts/integration/acronis/verify-acronis-dual.sh b/build-scripts/integration/acronis/verify-acronis-dual.sh new file mode 100644 index 0000000..a2d9c6a --- /dev/null +++ b/build-scripts/integration/acronis/verify-acronis-dual.sh @@ -0,0 +1,13 @@ +#!/bin/bash +for f in ADD ABA; do + rm -f /tmp/e.img + xorriso -osirrox on -indev "/mnt/f/efi/Paravis/Utilities/$f" -extract /efi.img /tmp/e.img >/dev/null 2>&1 + printf ' %-4s ' "$f" + mdir -i /tmp/e.img ::/EFI/BOOT 2>/dev/null | grep -oE 'BOOT(IA32|X64) +EFI +[0-9]+' | tr '\n' ' ' + echo +done +echo "--- el torito:" +for f in ADD ABA; do + echo " $f:" + xorriso -indev "/mnt/f/efi/Paravis/Utilities/$f" -report_el_torito plain 2>&1 | grep -E 'El Torito boot img' | sed 's/^/ /' +done diff --git a/build-scripts/integration/acronis/verify-new-acronis.sh b/build-scripts/integration/acronis/verify-new-acronis.sh new file mode 100644 index 0000000..cfd3821 --- /dev/null +++ b/build-scripts/integration/acronis/verify-new-acronis.sh @@ -0,0 +1,11 @@ +#!/bin/bash +for f in ADD ABA; do + iso="/mnt/f/efi/Paravis/Utilities/$f" + echo "== $f" + xorriso -indev "$iso" -report_el_torito plain 2>/dev/null | grep -E 'El Torito boot img' | sed 's/^/ /' + printf ' modules: ' + 7z l -ba "$iso" 2>/dev/null | grep -c 'boot/grub/i386-pc/.*\.mod' + printf ' kernel dirs: ' + 7z l -ba "$iso" 2>/dev/null | grep -oE '(ATI2025|ADDH12)/[a-z0-9]+\.dat' | tr '\n' ' ' + echo +done diff --git a/build-scripts/integration/krd/krd-backstore.sh b/build-scripts/integration/krd/krd-backstore.sh new file mode 100644 index 0000000..1f87bcf --- /dev/null +++ b/build-scripts/integration/krd/krd-backstore.sh @@ -0,0 +1,10 @@ +#!/bin/bash +cd /root/krd24/srm10/scripts || exit 1 +echo "=== список скриптов:" +ls -1 +echo +echo "=== всё про backstore:" +grep -rn 'KRD_BACKSTORE\|BACKSTORE\|\.bs' . 2>/dev/null | head -40 +echo +echo "=== всё про KRD_DATA_DIRECTORY / product dir:" +grep -rn 'KRD_DATA_DIRECTORY\|product_dir\|KRD_MOUNTS_FILE' . 2>/dev/null | head -40 diff --git a/build-scripts/integration/krd/krd-backstore2.sh b/build-scripts/integration/krd/krd-backstore2.sh new file mode 100644 index 0000000..4a13cb1 --- /dev/null +++ b/build-scripts/integration/krd/krd-backstore2.sh @@ -0,0 +1,10 @@ +#!/bin/bash +cd /root/krd24 || exit 1 +echo "=== backstore во всём squashfs:" +grep -rIl 'BACKSTORE\|backstore\|krd\.bs' sqroot 2>/dev/null | head -20 +echo +echo "=== упоминания (с контекстом):" +grep -rn 'KRD_BACKSTORE_ACTIVE\|krd\.bs\|backstore' sqroot/usr/sbin sqroot/usr/lib sqroot/etc 2>/dev/null | head -30 +echo +echo "=== find_product_dir.sh 100-215:" +sed -n '100,215p' srm10/scripts/find_product_dir.sh diff --git a/build-scripts/integration/krd/krd-backstore3.sh b/build-scripts/integration/krd/krd-backstore3.sh new file mode 100644 index 0000000..1f2ccf9 --- /dev/null +++ b/build-scripts/integration/krd/krd-backstore3.sh @@ -0,0 +1,7 @@ +#!/bin/bash +cd /root/krd24 || exit 1 +echo "=== live_env.sh, динамическая часть (95-200):" +sed -n '95,200p' sqroot/etc/KRD/live_env.sh +echo +echo "=== поиск KRD_LAYERS_BOOT_DIRECTORY / RW_DIRECTORY / BACKSTORE_ACTIVE во всём дереве:" +grep -rn 'KRD_LAYERS_BOOT_DIRECTORY\|KRD_LAYERS_RW_DIRECTORY\|KRD_BACKSTORE_ACTIVE_FILEPATH' sqroot srm10 2>/dev/null | head -20 diff --git a/build-scripts/integration/krd/krd-bases-test.sh b/build-scripts/integration/krd/krd-bases-test.sh new file mode 100644 index 0000000..feca02b --- /dev/null +++ b/build-scripts/integration/krd/krd-bases-test.sh @@ -0,0 +1,47 @@ +#!/bin/bash +# Проверка: базы из KRD2024_Data/Bases подхватываются при загрузке. +set -e +STAGE=/path/to/pf/KRD/files +IMG=/root/krd24/bases-fat32.img + +rm -f "$IMG"; truncate -s 6G "$IMG" +mkfs.vfat -F 32 -n PARAVIS "$IMG" >/dev/null 2>&1 +mkdir -p /mnt/krdtest; mount -o loop "$IMG" /mnt/krdtest +mkdir -p /mnt/krdtest/efi/Paravis/KRD +cp -r "$STAGE/." /mnt/krdtest/efi/Paravis/KRD/ + +# имитация "обновлённых баз", как их кладёт updater.sh +P=/mnt/krdtest/efi/Paravis/KRD/KRD2024_Data +mkdir -p "$P/Bases" "$P/Traces" +cp "$STAGE/live/KRD/30-bases.srm" "$P/Bases/42-freshbases.srm" +echo "1" > "$P/Bases/bases_are_correct.flag" +sync +echo "=== до загрузки:" +ls -A "$P" "$P/Bases" +umount /mnt/krdtest + +rm -f /tmp/qmon7.sock +qemu-system-x86_64 -m 3072 -smp 4 -machine q35 \ + -kernel "$STAGE/live/vmlinuz" -initrd "$STAGE/live/initrd.img" \ + -append "boot=live components live-media-path=/efi/Paravis/KRD/live locales=ru_RU.UTF-8 trace" \ + -drive file="$IMG",format=raw,if=ide -net none -display none -vga std \ + -monitor unix:/tmp/qmon7.sock,server,nowait -daemonize + +sleep 95 +python3 - <<'EOF' +import socket, time +s = socket.socket(socket.AF_UNIX); s.connect('/tmp/qmon7.sock'); time.sleep(0.3) +s.recv(65536); s.sendall(b'quit\n') +EOF +sleep 3 +pkill -f 'qemu-system-x86_64.*bases-fat32.img' 2>/dev/null || true +sleep 2 + +echo "=== логи KRT после загрузки:" +mount -o loop "$IMG" /mnt/krdtest +find /mnt/krdtest/efi/Paravis/KRD/KRD2024_Data/Traces -type f | head -10 +echo "--- про базы:" +grep -rhiE 'Fresh bases|fresh bases|Used default|bases srm' /mnt/krdtest/efi/Paravis/KRD/KRD2024_Data/Traces 2>/dev/null | head -15 +echo "--- продуктовая папка:" +find /mnt/krdtest/efi/Paravis/KRD/KRD2024_Data -maxdepth 1 | sed 's|/mnt/krdtest||' +umount /mnt/krdtest diff --git a/build-scripts/integration/krd/krd-dbg1.sh b/build-scripts/integration/krd/krd-dbg1.sh new file mode 100644 index 0000000..16c8a23 --- /dev/null +++ b/build-scripts/integration/krd/krd-dbg1.sh @@ -0,0 +1,38 @@ +#!/bin/bash +set -e +W=/root/krd24 +cd "$W" +rm -rf srm10dbg; cp -a srm10p srm10dbg + +python3 - <<'PYEOF' +import io +p='/root/krd24/srm10dbg/scripts/find_product_dir.sh' +s=io.open(p,encoding='utf-8').read() +anchor='''if [[ ! -f "${KRD_MOUNTS_FILE_PATH}" ]] +then + trace_message "${TRACE_LVL_ERROR}" "Volumes aren't mounted!" + trace_and_exit 1 +fi +''' +dbg=''' +{ + echo "=== PARAVIS DEBUG ===" + echo "-- mounts file <${KRD_MOUNTS_FILE_PATH}>:" + cat "${KRD_MOUNTS_FILE_PATH}" 2>&1 + echo "-- volumes dir <${KRD_VOLUMES_DIRECTORY}>:" + ls -la "${KRD_VOLUMES_DIRECTORY}" 2>&1 + echo "-- /proc/mounts (medium/live/volumes):" + grep -E 'medium|KRD' /proc/mounts 2>&1 + echo "=== END DEBUG ===" +} > /dev/ttyS0 2>&1 +''' +assert anchor in s +s=s.replace(anchor, anchor+dbg, 1) +io.open(p,'w',encoding='utf-8').write(s) +print('debug patch ok') +PYEOF + +rm -f 10-krd-dbg.srm +mksquashfs srm10dbg 10-krd-dbg.srm -comp xz -b 262144 -Xbcj x86 -noappend >/dev/null 2>&1 +cp -f 10-krd-dbg.srm /path/to/pf/KRD/files/live/KRD/10-krd.srm +ls -l /path/to/pf/KRD/files/live/KRD/10-krd.srm diff --git a/build-scripts/integration/krd/krd-dbg2.sh b/build-scripts/integration/krd/krd-dbg2.sh new file mode 100644 index 0000000..b61f31e --- /dev/null +++ b/build-scripts/integration/krd/krd-dbg2.sh @@ -0,0 +1,40 @@ +#!/bin/bash +# Отладочный прогон: KRD печатает состояние томов в COM-порт. +set -e +STAGE=/path/to/pf/KRD/files +IMG=/root/krd24/dbg-fat32.img + +rm -f "$IMG"; truncate -s 6G "$IMG" # 6G, чтобы пройти проверку размера тома 4G +mkfs.vfat -F 32 -n PARAVIS "$IMG" >/dev/null 2>&1 +mkdir -p /mnt/krdtest; mount -o loop "$IMG" /mnt/krdtest +mkdir -p /mnt/krdtest/efi/Paravis/KRD +cp -r "$STAGE/." /mnt/krdtest/efi/Paravis/KRD/ +sync +echo "=== до загрузки:"; ls -A /mnt/krdtest/efi/Paravis/KRD +umount /mnt/krdtest + +rm -f /tmp/qmon5.sock /tmp/krd.serial +qemu-system-x86_64 -m 3072 -smp 4 -machine q35 \ + -kernel "$STAGE/live/vmlinuz" -initrd "$STAGE/live/initrd.img" \ + -append "boot=live components live-media-path=/efi/Paravis/KRD/live locales=ru_RU.UTF-8 console=ttyS0,115200" \ + -drive file="$IMG",format=raw,if=ide -net none -display none -vga std \ + -serial file:/tmp/krd.serial \ + -monitor unix:/tmp/qmon5.sock,server,nowait -daemonize + +sleep 100 +python3 - <<'EOF' +import socket, time +s = socket.socket(socket.AF_UNIX); s.connect('/tmp/qmon5.sock'); time.sleep(0.3) +s.recv(65536); s.sendall(b'quit\n') +EOF +sleep 3 +pkill -f 'qemu-system-x86_64.*dbg-fat32.img' 2>/dev/null || true +sleep 2 + +echo "=== COM-порт, фрагмент PARAVIS DEBUG:" +sed -n '/=== PARAVIS DEBUG ===/,/=== END DEBUG ===/p' /tmp/krd.serial | head -60 +echo +echo "=== после загрузки:" +mount -o loop "$IMG" /mnt/krdtest +ls -A /mnt/krdtest; echo "--- KRD:"; ls -A /mnt/krdtest/efi/Paravis/KRD +umount /mnt/krdtest diff --git a/build-scripts/integration/krd/krd-dblmount.sh b/build-scripts/integration/krd/krd-dblmount.sh new file mode 100644 index 0000000..525b49c --- /dev/null +++ b/build-scripts/integration/krd/krd-dblmount.sh @@ -0,0 +1,17 @@ +#!/bin/bash +img=/root/krd24/dbl.img +rm -f $img; truncate -s 300M $img +mkfs.vfat -F 32 $img >/dev/null 2>&1 +mkdir -p /mnt/t_ro /mnt/t_rw +echo "=== mount ro:" +mount -o loop,ro $img /mnt/t_ro && echo " ok ro" +echo "=== второй mount того же образа rw (аналог устройства):" +# loop-устройство +LOOP=$(losetup -j $img | cut -d: -f1) +echo " loop=$LOOP" +mount -t vfat -o rw,utf8,uid=1000,gid=1000 "$LOOP" /mnt/t_rw 2>&1 && echo " ok rw" || echo " FAILED rw" +echo "=== запись через rw-монтирование:" +mkdir -p /mnt/t_rw/efi/Paravis/KRD/KRD2024_Data && echo " mkdir ok" || echo " mkdir failed" +ls -A /mnt/t_rw +umount /mnt/t_rw 2>/dev/null; umount /mnt/t_ro 2>/dev/null +losetup -d "$LOOP" 2>/dev/null diff --git a/build-scripts/integration/krd/krd-deploy-nobases.sh b/build-scripts/integration/krd/krd-deploy-nobases.sh new file mode 100644 index 0000000..3ad98f1 --- /dev/null +++ b/build-scripts/integration/krd/krd-deploy-nobases.sh @@ -0,0 +1,18 @@ +#!/bin/bash +set -e +W=/root/krd24 +F=/mnt/f/efi/Paravis/KRD +S=/path/to/pf/KRD/files + +echo "=== в стенд (D:\\PF2026\\KRD\\files) кладу оба варианта" +cp -f "$W/10-krd-emptybases.srm" "$S/live/KRD/10-krd-emptybases.srm" +cp -f "$W/15-bases-empty.srm" "$S/live/KRD/15-bases-empty.srm" +cp -f "$W/10-krd-final.srm" "$S/live/KRD/10-krd.srm" # основной (с полными базами) +ls -l "$S/live/KRD" + +echo +echo "=== на флешку: вариант без баз" +cp -f "$W/15-bases-empty.srm" "$F/live/KRD/15-bases-empty.srm" +cp -f "$W/10-krd-emptybases.srm" "$F/live/KRD/10-krd.srm" +rm -f "$F/live/KRD/30-bases.srm" +ls -l "$F/live/KRD" diff --git a/build-scripts/integration/krd/krd-eb2.sh b/build-scripts/integration/krd/krd-eb2.sh new file mode 100644 index 0000000..4edaddd --- /dev/null +++ b/build-scripts/integration/krd/krd-eb2.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -e +cd /root/krd24 +rm -rf eb; mkdir -p eb/Bin/Bases +rm -f 15-bases-empty.srm +mksquashfs eb 15-bases-empty.srm -comp xz -b 262144 -Xbcj x86 -noappend >/dev/null 2>&1 +unsquashfs -l 15-bases-empty.srm +cp -f 15-bases-empty.srm /root/krd24/nb3/live/KRD/ 2>/dev/null || true diff --git a/build-scripts/integration/krd/krd-emptybases-net.sh b/build-scripts/integration/krd/krd-emptybases-net.sh new file mode 100644 index 0000000..fa6730f --- /dev/null +++ b/build-scripts/integration/krd/krd-emptybases-net.sh @@ -0,0 +1,80 @@ +#!/bin/bash +# Тест: KRD без баз, но с патчем krt.sh + интернет. Скачает ли KRT базы сам? +set -e +SRC=/path/to/pf/KRD/files +NB=/root/krd24/nb3 +IMG=/root/krd24/nb3.img + +rm -rf "$NB"; mkdir -p "$NB/live/KRD" +cp "$SRC/live/vmlinuz" "$SRC/live/initrd.img" "$SRC/live/filesystem.squashfs" "$SRC/live/filesystem.packages" "$NB/live/" +cp "$SRC/live/KRD/20-krt.srm" "$NB/live/KRD/" +cp /root/krd24/10-krd-emptybases.srm "$NB/live/KRD/10-krd.srm" +cp /root/krd24/15-bases-empty.srm "$NB/live/KRD/" +cp "$SRC/krd_version.txt" "$SRC/krd_bases_timestamp.txt" "$NB/" + +rm -f "$IMG"; truncate -s 8G "$IMG" +mkfs.vfat -F 32 -n PARAVIS "$IMG" >/dev/null 2>&1 +mkdir -p /mnt/krdtest; mount -o loop "$IMG" /mnt/krdtest +mkdir -p /mnt/krdtest/efi/Paravis/KRD +cp -r "$NB/." /mnt/krdtest/efi/Paravis/KRD/ +sync; umount /mnt/krdtest +echo "=== раскладка (без баз):"; ls -R "$NB" | head -20 + +rm -f /tmp/qmonC.sock /tmp/nb3-*.ppm +qemu-system-x86_64 -m 4096 -smp 4 -machine q35 \ + -kernel "$NB/live/vmlinuz" -initrd "$NB/live/initrd.img" \ + -append "boot=live components live-media-path=/efi/Paravis/KRD/live locales=ru_RU.UTF-8 trace" \ + -drive file="$IMG",format=raw,if=ide -netdev user,id=n0 -device e1000,netdev=n0 \ + -display none -vga std -monitor unix:/tmp/qmonC.sock,server,nowait -daemonize + +python3 - <<'EOF' +import socket, time +def shot(name): + s = socket.socket(socket.AF_UNIX); s.connect('/tmp/qmonC.sock'); time.sleep(0.3) + s.recv(65536); s.sendall((f'screendump {name}\n').encode()); time.sleep(1.5) + try: s.recv(65536) + except Exception: pass + s.close() + +time.sleep(120); shot('/tmp/nb3-0.ppm') +time.sleep(60); shot('/tmp/nb3-1.ppm') +time.sleep(120); shot('/tmp/nb3-2.ppm') +s = socket.socket(socket.AF_UNIX); s.connect('/tmp/qmonC.sock'); time.sleep(0.3) +s.recv(65536); s.sendall(b'quit\n') +EOF +sleep 3 +pkill -f 'qemu-system-x86_64.*nb3.img' 2>/dev/null || true +sleep 2 + +echo "=== что появилось на носителе:" +mount -o loop "$IMG" /mnt/krdtest +find /mnt/krdtest/efi/Paravis/KRD/KRD2024_Data -maxdepth 2 2>/dev/null | sed 's|/mnt/krdtest||' | head -25 +echo "--- размеры:"; du -sh /mnt/krdtest/efi/Paravis/KRD/KRD2024_Data 2>/dev/null +echo "--- логи про базы/обновление:" +grep -rhiE 'bases|update|обнов' /mnt/krdtest/efi/Paravis/KRD/KRD2024_Data/Traces/*.log 2>/dev/null | tail -25 +umount /mnt/krdtest +python3 - <<'PYEOF' +import zlib, struct, glob +def ppm2png(src, dst): + d=open(src,'rb').read() + parts=[]; i=0 + while len(parts)<4: + while d[i:i+1].isspace(): i+=1 + j=i + while not d[j:j+1].isspace(): j+=1 + parts.append(d[i:j]); i=j + i+=1 + w=int(parts[1]); h=int(parts[2]); px=d[i:i+w*h*3] + raw=b''.join(b'\x00'+px[y*w*3:(y+1)*w*3] for y in range(h)) + def chunk(t,data): + c=t+data + return struct.pack('>I',len(data))+c+struct.pack('>I',zlib.crc32(c)&0xffffffff) + png=b'\x89PNG\r\n\x1a\n' + png+=chunk(b'IHDR',struct.pack('>IIBBBBB',w,h,8,2,0,0,0)) + png+=chunk(b'IDAT',zlib.compress(raw,9)) + png+=chunk(b'IEND',b'') + open(dst,'wb').write(png) + print(dst) +for i,f in enumerate(sorted(glob.glob('/tmp/nb3-*.ppm'))): + ppm2png(f, f'/path/to/pf/KRD/nb3-{i}.png') +PYEOF diff --git a/build-scripts/integration/krd/krd-emptybases.sh b/build-scripts/integration/krd/krd-emptybases.sh new file mode 100644 index 0000000..afabec5 --- /dev/null +++ b/build-scripts/integration/krd/krd-emptybases.sh @@ -0,0 +1,44 @@ +#!/bin/bash +# Пустой модуль баз + krt.sh, который его подставляет вместо отсутствующего 30-bases.srm. +set -e +W=/root/krd24 +cd "$W" + +echo "=== пустой модуль 15-bases-empty.srm" +rm -rf eb; mkdir -p eb/Bases +rm -f 15-bases-empty.srm +mksquashfs eb 15-bases-empty.srm -comp xz -b 262144 -Xbcj x86 -noappend >/dev/null 2>&1 +ls -l 15-bases-empty.srm +unsquashfs -l 15-bases-empty.srm + +echo "=== krt.sh: подстановка пустого модуля" +rm -rf srm10nb2; cp -a srm10nb srm10nb2 +python3 - <<'PYEOF' +import io +p='/root/krd24/srm10nb2/scripts/krt.sh' +s=io.open(p,encoding='utf-8').read() +old=''' if [[ -f "${bases_srm_path}" ]] + then + krt_srm_list+=("${bases_srm_path}") + else + log_disp_message "${LOG_FILENAME}" "${TRACE_LVL_WARNING}" "Bases module is absent <${bases_srm_path}>. Starting KRT without bases." + fi''' +new=''' if [[ -f "${bases_srm_path}" ]] + then + krt_srm_list+=("${bases_srm_path}") + elif [[ -f "${KRD_LIVE_LAYERS_SRM_FOLDER}/15-bases-empty.srm" ]] + then + log_disp_message "${LOG_FILENAME}" "${TRACE_LVL_WARNING}" "Bases module is absent, using empty bases module" + krt_srm_list+=("${KRD_LIVE_LAYERS_SRM_FOLDER}/15-bases-empty.srm") + else + log_disp_message "${LOG_FILENAME}" "${TRACE_LVL_WARNING}" "Bases module is absent <${bases_srm_path}>. Starting KRT without bases." + fi''' +assert old in s +io.open(p,'w',encoding='utf-8').write(s.replace(old,new,1)) +print(' ok') +PYEOF + +bash -n srm10nb2/scripts/krt.sh && echo " bash -n: OK" +rm -f 10-krd-emptybases.srm +mksquashfs srm10nb2 10-krd-emptybases.srm -comp xz -b 262144 -Xbcj x86 -noappend >/dev/null 2>&1 +ls -l 10-krd-emptybases.srm diff --git a/build-scripts/integration/krd/krd-final-test.sh b/build-scripts/integration/krd/krd-final-test.sh new file mode 100644 index 0000000..641c7ed --- /dev/null +++ b/build-scripts/integration/krd/krd-final-test.sh @@ -0,0 +1,48 @@ +#!/bin/bash +# Финальная проверка KRD 24: папка продукта внутри efi/Paravis/KRD + рабочий стол. +set -e +STAGE=/path/to/pf/KRD/files +IMG=/root/krd24/final-fat32.img + +rm -f "$IMG"; truncate -s 6G "$IMG" +mkfs.vfat -F 32 -n PARAVIS "$IMG" >/dev/null 2>&1 +mkdir -p /mnt/krdtest; mount -o loop "$IMG" /mnt/krdtest +mkdir -p /mnt/krdtest/efi/Paravis/KRD +cp -r "$STAGE/." /mnt/krdtest/efi/Paravis/KRD/ +sync +umount /mnt/krdtest + +rm -f /tmp/qmon6.sock /tmp/krd5.ppm /tmp/krd5b.ppm +qemu-system-x86_64 -m 3072 -smp 4 -machine q35 \ + -kernel "$STAGE/live/vmlinuz" -initrd "$STAGE/live/initrd.img" \ + -append "boot=live components live-media-path=/efi/Paravis/KRD/live locales=ru_RU.UTF-8" \ + -drive file="$IMG",format=raw,if=ide -net none -display none -vga std \ + -monitor unix:/tmp/qmon6.sock,server,nowait -daemonize + +sleep 105 +python3 - <<'EOF' +import socket, time +s = socket.socket(socket.AF_UNIX); s.connect('/tmp/qmon6.sock'); time.sleep(0.3) +s.recv(65536) +s.sendall(b'screendump /tmp/krd5.ppm\n'); time.sleep(1.5); s.recv(65536) +EOF +sleep 40 +python3 - <<'EOF' +import socket, time +s = socket.socket(socket.AF_UNIX); s.connect('/tmp/qmon6.sock'); time.sleep(0.3) +s.recv(65536) +s.sendall(b'screendump /tmp/krd5b.ppm\n'); time.sleep(1.5); s.recv(65536) +s.sendall(b'quit\n') +EOF +sleep 3 +pkill -f 'qemu-system-x86_64.*final-fat32.img' 2>/dev/null || true +sleep 2 + +echo "=== раздел после работы KRD:" +mount -o loop "$IMG" /mnt/krdtest +echo "--- корень:"; ls -A /mnt/krdtest +echo "--- efi/Paravis/KRD:"; ls -A /mnt/krdtest/efi/Paravis/KRD +echo "--- KRD2024_Data (2 уровня):"; find /mnt/krdtest/efi/Paravis/KRD/KRD2024_Data -maxdepth 2 | sed 's|/mnt/krdtest||' +echo "--- размер:"; du -sh /mnt/krdtest/efi/Paravis/KRD/KRD2024_Data +umount /mnt/krdtest +ls -l /tmp/krd5.ppm /tmp/krd5b.ppm diff --git a/build-scripts/integration/krd/krd-final1.sh b/build-scripts/integration/krd/krd-final1.sh new file mode 100644 index 0000000..7493031 --- /dev/null +++ b/build-scripts/integration/krd/krd-final1.sh @@ -0,0 +1,62 @@ +#!/bin/bash +set -e +W=/root/krd24 +cd "$W" + +echo "=== чистый srm + финальный патч" +rm -rf srm10f; unsquashfs -d srm10f 10-krd.srm >/dev/null 2>&1 + +python3 - <<'PYEOF' +import io +p='/root/krd24/srm10f/scripts/find_product_dir.sh' +s=io.open(p,encoding='utf-8').read() +anchor='''if [[ ! -f "${KRD_MOUNTS_FILE_PATH}" ]] +then + trace_message "${TRACE_LVL_ERROR}" "Volumes aren't mounted!" + trace_and_exit 1 +fi +''' +add=''' +# Paravis build: the product folder always lives inside efi/Paravis/KRD on the +# boot medium. No folders are created on other disks. +# live-boot mounts the medium read-only, and a second mount of the same block +# device reuses that superblock (so KRD's own rw mount stays ro) - hence the +# explicit remount. +paravis_medium="/run/live/medium" + +if [[ -d "${paravis_medium}/efi/Paravis/KRD/live" ]] +then + mount -o remount,rw "${paravis_medium}" 2>/dev/null + + if touch "${paravis_medium}/.paravis_rw_check" 2>/dev/null + then + rm -f "${paravis_medium}/.paravis_rw_check" + + paravis_product_dir="${paravis_medium}/efi/Paravis/KRD/${KRD_DATA_DIRECTORY_NAME}" + mkdir -p "${paravis_product_dir}/${KRD_TRACES_DIRNAME}" 2>/dev/null + + if [[ -d "${paravis_product_dir}/${KRD_TRACES_DIRNAME}" ]] + then + echo -e "${paravis_product_dir}" >> "${KRD_DATA_DIRECTORY_FILE_PATH}" + trace_message "${TRACE_LVL_INFO}" "Paravis build: product directory is <${paravis_product_dir}>" + trace_and_exit 0 + fi + fi +fi + +trace_message "${TRACE_LVL_ERROR}" "Paravis build: product folder is kept in RAM" +trace_and_exit 3 +''' +assert anchor in s, 'anchor' +assert 'Paravis build' not in s, 'already patched' +io.open(p,'w',encoding='utf-8').write(s.replace(anchor, anchor+add, 1)) +print(' патч применён') +PYEOF + +bash -n srm10f/scripts/find_product_dir.sh && echo " bash -n: OK" + +rm -f 10-krd-final.srm +mksquashfs srm10f 10-krd-final.srm -comp xz -b 262144 -Xbcj x86 -noappend >/dev/null 2>&1 +ls -l 10-krd-final.srm +cp -f 10-krd-final.srm /path/to/pf/KRD/files/live/KRD/10-krd.srm +echo " стенд обновлён (флешку обновим после теста)" diff --git a/build-scripts/integration/krd/krd-init-grep.sh b/build-scripts/integration/krd/krd-init-grep.sh new file mode 100644 index 0000000..2cef625 --- /dev/null +++ b/build-scripts/integration/krd/krd-init-grep.sh @@ -0,0 +1,7 @@ +#!/bin/bash +K=/tmp/insp/krd +echo "=== 'Cannot find device' context:" +grep -n -B 25 -A 10 'Cannot find device' "$K/init" | head -80 +echo +echo "=== subdir / datadev / basedev handling:" +grep -n 'subdir\|datadev\|basedev\|kernel.dat\|find_data\|hd0' "$K/init" | head -40 diff --git a/build-scripts/integration/krd/krd-kbd.sh b/build-scripts/integration/krd/krd-kbd.sh new file mode 100644 index 0000000..75cec3f --- /dev/null +++ b/build-scripts/integration/krd/krd-kbd.sh @@ -0,0 +1,75 @@ +#!/bin/bash +# Принять лицензию клавиатурой и увидеть главное окно KRT (без баз). +set -e +NB=/root/krd24/nb3 +IMG=/root/krd24/nb3.img + +rm -f "$IMG"; truncate -s 8G "$IMG" +mkfs.vfat -F 32 -n PARAVIS "$IMG" >/dev/null 2>&1 +mkdir -p /mnt/krdtest; mount -o loop "$IMG" /mnt/krdtest +mkdir -p /mnt/krdtest/efi/Paravis/KRD +cp -r "$NB/." /mnt/krdtest/efi/Paravis/KRD/ +sync; umount /mnt/krdtest + +rm -f /tmp/qmonD.sock /tmp/k*.ppm +qemu-system-x86_64 -m 4096 -smp 4 -machine q35 \ + -kernel "$NB/live/vmlinuz" -initrd "$NB/live/initrd.img" \ + -append "boot=live components live-media-path=/efi/Paravis/KRD/live locales=ru_RU.UTF-8 trace" \ + -drive file="$IMG",format=raw,if=ide -netdev user,id=n0 -device e1000,netdev=n0 \ + -display none -vga std -monitor unix:/tmp/qmonD.sock,server,nowait -daemonize + +python3 - <<'EOF' +import socket, time +def cmd(lines, pause=0.5): + s = socket.socket(socket.AF_UNIX); s.connect('/tmp/qmonD.sock'); time.sleep(0.25) + s.recv(65536) + for c in lines: + s.sendall((c+'\n').encode()); time.sleep(pause) + s.settimeout(1.0) + try: s.recv(65536) + except Exception: pass + s.close() + +time.sleep(155) +cmd(['screendump /tmp/k0.ppm']) + +# Tab -> чекбокс 1, Space; Tab -> 2, Space; Tab -> 3, Space +for i,(t,s_) in enumerate([('sendkey tab','sendkey spc')]*3, start=1): + cmd([t]); time.sleep(0.4) + cmd([s_]); time.sleep(0.6) + cmd([f'screendump /tmp/k{i}.ppm']) +# далее: чекбоксы -> Отказаться -> Принять +cmd(['sendkey tab']); cmd(['sendkey tab']); time.sleep(0.5) +cmd(['screendump /tmp/k4.ppm']) +cmd(['sendkey ret']); time.sleep(10) +cmd(['screendump /tmp/k5.ppm']); time.sleep(8) +cmd(['screendump /tmp/k6.ppm']) +cmd(['quit']) +EOF +sleep 3 +pkill -f 'qemu-system-x86_64.*nb3.img' 2>/dev/null || true +python3 - <<'PYEOF' +import zlib, struct, glob, os +def ppm2png(src, dst): + d=open(src,'rb').read() + parts=[]; i=0 + while len(parts)<4: + while d[i:i+1].isspace(): i+=1 + j=i + while not d[j:j+1].isspace(): j+=1 + parts.append(d[i:j]); i=j + i+=1 + w=int(parts[1]); h=int(parts[2]); px=d[i:i+w*h*3] + raw=b''.join(b'\x00'+px[y*w*3:(y+1)*w*3] for y in range(h)) + def chunk(t,data): + c=t+data + return struct.pack('>I',len(data))+c+struct.pack('>I',zlib.crc32(c)&0xffffffff) + png=b'\x89PNG\r\n\x1a\n' + png+=chunk(b'IHDR',struct.pack('>IIBBBBB',w,h,8,2,0,0,0)) + png+=chunk(b'IDAT',zlib.compress(raw,9)) + png+=chunk(b'IEND',b'') + open(dst,'wb').write(png) + print(dst) +for f in sorted(glob.glob('/tmp/k?.ppm')): + ppm2png(f, '/path/to/pf/KRD/' + os.path.basename(f).replace('.ppm','.png')) +PYEOF diff --git a/build-scripts/integration/krd/krd-kbd2.sh b/build-scripts/integration/krd/krd-kbd2.sh new file mode 100644 index 0000000..00f9ec5 --- /dev/null +++ b/build-scripts/integration/krd/krd-kbd2.sh @@ -0,0 +1,74 @@ +#!/bin/bash +# Принять лицензию: Space (1), Tab Space (2), Tab Space (3), Tab Tab, Enter. +set -e +NB=/root/krd24/nb3 +IMG=/root/krd24/nb3.img + +rm -f "$IMG"; truncate -s 8G "$IMG" +mkfs.vfat -F 32 -n PARAVIS "$IMG" >/dev/null 2>&1 +mkdir -p /mnt/krdtest; mount -o loop "$IMG" /mnt/krdtest +mkdir -p /mnt/krdtest/efi/Paravis/KRD +cp -r "$NB/." /mnt/krdtest/efi/Paravis/KRD/ +sync; umount /mnt/krdtest + +rm -f /tmp/qmonE.sock /tmp/k*.ppm +qemu-system-x86_64 -m 4096 -smp 4 -machine q35 \ + -kernel "$NB/live/vmlinuz" -initrd "$NB/live/initrd.img" \ + -append "boot=live components live-media-path=/efi/Paravis/KRD/live locales=ru_RU.UTF-8 trace" \ + -drive file="$IMG",format=raw,if=ide -netdev user,id=n0 -device e1000,netdev=n0 \ + -display none -vga std -monitor unix:/tmp/qmonE.sock,server,nowait -daemonize + +python3 - <<'EOF' +import socket, time +def cmd(lines, pause=0.5): + s = socket.socket(socket.AF_UNIX); s.connect('/tmp/qmonE.sock'); time.sleep(0.25) + s.recv(65536) + for c in lines: + s.sendall((c+'\n').encode()); time.sleep(pause) + s.settimeout(1.0) + try: s.recv(65536) + except Exception: pass + s.close() + +time.sleep(155) +cmd(['screendump /tmp/k0.ppm']) + +cmd(['sendkey spc']); time.sleep(0.5) # 1-я галочка +cmd(['sendkey tab']); cmd(['sendkey spc']); time.sleep(0.5) # 2-я +cmd(['sendkey tab']); cmd(['sendkey spc']); time.sleep(0.5) # 3-я +cmd(['screendump /tmp/k1.ppm']) +cmd(['sendkey tab']); cmd(['sendkey tab']); time.sleep(0.5) # Принять +cmd(['screendump /tmp/k2.ppm']) +cmd(['sendkey ret']); time.sleep(12) +cmd(['screendump /tmp/k3.ppm']); time.sleep(10) +cmd(['screendump /tmp/k4.ppm']); time.sleep(10) +cmd(['screendump /tmp/k5.ppm']) +cmd(['quit']) +EOF +sleep 3 +pkill -f 'qemu-system-x86_64.*nb3.img' 2>/dev/null || true +python3 - <<'PYEOF' +import zlib, struct, glob, os +def ppm2png(src, dst): + d=open(src,'rb').read() + parts=[]; i=0 + while len(parts)<4: + while d[i:i+1].isspace(): i+=1 + j=i + while not d[j:j+1].isspace(): j+=1 + parts.append(d[i:j]); i=j + i+=1 + w=int(parts[1]); h=int(parts[2]); px=d[i:i+w*h*3] + raw=b''.join(b'\x00'+px[y*w*3:(y+1)*w*3] for y in range(h)) + def chunk(t,data): + c=t+data + return struct.pack('>I',len(data))+c+struct.pack('>I',zlib.crc32(c)&0xffffffff) + png=b'\x89PNG\r\n\x1a\n' + png+=chunk(b'IHDR',struct.pack('>IIBBBBB',w,h,8,2,0,0,0)) + png+=chunk(b'IDAT',zlib.compress(raw,9)) + png+=chunk(b'IEND',b'') + open(dst,'wb').write(png) + print(dst) +for f in sorted(glob.glob('/tmp/k?.ppm')): + ppm2png(f, '/path/to/pf/KRD/' + os.path.basename(f).replace('.ppm','.png')) +PYEOF diff --git a/build-scripts/integration/krd/krd-net-test.sh b/build-scripts/integration/krd/krd-net-test.sh new file mode 100644 index 0000000..add081d --- /dev/null +++ b/build-scripts/integration/krd/krd-net-test.sh @@ -0,0 +1,49 @@ +#!/bin/bash +# Проверка автообновления баз: QEMU с пользовательской сетью + трассировка. +set -e +STAGE=/path/to/pf/KRD/files +IMG=/root/krd24/net-fat32.img + +rm -f "$IMG"; truncate -s 8G "$IMG" +mkfs.vfat -F 32 -n PARAVIS "$IMG" >/dev/null 2>&1 +mkdir -p /mnt/krdtest; mount -o loop "$IMG" /mnt/krdtest +mkdir -p /mnt/krdtest/efi/Paravis/KRD +cp -r "$STAGE/." /mnt/krdtest/efi/Paravis/KRD/ +sync +echo "=== до загрузки:"; ls -A /mnt/krdtest/efi/Paravis/KRD +umount /mnt/krdtest + +rm -f /tmp/qmon8.sock /tmp/krd8.ppm +qemu-system-x86_64 -m 4096 -smp 4 -machine q35 \ + -kernel "$STAGE/live/vmlinuz" -initrd "$STAGE/live/initrd.img" \ + -append "boot=live components live-media-path=/efi/Paravis/KRD/live locales=ru_RU.UTF-8 trace" \ + -drive file="$IMG",format=raw,if=ide \ + -netdev user,id=n0 -device e1000,netdev=n0 \ + -display none -vga std \ + -monitor unix:/tmp/qmon8.sock,server,nowait -daemonize + +sleep 120 +python3 - <<'EOF' +import socket, time +s = socket.socket(socket.AF_UNIX); s.connect('/tmp/qmon8.sock'); time.sleep(0.3) +s.recv(65536) +s.sendall(b'screendump /tmp/krd8.ppm\n'); time.sleep(1.5); s.recv(65536) +EOF +sleep 120 +python3 - <<'EOF' +import socket, time +s = socket.socket(socket.AF_UNIX); s.connect('/tmp/qmon8.sock'); time.sleep(0.3) +s.recv(65536); s.sendall(b'quit\n') +EOF +sleep 3 +pkill -f 'qemu-system-x86_64.*net-fat32.img' 2>/dev/null || true +sleep 2 + +echo "=== после ~4 минут работы:" +mount -o loop "$IMG" /mnt/krdtest +echo "--- KRD:"; ls -A /mnt/krdtest/efi/Paravis/KRD +echo "--- продуктовая папка:"; find /mnt/krdtest/efi/Paravis/KRD/KRD2024_Data -maxdepth 2 2>/dev/null | sed 's|/mnt/krdtest||' | head -20 +echo "--- размер:"; du -sh /mnt/krdtest/efi/Paravis/KRD/KRD2024_Data 2>/dev/null +echo "--- про обновление в логах:" +grep -rhiE 'update|обнов|bases' /mnt/krdtest/efi/Paravis/KRD/KRD2024_Data/Traces/*.log 2>/dev/null | head -30 +umount /mnt/krdtest diff --git a/build-scripts/integration/krd/krd-new-cfg.sh b/build-scripts/integration/krd/krd-new-cfg.sh new file mode 100644 index 0000000..fc22698 --- /dev/null +++ b/build-scripts/integration/krd/krd-new-cfg.sh @@ -0,0 +1,24 @@ +#!/bin/bash +ISO=/path/to/pf/KRD/krd.iso +echo "=== /live:" +xorriso -indev "$ISO" -ls /live 2>/dev/null | head -30 +echo +echo "=== /boot/grub/grub.cfg:" +xorriso -osirrox on -indev "$ISO" -extract /boot/grub/grub.cfg /tmp/krd-grub.cfg >/dev/null 2>&1 +cat /tmp/krd-grub.cfg +echo +echo "=== /boot/grub/cfg/menu.cfg:" +xorriso -osirrox on -indev "$ISO" -extract /boot/grub/cfg/menu.cfg /tmp/krd-menu.cfg >/dev/null 2>&1 +cat /tmp/krd-menu.cfg +echo +echo "=== /boot/grub/cfg/ru.cfg:" +xorriso -osirrox on -indev "$ISO" -extract /boot/grub/cfg/ru.cfg /tmp/krd-ru.cfg >/dev/null 2>&1 +cat /tmp/krd-ru.cfg +echo +echo "=== /boot/grub/config.cfg:" +xorriso -osirrox on -indev "$ISO" -extract /boot/grub/config.cfg /tmp/krd-config.cfg >/dev/null 2>&1 +cat /tmp/krd-config.cfg +echo +echo "=== krd_version.txt:" +xorriso -osirrox on -indev "$ISO" -extract /krd_version.txt /tmp/krd-ver.txt >/dev/null 2>&1 +cat /tmp/krd-ver.txt diff --git a/build-scripts/integration/krd/krd-new-initrd.sh b/build-scripts/integration/krd/krd-new-initrd.sh new file mode 100644 index 0000000..5926b8f --- /dev/null +++ b/build-scripts/integration/krd/krd-new-initrd.sh @@ -0,0 +1,24 @@ +#!/bin/bash +set -e +W=/root/krd24 +rm -rf "$W"; mkdir -p "$W"; cd "$W" +ISO=/path/to/pf/KRD/krd.iso +xorriso -osirrox on -indev "$ISO" -extract /live/initrd.img initrd.img >/dev/null 2>&1 +ls -l initrd.img +mkdir ir +cd ir +# Debian-style: possibly gzip or zstd or uncompressed cpio +file ../initrd.img +case "$(file -b ../initrd.img)" in + *gzip*) gzip -dc ../initrd.img | cpio -idm --quiet ;; + *XZ*) xz -dc ../initrd.img | cpio -idm --quiet ;; + *Zstandard*) zstd -dc ../initrd.img | cpio -idm --quiet ;; + *cpio*) cpio -idm --quiet < ../initrd.img ;; + *) echo "unknown format"; exit 1 ;; +esac +echo "=== top level:" +ls | head -30 +echo +echo "=== init: $(ls -l init 2>/dev/null | awk '{print $5}') bytes" +echo "=== grep boot params:" +grep -nE 'findiso|live-media-path|subdir|bootfrom|live-media|KRD|\.srm|squashfs' init | head -40 diff --git a/build-scripts/integration/krd/krd-new-initrd2.sh b/build-scripts/integration/krd/krd-new-initrd2.sh new file mode 100644 index 0000000..f2f32e8 --- /dev/null +++ b/build-scripts/integration/krd/krd-new-initrd2.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -e +apt-get install -y zstd cpio >/tmp/apt-zstd.log 2>&1 || true +W=/root/krd24 +cd "$W"; rm -rf ir; mkdir ir; cd ir +zstd -dc ../initrd.img | cpio -idm --quiet +echo "=== top level:" +ls | head -40 +echo +echo "=== init size: $(stat -c %s init 2>/dev/null)" +echo "=== grep params in init:" +grep -nE 'findiso|live-media-path|subdir|bootfrom|live-media|krd|srm|squashfs' init | head -50 diff --git a/build-scripts/integration/krd/krd-new-initrd3.sh b/build-scripts/integration/krd/krd-new-initrd3.sh new file mode 100644 index 0000000..22fd934 --- /dev/null +++ b/build-scripts/integration/krd/krd-new-initrd3.sh @@ -0,0 +1,10 @@ +#!/bin/bash +cd /root/krd24/ir || exit 1 +echo "=== init:" +cat init +echo +echo "=== scripts:" +ls -l scripts | head -30 +echo +echo "=== recursive grep for findiso / media path:" +grep -rnE 'findiso|live-media-path|live-media|bootfrom|subdir' scripts lib 2>/dev/null | head -40 diff --git a/build-scripts/integration/krd/krd-new-layers.sh b/build-scripts/integration/krd/krd-new-layers.sh new file mode 100644 index 0000000..be82b0e --- /dev/null +++ b/build-scripts/integration/krd/krd-new-layers.sh @@ -0,0 +1,13 @@ +#!/bin/bash +echo "=== в initrd:" +grep -rn 'KRD_LIVE_LAYERS\|live_layers\|KRD_SRM' /root/krd24/ir 2>/dev/null | head -20 +echo +echo "=== в squashfs (по списку файлов /etc/KRD):" +cd /root/krd24 || exit 1 +unsquashfs -l filesystem.squashfs 2>/dev/null | grep 'squashfs-root/etc/KRD' +echo +echo "=== содержимое /etc/KRD/*:" +for f in $(unsquashfs -l filesystem.squashfs 2>/dev/null | grep 'squashfs-root/etc/KRD/' | sed 's/^squashfs-root\///'); do + echo "----- /$f" + unsquashfs -cat filesystem.squashfs "$f" 2>/dev/null | grep -nE 'KRD_LIVE|LAYERS|SRM|live' | head -20 +done diff --git a/build-scripts/integration/krd/krd-new-livepath.sh b/build-scripts/integration/krd/krd-new-livepath.sh new file mode 100644 index 0000000..2ef1936 --- /dev/null +++ b/build-scripts/integration/krd/krd-new-livepath.sh @@ -0,0 +1,13 @@ +#!/bin/bash +cd /root/krd24/ir || exit 1 +echo "=== is_live_path:" +grep -n -A12 'is_live_path ()' lib/live/boot/*.sh | head -30 +echo +echo "=== LIVE_MEDIA_PATH default / usage:" +grep -rn 'LIVE_MEDIA_PATH' lib/live/boot/*.sh | head -20 +echo +echo "=== 0001-init-vars.sh:" +cat lib/live/boot/0001-init-vars.sh +echo +echo "=== свободно в WSL:" +df -h / | tail -1 diff --git a/build-scripts/integration/krd/krd-new-ls.sh b/build-scripts/integration/krd/krd-new-ls.sh new file mode 100644 index 0000000..4d7bc81 --- /dev/null +++ b/build-scripts/integration/krd/krd-new-ls.sh @@ -0,0 +1,10 @@ +#!/bin/bash +ISO=/path/to/pf/KRD/krd.iso +echo "=== root listing:" +xorriso -indev "$ISO" -ls / 2>/dev/null | head -40 +echo +echo "=== all files (first 80):" +xorriso -indev "$ISO" -find / -type f 2>/dev/null | sed "s/^'//;s/'$//" | sort | head -80 +echo +echo "=== el torito:" +xorriso -indev "$ISO" -report_el_torito plain 2>/dev/null | head -20 diff --git a/build-scripts/integration/krd/krd-new-medium.sh b/build-scripts/integration/krd/krd-new-medium.sh new file mode 100644 index 0000000..dba8652 --- /dev/null +++ b/build-scripts/integration/krd/krd-new-medium.sh @@ -0,0 +1,7 @@ +#!/bin/bash +cd /root/krd24/ir || exit 1 +echo "=== /run/live/medium usage:" +grep -rn '/run/live/medium\|medium=' lib/live/boot/*.sh | head -30 +echo +echo "=== mount_images_in_directory / findiso:" +sed -n '200,275p' lib/live/boot/9990-misc-helpers.sh diff --git a/build-scripts/integration/krd/krd-new-menu.sh b/build-scripts/integration/krd/krd-new-menu.sh new file mode 100644 index 0000000..9c9dc84 --- /dev/null +++ b/build-scripts/integration/krd/krd-new-menu.sh @@ -0,0 +1,13 @@ +#!/bin/bash +ISO=/path/to/pf/KRD/krd.iso +echo "=== /boot/grub/krd_menu.cfg:" +xorriso -osirrox on -indev "$ISO" -extract /boot/grub/krd_menu.cfg /tmp/krd_menu.cfg >/dev/null 2>&1 && cat /tmp/krd_menu.cfg +echo +echo "=== sizes in /live:" +xorriso -indev "$ISO" -find /live -exec lsdl -- 2>/dev/null | head -20 +echo +echo "=== /live/KRD contents:" +xorriso -indev "$ISO" -find /live/KRD 2>/dev/null | head -40 +echo +echo "=== initrd / kernel / squashfs sizes via xorriso:" +xorriso -indev "$ISO" -ls /live 2>/dev/null diff --git a/build-scripts/integration/krd/krd-new-misc.sh b/build-scripts/integration/krd/krd-new-misc.sh new file mode 100644 index 0000000..1157d74 --- /dev/null +++ b/build-scripts/integration/krd/krd-new-misc.sh @@ -0,0 +1,5 @@ +#!/bin/bash +cd /root/krd24/ir || exit 1 +sed -n '1,80p' lib/live/boot/9990-misc-helpers.sh +echo "=== is_live_path def:" +grep -rn 'is_live_path' lib/live/boot/ | head diff --git a/build-scripts/integration/krd/krd-new-prod.sh b/build-scripts/integration/krd/krd-new-prod.sh new file mode 100644 index 0000000..5e947ef --- /dev/null +++ b/build-scripts/integration/krd/krd-new-prod.sh @@ -0,0 +1,7 @@ +#!/bin/bash +cd /root/krd24/srm10 || exit 1 +echo "=== все упоминания BOOT_FOLDER / medium / DATA_DIRECTORY:" +grep -rn 'KRD_LIVE_LAYERS_BOOT_FOLDER\|/run/live\|KRD_DATA_DIRECTORY_NAME\|\.product_dir' . 2>/dev/null | head -30 +echo +echo "=== find_product_dir.sh:" +cat scripts/find_product_dir.sh 2>/dev/null | head -80 diff --git a/build-scripts/integration/krd/krd-new-qemu.sh b/build-scripts/integration/krd/krd-new-qemu.sh new file mode 100644 index 0000000..d1f63d5 --- /dev/null +++ b/build-scripts/integration/krd/krd-new-qemu.sh @@ -0,0 +1,47 @@ +#!/bin/bash +# KRD 24 из файлов: подготовка стенда и запуск в QEMU (vvfat = папка как FAT-диск). +set -e +STAGE=/path/to/pf/KRD/files +ISO=/path/to/pf/KRD/krd.iso +W=/root/krd24 + +echo "=== раскладка:" +rm -rf "$STAGE" +mkdir -p "$STAGE/live/KRD" + +for f in live/vmlinuz live/initrd.img live/filesystem.packages live/KRD/10-krd.srm live/KRD/20-krt.srm live/KRD/30-bases.srm krd_version.txt krd_bases_timestamp.txt; do + xorriso -osirrox on -indev "$ISO" -extract "/$f" "$STAGE/$f" >/dev/null 2>&1 && echo " $f" +done +cp -f "$W/filesystem-patched.squashfs" "$STAGE/live/filesystem.squashfs" +ls -lR "$STAGE" | head -30 + +echo +echo "=== запуск QEMU (kernel + initrd напрямую, носитель = vvfat)" +rm -f /tmp/qmon2.sock /tmp/krd1.ppm /tmp/krd2.ppm +qemu-system-x86_64 -m 3072 -smp 4 -machine q35 \ + -kernel "$STAGE/live/vmlinuz" \ + -initrd "$STAGE/live/initrd.img" \ + -append "boot=live components live-media-path=/efi/Paravis/KRD/live locales=ru_RU.UTF-8 quiet" \ + -drive "file=fat:rw:$STAGE,format=raw" \ + -net none -display none -vga std \ + -monitor unix:/tmp/qmon2.sock,server,nowait -daemonize + +sleep 90 +python3 - <<'EOF' +import socket, time +s = socket.socket(socket.AF_UNIX); s.connect('/tmp/qmon2.sock'); time.sleep(0.3) +s.recv(65536) +s.sendall(b'screendump /tmp/krd1.ppm\n'); time.sleep(1.5); s.recv(65536) +EOF +sleep 60 +python3 - <<'EOF' +import socket, time +s = socket.socket(socket.AF_UNIX); s.connect('/tmp/qmon2.sock'); time.sleep(0.3) +s.recv(65536) +s.sendall(b'screendump /tmp/krd2.ppm\n'); time.sleep(1.5); s.recv(65536) +s.sendall(b'info registers\n'); time.sleep(0.5) +s.sendall(b'quit\n') +EOF +sleep 2 +pkill -f 'qemu-system-x86_64.*live-media-path' 2>/dev/null || true +ls -l /tmp/krd1.ppm /tmp/krd2.ppm diff --git a/build-scripts/integration/krd/krd-new-qemu2.sh b/build-scripts/integration/krd/krd-new-qemu2.sh new file mode 100644 index 0000000..92d1787 --- /dev/null +++ b/build-scripts/integration/krd/krd-new-qemu2.sh @@ -0,0 +1,48 @@ +#!/bin/bash +# KRD 24 из файлов: образ FAT32 + запуск в QEMU. +set -e +STAGE=/path/to/pf/KRD/files +IMG=/root/krd24/test-fat32.img + +echo "=== готовлю FAT32-образ" +apt-get install -y dosfstools mtools >/tmp/apt-fat.log 2>&1 || true +rm -f "$IMG" +truncate -s 1200M "$IMG" +mkfs.vfat -F 32 -n PARAVIS "$IMG" > /tmp/mkfat.log 2>&1 +mkdir -p /mnt/krdtest +mount -o loop "$IMG" /mnt/krdtest +mkdir -p /mnt/krdtest/efi/Paravis/KRD +cp -r "$STAGE/." /mnt/krdtest/efi/Paravis/KRD/ +sync +du -sh /mnt/krdtest; df -h /mnt/krdtest | tail -1 +umount /mnt/krdtest +ls -l "$IMG" + +echo "=== запуск QEMU" +rm -f /tmp/qmon2.sock /tmp/krd1.ppm /tmp/krd2.ppm +qemu-system-x86_64 -m 3072 -smp 4 -machine q35 \ + -kernel "$STAGE/live/vmlinuz" \ + -initrd "$STAGE/live/initrd.img" \ + -append "boot=live components live-media-path=/efi/Paravis/KRD/live locales=ru_RU.UTF-8" \ + -drive file="$IMG",format=raw,if=ide \ + -net none -display none -vga std \ + -monitor unix:/tmp/qmon2.sock,server,nowait -daemonize + +sleep 100 +python3 - <<'EOF' +import socket, time +s = socket.socket(socket.AF_UNIX); s.connect('/tmp/qmon2.sock'); time.sleep(0.3) +s.recv(65536) +s.sendall(b'screendump /tmp/krd1.ppm\n'); time.sleep(1.5); s.recv(65536) +EOF +sleep 70 +python3 - <<'EOF' +import socket, time +s = socket.socket(socket.AF_UNIX); s.connect('/tmp/qmon2.sock'); time.sleep(0.3) +s.recv(65536) +s.sendall(b'screendump /tmp/krd2.ppm\n'); time.sleep(1.5); s.recv(65536) +s.sendall(b'quit\n') +EOF +sleep 2 +pkill -f 'qemu-system-x86_64.*krd24/test-fat32.img' 2>/dev/null || true +ls -l /tmp/krd1.ppm /tmp/krd2.ppm diff --git a/build-scripts/integration/krd/krd-new-repack.sh b/build-scripts/integration/krd/krd-new-repack.sh new file mode 100644 index 0000000..a61418b --- /dev/null +++ b/build-scripts/integration/krd/krd-new-repack.sh @@ -0,0 +1,36 @@ +#!/bin/bash +set -e +W=/root/krd24 +cd "$W" + +if grep -q 'Paravis: KRD from files' sqroot/etc/KRD/live_env.sh; then + echo " уже пропатчено" +else + python3 - <<'EOF' +import io +p='/root/krd24/sqroot/etc/KRD/live_env.sh' +s=io.open(p,encoding='utf-8').read() +old='export KRD_LIVE_LAYERS_BOOT_FOLDER="/run/live/medium"\n' +new=('export KRD_LIVE_LAYERS_BOOT_FOLDER="/run/live/medium"\n' + '# Paravis: KRD from files (efi/Paravis/KRD/live) instead of ISO image\n' + 'if [[ -d "/run/live/medium/efi/Paravis/KRD/live/KRD" ]]\n' + 'then\n' + ' export KRD_LIVE_LAYERS_BOOT_FOLDER="/run/live/medium/efi/Paravis/KRD"\n' + 'fi\n') +assert old in s +io.open(p,'w',encoding='utf-8').write(s.replace(old,new,1)) +print(' live_env.sh: патч применён') +EOF +fi +echo "=== результат:" +sed -n '76,86p' sqroot/etc/KRD/live_env.sh + +echo "=== пересборка squashfs (xz, 256K, 16 потоков) ..." +rm -f filesystem-patched.squashfs +mksquashfs sqroot filesystem-patched.squashfs \ + -comp xz -b 262144 -noappend -processors 16 > /tmp/mksq.log 2>&1 || { tail -20 /tmp/mksq.log; exit 1; } +tail -4 /tmp/mksq.log +ls -l filesystem.squashfs filesystem-patched.squashfs +echo "=== проверка нового образа:" +unsquashfs -s filesystem-patched.squashfs | head -6 +unsquashfs -cat filesystem-patched.squashfs etc/KRD/live_env.sh 2>/dev/null | sed -n '76,86p' diff --git a/build-scripts/integration/krd/krd-new-sq.sh b/build-scripts/integration/krd/krd-new-sq.sh new file mode 100644 index 0000000..1ef908a --- /dev/null +++ b/build-scripts/integration/krd/krd-new-sq.sh @@ -0,0 +1,13 @@ +#!/bin/bash +set -e +apt-get install -y squashfs-tools >/tmp/apt-sq.log 2>&1 || true +W=/root/krd24 +cd "$W" +# извлечь squashfs из ISO +[ -f filesystem.squashfs ] || xorriso -osirrox on -indev /path/to/pf/KRD/krd.iso -extract /live/filesystem.squashfs filesystem.squashfs >/dev/null 2>&1 +ls -l filesystem.squashfs +echo "=== файлы/скрипты, связанные с krd:" +unsquashfs -l filesystem.squashfs 2>/dev/null | grep -iE 'krd|kaspersky|\.srm' | head -40 +echo +echo "=== root-level dirs:" +unsquashfs -l filesystem.squashfs 2>/dev/null | awk -F/ 'NF<=3' | head -40 diff --git a/build-scripts/integration/krd/krd-new-sq2.sh b/build-scripts/integration/krd/krd-new-sq2.sh new file mode 100644 index 0000000..3d168f0 --- /dev/null +++ b/build-scripts/integration/krd/krd-new-sq2.sh @@ -0,0 +1,11 @@ +#!/bin/bash +cd /root/krd24 || exit 1 +S=filesystem.squashfs +echo "=== /etc/KRD/live_env.sh:" +unsquashfs -cat $S etc/KRD/live_env.sh 2>/dev/null | head -60 +echo +echo "=== /etc/systemd/system/krd.service:" +unsquashfs -cat $S etc/systemd/system/krd.service 2>/dev/null +echo +echo "=== krd-файлы в /usr:" +unsquashfs -l $S 2>/dev/null | grep -E 'squashfs-root/(usr/(bin|sbin|lib)/[^/]*krd|usr/lib/krd|etc/init\.d/.*krd|opt/)' | head -30 diff --git a/build-scripts/integration/krd/krd-new-sqinfo.sh b/build-scripts/integration/krd/krd-new-sqinfo.sh new file mode 100644 index 0000000..a3dc161 --- /dev/null +++ b/build-scripts/integration/krd/krd-new-sqinfo.sh @@ -0,0 +1,13 @@ +#!/bin/bash +cd /root/krd24 || exit 1 +echo "=== squashfs info:" +unsquashfs -s filesystem.squashfs | head -25 +echo +echo "=== число файлов:" +unsquashfs -l filesystem.squashfs 2>/dev/null | wc -l +echo +echo "=== live_env.sh строки 60-95:" +unsquashfs -cat filesystem.squashfs etc/KRD/live_env.sh 2>/dev/null | sed -n '60,95p' | cat -n +echo +echo "=== есть ли xattr в образе (пример):" +unsquashfs -l filesystem.squashfs 2>/dev/null | grep -E 'usr/bin/(ping|su|passwd)$' | head diff --git a/build-scripts/integration/krd/krd-new-srm10.sh b/build-scripts/integration/krd/krd-new-srm10.sh new file mode 100644 index 0000000..f067489 --- /dev/null +++ b/build-scripts/integration/krd/krd-new-srm10.sh @@ -0,0 +1,11 @@ +#!/bin/bash +set -e +W=/root/krd24 +cd "$W" +xorriso -osirrox on -indev /path/to/pf/KRD/krd.iso -extract /live/KRD/10-krd.srm 10-krd.srm >/dev/null 2>&1 +unsquashfs -l 10-krd.srm 2>/dev/null | head -30 +echo "=== ищем проверки целостности/путей:" +rm -rf srm10; unsquashfs -d srm10 10-krd.srm >/dev/null 2>&1 || true +grep -rn 'KRD_MAKE_INTEGRITY_CHECKS\|live/medium\|live/KRD\|LAYERS_BOOT' srm10 2>/dev/null | head -20 +echo "=== scripts:" +ls srm10/opt/KRD/scripts 2>/dev/null | head -20 diff --git a/build-scripts/integration/krd/krd-new-start.sh b/build-scripts/integration/krd/krd-new-start.sh new file mode 100644 index 0000000..9043913 --- /dev/null +++ b/build-scripts/integration/krd/krd-new-start.sh @@ -0,0 +1,10 @@ +#!/bin/bash +cd /root/krd24 || exit 1 +S=filesystem.squashfs +unsquashfs -cat $S usr/sbin/krd.start 2>/dev/null > /tmp/krd.start +wc -l /tmp/krd.start +echo "=== ключевые места:" +grep -nE 'live|findiso|media|srm|KRD_DATA|Bases|mount|medium' /tmp/krd.start | head -60 +echo +echo "=== ищем скрипты, которые кладут .srm:" +unsquashfs -l $S 2>/dev/null | grep -E 'squashfs-root/(opt|usr/share|usr/lib)/.*(krd|KRD)' | head -30 diff --git a/build-scripts/integration/krd/krd-new-start2.sh b/build-scripts/integration/krd/krd-new-start2.sh new file mode 100644 index 0000000..39b3123 --- /dev/null +++ b/build-scripts/integration/krd/krd-new-start2.sh @@ -0,0 +1,2 @@ +#!/bin/bash +sed -n '1,110p' /tmp/krd.start diff --git a/build-scripts/integration/krd/krd-new-unpack.sh b/build-scripts/integration/krd/krd-new-unpack.sh new file mode 100644 index 0000000..7d987ed --- /dev/null +++ b/build-scripts/integration/krd/krd-new-unpack.sh @@ -0,0 +1,14 @@ +#!/bin/bash +set -e +W=/root/krd24 +cd "$W" +echo "=== nproc: $(nproc)" +echo "=== кто читает timestamp/version на носителе:" +grep -rn 'krd_bases_timestamp\|krd_version' srm10 2>/dev/null | head -10 +echo +echo "=== распаковка squashfs (может занять пару минут)..." +rm -rf sqroot +unsquashfs -d sqroot filesystem.squashfs > /tmp/unsq.log 2>&1 +tail -3 /tmp/unsq.log +echo "=== live_env.sh до правки (строки 74-82):" +sed -n '74,82p' sqroot/etc/KRD/live_env.sh diff --git a/build-scripts/integration/krd/krd-nobases-net.sh b/build-scripts/integration/krd/krd-nobases-net.sh new file mode 100644 index 0000000..9531512 --- /dev/null +++ b/build-scripts/integration/krd/krd-nobases-net.sh @@ -0,0 +1,79 @@ +#!/bin/bash +# Тест: KRD без баз, но с патчем krt.sh + интернет. Скачает ли KRT базы сам? +set -e +SRC=/path/to/pf/KRD/files +NB=/root/krd24/nb2 +IMG=/root/krd24/nb2.img + +rm -rf "$NB"; mkdir -p "$NB/live/KRD" +cp "$SRC/live/vmlinuz" "$SRC/live/initrd.img" "$SRC/live/filesystem.squashfs" "$SRC/live/filesystem.packages" "$NB/live/" +cp "$SRC/live/KRD/20-krt.srm" "$NB/live/KRD/" +cp /root/krd24/10-krd-nobases.srm "$NB/live/KRD/10-krd.srm" +cp "$SRC/krd_version.txt" "$SRC/krd_bases_timestamp.txt" "$NB/" + +rm -f "$IMG"; truncate -s 8G "$IMG" +mkfs.vfat -F 32 -n PARAVIS "$IMG" >/dev/null 2>&1 +mkdir -p /mnt/krdtest; mount -o loop "$IMG" /mnt/krdtest +mkdir -p /mnt/krdtest/efi/Paravis/KRD +cp -r "$NB/." /mnt/krdtest/efi/Paravis/KRD/ +sync; umount /mnt/krdtest +echo "=== раскладка (без баз):"; ls -R "$NB" | head -20 + +rm -f /tmp/qmonB.sock /tmp/nb2-*.ppm +qemu-system-x86_64 -m 4096 -smp 4 -machine q35 \ + -kernel "$NB/live/vmlinuz" -initrd "$NB/live/initrd.img" \ + -append "boot=live components live-media-path=/efi/Paravis/KRD/live locales=ru_RU.UTF-8 trace" \ + -drive file="$IMG",format=raw,if=ide -netdev user,id=n0 -device e1000,netdev=n0 \ + -display none -vga std -monitor unix:/tmp/qmonB.sock,server,nowait -daemonize + +python3 - <<'EOF' +import socket, time +def shot(name): + s = socket.socket(socket.AF_UNIX); s.connect('/tmp/qmonB.sock'); time.sleep(0.3) + s.recv(65536); s.sendall((f'screendump {name}\n').encode()); time.sleep(1.5) + try: s.recv(65536) + except Exception: pass + s.close() + +time.sleep(120); shot('/tmp/nb2-0.ppm') +time.sleep(60); shot('/tmp/nb2-1.ppm') +time.sleep(120); shot('/tmp/nb2-2.ppm') +s = socket.socket(socket.AF_UNIX); s.connect('/tmp/qmonB.sock'); time.sleep(0.3) +s.recv(65536); s.sendall(b'quit\n') +EOF +sleep 3 +pkill -f 'qemu-system-x86_64.*nb2.img' 2>/dev/null || true +sleep 2 + +echo "=== что появилось на носителе:" +mount -o loop "$IMG" /mnt/krdtest +find /mnt/krdtest/efi/Paravis/KRD/KRD2024_Data -maxdepth 2 2>/dev/null | sed 's|/mnt/krdtest||' | head -25 +echo "--- размеры:"; du -sh /mnt/krdtest/efi/Paravis/KRD/KRD2024_Data 2>/dev/null +echo "--- логи про базы/обновление:" +grep -rhiE 'bases|update|обнов' /mnt/krdtest/efi/Paravis/KRD/KRD2024_Data/Traces/*.log 2>/dev/null | tail -25 +umount /mnt/krdtest +python3 - <<'PYEOF' +import zlib, struct, glob +def ppm2png(src, dst): + d=open(src,'rb').read() + parts=[]; i=0 + while len(parts)<4: + while d[i:i+1].isspace(): i+=1 + j=i + while not d[j:j+1].isspace(): j+=1 + parts.append(d[i:j]); i=j + i+=1 + w=int(parts[1]); h=int(parts[2]); px=d[i:i+w*h*3] + raw=b''.join(b'\x00'+px[y*w*3:(y+1)*w*3] for y in range(h)) + def chunk(t,data): + c=t+data + return struct.pack('>I',len(data))+c+struct.pack('>I',zlib.crc32(c)&0xffffffff) + png=b'\x89PNG\r\n\x1a\n' + png+=chunk(b'IHDR',struct.pack('>IIBBBBB',w,h,8,2,0,0,0)) + png+=chunk(b'IDAT',zlib.compress(raw,9)) + png+=chunk(b'IEND',b'') + open(dst,'wb').write(png) + print(dst) +for i,f in enumerate(sorted(glob.glob('/tmp/nb2-*.ppm'))): + ppm2png(f, f'/path/to/pf/KRD/nb2-{i}.png') +PYEOF diff --git a/build-scripts/integration/krd/krd-nobases-patch.sh b/build-scripts/integration/krd/krd-nobases-patch.sh new file mode 100644 index 0000000..36836ac --- /dev/null +++ b/build-scripts/integration/krd/krd-nobases-patch.sh @@ -0,0 +1,32 @@ +#!/bin/bash +# Патч krt.sh: разрешить запуск KRT без SRM баз (тогда KRT сам предложит/скачает базы). +set -e +W=/root/krd24 +cd "$W" + +rm -rf srm10nb; cp -a srm10f srm10nb + +python3 - <<'PYEOF' +import io +p='/root/krd24/srm10nb/scripts/krt.sh' +s=io.open(p,encoding='utf-8').read() +old=' krt_srm_list=("${KRD_LIVE_LAYERS_SRM_FOLDER}/${KRD_LIVE_KRT_SRM_NAME}" "${bases_srm_path}")' +new=''' # Paravis: allow KRT to start without bases module (bases are downloaded later) + krt_srm_list=("${KRD_LIVE_LAYERS_SRM_FOLDER}/${KRD_LIVE_KRT_SRM_NAME}") + + if [[ -f "${bases_srm_path}" ]] + then + krt_srm_list+=("${bases_srm_path}") + else + log_disp_message "${LOG_FILENAME}" "${TRACE_LVL_WARNING}" "Bases module is absent <${bases_srm_path}>. Starting KRT without bases." + fi''' +assert old in s, 'anchor not found' +io.open(p,'w',encoding='utf-8').write(s.replace(old,new,1)) +print(' krt.sh: патч применён') +PYEOF + +bash -n srm10nb/scripts/krt.sh && echo " bash -n: OK" + +rm -f 10-krd-nobases.srm +mksquashfs srm10nb 10-krd-nobases.srm -comp xz -b 262144 -Xbcj x86 -noappend >/dev/null 2>&1 +ls -l 10-krd-nobases.srm diff --git a/build-scripts/integration/krd/krd-nobases-test.sh b/build-scripts/integration/krd/krd-nobases-test.sh new file mode 100644 index 0000000..5653a2f --- /dev/null +++ b/build-scripts/integration/krd/krd-nobases-test.sh @@ -0,0 +1,45 @@ +#!/bin/bash +# Проверка: что будет без 30-bases.srm. +set -e +SRC=/path/to/pf/KRD/files +NB=/root/krd24/nobases +IMG=/root/krd24/nobases.img + +rm -rf "$NB"; mkdir -p "$NB/live/KRD" +cp "$SRC/live/vmlinuz" "$SRC/live/initrd.img" "$SRC/live/filesystem.squashfs" "$SRC/live/filesystem.packages" "$NB/live/" +cp "$SRC/live/KRD/10-krd.srm" "$SRC/live/KRD/20-krt.srm" "$NB/live/KRD/" +cp "$SRC/krd_version.txt" "$SRC/krd_bases_timestamp.txt" "$NB/" +ls -R "$NB" | head -20 + +rm -f "$IMG"; truncate -s 8G "$IMG" +mkfs.vfat -F 32 -n PARAVIS "$IMG" >/dev/null 2>&1 +mkdir -p /mnt/krdtest; mount -o loop "$IMG" /mnt/krdtest +mkdir -p /mnt/krdtest/efi/Paravis/KRD +cp -r "$NB/." /mnt/krdtest/efi/Paravis/KRD/ +sync; umount /mnt/krdtest + +rm -f /tmp/qmonA.sock /tmp/nobases.ppm +qemu-system-x86_64 -m 4096 -smp 4 -machine q35 \ + -kernel "$NB/live/vmlinuz" -initrd "$NB/live/initrd.img" \ + -append "boot=live components live-media-path=/efi/Paravis/KRD/live locales=ru_RU.UTF-8 trace" \ + -drive file="$IMG",format=raw,if=ide -netdev user,id=n0 -device e1000,netdev=n0 \ + -display none -vga std -monitor unix:/tmp/qmonA.sock,server,nowait -daemonize + +sleep 130 +python3 - <<'EOF' +import socket, time +s = socket.socket(socket.AF_UNIX); s.connect('/tmp/qmonA.sock'); time.sleep(0.3) +s.recv(65536) +s.sendall(b'screendump /tmp/nobases.ppm\n'); time.sleep(1.5); s.recv(65536) +s.sendall(b'quit\n') +EOF +sleep 3 +pkill -f 'qemu-system-x86_64.*nobases.img' 2>/dev/null || true +sleep 2 + +echo "=== логи (trace) о запуске KRT:" +mount -o loop "$IMG" /mnt/krdtest +find /mnt/krdtest/efi/Paravis/KRD/KRD2024_Data/Traces -type f 2>/dev/null | head +grep -rhiE 'can.t mount|overlay|SRM|bases|exit with code' /mnt/krdtest/efi/Paravis/KRD/KRD2024_Data/Traces/*.log 2>/dev/null | tail -20 +umount /mnt/krdtest +ls -l /tmp/nobases.ppm diff --git a/build-scripts/integration/krd/krd-ovl.sh b/build-scripts/integration/krd/krd-ovl.sh new file mode 100644 index 0000000..cc76fa7 --- /dev/null +++ b/build-scripts/integration/krd/krd-ovl.sh @@ -0,0 +1,7 @@ +#!/bin/bash +cd /root/krd24/srm10f/scripts || exit 1 +echo "=== overlayfs_mount.sh: обработка списка srm ===" +grep -n 'for \|mount \|exit\|srm' overlayfs_mount.sh | head -40 +echo +echo "=== фрагмент, где монтируются модули:" +sed -n '60,140p' overlayfs_mount.sh diff --git a/build-scripts/integration/krd/krd-paravis-dir.sh b/build-scripts/integration/krd/krd-paravis-dir.sh new file mode 100644 index 0000000..2f2eb93 --- /dev/null +++ b/build-scripts/integration/krd/krd-paravis-dir.sh @@ -0,0 +1,69 @@ +#!/bin/bash +set -e +W=/root/krd24 +cd "$W" + +echo "=== распаковка чистого 10-krd.srm" +rm -rf srm10p; unsquashfs -d srm10p 10-krd.srm >/dev/null 2>&1 + +echo "=== патч find_product_dir.sh" +python3 - <<'PYEOF' +import io +p='/root/krd24/srm10p/scripts/find_product_dir.sh' +s=io.open(p,encoding='utf-8').read() +anchor='''if [[ ! -f "${KRD_MOUNTS_FILE_PATH}" ]] +then + trace_message "${TRACE_LVL_ERROR}" "Volumes aren't mounted!" + trace_and_exit 1 +fi +''' +add=''' +# Paravis build: the product folder always lives inside efi/Paravis/KRD +# on the boot medium (no folders on other disks). +paravis_product_dir="" + +for mount_dir in $(awk '{print $2}' "${KRD_MOUNTS_FILE_PATH}") +do + if [[ -d "${mount_dir}/efi/Paravis/KRD/live" ]] + then + paravis_product_dir="${mount_dir}/efi/Paravis/KRD/${KRD_DATA_DIRECTORY_NAME}" + break + fi +done + +if [[ -n "${paravis_product_dir}" ]] +then + mkdir -p "${paravis_product_dir}/${KRD_TRACES_DIRNAME}" + + if [[ ${?} -eq 0 ]] + then + echo -e "${paravis_product_dir}" >> "${KRD_DATA_DIRECTORY_FILE_PATH}" + trace_message "${TRACE_LVL_INFO}" "Paravis build: product directory is <${paravis_product_dir}>" + trace_and_exit 0 + fi +fi + +trace_message "${TRACE_LVL_ERROR}" "Paravis build: product folder is kept in RAM" +trace_and_exit 3 +''' +assert anchor in s, 'anchor not found' +assert 'Paravis build' not in s, 'already patched' +s=s.replace(anchor, anchor+add, 1) +io.open(p,'w',encoding='utf-8').write(s) +print(' патч применён') +PYEOF + +echo "=== проверка синтаксиса скрипта" +bash -n srm10p/scripts/find_product_dir.sh && echo " bash -n: OK" + +echo "=== пересборка 10-krd.srm" +rm -f 10-krd-paravis.srm +mksquashfs srm10p 10-krd-paravis.srm -comp xz -b 262144 -Xbcj x86 -noappend > /tmp/mksrm2.log 2>&1 +tail -2 /tmp/mksrm2.log +ls -l 10-krd.srm 10-krd-paravis.srm +unsquashfs -cat 10-krd-paravis.srm scripts/find_product_dir.sh 2>/dev/null | sed -n '/Paravis build/,+6p' + +echo "=== копирую в стенд и на флешку" +cp -f 10-krd-paravis.srm /path/to/pf/KRD/files/live/KRD/10-krd.srm +cp -f 10-krd-paravis.srm /mnt/f/efi/Paravis/KRD/live/KRD/10-krd.srm +ls -l /mnt/f/efi/Paravis/KRD/live/KRD/10-krd.srm diff --git a/build-scripts/integration/krd/krd-paravis-test.sh b/build-scripts/integration/krd/krd-paravis-test.sh new file mode 100644 index 0000000..160977a --- /dev/null +++ b/build-scripts/integration/krd/krd-paravis-test.sh @@ -0,0 +1,49 @@ +#!/bin/bash +# Проверка: KRD создаёт продуктовую папку внутри efi/Paravis/KRD. +set -e +STAGE=/path/to/pf/KRD/files +IMG=/root/krd24/test-fat32.img + +rm -f "$IMG"; truncate -s 1200M "$IMG" +mkfs.vfat -F 32 -n PARAVIS "$IMG" >/dev/null 2>&1 +mkdir -p /mnt/krdtest; mount -o loop "$IMG" /mnt/krdtest +mkdir -p /mnt/krdtest/efi/Paravis/KRD +cp -r "$STAGE/." /mnt/krdtest/efi/Paravis/KRD/ +sync +echo "=== до загрузки:" +ls -A /mnt/krdtest/efi/Paravis/KRD +umount /mnt/krdtest + +rm -f /tmp/qmon4.sock /tmp/krd4.ppm /tmp/krd4b.ppm +qemu-system-x86_64 -m 3072 -smp 4 -machine q35 \ + -kernel "$STAGE/live/vmlinuz" -initrd "$STAGE/live/initrd.img" \ + -append "boot=live components live-media-path=/efi/Paravis/KRD/live locales=ru_RU.UTF-8" \ + -drive file="$IMG",format=raw,if=ide -net none -display none -vga std \ + -monitor unix:/tmp/qmon4.sock,server,nowait -daemonize + +sleep 110 +python3 - <<'EOF' +import socket, time +s = socket.socket(socket.AF_UNIX); s.connect('/tmp/qmon4.sock'); time.sleep(0.3) +s.recv(65536) +s.sendall(b'screendump /tmp/krd4.ppm\n'); time.sleep(1.5); s.recv(65536) +EOF +sleep 25 +python3 - <<'EOF' +import socket, time +s = socket.socket(socket.AF_UNIX); s.connect('/tmp/qmon4.sock'); time.sleep(0.3) +s.recv(65536) +s.sendall(b'screendump /tmp/krd4b.ppm\n'); time.sleep(1.5); s.recv(65536) +s.sendall(b'quit\n') +EOF +sleep 3 +pkill -f 'qemu-system-x86_64.*test-fat32.img' 2>/dev/null || true +sleep 2 + +echo "=== после загрузки:" +mount -o loop "$IMG" /mnt/krdtest +echo "--- корень раздела:"; ls -A /mnt/krdtest +echo "--- efi/Paravis/KRD:"; ls -A /mnt/krdtest/efi/Paravis/KRD +echo "--- продуктовая папка:"; find /mnt/krdtest/efi/Paravis/KRD -maxdepth 2 -type d | sed 's|/mnt/krdtest||' +umount /mnt/krdtest +ls -l /tmp/krd4.ppm /tmp/krd4b.ppm diff --git a/build-scripts/integration/krd/krd-ppm2png.sh b/build-scripts/integration/krd/krd-ppm2png.sh new file mode 100644 index 0000000..3c7abdd --- /dev/null +++ b/build-scripts/integration/krd/krd-ppm2png.sh @@ -0,0 +1,29 @@ +#!/bin/bash +python3 - <<'EOF' +import zlib, struct +def ppm2png(src, dst): + d=open(src,'rb').read() + parts=[]; i=0 + while len(parts)<4: + while d[i:i+1].isspace(): i+=1 + if d[i:i+1]==b'#': + while d[i:i+1] not in (b'\n',b'\r'): i+=1 + continue + j=i + while not d[j:j+1].isspace(): j+=1 + parts.append(d[i:j]); i=j + i+=1 + w=int(parts[1]); h=int(parts[2]); px=d[i:i+w*h*3] + raw=b''.join(b'\x00'+px[y*w*3:(y+1)*w*3] for y in range(h)) + def chunk(t,data): + c=t+data + return struct.pack('>I',len(data))+c+struct.pack('>I',zlib.crc32(c)&0xffffffff) + png=b'\x89PNG\r\n\x1a\n' + png+=chunk(b'IHDR',struct.pack('>IIBBBBB',w,h,8,2,0,0,0)) + png+=chunk(b'IDAT',zlib.compress(raw,9)) + png+=chunk(b'IEND',b'') + open(dst,'wb').write(png) + print(dst,w,h,len(png)) +ppm2png('/tmp/krd1.ppm','/path/to/pf/KRD/preview-1.png') +ppm2png('/tmp/krd2.ppm','/path/to/pf/KRD/preview-2.png') +EOF diff --git a/build-scripts/integration/krd/krd-ppm2png2.sh b/build-scripts/integration/krd/krd-ppm2png2.sh new file mode 100644 index 0000000..598a45c --- /dev/null +++ b/build-scripts/integration/krd/krd-ppm2png2.sh @@ -0,0 +1,25 @@ +python3 - <<'EOF' +import zlib, struct +def ppm2png(src, dst): + d=open(src,'rb').read() + parts=[]; i=0 + while len(parts)<4: + while d[i:i+1].isspace(): i+=1 + j=i + while not d[j:j+1].isspace(): j+=1 + parts.append(d[i:j]); i=j + i+=1 + w=int(parts[1]); h=int(parts[2]); px=d[i:i+w*h*3] + raw=b''.join(b'\x00'+px[y*w*3:(y+1)*w*3] for y in range(h)) + def chunk(t,data): + c=t+data + return struct.pack('>I',len(data))+c+struct.pack('>I',zlib.crc32(c)&0xffffffff) + png=b'\x89PNG\r\n\x1a\n' + png+=chunk(b'IHDR',struct.pack('>IIBBBBB',w,h,8,2,0,0,0)) + png+=chunk(b'IDAT',zlib.compress(raw,9)) + png+=chunk(b'IEND',b'') + open(dst,'wb').write(png) + print(dst,w,h,len(png)) +ppm2png('/tmp/krd5.ppm','/path/to/pf/KRD/preview-3.png') +ppm2png('/tmp/krd5b.ppm','/path/to/pf/KRD/preview-4.png') +EOF diff --git a/build-scripts/integration/krd/krd-ram-test.sh b/build-scripts/integration/krd/krd-ram-test.sh new file mode 100644 index 0000000..32f6661 --- /dev/null +++ b/build-scripts/integration/krd/krd-ram-test.sh @@ -0,0 +1,45 @@ +#!/bin/bash +# Проверка: KRD 24 с RAM-каталогом продукта не создаёт KRD2024_Data на носителе. +set -e +STAGE=/path/to/pf/KRD/files +IMG=/root/krd24/test-fat32.img + +apt-get install -y dosfstools >/tmp/apt-fat.log 2>&1 || true +rm -f "$IMG"; truncate -s 1200M "$IMG" +mkfs.vfat -F 32 -n PARAVIS "$IMG" >/dev/null 2>&1 +mkdir -p /mnt/krdtest; mount -o loop "$IMG" /mnt/krdtest +mkdir -p /mnt/krdtest/efi/Paravis/KRD +cp -r "$STAGE/." /mnt/krdtest/efi/Paravis/KRD/ +sync +echo "=== до загрузки, корень образа:" +ls -A /mnt/krdtest +umount /mnt/krdtest + +rm -f /tmp/qmon3.sock /tmp/krd3.ppm +qemu-system-x86_64 -m 3072 -smp 4 -machine q35 \ + -kernel "$STAGE/live/vmlinuz" -initrd "$STAGE/live/initrd.img" \ + -append "boot=live components live-media-path=/efi/Paravis/KRD/live locales=ru_RU.UTF-8" \ + -drive file="$IMG",format=raw,if=ide -net none -display none -vga std \ + -monitor unix:/tmp/qmon3.sock,server,nowait -daemonize + +sleep 110 +python3 - <<'EOF' +import socket, time +s = socket.socket(socket.AF_UNIX); s.connect('/tmp/qmon3.sock'); time.sleep(0.3) +s.recv(65536) +s.sendall(b'screendump /tmp/krd3.ppm\n'); time.sleep(1.5); s.recv(65536) +s.sendall(b'quit\n') +EOF +sleep 3 +pkill -f 'qemu-system-x86_64.*test-fat32.img' 2>/dev/null || true +sleep 2 + +echo "=== после загрузки, корень образа:" +mount -o loop "$IMG" /mnt/krdtest +ls -A /mnt/krdtest +echo "--- поиск KRD2024_Data / любых новых каталогов:" +find /mnt/krdtest -maxdepth 3 -iname '*KRD2024*' -o -maxdepth 2 -type d -iname '*.bs' 2>/dev/null +echo "--- верхний уровень efi/Paravis/KRD:" +ls -A /mnt/krdtest/efi/Paravis/KRD +umount /mnt/krdtest +ls -l /tmp/krd3.ppm diff --git a/build-scripts/integration/krd/krd-ram1.sh b/build-scripts/integration/krd/krd-ram1.sh new file mode 100644 index 0000000..f373ca3 --- /dev/null +++ b/build-scripts/integration/krd/krd-ram1.sh @@ -0,0 +1,16 @@ +#!/bin/bash +cd /root/krd24 || exit 1 +echo "=== кто вызывает find_product_dir.sh:" +grep -rn 'find_product_dir' sqroot srm10 2>/dev/null | head +echo +echo "=== как обрабатывается результат (near call):" +for f in $(grep -rl 'find_product_dir' srm10 sqroot 2>/dev/null); do + echo "--- $f" + grep -n -B4 -A12 'find_product_dir' "$f" | head -40 +done +echo +echo "=== параметры 10-krd.srm:" +unsquashfs -s 10-krd.srm | head -8 +echo +echo "=== find_product_dir.sh, начало (30-100):" +sed -n '30,100p' srm10/scripts/find_product_dir.sh diff --git a/build-scripts/integration/krd/krd-ram2.sh b/build-scripts/integration/krd/krd-ram2.sh new file mode 100644 index 0000000..cb311f9 --- /dev/null +++ b/build-scripts/integration/krd/krd-ram2.sh @@ -0,0 +1,46 @@ +#!/bin/bash +set -e +W=/root/krd24 +cd "$W/srm10/scripts" + +if grep -q 'Paravis build: product folder is kept in RAM' find_product_dir.sh; then + echo " уже пропатчено" +else + python3 - <<'EOF' +import io +p='/root/krd24/srm10/scripts/find_product_dir.sh' +s=io.open(p,encoding='utf-8').read() +anchor='''if [[ ! -f "${KRD_MOUNTS_FILE_PATH}" ]] +then + trace_message "${TRACE_LVL_ERROR}" "Volumes aren't mounted!" + trace_and_exit 1 +fi +''' +add=''' +# Paravis build: never create on disks. +# Product folder stays in RAM (${KRD_DEFAULT_DATA_DIRECTORY}). +trace_message "${TRACE_LVL_INFO}" "Paravis build: product folder is kept in RAM" +trace_and_exit 3 +''' +assert anchor in s, 'anchor not found' +s=s.replace(anchor, anchor+add, 1) +io.open(p,'w',encoding='utf-8').write(s) +print(' find_product_dir.sh: патч применён') +EOF +fi +echo "=== проверка:" +sed -n '/Volumes aren.t mounted/,/trace_and_exit 3/p' find_product_dir.sh | head -12 + +cd "$W" +echo "=== пересборка 10-krd.srm" +rm -f 10-krd-new.srm +mksquashfs srm10 10-krd-new.srm -comp xz -b 262144 -Xbcj x86 -noappend > /tmp/mksrm.log 2>&1 +tail -3 /tmp/mksrm.log +ls -l 10-krd.srm 10-krd-new.srm +echo "=== содержимое нового SRM:" +unsquashfs -cat 10-krd-new.srm scripts/find_product_dir.sh 2>/dev/null | grep -A3 'kept in RAM' + +echo "=== копирую в стенд и на флешку" +cp -f 10-krd-new.srm /path/to/pf/KRD/files/live/KRD/10-krd.srm +cp -f 10-krd-new.srm /mnt/f/efi/Paravis/KRD/live/KRD/10-krd.srm +ls -l /mnt/f/efi/Paravis/KRD/live/KRD/10-krd.srm diff --git a/build-scripts/integration/krd/krd-replace-bases.sh b/build-scripts/integration/krd/krd-replace-bases.sh new file mode 100644 index 0000000..524efe4 --- /dev/null +++ b/build-scripts/integration/krd/krd-replace-bases.sh @@ -0,0 +1,40 @@ +#!/bin/bash +# Замена баз KRD на флешке из нового образа KRD. +# Использование: bash krd-replace-bases.sh [путь-к-новому-krd.iso] +set -e + +ISO="${1:-/path/to/pf/KRD/krd-new.iso}" +DST=/mnt/f/efi/Paravis/KRD +BAK=/path/to/pf/KRD/backup +TMP=/root/krd-bases-new + +[ -f "$ISO" ] || { echo "Нет файла: $ISO"; exit 1; } + +echo "=== версия в новом образе:" +xorriso -osirrox on -indev "$ISO" -extract /krd_version.txt /tmp/newver.txt >/dev/null 2>&1 || true +cat /tmp/newver.txt 2>/dev/null || echo " (нет krd_version.txt)" +echo "=== дата баз в новом образе:" +xorriso -osirrox on -indev "$ISO" -extract /krd_bases_timestamp.txt /tmp/newts.txt >/dev/null 2>&1 || true +cat /tmp/newts.txt 2>/dev/null || echo " (нет krd_bases_timestamp.txt)" + +echo "=== дата баз сейчас на флешке:" +cat "$DST/krd_bases_timestamp.txt" 2>/dev/null || echo " (нет)" + +mkdir -p "$TMP" "$BAK" +rm -f "$TMP/30-bases.srm" +echo "=== распаковка баз из нового образа..." +xorriso -osirrox on -indev "$ISO" -extract /live/KRD/30-bases.srm "$TMP/30-bases.srm" >/dev/null 2>&1 +ls -l "$TMP/30-bases.srm" + +echo "=== бэкап текущих баз..." +cp -f "$DST/live/KRD/30-bases.srm" "$BAK/30-bases-$(date +%Y%m%d-%H%M).srm" + +echo "=== замена..." +cp -f "$TMP/30-bases.srm" "$DST/live/KRD/30-bases.srm" +[ -f /tmp/newts.txt ] && cp -f /tmp/newts.txt "$DST/krd_bases_timestamp.txt" +[ -f /tmp/newver.txt ] && cp -f /tmp/newver.txt "$DST/krd_version.txt" + +echo "=== результат:" +ls -l "$DST/live/KRD/30-bases.srm" "$DST/krd_bases_timestamp.txt" +sha256sum "$DST/live/KRD/30-bases.srm" | awk '{print " sha256="substr($1,1,16)}' +echo "=== свободно на F: $(df -h /mnt/f | awk 'NR==2{print $4}')" diff --git a/build-scripts/integration/krd/krd-ui1.sh b/build-scripts/integration/krd/krd-ui1.sh new file mode 100644 index 0000000..508f6ca --- /dev/null +++ b/build-scripts/integration/krd/krd-ui1.sh @@ -0,0 +1,79 @@ +#!/bin/bash +# Интерактивный прогон: принять лицензию и снять главное окно KRT. +set -e +STAGE=/path/to/pf/KRD/files +IMG=/root/krd24/ui-fat32.img + +rm -f "$IMG"; truncate -s 8G "$IMG" +mkfs.vfat -F 32 -n PARAVIS "$IMG" >/dev/null 2>&1 +mkdir -p /mnt/krdtest; mount -o loop "$IMG" /mnt/krdtest +mkdir -p /mnt/krdtest/efi/Paravis/KRD +cp -r "$STAGE/." /mnt/krdtest/efi/Paravis/KRD/ +sync; umount /mnt/krdtest + +rm -f /tmp/qmon9.sock /tmp/ui*.ppm +qemu-system-x86_64 -m 4096 -smp 4 -machine q35 \ + -kernel "$STAGE/live/vmlinuz" -initrd "$STAGE/live/initrd.img" \ + -append "boot=live components live-media-path=/efi/Paravis/KRD/live locales=ru_RU.UTF-8 trace" \ + -drive file="$IMG",format=raw,if=ide \ + -netdev user,id=n0 -device e1000,netdev=n0 \ + -device qemu-xhci -device usb-tablet -display none -vga std \ + -monitor unix:/tmp/qmon9.sock,server,nowait -daemonize + +python3 - <<'EOF' +import socket, time +def mon(cmds, pause=0.6): + s = socket.socket(socket.AF_UNIX); s.connect('/tmp/qmon9.sock'); time.sleep(0.3) + s.recv(65536) + for c in cmds: + s.sendall((c+'\n').encode()); time.sleep(pause) + s.settimeout(1.0) + try: s.recv(65536) + except Exception: pass + s.close() + +time.sleep(110) +mon(['screendump /tmp/ui0.ppm']) + +# три чекбокса лицензии +for (x, y) in [(366,526),(366,558),(366,611)]: + mon([f'mouse_move {x} {y}', 'mouse_button 1', 'mouse_button 0'], 0.5) + time.sleep(0.7) +mon(['screendump /tmp/ui1.ppm']) + +# кнопка "Принять" +mon(['mouse_move 864 656', 'mouse_button 1', 'mouse_button 0'], 0.6) +time.sleep(12) +mon(['screendump /tmp/ui2.ppm']) +time.sleep(10) +mon(['screendump /tmp/ui3.ppm']) +mon(['quit']) +EOF +sleep 3 +pkill -f 'qemu-system-x86_64.*ui-fat32.img' 2>/dev/null || true +ls -l /tmp/ui*.ppm +python3 - <<'EOF' +import zlib, struct +def ppm2png(src, dst): + d=open(src,'rb').read() + parts=[]; i=0 + while len(parts)<4: + while d[i:i+1].isspace(): i+=1 + j=i + while not d[j:j+1].isspace(): j+=1 + parts.append(d[i:j]); i=j + i+=1 + w=int(parts[1]); h=int(parts[2]); px=d[i:i+w*h*3] + raw=b''.join(b'\x00'+px[y*w*3:(y+1)*w*3] for y in range(h)) + def chunk(t,data): + c=t+data + return struct.pack('>I',len(data))+c+struct.pack('>I',zlib.crc32(c)&0xffffffff) + png=b'\x89PNG\r\n\x1a\n' + png+=chunk(b'IHDR',struct.pack('>IIBBBBB',w,h,8,2,0,0,0)) + png+=chunk(b'IDAT',zlib.compress(raw,9)) + png+=chunk(b'IEND',b'') + open(dst,'wb').write(png) + print(dst,w,h) +for n in range(4): + ppm2png(f'/tmp/ui{n}.ppm', f'/path/to/pf/KRD/ui-{n}.png') +EOF diff --git a/build-scripts/integration/krd/krd-ui2.sh b/build-scripts/integration/krd/krd-ui2.sh new file mode 100644 index 0000000..f206e99 --- /dev/null +++ b/build-scripts/integration/krd/krd-ui2.sh @@ -0,0 +1,78 @@ +#!/bin/bash +# Принять лицензию KRT и посмотреть главное окно. +set -e +STAGE=/path/to/pf/KRD/files +IMG=/root/krd24/ui-fat32.img + +rm -f "$IMG"; truncate -s 8G "$IMG" +mkfs.vfat -F 32 -n PARAVIS "$IMG" >/dev/null 2>&1 +mkdir -p /mnt/krdtest; mount -o loop "$IMG" /mnt/krdtest +mkdir -p /mnt/krdtest/efi/Paravis/KRD +cp -r "$STAGE/." /mnt/krdtest/efi/Paravis/KRD/ +sync; umount /mnt/krdtest + +rm -f /tmp/qmon9.sock /tmp/ui*.ppm +qemu-system-x86_64 -m 4096 -smp 4 -machine q35 \ + -kernel "$STAGE/live/vmlinuz" -initrd "$STAGE/live/initrd.img" \ + -append "boot=live components live-media-path=/efi/Paravis/KRD/live locales=ru_RU.UTF-8 trace" \ + -drive file="$IMG",format=raw,if=ide \ + -netdev user,id=n0 -device e1000,netdev=n0 \ + -device qemu-xhci -device usb-tablet -display none -vga std \ + -monitor unix:/tmp/qmon9.sock,server,nowait -daemonize + +python3 - <<'EOF' +import socket, time +def mon(cmds, pause=0.6): + s = socket.socket(socket.AF_UNIX); s.connect('/tmp/qmon9.sock'); time.sleep(0.25) + s.recv(65536) + for c in cmds: + s.sendall((c+'\n').encode()); time.sleep(pause) + s.settimeout(1.0) + try: s.recv(65536) + except Exception: pass + s.close() + +time.sleep(150) +mon(['screendump /tmp/ui0.ppm']) + +# мышью — по одному чекбоксу, с проверкой +for i,(x,y) in enumerate([(366,525),(366,558),(366,611)], start=1): + mon([f'mouse_move {x} {y}', 'mouse_button 1', 'mouse_button 0'], 0.4) + time.sleep(1.0) + mon([f'screendump /tmp/ui{i}.ppm']) + +# "Принять" +mon(['mouse_move 865 657', 'mouse_button 1', 'mouse_button 0'], 0.5) +time.sleep(8) +mon(['screendump /tmp/ui4.ppm']) +time.sleep(8) +mon(['screendump /tmp/ui5.ppm']) +mon(['quit']) +EOF +sleep 3 +pkill -f 'qemu-system-x86_64.*ui-fat32.img' 2>/dev/null || true +python3 - <<'EOF' +import zlib, struct +def ppm2png(src, dst): + d=open(src,'rb').read() + parts=[]; i=0 + while len(parts)<4: + while d[i:i+1].isspace(): i+=1 + j=i + while not d[j:j+1].isspace(): j+=1 + parts.append(d[i:j]); i=j + i+=1 + w=int(parts[1]); h=int(parts[2]); px=d[i:i+w*h*3] + raw=b''.join(b'\x00'+px[y*w*3:(y+1)*w*3] for y in range(h)) + def chunk(t,data): + c=t+data + return struct.pack('>I',len(data))+c+struct.pack('>I',zlib.crc32(c)&0xffffffff) + png=b'\x89PNG\r\n\x1a\n' + png+=chunk(b'IHDR',struct.pack('>IIBBBBB',w,h,8,2,0,0,0)) + png+=chunk(b'IDAT',zlib.compress(raw,9)) + png+=chunk(b'IEND',b'') + open(dst,'wb').write(png) + print(dst,w,h) +for n in range(6): + ppm2png(f'/tmp/ui{n}.ppm', f'/path/to/pf/KRD/ui-{n}.png') +EOF diff --git a/build-scripts/integration/krd/krd-ui3.sh b/build-scripts/integration/krd/krd-ui3.sh new file mode 100644 index 0000000..471bd19 --- /dev/null +++ b/build-scripts/integration/krd/krd-ui3.sh @@ -0,0 +1,103 @@ +#!/bin/bash +# Принять лицензию KRT через QMP (абсолютные координаты) и снять главное окно. +set -e +STAGE=/path/to/pf/KRD/files +IMG=/root/krd24/ui-fat32.img + +rm -f "$IMG"; truncate -s 8G "$IMG" +mkfs.vfat -F 32 -n PARAVIS "$IMG" >/dev/null 2>&1 +mkdir -p /mnt/krdtest; mount -o loop "$IMG" /mnt/krdtest +mkdir -p /mnt/krdtest/efi/Paravis/KRD +cp -r "$STAGE/." /mnt/krdtest/efi/Paravis/KRD/ +sync; umount /mnt/krdtest + +rm -f /tmp/qmp.sock /tmp/ui*.ppm +qemu-system-x86_64 -m 4096 -smp 4 -machine q35 \ + -kernel "$STAGE/live/vmlinuz" -initrd "$STAGE/live/initrd.img" \ + -append "boot=live components live-media-path=/efi/Paravis/KRD/live locales=ru_RU.UTF-8 trace" \ + -drive file="$IMG",format=raw,if=ide \ + -netdev user,id=n0 -device e1000,netdev=n0 \ + -device qemu-xhci -device usb-tablet -display none -vga std \ + -qmp unix:/tmp/qmp.sock,server,nowait -daemonize + +python3 - <<'EOF' +import json, socket, time + +class Q: + def __init__(self, path): + self.s = socket.socket(socket.AF_UNIX); self.s.connect(path) + self.f = self.s.makefile('rwb') + self._read() + self.cmd('qmp_capabilities') + def _read(self): + while True: + line = self.f.readline() + if not line: return None + msg = json.loads(line) + if 'event' in msg: continue + return msg + def cmd(self, name, args=None): + self.f.write((json.dumps({'execute': name, 'arguments': args or {}})+'\n').encode()) + self.f.flush() + return self._read() + def hmp(self, line): + return self.cmd('human-monitor-command', {'command-line': line}) + +W, H = 1280, 800 +def absxy(x, y): + return int(x*32767/W), int(y*32767/H) + +def click(q, x, y): + ax, ay = absxy(x, y) + q.cmd('input-send-event', {'events': [ + {'type':'abs','data':{'axis':'x','value':ax}}, + {'type':'abs','data':{'axis':'y','value':ay}}, + ]}) + time.sleep(0.15) + q.cmd('input-send-event', {'events':[{'type':'btn','data':{'down':True,'button':'left'}}]}) + time.sleep(0.1) + q.cmd('input-send-event', {'events':[{'type':'btn','data':{'down':False,'button':'left'}}]}) + time.sleep(0.6) + +time.sleep(150) +q = Q('/tmp/qmp.sock') +q.hmp('screendump /tmp/ui0.ppm') + +for i,(x,y) in enumerate([(366,525),(366,558),(366,611)], start=1): + click(q, x, y) + q.hmp(f'screendump /tmp/ui{i}.ppm') + +click(q, 865, 657) +time.sleep(8) +q.hmp('screendump /tmp/ui4.ppm') +time.sleep(8) +q.hmp('screendump /tmp/ui5.ppm') +q.cmd('quit') +EOF +sleep 3 +pkill -f 'qemu-system-x86_64.*ui-fat32.img' 2>/dev/null || true +python3 - <<'PYEOF' +import zlib, struct +def ppm2png(src, dst): + d=open(src,'rb').read() + parts=[]; i=0 + while len(parts)<4: + while d[i:i+1].isspace(): i+=1 + j=i + while not d[j:j+1].isspace(): j+=1 + parts.append(d[i:j]); i=j + i+=1 + w=int(parts[1]); h=int(parts[2]); px=d[i:i+w*h*3] + raw=b''.join(b'\x00'+px[y*w*3:(y+1)*w*3] for y in range(h)) + def chunk(t,data): + c=t+data + return struct.pack('>I',len(data))+c+struct.pack('>I',zlib.crc32(c)&0xffffffff) + png=b'\x89PNG\r\n\x1a\n' + png+=chunk(b'IHDR',struct.pack('>IIBBBBB',w,h,8,2,0,0,0)) + png+=chunk(b'IDAT',zlib.compress(raw,9)) + png+=chunk(b'IEND',b'') + open(dst,'wb').write(png) + print(dst,w,h) +for n in range(6): + ppm2png(f'/tmp/ui{n}.ppm', f'/path/to/pf/KRD/ui-{n}.png') +PYEOF diff --git a/build-scripts/integration/krd/krd-upd-ui1.sh b/build-scripts/integration/krd/krd-upd-ui1.sh new file mode 100644 index 0000000..4c687af --- /dev/null +++ b/build-scripts/integration/krd/krd-upd-ui1.sh @@ -0,0 +1,16 @@ +#!/bin/bash +cd /root/krd24 || exit 1 +echo "=== кто ссылается на run_update / updater:" +grep -rIl 'run_update\|updater\.sh' sqroot srm10f 2>/dev/null | head -20 +echo +echo "=== .desktop-файлы с update/bases:" +grep -rIl -iE 'update|bases|обнов' sqroot/usr/share/applications sqroot/home/krd/.config 2>/dev/null | head -20 +echo +echo "=== все .desktop в /usr/share/applications:" +ls sqroot/usr/share/applications 2>/dev/null | head -40 +echo +echo "=== /opt/KRD/applications (из SRM):" +ls srm10f/applications 2>/dev/null +echo +echo "=== desktop-файлы из SRM:" +for f in srm10f/applications/*.desktop; do echo "--- $f"; cat "$f"; done diff --git a/build-scripts/integration/krd/krd-upd-ui2.sh b/build-scripts/integration/krd/krd-upd-ui2.sh new file mode 100644 index 0000000..13b3ab6 --- /dev/null +++ b/build-scripts/integration/krd/krd-upd-ui2.sh @@ -0,0 +1,17 @@ +#!/bin/bash +cd /root/krd24 || exit 1 +echo "=== l10n KRT: слова про обновление:" +grep -inE 'обнов|update|баз' srm10f/l10n/krt_ru.l10n | head -30 +echo +echo "=== l10n common:" +grep -inE 'обнов|update' srm10f/l10n/common_ru.l10n | head -20 +echo +echo "=== кто вызывает run_update.sh (все совпадения):" +grep -rn 'run_update' sqroot srm10f 2>/dev/null | head -10 +echo +echo "=== содержимое make_unique_update.sh (первые 40 строк):" +sed -n '1,40p' srm10f/scripts/make_unique_update.sh +echo +echo "=== есть ли в squashfs ярлык/скрипт обновления:" +grep -rIl 'update' sqroot/usr/share/applications sqroot/etc/xdg/autostart sqroot/usr/local/bin 2>/dev/null | head +ls sqroot/usr/local/bin 2>/dev/null | head -20 diff --git a/build-scripts/integration/krd/krd-upd-ui3.sh b/build-scripts/integration/krd/krd-upd-ui3.sh new file mode 100644 index 0000000..b153902 --- /dev/null +++ b/build-scripts/integration/krd/krd-upd-ui3.sh @@ -0,0 +1,12 @@ +#!/bin/bash +cd /root/krd24 || exit 1 +echo "=== распаковка 20-krt.srm:" +rm -rf srm20; unsquashfs -d srm20 /path/to/pf/KRD/files/live/KRD/20-krt.srm >/dev/null 2>&1 || true +ls srm20 2>/dev/null | head +find srm20 -maxdepth 3 -type f | head -20 +echo +echo "=== строки KRT про обновление/скрипт:" +for f in $(find srm20 -maxdepth 4 -type f -name 'KRT*' -o -maxdepth 4 -type f -name '*.so' | head -5); do + echo "--- $f" + strings -a "$f" | grep -iE 'make_unique_update|run_update|updater|Update bases|обнов' | head -10 +done diff --git a/build-scripts/integration/krd/krd-upd-ui4.sh b/build-scripts/integration/krd/krd-upd-ui4.sh new file mode 100644 index 0000000..0e7a641 --- /dev/null +++ b/build-scripts/integration/krd/krd-upd-ui4.sh @@ -0,0 +1,17 @@ +#!/bin/bash +cd /root/krd24/srm20/Bin || exit 1 +echo "=== файлы:" +ls -l KRT libapp_core.so 2>/dev/null +echo +echo "=== строки про обновление (англ/рус) в KRT и libapp_core:" +for f in KRT libapp_core.so; do + echo "--- $f" + strings -a -el "$f" 2>/dev/null | grep -iE 'update|обновл' | head -20 + strings -a "$f" 2>/dev/null | grep -iE '^update|update bases|updat(e|ing) ' | head -20 +done +echo +echo "=== ресурсы/переводы:" +find . -maxdepth 2 -iname '*krt*' -o -maxdepth 2 -iname '*.qm' -o -maxdepth 2 -iname '*l10n*' | head -20 +echo +echo "=== есть ли в KRT вызовы скриптов:" +strings -a KRT | grep -E '\.sh$|/opt/KRD|/usr/sbin/krd|sudo' | head -20 diff --git a/build-scripts/integration/krd/krd-upd-ui5.sh b/build-scripts/integration/krd/krd-upd-ui5.sh new file mode 100644 index 0000000..c56f5d0 --- /dev/null +++ b/build-scripts/integration/krd/krd-upd-ui5.sh @@ -0,0 +1,10 @@ +#!/bin/bash +cd /root/krd24/srm20/Bin || exit 1 +echo "=== libKrtGui.so: русские строки про обновление:" +strings -a libKrtGui.so | grep -aE 'Обнов|обнов' | head -30 +echo +echo "=== английские UI-строки update:" +strings -a libKrtGui.so | grep -aE '^Update|Update |Updat' | head -30 +echo +echo "=== make_update.sh:" +unsquashfs -cat /path/to/pf/KRD/files/live/KRD/10-krd.srm scripts/make_update.sh 2>/dev/null | head -60 diff --git a/build-scripts/integration/krd/krd-upd-ui6.sh b/build-scripts/integration/krd/krd-upd-ui6.sh new file mode 100644 index 0000000..0a3653b --- /dev/null +++ b/build-scripts/integration/krd/krd-upd-ui6.sh @@ -0,0 +1,17 @@ +#!/bin/bash +cd /root/krd24 || exit 1 +echo "=== все файлы 20-krt.srm (кроме lib):" +find srm20 -type f | grep -v '/lib/' | head -40 +echo +echo "=== поиск русских строк про обновление во всех файлах KRT:" +grep -rla 'Обнов' srm20 2>/dev/null | head +echo +echo "=== UTF-16 (Qt) строки:" +for f in srm20/Bin/KRT srm20/Bin/libKrtGui.so srm20/Bin/libapp_core.so; do + printf " %-30s " "$(basename $f)" + strings -a -el "$f" | grep -acE 'Обнов|Update' || true +done +echo +echo "=== настройки KRT (settings.dat/kvdb) — упоминания update:" +strings -a srm20/Bin/settings.dat 2>/dev/null | grep -iE 'update|обнов' | head -10 +strings -a srm20/Bin/settings.kvdb 2>/dev/null | grep -iE 'update|обнов' | head -10 diff --git a/build-scripts/integration/krd/krd-upd-ui7.sh b/build-scripts/integration/krd/krd-upd-ui7.sh new file mode 100644 index 0000000..0ef80cb --- /dev/null +++ b/build-scripts/integration/krd/krd-upd-ui7.sh @@ -0,0 +1,10 @@ +#!/bin/bash +cd /root/krd24/srm20/Bin || exit 1 +echo "=== UTF-16 строки libKrtGui.so (Update/Обнов):" +strings -a -el libKrtGui.so | grep -aE 'Обнов|Update' | head -30 +echo +echo "=== UTF-16 строки KRT:" +strings -a -el KRT | grep -aE 'Обнов|Update' | head -20 +echo +echo "=== ищем UI-подписи кнопок (рус) в libKrtGui.so, любые:" +strings -a -el libKrtGui.so | head -60 diff --git a/build-scripts/integration/krd/krd-upd1.sh b/build-scripts/integration/krd/krd-upd1.sh new file mode 100644 index 0000000..a6b52a2 --- /dev/null +++ b/build-scripts/integration/krd/krd-upd1.sh @@ -0,0 +1,7 @@ +#!/bin/bash +cd /root/krd24/srm10f/scripts || exit 1 +echo "=== updater.sh: пути/запись ===" +grep -nE 'SRM|freshbases|KRD_UPDATES|product|PRODUCT|cp |mv |wget|curl|download|target' updater.sh | head -60 +echo +echo "=== run_update.sh ===" +sed -n '1,120p' run_update.sh diff --git a/build-scripts/integration/krd/krd-upd2.sh b/build-scripts/integration/krd/krd-upd2.sh new file mode 100644 index 0000000..949162d --- /dev/null +++ b/build-scripts/integration/krd/krd-upd2.sh @@ -0,0 +1,10 @@ +#!/bin/bash +cd /root/krd24/srm10f/scripts || exit 1 +echo "=== get_fresh_bases_path:" +grep -n -A30 'get_fresh_bases_path ()' krt.sh | head -45 +echo +echo "=== использование в krt.sh (340-380):" +sed -n '340,380p' krt.sh +echo +echo "=== как KRT получает базы (450-480):" +sed -n '450,480p' krt.sh diff --git a/build-scripts/integration/krd/krd-upd3.sh b/build-scripts/integration/krd/krd-upd3.sh new file mode 100644 index 0000000..6a21272 --- /dev/null +++ b/build-scripts/integration/krd/krd-upd3.sh @@ -0,0 +1,5 @@ +#!/bin/bash +cd /root/krd24/srm10f/scripts || exit 1 +grep -rn 'get_fresh_bases_path' . | head +echo "=== определение:" +grep -n -A40 'get_fresh_bases_path' script_helpers.sh | head -60 diff --git a/build-scripts/integration/krd/krd-upd4.sh b/build-scripts/integration/krd/krd-upd4.sh new file mode 100644 index 0000000..39fbade --- /dev/null +++ b/build-scripts/integration/krd/krd-upd4.sh @@ -0,0 +1,3 @@ +#!/bin/bash +cd /root/krd24/srm10f/scripts || exit 1 +sed -n '30,95p' krt.sh diff --git a/build-scripts/integration/krd/krd-upd5.sh b/build-scripts/integration/krd/krd-upd5.sh new file mode 100644 index 0000000..03359ae --- /dev/null +++ b/build-scripts/integration/krd/krd-upd5.sh @@ -0,0 +1,4 @@ +#!/bin/bash +cd /root/krd24/srm10f/scripts || exit 1 +echo "=== updater.sh 240-300:" +sed -n '240,300p' updater.sh diff --git a/build-scripts/integration/krd/krd-vols.sh b/build-scripts/integration/krd/krd-vols.sh new file mode 100644 index 0000000..8b08ce4 --- /dev/null +++ b/build-scripts/integration/krd/krd-vols.sh @@ -0,0 +1,7 @@ +#!/bin/bash +cd /root/krd24/srm10/scripts || exit 1 +echo "=== mount_all_volumes.sh — как выбираются устройства и флаги:" +grep -n 'mount \|mountpoint\|live\|ro\b\|rw\b\|KRD_RO_VOLUMES\|VOLUMES_DIRECTORY' mount_all_volumes.sh | head -50 +echo +echo "=== mount_volumes.sh целиком (первые 120 строк):" +sed -n '1,120p' mount_volumes.sh diff --git a/build-scripts/integration/krd/krd-vols2.sh b/build-scripts/integration/krd/krd-vols2.sh new file mode 100644 index 0000000..08a839d --- /dev/null +++ b/build-scripts/integration/krd/krd-vols2.sh @@ -0,0 +1,4 @@ +#!/bin/bash +cd /root/krd24/srm10/scripts || exit 1 +echo "=== mount_all_volumes.sh 560-730:" +sed -n '560,730p' mount_all_volumes.sh diff --git a/build-scripts/integration/krd/krd-vols3.sh b/build-scripts/integration/krd/krd-vols3.sh new file mode 100644 index 0000000..30ef2cd --- /dev/null +++ b/build-scripts/integration/krd/krd-vols3.sh @@ -0,0 +1,6 @@ +#!/bin/bash +cd /root/krd24/srm10/scripts || exit 1 +echo "=== find_product_dir.sh 215-330:" +sed -n '215,330p' find_product_dir.sh +echo "=== script_helpers: trace_and_exit:" +grep -n -A10 'trace_and_exit ()' script_helpers.sh | head -20 diff --git a/build-scripts/integration/krd/krd18-grep.sh b/build-scripts/integration/krd/krd18-grep.sh new file mode 100644 index 0000000..62e7880 --- /dev/null +++ b/build-scripts/integration/krd/krd18-grep.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -e +W=/root/krd18 +cd "$W" +for m in 003-kl 004-krt; do + echo "=== $m.srm" + rm -rf "s-$m"; unsquashfs -d "s-$m" "/mnt/f/efi/Paravis/KRD/data/$m.srm" >/dev/null 2>&1 || true + echo " файлов: $(find s-$m -type f | wc -l)" + grep -rIl 'KRD2018_Data\|2018_Data' "s-$m" 2>/dev/null | head -10 + grep -rn 'KRD2018_Data\|2018_Data' "s-$m" 2>/dev/null | head -5 +done +echo +echo "=== ищем по всем модулям строку (быстро, только малые):" +for f in /mnt/f/efi/Paravis/KRD/data/00[3-8]*.srm; do + printf " %-16s " "$(basename $f)" + unsquashfs -cat "$f" 2>/dev/null >/dev/null || true + # ищем строку прямо в squashfs (может быть сжата, поэтому ненадёжно) + strings -a "$f" | grep -c 'KRD2018_Data' || true +done diff --git a/build-scripts/integration/krd/krd18-inspect.sh b/build-scripts/integration/krd/krd18-inspect.sh new file mode 100644 index 0000000..e4a0a1f --- /dev/null +++ b/build-scripts/integration/krd/krd18-inspect.sh @@ -0,0 +1,20 @@ +#!/bin/bash +set -e +W=/root/krd18 +rm -rf "$W"; mkdir -p "$W"; cd "$W" + +echo "=== распаковка initrd.xz:" +mkdir ir && cd ir +xz -dc /mnt/f/efi/Paravis/KRD/initrd.xz | cpio -idm --quiet 2>/dev/null || xz -dc /mnt/f/efi/Paravis/KRD/initrd.xz | cpio -idm 2>/dev/null +ls | head -20 +echo +echo "=== поиск KRD2018_Data / datadir в initrd:" +grep -rn 'KRD2018_Data\|2018_Data\|KRD_DATA\|datadir\|datadev' . 2>/dev/null | head -20 +cd .. + +echo +echo "=== модули data/*.srm:" +for f in /mnt/f/efi/Paravis/KRD/data/*.srm; do + printf " %-24s " "$(basename $f)" + unsquashfs -s "$f" 2>/dev/null | head -1 || echo "(не squashfs)" +done diff --git a/build-scripts/integration/krd/krd18-test.sh b/build-scripts/integration/krd/krd18-test.sh new file mode 100644 index 0000000..7686285 --- /dev/null +++ b/build-scripts/integration/krd/krd18-test.sh @@ -0,0 +1,36 @@ +#!/bin/bash +# Проверка krd18.efi на 32-битной OVMF с реальными файлами KRD 18. +set -e +IMG=/root/krd18.img +rm -f "$IMG"; truncate -s 1400M "$IMG" +printf 'label: dos\nstart=1MiB, type=0c, bootable\n' | sfdisk "$IMG" >/dev/null 2>&1 +LOOP=$(losetup -f --show -P "$IMG"); sleep 1 +mkfs.vfat -F 32 -n PARAVIS "${LOOP}p1" >/dev/null 2>&1 +mkdir -p /mnt/k18; mount "${LOOP}p1" /mnt/k18 +mkdir -p /mnt/k18/EFI/BOOT /mnt/k18/efi/Paravis/KRD/data +cp -f /path/to/pf/KRD/images/krd18.efi /mnt/k18/EFI/BOOT/BOOTIA32.EFI +cp -f /mnt/f/efi/Paravis/KRD/k-x86 /mnt/k18/efi/Paravis/KRD/ +cp -f /mnt/f/efi/Paravis/KRD/initrd.xz /mnt/k18/efi/Paravis/KRD/ +cp -f /mnt/f/efi/Paravis/KRD/data/* /mnt/k18/efi/Paravis/KRD/data/ +sync +du -sh /mnt/k18/efi/Paravis/KRD +umount /mnt/k18; losetup -d "$LOOP" + +rm -f /tmp/k18a.ppm /tmp/km18.sock +qemu-system-i386 -m 2048 -machine q35 \ + -drive if=pflash,format=raw,readonly=on,file=/usr/share/OVMF/OVMF32_CODE_4M.fd \ + -drive if=pflash,format=raw,file=/root/OVMF32_VARS.fd \ + -drive file="$IMG",format=raw,if=ide \ + -display none -vga std -monitor unix:/tmp/km18.sock,server,nowait -daemonize +sleep 60 +python3 - <<'EOF' +import socket, time +s=socket.socket(socket.AF_UNIX); s.connect('/tmp/km18.sock'); time.sleep(0.3) +s.recv(65536); s.sendall(b'screendump /tmp/k18a.ppm\n'); time.sleep(1.5) +try: s.recv(65536) +except Exception: pass +s.sendall(b'quit\n') +EOF +sleep 2 +pkill -f 'qemu-system-i386.*krd18.img' 2>/dev/null || true +ls -l /tmp/k18a.ppm diff --git a/build-scripts/integration/krd/krd32-direct.sh b/build-scripts/integration/krd/krd32-direct.sh new file mode 100644 index 0000000..16fad48 --- /dev/null +++ b/build-scripts/integration/krd/krd32-direct.sh @@ -0,0 +1,29 @@ +#!/bin/bash +# Отладка KRD-переходника: грузим его напрямую как BOOTIA32.EFI. +set -e +IMG=/root/xor32.img +LOOP=$(losetup -f --show -P "$IMG"); sleep 1 +mount "${LOOP}p1" /mnt/x32p1 +cp -f /path/to/pf/KRD/images/krd32.efi /mnt/x32p1/EFI/BOOT/BOOTIA32.EFI +sync +ls -l /mnt/x32p1/efi/Paravis/KRD/live/ +umount /mnt/x32p1; losetup -d "$LOOP" + +rm -f /tmp/k32.ppm /tmp/km32.sock +qemu-system-i386 -m 1024 -machine q35 \ + -drive if=pflash,format=raw,readonly=on,file=/usr/share/OVMF/OVMF32_CODE_4M.fd \ + -drive if=pflash,format=raw,file=/root/OVMF32_VARS.fd \ + -drive file="$IMG",format=raw,if=ide \ + -display none -vga std -monitor unix:/tmp/km32.sock,server,nowait -daemonize +sleep 15 +python3 - <<'EOF' +import socket, time +s=socket.socket(socket.AF_UNIX); s.connect('/tmp/km32.sock'); time.sleep(0.3) +s.recv(65536); s.sendall(b'screendump /tmp/k32.ppm\n'); time.sleep(1.5) +try: s.recv(65536) +except Exception: pass +s.sendall(b'quit\n') +EOF +sleep 2 +pkill -f 'qemu-system-i386.*xor32.img' 2>/dev/null || true +ls -l /tmp/k32.ppm diff --git a/build-scripts/integration/krd/krd32-direct2.sh b/build-scripts/integration/krd/krd32-direct2.sh new file mode 100644 index 0000000..f08e9a1 --- /dev/null +++ b/build-scripts/integration/krd/krd32-direct2.sh @@ -0,0 +1,36 @@ +#!/bin/bash +# KRD-переходник: ждём дольше, снимаем два скриншота. +set -e +IMG=/root/xor32.img +LOOP=$(losetup -f --show -P "$IMG"); sleep 1 +mount "${LOOP}p1" /mnt/x32p1 +cp -f /path/to/pf/KRD/images/krd32.efi /mnt/x32p1/EFI/BOOT/BOOTIA32.EFI +sync; umount /mnt/x32p1; losetup -d "$LOOP" + +rm -f /tmp/k32a.ppm /tmp/k32b.ppm /tmp/km32b.sock +qemu-system-i386 -m 2048 -machine q35 \ + -drive if=pflash,format=raw,readonly=on,file=/usr/share/OVMF/OVMF32_CODE_4M.fd \ + -drive if=pflash,format=raw,file=/root/OVMF32_VARS.fd \ + -drive file="$IMG",format=raw,if=ide \ + -display none -vga std -monitor unix:/tmp/km32b.sock,server,nowait -daemonize +sleep 40 +python3 - <<'EOF' +import socket, time +s=socket.socket(socket.AF_UNIX); s.connect('/tmp/km32b.sock'); time.sleep(0.3) +s.recv(65536); s.sendall(b'screendump /tmp/k32a.ppm\n'); time.sleep(1.5) +try: s.recv(65536) +except Exception: pass +s.close() +EOF +sleep 50 +python3 - <<'EOF' +import socket, time +s=socket.socket(socket.AF_UNIX); s.connect('/tmp/km32b.sock'); time.sleep(0.3) +s.recv(65536); s.sendall(b'screendump /tmp/k32b.ppm\n'); time.sleep(1.5) +try: s.recv(65536) +except Exception: pass +s.sendall(b'quit\n') +EOF +sleep 2 +pkill -f 'qemu-system-i386.*xor32.img' 2>/dev/null || true +ls -l /tmp/k32a.ppm /tmp/k32b.ppm diff --git a/build-scripts/integration/krd/krd64-test.sh b/build-scripts/integration/krd/krd64-test.sh new file mode 100644 index 0000000..49089de --- /dev/null +++ b/build-scripts/integration/krd/krd64-test.sh @@ -0,0 +1,34 @@ +#!/bin/bash +# Проверка krd64.efi на 64-битной OVMF. +set -e +IMG=/root/krd64.img +rm -f "$IMG"; truncate -s 200M "$IMG" +printf 'label: dos\nstart=1MiB, type=0c, bootable\n' | sfdisk "$IMG" >/dev/null 2>&1 +LOOP=$(losetup -f --show -P "$IMG"); sleep 1 +mkfs.vfat -F 32 -n KRD64 "${LOOP}p1" >/dev/null 2>&1 +mkdir -p /mnt/k64; mount "${LOOP}p1" /mnt/k64 +mkdir -p /mnt/k64/EFI/BOOT /mnt/k64/efi/Paravis/KRD/live +cp -f /path/to/pf/KRD/images/krd64.efi /mnt/k64/EFI/BOOT/BOOTX64.EFI +cp -f /mnt/f/efi/Paravis/KRD/live/vmlinuz /mnt/k64/efi/Paravis/KRD/live/ +cp -f /mnt/f/efi/Paravis/KRD/live/initrd.img /mnt/k64/efi/Paravis/KRD/live/ +sync +umount /mnt/k64; losetup -d "$LOOP" + +rm -f /tmp/k64a.ppm /tmp/km64.sock +qemu-system-x86_64 -m 2048 -machine q35 \ + -drive if=pflash,format=raw,readonly=on,file=/usr/share/OVMF/OVMF_CODE_4M.fd \ + -drive if=pflash,format=raw,file=/root/OVMF64_VARS.fd \ + -drive file="$IMG",format=raw,if=ide \ + -display none -vga std -monitor unix:/tmp/km64.sock,server,nowait -daemonize +sleep 45 +python3 - <<'EOF' +import socket, time +s=socket.socket(socket.AF_UNIX); s.connect('/tmp/km64.sock'); time.sleep(0.3) +s.recv(65536); s.sendall(b'screendump /tmp/k64a.ppm\n'); time.sleep(1.5) +try: s.recv(65536) +except Exception: pass +s.sendall(b'quit\n') +EOF +sleep 2 +pkill -f 'qemu-system-x86_64.*krd64.img' 2>/dev/null || true +ls -l /tmp/k64a.ppm diff --git a/build-scripts/integration/krd/x86-erase-krd.sh b/build-scripts/integration/krd/x86-erase-krd.sh new file mode 100644 index 0000000..c4e7e10 --- /dev/null +++ b/build-scripts/integration/krd/x86-erase-krd.sh @@ -0,0 +1,17 @@ +#!/bin/bash +python3 - <<'EOF' +from PIL import Image, ImageDraw + +pairs = [ + ('x86-1', '/mnt/f/efi/Boot/1x86.bmp', (40, 474, 470, 508)), + ('x86-2', '/mnt/f/efi/Boot/2x86.bmp', (28, 460, 520, 521)), +] +BG = (233, 233, 233) +for name, src, box in pairs: + im = Image.open(src).convert('RGB') + d = ImageDraw.Draw(im) + d.rectangle(box, fill=BG) + out = f'/path/to/pf/KRD/images/{name}-nokrd.png' + im.save(out) + print(out, box) +EOF diff --git a/build-scripts/integration/krd/x86-hooks.sh b/build-scripts/integration/krd/x86-hooks.sh new file mode 100644 index 0000000..e3c1655 --- /dev/null +++ b/build-scripts/integration/krd/x86-hooks.sh @@ -0,0 +1,14 @@ +#!/bin/bash +python3 - <<'EOF' +from PIL import Image +import numpy as np +im = Image.open('/mnt/f/efi/Boot/2x86.bmp').convert('RGB') +a = np.array(im).astype(int) +bg = np.array([233,233,233]) +print('y: x-диапазоны не-фона в зоне x 400..530') +for y in range(440, 545): + row = a[y, 400:530] + nb = np.where(np.abs(row - bg).sum(axis=1) > 30)[0] + if len(nb): + print(f' y={y}: x {400+nb.min()}..{400+nb.max()} ({len(nb)} px)') +EOF diff --git a/build-scripts/integration/krd/x86-row-probe.sh b/build-scripts/integration/krd/x86-row-probe.sh new file mode 100644 index 0000000..126518f --- /dev/null +++ b/build-scripts/integration/krd/x86-row-probe.sh @@ -0,0 +1,15 @@ +#!/bin/bash +python3 - <<'EOF' +from PIL import Image +import numpy as np + +for name, path in (('x86-1','/mnt/f/efi/Boot/1x86.bmp'), ('x86-2','/mnt/f/efi/Boot/2x86.bmp')): + im = Image.open(path).convert('RGB'); a = np.array(im).astype(int) + print('==', name, im.size) + for y in range(470, 512, 4): + row = a[y] + # не-фон (фон ~233,233,233) + nb = np.where(np.abs(row - np.array([233,233,233])).sum(axis=1) > 30)[0] + if len(nb): + print(f' y={y}: x {nb.min()}..{nb.max()} ({len(nb)} px)') +EOF diff --git a/build-scripts/integration/krd/x86-runs.sh b/build-scripts/integration/krd/x86-runs.sh new file mode 100644 index 0000000..03b4c08 --- /dev/null +++ b/build-scripts/integration/krd/x86-runs.sh @@ -0,0 +1,26 @@ +#!/bin/bash +python3 - <<'EOF' +from PIL import Image +import numpy as np + +for name, path in (('x86-1','/mnt/f/efi/Boot/1x86.bmp'), ('x86-2','/mnt/f/efi/Boot/2x86.bmp')): + im = Image.open(path).convert('RGB'); a = np.array(im).astype(int) + print('==', name) + for y in (484, 488, 492, 496): + row = a[y] + nb = np.abs(row - np.array([233,233,233])).sum(axis=1) > 30 + # runs + runs = [] + i = 0 + while i < len(nb): + if nb[i]: + j = i + while j < len(nb) and nb[j]: j += 1 + runs.append((i, j-1)) + i = j + else: + i += 1 + # только крупные + big = [r for r in runs if r[1]-r[0] > 3] + print(f' y={y}: ' + ', '.join(f'{r[0]}..{r[1]}' for r in big[:6])) +EOF diff --git a/build-scripts/integration/krd/x86nokrd-nav.sh b/build-scripts/integration/krd/x86nokrd-nav.sh new file mode 100644 index 0000000..6bb1e77 --- /dev/null +++ b/build-scripts/integration/krd/x86nokrd-nav.sh @@ -0,0 +1,30 @@ +#!/bin/bash +# Навигация: 5 нажатий Down из пункта 2 — не должно быть пустого пункта. +set -e +IMG=/root/x86nokrd.img +rm -f /tmp/xnk2.ppm /tmp/xnk2.sock +qemu-system-i386 -m 1024 -machine q35 \ + -drive if=pflash,format=raw,readonly=on,file=/usr/share/OVMF/OVMF32_CODE_4M.fd \ + -drive if=pflash,format=raw,file=/root/OVMF32_VARS.fd \ + -drive file="$IMG",format=raw,if=ide \ + -display none -vga std -monitor unix:/tmp/xnk2.sock,server,nowait -daemonize +python3 - <<'EOF' +import socket, time +sock='/tmp/xnk2.sock' +def mon(cmd, pause=0.3): + s=socket.socket(socket.AF_UNIX); s.connect(sock); time.sleep(0.2) + s.recv(65536); s.sendall((cmd+'\n').encode()); time.sleep(pause) + try: s.recv(65536) + except Exception: pass + s.close() +time.sleep(12) +for _ in range(5): + mon('sendkey down') +time.sleep(0.6) +mon('screendump /tmp/xnk2.ppm') +time.sleep(1) +mon('quit') +EOF +sleep 2 +pkill -f 'qemu-system-i386.*x86nokrd.img' 2>/dev/null || true +ls -l /tmp/xnk2.ppm diff --git a/build-scripts/integration/krd/x86nokrd-test.sh b/build-scripts/integration/krd/x86nokrd-test.sh new file mode 100644 index 0000000..96a6dc4 --- /dev/null +++ b/build-scripts/integration/krd/x86nokrd-test.sh @@ -0,0 +1,42 @@ +#!/bin/bash +# Тест ia32-меню без пункта KRD (конфиг + картинки). +set -e +IMG=/root/x86nokrd.img +rm -f "$IMG"; truncate -s 200M "$IMG" +printf 'label: dos\nstart=1MiB, type=0c, bootable\n' | sfdisk "$IMG" >/dev/null 2>&1 +LOOP=$(losetup -f --show -P "$IMG"); sleep 1 +mkfs.vfat -F 32 -n PARAVIS "${LOOP}p1" >/dev/null 2>&1 +mkdir -p /mnt/xnk; mount "${LOOP}p1" /mnt/xnk +mkdir -p /mnt/xnk/EFI/BOOT /mnt/xnk/efi/Boot +cp -f /mnt/f/efi/Paravis/Boot/xor/UEFI/bootia32.efi /mnt/xnk/EFI/BOOT/BOOTIA32.EFI +cp -f /path/to/pf/KRD/images/xor/x86.xor /mnt/xnk/efi/Boot/x86.xor +cp -f /path/to/pf/KRD/images/x86-1-nokrd.png /mnt/xnk/efi/Boot/1x86.bmp 2>/dev/null || true +cp -f /path/to/pf/KRD/images/x86-2-nokrd.png /mnt/xnk/efi/Boot/2x86.bmp 2>/dev/null || true +python3 - <<'EOF' +from PIL import Image +for n in ('1x86','2x86'): + src = f'/path/to/pf/KRD/images/x86-{1 if n=="1x86" else 2}-nokrd.png' + Image.open(src).convert('RGB').save(f'/mnt/xnk/efi/Boot/{n}.bmp') +print('bmp ok') +EOF +sync +umount /mnt/xnk; losetup -d "$LOOP" + +rm -f /tmp/xnk.ppm /tmp/xnk.sock +qemu-system-i386 -m 1024 -machine q35 \ + -drive if=pflash,format=raw,readonly=on,file=/usr/share/OVMF/OVMF32_CODE_4M.fd \ + -drive if=pflash,format=raw,file=/root/OVMF32_VARS.fd \ + -drive file="$IMG",format=raw,if=ide \ + -display none -vga std -monitor unix:/tmp/xnk.sock,server,nowait -daemonize +sleep 14 +python3 - <<'EOF' +import socket, time +s=socket.socket(socket.AF_UNIX); s.connect('/tmp/xnk.sock'); time.sleep(0.3) +s.recv(65536); s.sendall(b'screendump /tmp/xnk.ppm\n'); time.sleep(1.5) +try: s.recv(65536) +except Exception: pass +s.sendall(b'quit\n') +EOF +sleep 2 +pkill -f 'qemu-system-i386.*x86nokrd.img' 2>/dev/null || true +ls -l /tmp/xnk.ppm diff --git a/build-scripts/integration/sg2d/sg2d-default.sh b/build-scripts/integration/sg2d/sg2d-default.sh new file mode 100644 index 0000000..fff61b5 --- /dev/null +++ b/build-scripts/integration/sg2d/sg2d-default.sh @@ -0,0 +1,11 @@ +#!/bin/bash +set -e +cd /root +rm -rf sg2d +git clone --depth 1 -q https://github.com/supergrub/supergrub.git sg2d +cd sg2d +echo "=== default/timeout in menus:" +grep -rn 'set default\|set timeout\|default=' menus/ | head -20 +echo +echo "=== main.cfg (first 120 lines):" +sed -n '30,120p' menus/sgd/main.cfg diff --git a/build-scripts/integration/sg2d/sg2d-dl.sh b/build-scripts/integration/sg2d/sg2d-dl.sh new file mode 100644 index 0000000..0f25aa0 --- /dev/null +++ b/build-scripts/integration/sg2d/sg2d-dl.sh @@ -0,0 +1,8 @@ +#!/bin/bash +echo "=== download page links:" +curl -sL --max-time 60 "https://www.supergrubdisk.org/supergrub2-download/" \ + | grep -oE 'href="[^"]+\.(zip|img|iso|tar\.gz|efi)"' | sort -u | head -30 +echo +echo "=== sourceforge listing:" +curl -sL --max-time 60 "https://sourceforge.net/projects/supergrub2/files/" \ + | grep -oE 'supergrub2-[0-9][^"/]*' | sort -u | head -20 diff --git a/build-scripts/integration/sg2d/sg2d-efi-probe.sh b/build-scripts/integration/sg2d/sg2d-efi-probe.sh new file mode 100644 index 0000000..2fdf067 --- /dev/null +++ b/build-scripts/integration/sg2d/sg2d-efi-probe.sh @@ -0,0 +1,17 @@ +#!/bin/bash +W=/root/efichk +rm -rf "$W"; mkdir -p "$W"; cd "$W" +cp /path/to/pf/super/x64.efi new.efi +cp /mnt/f/efi/Paravis/Boot/grub2/apps/super.efi old.efi +for f in new old; do + echo "===== $f" + objdump -h $f.efi 2>/dev/null | awk '$2 ~ /memdisk|mods|grub/ {print " section:",$2,$3}' + objcopy -O binary --only-section=.memdisk $f.efi $f.mem 2>/dev/null + ls -l $f.mem 2>/dev/null | awk '{print " memdisk:",$5,"bytes"}' + if [ -s $f.mem ]; then + file $f.mem | sed 's/^/ /' + mkdir -p $f.dir && cd $f.dir + (cpio -itv < ../$f.mem 2>/dev/null || tar tvf ../$f.mem 2>/dev/null) | awk '{print " "$NF, $5}' | sort | head -40 + cd .. + fi +done diff --git a/build-scripts/integration/sg2d/sg2d-entries.sh b/build-scripts/integration/sg2d/sg2d-entries.sh new file mode 100644 index 0000000..16fec12 --- /dev/null +++ b/build-scripts/integration/sg2d/sg2d-entries.sh @@ -0,0 +1,7 @@ +#!/bin/bash +cd /root/sg2d || exit 1 +echo "=== main menu options (process_main_option calls):" +grep -n 'process_main_option\|^menuentry' menus/sgd/main.cfg | head -30 +echo +echo "=== 195..250:" +sed -n '195,250p' menus/sgd/main.cfg diff --git a/build-scripts/integration/sg2d/sg2d-final-check.sh b/build-scripts/integration/sg2d/sg2d-final-check.sh new file mode 100644 index 0000000..cc0fb21 --- /dev/null +++ b/build-scripts/integration/sg2d/sg2d-final-check.sh @@ -0,0 +1,13 @@ +#!/bin/bash +cd /root/sg2dwork || exit 1 +echo "=== ISO main.cfg (patched?):" +xorriso -osirrox on -indev super.iso -extract /boot/grub/sgd/main.cfg /tmp/mc2.cfg >/dev/null 2>&1 +grep -n 'set default\|id=detect' /tmp/mc2.cfg | head -5 +xorriso -osirrox on -indev super.iso -extract /boot/grub/grub.cfg /tmp/gc2.cfg >/dev/null 2>&1 +echo "=== ISO grub.cfg:" +grep -n 'set lang' /tmp/gc2.cfg | head -3 +echo "=== ISO EFI images:" +xorriso -indev super.iso -report_el_torito plain 2>/dev/null | grep -E 'boot img|img path' +echo "=== deployed file signature:" +cp /path/to/pf/super/x64.efi /tmp/sig.efi +sbverify --cert /path/to/pf/Ventoy/keys/ventoy.crt /tmp/sig.efi diff --git a/build-scripts/integration/sg2d/sg2d-get.sh b/build-scripts/integration/sg2d/sg2d-get.sh new file mode 100644 index 0000000..deaac2a --- /dev/null +++ b/build-scripts/integration/sg2d/sg2d-get.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -e +cd /tmp +rm -rf sg2drel sg2d.zip +curl -sL --max-time 900 "https://downloads.sourceforge.net/project/supergrub2/2.06s4/super_grub2_disk_2.06s4.zip" -o sg2d.zip +echo "zip size: $(stat -c %s sg2d.zip)" +mkdir -p sg2drel +7z x -y -osg2drel sg2d.zip >/dev/null +echo "=== contents:" +find sg2drel -maxdepth 2 -type f -printf ' %-60P %10s\n' | head -40 +echo "=== efi files inside:" +find sg2drel -iname '*.efi' -printf ' %-60P %10s\n' | head -20 diff --git a/build-scripts/integration/sg2d/sg2d-info.sh b/build-scripts/integration/sg2d/sg2d-info.sh new file mode 100644 index 0000000..760960a --- /dev/null +++ b/build-scripts/integration/sg2d/sg2d-info.sh @@ -0,0 +1,12 @@ +#!/bin/bash +echo "=== repo:" +curl -sL --max-time 60 "https://api.github.com/repos/supergrub/supergrub" \ + | python3 -c "import sys,json; d=json.load(sys.stdin); print('name:',d.get('full_name'),'| default:',d.get('default_branch'),'| size:',d.get('size'),'KB'); print('desc:',d.get('description'))" +echo "=== tags:" +curl -sL --max-time 60 "https://api.github.com/repos/supergrub/supergrub/tags?per_page=10" \ + | python3 -c "import sys,json; [print(' ', t['name']) for t in json.load(sys.stdin)]" +echo "=== root contents:" +curl -sL --max-time 60 "https://api.github.com/repos/supergrub/supergrub/contents/" \ + | python3 -c "import sys,json; [print(' %-24s %s' % (e['name'], e['type'])) for e in json.load(sys.stdin)]" +echo "=== supergrubdisk.org reachable?" +curl -sI --max-time 30 https://www.supergrubdisk.org/ | head -3 diff --git a/build-scripts/integration/sg2d/sg2d-iso-check2.sh b/build-scripts/integration/sg2d/sg2d-iso-check2.sh new file mode 100644 index 0000000..0ed2e67 --- /dev/null +++ b/build-scripts/integration/sg2d/sg2d-iso-check2.sh @@ -0,0 +1,11 @@ +#!/bin/bash +cd /root/sg2dwork || exit 1 +echo "=== files under /boot/grub/sgd (or similar) with default:" +xorriso -indev super.iso -find /boot/grub -name 'main.cfg' 2>/dev/null +for p in $(xorriso -indev super.iso -find /boot/grub -name 'main.cfg' 2>/dev/null | tr -d "'"); do + echo "--- $p" + xorriso -osirrox on -indev super.iso -extract "$p" /tmp/mc.cfg >/dev/null 2>&1 + grep -n 'set default' /tmp/mc.cfg +done +echo "=== also check embedded menu in x64.efi (memdisk) via strings:" +strings -a /path/to/pf/super/x64.efi 2>/dev/null | grep -c 'set default=1' || true diff --git a/build-scripts/integration/sg2d/sg2d-iso-efi.sh b/build-scripts/integration/sg2d/sg2d-iso-efi.sh new file mode 100644 index 0000000..163f611 --- /dev/null +++ b/build-scripts/integration/sg2d/sg2d-iso-efi.sh @@ -0,0 +1,16 @@ +#!/bin/bash +cd /root/sg2dwork || exit 1 +rm -rf isochk; mkdir isochk; cd isochk +xorriso -osirrox on -indev ../super.iso -extract /efi.img efi.img >/dev/null 2>&1 +ls -l efi.img +mkdir mnt +mount -o loop,ro efi.img mnt 2>/dev/null || { echo "mount failed"; exit 1; } +find mnt -maxdepth 3 | sed 's/^/ /' | head -30 +echo "--- sizes:" +find mnt -name '*.efi' -exec ls -l {} \; +umount mnt +# also check that ISO's menus were patched +mkdir iso2 +xorriso -osirrox on -indev ../super.iso -extract /boot/grub/grub.cfg iso2/grub.cfg >/dev/null 2>&1 +echo "--- ISO grub.cfg lang/default:" +grep -n 'set lang\|set default' iso2/grub.cfg | head diff --git a/build-scripts/integration/sg2d/sg2d-iso-inspect.sh b/build-scripts/integration/sg2d/sg2d-iso-inspect.sh new file mode 100644 index 0000000..ede8a32 --- /dev/null +++ b/build-scripts/integration/sg2d/sg2d-iso-inspect.sh @@ -0,0 +1,9 @@ +#!/bin/bash +cd /root/sg2dwork || exit 1 +echo "=== ISO tree:" +xorriso -indev super.iso -ls / 2>/dev/null | head -30 +echo "=== find efi:" +xorriso -indev super.iso -find / -name '*efi*' 2>/dev/null | head -20 +xorriso -indev super.iso -find / -name '*.EFI' 2>/dev/null | head -20 +echo "=== boot catalog:" +xorriso -indev super.iso -report_el_torito plain 2>/dev/null | head -40 diff --git a/build-scripts/integration/sg2d/sg2d-iso.sh b/build-scripts/integration/sg2d/sg2d-iso.sh new file mode 100644 index 0000000..85b05df --- /dev/null +++ b/build-scripts/integration/sg2d/sg2d-iso.sh @@ -0,0 +1,11 @@ +#!/bin/bash +# Rebuild Super GRUB2 ISO (Russian + 2nd item default) from the already-patched tree. +set -e +cd /root/sg2dwork/sg2d || exit 1 +grep -n 'set default' menus/sgd/main.cfg | head -3 +./supergrub-mkrescue -o=/root/sg2dwork/super.iso \ + --grub-mkrescue-binary=/usr/bin/grub-mkrescue \ + --grub-mkfont-binary=/usr/bin/grub-mkfont > /tmp/sg_iso.log 2>&1 || { tail -15 /tmp/sg_iso.log; exit 1; } +ls -l /root/sg2dwork/super.iso +echo "--- EFI content of ISO:" +xorriso -indev /root/sg2dwork/super.iso -find /EFI -exec lsdl -- 2>/dev/null | head -40 diff --git a/build-scripts/integration/sg2d/sg2d-list.sh b/build-scripts/integration/sg2d/sg2d-list.sh new file mode 100644 index 0000000..b984a3d --- /dev/null +++ b/build-scripts/integration/sg2d/sg2d-list.sh @@ -0,0 +1,5 @@ +#!/bin/bash +cd /tmp +curl -sL --max-time 90 "https://sourceforge.net/projects/supergrub2/files/2.06s4/" -o sg2d_list.html +echo "=== files in 2.06s4:" +grep -oE '/2\.06s4/[A-Za-z0-9._-]+' sg2d_list.html | sort -u | head -30 diff --git a/build-scripts/integration/sg2d/sg2d-maincfg.sh b/build-scripts/integration/sg2d/sg2d-maincfg.sh new file mode 100644 index 0000000..276ff34 --- /dev/null +++ b/build-scripts/integration/sg2d/sg2d-maincfg.sh @@ -0,0 +1,7 @@ +#!/bin/bash +cd /root/sg2d || exit 1 +echo "=== main.cfg 140..190:" +sed -n '140,190p' menus/sgd/main.cfg +echo +echo "=== where the main menu entries are created (tail):" +tail -40 menus/sgd/main.cfg diff --git a/build-scripts/integration/sg2d/sg2d-mkrescue.sh b/build-scripts/integration/sg2d/sg2d-mkrescue.sh new file mode 100644 index 0000000..49b0451 --- /dev/null +++ b/build-scripts/integration/sg2d/sg2d-mkrescue.sh @@ -0,0 +1,7 @@ +#!/bin/bash +cd /root/sg2dwork/sg2d || exit 1 +echo "=== mkrescue options:" +grep -n 'grub-mkrescue-binary\|GRUB_MKRESCUE_BINARY\|-o=\|-O=' supergrub-mkrescue | head -20 +echo +echo "=== usage:" +sed -n '20,45p' supergrub-mkrescue diff --git a/build-scripts/integration/sg2d/sg2d-mkrescue2.sh b/build-scripts/integration/sg2d/sg2d-mkrescue2.sh new file mode 100644 index 0000000..b2b36b4 --- /dev/null +++ b/build-scripts/integration/sg2d/sg2d-mkrescue2.sh @@ -0,0 +1,6 @@ +#!/bin/bash +cd /root/sg2dwork/sg2d || exit 1 +echo "=== all --*-binary options:" +grep -n -- '--.*-binary)' supergrub-mkrescue +echo "=== defaults:" +grep -n 'GRUB_.*_BINARY=' supergrub-mkrescue | head -20 diff --git a/build-scripts/integration/sg2d/sg2d-mkrescue3.sh b/build-scripts/integration/sg2d/sg2d-mkrescue3.sh new file mode 100644 index 0000000..b32e344 --- /dev/null +++ b/build-scripts/integration/sg2d/sg2d-mkrescue3.sh @@ -0,0 +1,4 @@ +#!/bin/bash +cd /root/sg2dwork/sg2d || exit 1 +echo "=== lines 100..125:" +sed -n '100,125p' supergrub-mkrescue diff --git a/build-scripts/integration/sg2d/sg2d-ppm2png.sh b/build-scripts/integration/sg2d/sg2d-ppm2png.sh new file mode 100644 index 0000000..37feb53 --- /dev/null +++ b/build-scripts/integration/sg2d/sg2d-ppm2png.sh @@ -0,0 +1,32 @@ +#!/bin/bash +python3 - <<'EOF' +import zlib, struct +def ppm2png(src, dst): + d=open(src,'rb').read() + # parse header + parts=[]; i=0 + while len(parts)<4: + while d[i:i+1].isspace(): i+=1 + if d[i:i+1]==b'#': + while d[i:i+1] not in (b'\n',b'\r'): i+=1 + continue + j=i + while not d[j:j+1].isspace(): j+=1 + parts.append(d[i:j]); i=j + i+=1 + w=int(parts[1]); h=int(parts[2]) + px=d[i:i+w*h*3] + raw=b''.join(b'\x00'+px[y*w*3:(y+1)*w*3] for y in range(h)) + def chunk(t,data): + c=t+data + return struct.pack('>I',len(data))+c+struct.pack('>I',zlib.crc32(c)&0xffffffff) + png=b'\x89PNG\r\n\x1a\n' + png+=chunk(b'IHDR',struct.pack('>IIBBBBB',w,h,8,2,0,0,0)) + png+=chunk(b'IDAT',zlib.compress(raw,9)) + png+=chunk(b'IEND',b'') + open(dst,'wb').write(png) + print(dst,w,h,len(png)) +ppm2png('/tmp/shot.ppm','/path/to/pf/super/preview.png') +ppm2png('/tmp/shot2.ppm','/path/to/pf/super/preview2.png') +EOF +ls -l /path/to/pf/super/ diff --git a/build-scripts/integration/sg2d/sg2d-probe.sh b/build-scripts/integration/sg2d/sg2d-probe.sh new file mode 100644 index 0000000..259fc40 --- /dev/null +++ b/build-scripts/integration/sg2d/sg2d-probe.sh @@ -0,0 +1,13 @@ +#!/bin/bash +for u in \ + "https://sourceforge.net/projects/supergrub2/files/2.06s4/" \ + "https://downloads.sourceforge.net/project/supergrub2/2.06s4/supergrub2-2.06s4.iso" \ + "https://downloads.sourceforge.net/project/supergrub2/2.06s4/supergrub2-2.06s4-multiarch-USB.img" \ + "https://downloads.sourceforge.net/project/supergrub2/2.06s4/supergrub2-2.06s4-standalone-efi.zip" \ +; do + printf '%-88s ' "$(echo "$u" | cut -c1-88)" + code=$(curl -sL -o /dev/null -w '%{http_code} %{size_download}' --max-time 45 "$u" 2>/dev/null) + echo "$code" +done +echo "=== files listing via sf api:" +curl -sL --max-time 45 "https://sourceforge.net/projects/supergrub2/best_release.json" | head -c 400; echo diff --git a/build-scripts/integration/sg2d/sg2d-qemu-env.sh b/build-scripts/integration/sg2d/sg2d-qemu-env.sh new file mode 100644 index 0000000..88e1b18 --- /dev/null +++ b/build-scripts/integration/sg2d/sg2d-qemu-env.sh @@ -0,0 +1,5 @@ +#!/bin/bash +echo "=== qemu:"; which qemu-system-x86_64 || true +echo "=== ovmf:"; ls -l /usr/share/OVMF/ 2>/dev/null | head +ls -l /usr/share/ovmf/ 2>/dev/null | head +echo "=== mtools:"; which mformat mcopy || true diff --git a/build-scripts/integration/sg2d/sg2d-qemu-test.sh b/build-scripts/integration/sg2d/sg2d-qemu-test.sh new file mode 100644 index 0000000..b11b31a --- /dev/null +++ b/build-scripts/integration/sg2d/sg2d-qemu-test.sh @@ -0,0 +1,40 @@ +#!/bin/bash +# Boot the freshly built Super GRUB2 x64.efi in QEMU/OVMF and screenshot the menu. +set -e +W=/root/qtest +rm -rf "$W"; mkdir -p "$W"; cd "$W" + +dd if=/dev/zero of=esp.img bs=1M count=64 status=none +mformat -i esp.img -F :: >/dev/null +mmd -i esp.img ::/EFI ::/EFI/BOOT +mcopy -i esp.img /root/sg2dwork/super-x64.efi ::/EFI/BOOT/BOOTX64.EFI +cp /usr/share/OVMF/OVMF_VARS_4M.fd vars.fd + +rm -f /tmp/qmon.sock /tmp/shot.ppm +qemu-system-x86_64 -m 1024 -machine q35 \ + -drive if=pflash,format=raw,readonly=on,file=/usr/share/OVMF/OVMF_CODE_4M.fd \ + -drive if=pflash,format=raw,file=vars.fd \ + -drive format=raw,file=esp.img \ + -net none -display none \ + -monitor unix:/tmp/qmon.sock,server,nowait -daemonize + +sleep 25 +python3 - <<'EOF' +import socket, time +s = socket.socket(socket.AF_UNIX); s.connect('/tmp/qmon.sock'); time.sleep(0.3) +s.recv(65536) +s.sendall(b'screendump /tmp/shot.ppm\n'); time.sleep(1.5) +s.recv(65536) +s.sendall(b'screendump /tmp/shot2.ppm\n'); time.sleep(1.5) +s.sendall(b'quit\n') +EOF +sleep 2 +pkill -f 'qemu-system-x86_64.*qtest' 2>/dev/null || true +ls -l /tmp/shot*.ppm +python3 - <<'EOF' +import struct +for n in ('/tmp/shot.ppm','/tmp/shot2.ppm'): + d=open(n,'rb').read() + print(n, d[:20], len(d)) +EOF +command -v convert >/dev/null && { convert /tmp/shot.ppm /path/to/pf/super/preview.png; convert /tmp/shot2.ppm /path/to/pf/super/preview2.png; ls -l /path/to/pf/super/preview*.png; } || echo "no imagemagick" diff --git a/build-scripts/integration/sg2d/sg2d-repo.sh b/build-scripts/integration/sg2d/sg2d-repo.sh new file mode 100644 index 0000000..4dbcf7b --- /dev/null +++ b/build-scripts/integration/sg2d/sg2d-repo.sh @@ -0,0 +1,12 @@ +#!/bin/bash +cd /tmp/sg2d || exit 1 +echo "=== releases dir:" +ls releases/ 2>/dev/null | head -20 +echo "=== news-releases:" +ls news-releases/ 2>/dev/null | head -10 +echo "=== version header:" +head -20 info_cfg_header.cfg 2>/dev/null +echo "=== urls in release scripts:" +grep -rhoE 'https?://[^"'"'"' ]+' supergrub-official-release supergrub-release-news supergrub-release-changes 2>/dev/null | sort -u | head -20 +echo "=== po has ru?" +ls po/ | grep -iE 'ru|RU' diff --git a/build-scripts/integration/sg2d/sg2d-src.sh b/build-scripts/integration/sg2d/sg2d-src.sh new file mode 100644 index 0000000..2065889 --- /dev/null +++ b/build-scripts/integration/sg2d/sg2d-src.sh @@ -0,0 +1,13 @@ +#!/bin/bash +cd /tmp +rm -rf sg2d +git clone --depth 1 -q https://github.com/supergrub/supergrub.git sg2d +cd sg2d +echo "=== version files:" +cat supergrub-build-config 2>/dev/null | head -20 +echo "=== language handling in menus:" +grep -rn 'lang' menus/ 2>/dev/null | head -20 +echo "=== po files:" +ls po/ | head +echo "=== mkstandalone:" +sed -n '1,60p' supergrub-mkstandalone diff --git a/build-scripts/integration/sg2d/stage-sg2d.sh b/build-scripts/integration/sg2d/stage-sg2d.sh new file mode 100644 index 0000000..4668ee1 --- /dev/null +++ b/build-scripts/integration/sg2d/stage-sg2d.sh @@ -0,0 +1,20 @@ +#!/bin/bash +set -e +K=/path/to/pf/Ventoy/keys +D=/path/to/pf/ParavisGrub +A=$D/apps +mkdir -p "$A" + +echo "=== SG2D build sanity" +strings -a /tmp/sg2d_ru.efi | grep -aiE 'Super GRUB2 Disk|sg2d_directory|Language' | sort -u | head -6 + +echo "=== sign -> staged apps/super.efi" +sbsign --key "$K/ventoy.key" --cert "$K/ventoy.crt" --output "$A/super.efi" /tmp/sg2d_ru.efi +sbverify --cert "$K/ventoy.crt" "$A/super.efi" +ls -l "$A/super.efi" +sha256sum "$A/super.efi" + +echo +echo "=== what will be deployed (structure check)" +echo " p1 efi/Paravis/Boot/grub2/ <- only our new loader lives here" +ls -l "$D" "$D/menu" "$A" diff --git a/build-scripts/integration/signing/resign-xorboot-all.sh b/build-scripts/integration/signing/resign-xorboot-all.sh new file mode 100644 index 0000000..f03fe1d --- /dev/null +++ b/build-scripts/integration/signing/resign-xorboot-all.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -e +K=/path/to/pf/Ventoy/keys +BK="/path/to/pf/Ventoy/backup/xorboot-uefi/sign" +TMP=/tmp/xorsbat +rm -rf "$TMP"; mkdir -p "$TMP" + +cd "$BK" +files=$(find . -type f -name '*.efi' | sort) +n=0 +for rel in $files; do + src="$BK/$rel" + dst="/mnt/f/$rel" + base=$(basename "$rel") + echo "--- $rel" + # add .sbat (idempotent) then sign + python3 /path/to/pf/Ventoy/add-sbat.py "$src" "$TMP/stage.efi" + if sbattach --detach "$TMP/old.p7" "$TMP/stage.efi" >/dev/null 2>&1; then + sbattach --remove "$TMP/stage.efi" + echo " (stripped old signature)" + fi + sbsign --key "$K/ventoy.key" --cert "$K/ventoy.crt" --output "$TMP/out.efi" "$TMP/stage.efi" >/dev/null 2>&1 + sbverify --cert "$K/ventoy.crt" "$TMP/out.efi" >/dev/null + cp -f "$TMP/out.efi" "$dst" + n=$((n+1)) + printf " deployed %-58s %s\n" "$rel" "$(stat -c %s "$dst")" +done +echo "total: $n" diff --git a/build-scripts/integration/signing/sbverify-test.sh b/build-scripts/integration/signing/sbverify-test.sh new file mode 100644 index 0000000..b8e6daf --- /dev/null +++ b/build-scripts/integration/signing/sbverify-test.sh @@ -0,0 +1,15 @@ +#!/bin/bash +C=/path/to/pf/Ventoy/keys/ventoy.crt +t() { + printf '%-42s ' "${1#/mnt/}" + out=$(sbverify --cert "$C" "$1" 2>&1); rc=$? + echo "rc=$rc $(echo "$out" | tr '\n' ' ' | cut -c1-90)" +} +echo "--- should FAIL (Microsoft-signed shim):" +t /mnt/g/EFI/BOOT/BOOTX64.EFI +echo "--- should FAIL (unsigned):" +t /path/to/pf/Ventoy/backup/xorboot-uefi/bootx64.efi.orig +echo "--- should PASS (ours):" +t /path/to/pf/Ventoy/xorboot/fbx64-xor.efi +t /mnt/g/EFI/BOOT/fbx64.efi +t /mnt/f/EFI/Boot/fbx64.efi diff --git a/build-scripts/integration/signing/sig-check.sh b/build-scripts/integration/signing/sig-check.sh new file mode 100644 index 0000000..b6d9193 --- /dev/null +++ b/build-scripts/integration/signing/sig-check.sh @@ -0,0 +1,29 @@ +#!/bin/bash +W=/tmp/sigchk +rm -rf $W; mkdir -p $W + +echo "=== our cert:" +openssl x509 -in /path/to/pf/Ventoy/keys/ventoy.crt -inform PEM -outform DER -out $W/ours.der +openssl x509 -in $W/ours.der -inform DER -noout -subject -fingerprint -sha256 + +check() { + local f="$1" + echo + echo "=== $f" + rm -f "$W/sig.p7" "$W/certs.pem" $W/c*.pem + if ! sbattach --detach "$W/sig.p7" "$f" >/dev/null 2>&1; then + echo " no signature" + return + fi + openssl pkcs7 -inform DER -in "$W/sig.p7" -print_certs -out "$W/certs.pem" 2>/dev/null + awk 'BEGIN{f=""} /BEGIN CERTIFICATE/{c++; f=sprintf("'$W'/c%d.pem", c)} {if(f) print > f} /END CERTIFICATE/{f=""}' "$W/certs.pem" + for c in $W/c*.pem; do + [ -f "$c" ] || continue + echo " cert:" + openssl x509 -in "$c" -noout -subject -fingerprint -sha256 | sed 's/^/ /' + done +} + +check "/mnt/g/EFI/BOOT/fbx64.efi" +check "/mnt/f/EFI/Boot/fbx64.efi" +check "/mnt/g/EFI/BOOT/grubx64_real.efi" diff --git a/build-scripts/integration/signing/sign-efi.sh b/build-scripts/integration/signing/sign-efi.sh new file mode 100644 index 0000000..a193000 --- /dev/null +++ b/build-scripts/integration/signing/sign-efi.sh @@ -0,0 +1,36 @@ +#!/bin/bash +set -e + +EFI_DIR=/root/vtbuild-efi +IN=$EFI_DIR/INSTALL/EFI/BOOT/grubx64_real.efi +MOD=$EFI_DIR/GRUB2/INSTALL/lib/grub/x86_64-efi/ventoy.mod +OUTDIR=/path/to/pf/Ventoy +KEYS=$OUTDIR/keys + +echo "=== ventoy.mod: $(stat -c %s $MOD) bytes" +for p in "ISO/Ventoy/ventoy.json" "VTOY_DATA_PART_IDX" "VTOY_EFI_PART_IDX"; do + echo " $p : $(strings -a $MOD | grep -c -F "$p")" +done +echo "=== image: $(stat -c %s $IN) bytes" + +mkdir -p "$KEYS" +if [ ! -f "$KEYS/ventoy.key" ] || [ ! -f "$KEYS/ventoy.crt" ]; then + echo "=== generating signing key" + openssl req -new -x509 -newkey rsa:2048 -sha256 -days 3650 -nodes \ + -keyout "$KEYS/ventoy.key" -out "$KEYS/ventoy.crt" \ + -subj "/CN=Paravis Ventoy Secure Boot/" \ + -addext "basicConstraints=critical,CA:TRUE" \ + -addext "keyUsage=critical,digitalSignature,keyCertSign" \ + -addext "extendedKeyUsage=codeSigning" +else + echo "=== signing key already exists (kept)" +fi + +openssl x509 -in "$KEYS/ventoy.crt" -outform DER -out "$KEYS/ventoy.cer" + +echo "=== signing" +sbsign --key "$KEYS/ventoy.key" --cert "$KEYS/ventoy.crt" --output "$OUTDIR/grubx64_real.efi.signed" "$IN" +echo "=== verify" +sbverify --cert "$KEYS/ventoy.crt" "$OUTDIR/grubx64_real.efi.signed" +echo "=== result: $(stat -c %s "$OUTDIR/grubx64_real.efi.signed") bytes" +ls -l "$KEYS" diff --git a/build-scripts/integration/signing/sign-xorboot-ossl.sh b/build-scripts/integration/signing/sign-xorboot-ossl.sh new file mode 100644 index 0000000..129642c --- /dev/null +++ b/build-scripts/integration/signing/sign-xorboot-ossl.sh @@ -0,0 +1,22 @@ +#!/bin/bash +set -e +K=/path/to/pf/Ventoy/keys +OUT=/path/to/pf/Ventoy/xorboot +ORIG="/path/to/pf/Ventoy/backup/xorboot-uefi/bootx64.efi.orig" + +apt-get install -y osslsigncode >/tmp/apt_ossl.log 2>&1 || true +which osslsigncode || { echo "osslsigncode not available"; exit 1; } + +echo "=== sign with osslsigncode (sha256)" +osslsigncode sign -certs "$K/ventoy.crt" -key "$K/ventoy.key" -h sha256 \ + -in "$ORIG" -out "$OUT/fbx64-xor-ossl.efi" +ls -l "$OUT/fbx64-xor-ossl.efi" +sbverify --cert "$K/ventoy.crt" "$OUT/fbx64-xor-ossl.efi" + +echo "=== certs in the new signature:" +rm -f /tmp/o.p7 +sbattach --detach /tmp/o.p7 "$OUT/fbx64-xor-ossl.efi" >/dev/null +openssl pkcs7 -inform DER -in /tmp/o.p7 -print_certs -noout | head -10 + +echo "=== structure:" +python3 /path/to/pf/Ventoy/pedump.py "$OUT/fbx64-xor-ossl.efi" | tail -6 diff --git a/build-scripts/integration/signing/sign-xorboot-tree.sh b/build-scripts/integration/signing/sign-xorboot-tree.sh new file mode 100644 index 0000000..fe6d8b3 --- /dev/null +++ b/build-scripts/integration/signing/sign-xorboot-tree.sh @@ -0,0 +1,47 @@ +#!/bin/bash +set -e +K=/path/to/pf/Ventoy/keys +BK="/path/to/pf/Ventoy/backup/xorboot-uefi/sign" +TMP=/tmp/xorsign +rm -rf "$TMP"; mkdir -p "$TMP" "$BK" + +files=( + "/mnt/f/EFI/Boot/bootia32.efi" + "/mnt/f/efi/Paravis/Boot/gfm/x64.efi" + "/mnt/f/efi/Paravis/Boot/gfm/x86.efi" + "/mnt/f/efi/Paravis/Boot/mem/memtest32.efi" + "/mnt/f/efi/Paravis/Boot/mem/memtest64.efi" + "/mnt/f/efi/Paravis/Boot/mgr/UEFI/8PE.efi" + "/mnt/f/efi/Paravis/Boot/mgr/UEFI/bootia32.efi" + "/mnt/f/efi/Paravis/Boot/super/x64.efi" + "/mnt/f/efi/Paravis/Boot/super/x86.efi" + "/mnt/f/efi/Paravis/Boot/xor/UEFI/bootia32.efi" + "/mnt/f/efi/Paravis/Boot/xor/UEFI/bootx64.efi" + "/mnt/f/efi/Paravis/Boot/xor/UEFI/Linux/bootia32.efi" + "/mnt/f/efi/Paravis/Boot/xor/UEFI/Linux/bootx64.efi" + "/mnt/f/efi/Paravis/Boot/xor/UEFI/MSDaRT/bootx64.efi" + "/mnt/f/efi/Paravis/Boot/xor/UEFI/Strelec/bootx64.efi" + "/mnt/f/efi/Paravis/Boot/xor/UEFI/Utilits/bootia32.efi" + "/mnt/f/efi/Paravis/Boot/xor/UEFI/Utilits/bootx64.efi" +) + +n=0 +for f in "${files[@]}"; do + [ -f "$f" ] || { echo "MISSING $f"; continue; } + rel="${f#/mnt/f/}" + mkdir -p "$BK/$(dirname "$rel")" + cp -f "$f" "$BK/$rel" + + tmp="$TMP/work.efi" + cp -f "$f" "$tmp" + if sbattach --detach "$TMP/sig.p7" "$tmp" >/dev/null 2>&1; then + echo " [strip old signature] $rel" + sbattach --remove "$tmp" + fi + sbsign --key "$K/ventoy.key" --cert "$K/ventoy.crt" --output "$TMP/out.efi" "$tmp" >/dev/null 2>&1 + sbverify --cert "$K/ventoy.crt" "$TMP/out.efi" >/dev/null + cp -f "$TMP/out.efi" "$f" + n=$((n+1)) + printf " signed %-52s %s\n" "$rel" "$(stat -c %s "$f")" +done +echo "total signed: $n" diff --git a/build-scripts/integration/signing/sign-xorboot.sh b/build-scripts/integration/signing/sign-xorboot.sh new file mode 100644 index 0000000..3b5bac9 --- /dev/null +++ b/build-scripts/integration/signing/sign-xorboot.sh @@ -0,0 +1,20 @@ +#!/bin/bash +set -e +K=/path/to/pf/Ventoy/keys +OUT=/path/to/pf/Ventoy/xorboot +mkdir -p "$OUT" + +echo "=== sign x64 xorboot" +sbsign --key "$K/ventoy.key" --cert "$K/ventoy.crt" \ + --output "$OUT/fbx64-xor.efi" "/mnt/f/EFI/Boot/bootx64.efi" +sbverify --cert "$K/ventoy.crt" "$OUT/fbx64-xor.efi" +ls -l "$OUT/fbx64-xor.efi" + +echo "=== sign ia32 xorboot (optional, for 32-bit UEFI)" +sbsign --key "$K/ventoy.key" --cert "$K/ventoy.crt" \ + --output "$OUT/bootia32-xor.efi" "/mnt/f/EFI/Boot/bootia32.efi" +sbverify --cert "$K/ventoy.crt" "$OUT/bootia32-xor.efi" +ls -l "$OUT/bootia32-xor.efi" + +echo "=== sha256" +sha256sum "$OUT/fbx64-xor.efi" "$OUT/bootia32-xor.efi" diff --git a/build-scripts/integration/xor/mt86p-clone.sh b/build-scripts/integration/xor/mt86p-clone.sh new file mode 100644 index 0000000..4ca8ce7 --- /dev/null +++ b/build-scripts/integration/xor/mt86p-clone.sh @@ -0,0 +1,14 @@ +#!/bin/bash +set -e +cd /tmp +rm -rf mt86p +git clone --depth 1 https://github.com/memtest86plus/memtest86plus.git mt86p >/tmp/mt86p_clone.log 2>&1 || { tail -5 /tmp/mt86p_clone.log; exit 1; } +cd mt86p +echo "=== version/tag:" +git describe --tags 2>/dev/null || true +grep -rn 'VERSION' app/version.h 2>/dev/null | head -3 || true +echo "=== build docs:" +sed -n '/[Bb]uild/,+25p' README.md | head -60 +echo "=== make targets hinted:" +grep -nE '^[a-z0-9_]+:' Makefile 2>/dev/null | head -20 +ls diff --git a/build-scripts/integration/xor/restore-super-x64.sh b/build-scripts/integration/xor/restore-super-x64.sh new file mode 100644 index 0000000..175213f --- /dev/null +++ b/build-scripts/integration/xor/restore-super-x64.sh @@ -0,0 +1,10 @@ +#!/bin/bash +set -e +K=/path/to/pf/Ventoy/keys +BK=/path/to/pf/Ventoy/backup/xorboot-uefi/sign/EFI/Paravis/Boot/super/x64.efi +rm -rf /tmp/rs; mkdir -p /tmp/rs +python3 /path/to/pf/Ventoy/add-sbat.py "$BK" /tmp/rs/stage.efi +sbsign --key "$K/ventoy.key" --cert "$K/ventoy.crt" --output /tmp/rs/out.efi /tmp/rs/stage.efi >/dev/null +sbverify --cert "$K/ventoy.crt" /tmp/rs/out.efi +cp -f /tmp/rs/out.efi /mnt/f/efi/Paravis/Boot/super/x64.efi +ls -l /mnt/f/efi/Paravis/Boot/super/x64.efi diff --git a/build-scripts/integration/xor/restore-xorboot-original.ps1 b/build-scripts/integration/xor/restore-xorboot-original.ps1 new file mode 100644 index 0000000..59a3064 --- /dev/null +++ b/build-scripts/integration/xor/restore-xorboot-original.ps1 @@ -0,0 +1,35 @@ +# Restore all XorBoot UEFI files to their pre-change (original, unsigned) state. +$bk = 'C:\PF\Ventoy\backup\xorboot-uefi' +$sgn = Join-Path $bk 'sign' +$dstRoot = 'F:\' + +function Restore-One([string]$src, [string]$dst) { + if (!(Test-Path $src)) { " MISSING BACKUP: $src"; return } + Copy-Item $src $dst -Force + $h1 = (Get-FileHash $src -Algorithm SHA256).Hash + $h2 = (Get-FileHash $dst -Algorithm SHA256).Hash + $ok = if ($h1 -eq $h2) { 'ok' } else { 'HASH MISMATCH' } + " {0,-56} {1,9} {2}" -f $dst.Replace('F:\',''), (Get-Item $dst).Length, $ok +} + +"=== main loaders" +Restore-One (Join-Path $bk 'bootx64.efi.orig') 'F:\EFI\Boot\bootx64.efi' +Restore-One (Join-Path $bk 'bootia32.efi.orig') 'F:\EFI\Boot\bootia32.efi' + +"=== remove files we added" +foreach ($f in 'F:\EFI\Boot\fbx64.efi', 'F:\EFI\Boot\mmx64.efi') { + if (Test-Path $f) { Remove-Item $f -Force; " removed: $f" } else { " already absent: $f" } +} + +"=== sub-loaders" +Get-ChildItem $sgn -Recurse -File -Filter '*.efi' | ForEach-Object { + $rel = $_.FullName.Substring($sgn.Length + 1) + Restore-One $_.FullName (Join-Path $dstRoot $rel) +} + +"=== result: signature state of all EFI under F:\efi" +Get-ChildItem 'F:\efi' -Recurse -File -Filter '*.efi' | Sort-Object FullName | ForEach-Object { + $s = Get-AuthenticodeSignature $_.FullName + $subj = if ($s.SignerCertificate) { ($s.SignerCertificate.Subject -replace '^CN=([^,]+).*', '$1') } else { '-' } + " {0,-52} {1,9} {2,-12} {3}" -f $_.FullName.Replace('F:\', ''), $_.Length, $s.Status, $subj +} diff --git a/build-scripts/integration/xor/xor-colors.sh b/build-scripts/integration/xor/xor-colors.sh new file mode 100644 index 0000000..dd749d9 --- /dev/null +++ b/build-scripts/integration/xor/xor-colors.sh @@ -0,0 +1,42 @@ +#!/bin/bash +python3 - <<'EOF' +from PIL import Image +import numpy as np + +imgs = { + 'legacy-normal': '/path/to/pf/PSD/main/main1.bmp', + 'legacy-high': '/path/to/pf/PSD/main/main2.bmp', + 'x64-normal': '/path/to/pf/PSD/UEFI/x64/main/main1.bmp', + 'x64-high': '/path/to/pf/PSD/UEFI/x64/main/main2.bmp', + 'x86-normal': '/path/to/pf/PSD/UEFI/x86/main/main1.bmp', + 'x86-high': '/path/to/pf/PSD/UEFI/x86/main/main2.bmp', +} +# y-полосы строк (из PSD bbox): A = Grub2/GFM, B = Kaspersky +bands = { + 'legacy-normal': (424, 444, 481, 501), + 'legacy-high': (424, 444, 481, 501), + 'x64-normal': (356, 376, 416, 436), + 'x64-high': (356, 376, 416, 436), + 'x86-normal': (424, 444, 481, 501), + 'x86-high': (424, 444, 481, 501), +} +for name, path in imgs.items(): + im = Image.open(path).convert('RGB') + a = np.array(im) + yA0, yA1, yB0, yB1 = bands[name] + print('==', name, im.size) + for tag, (y0, y1) in (('A', (yA0, yA1)), ('B', (yB0, yB1))): + band = a[y0-4:y1+4, 40:470] + # фон: самый частый цвет + cols, counts = np.unique(band.reshape(-1,3), axis=0, return_counts=True) + bg = cols[counts.argmax()] + # текст: пиксели, максимально отличающиеся от фона + diff = np.abs(band.astype(int) - bg.astype(int)).sum(axis=2) + ink = band[diff > 120] + if len(ink): + tc = np.median(ink, axis=0).astype(int) + else: + tc = None + print(f' {tag}: bg={tuple(int(x) for x in bg)} ink={tuple(int(x) for x in tc) if tc is not None else None} ' + f'unique_bg_ratio={counts.max()/counts.sum():.3f}') +EOF diff --git a/build-scripts/integration/xor/xor-edit1.py.sh b/build-scripts/integration/xor/xor-edit1.py.sh new file mode 100644 index 0000000..f8b0c2f --- /dev/null +++ b/build-scripts/integration/xor/xor-edit1.py.sh @@ -0,0 +1,118 @@ +#!/bin/bash +python3 - <<'EOF' +from PIL import Image, ImageDraw, ImageFont +import numpy as np, os, shutil + +FONT = '/path/to/pf/PSD/fonts/Montserrat-VF.ttf' +OUT = '/path/to/pf/KRD/images' +os.makedirs(OUT, exist_ok=True) + +items = [ + # name, src, yA (grub2 строка), yB (kaspersky строка) + ('legacy-1', '/path/to/pf/PSD/main/main1.bmp', 424, 481), + ('legacy-2', '/path/to/pf/PSD/main/main2.bmp', 424, 481), + ('x64-1', '/path/to/pf/PSD/UEFI/x64/main/main1.bmp', 356, 416), + ('x64-2', '/path/to/pf/PSD/UEFI/x64/main/main2.bmp', 356, 416), + ('x86-1', '/path/to/pf/PSD/UEFI/x86/main/main1.bmp', 424, 481), + ('x86-2', '/path/to/pf/PSD/UEFI/x86/main/main2.bmp', 424, 481), +] + +OLD_A = 'Grub2 FileManager (ISO образы)' +NEW_A = 'Ventoy (ISO образы)' +OLD_B = 'Kaspersky Rescue Disk 18' +NEW_B = 'Kaspersky Rescue Disk 24' + +def font(size=20, wght=550): + f = ImageFont.truetype(FONT, size) + f.set_variation_by_axes([wght]) + return f + +def render_mask(text, size=20, wght=550, pad=40): + f = font(size, wght) + img = Image.new('L', (1000, 120), 0) + ImageDraw.Draw(img).text((pad, 30), text, font=f, fill=255) + m = np.array(img) > 127 + ys, xs = np.where(m) + return m[ys.min():ys.max()+1, xs.min():xs.max()+1], xs.min()-pad, ys.min()-30 # обрезанный mask + смещение + +def analyze(a, y, h=30): + band = a[y-8:y+22, 30:500] + cols, counts = np.unique(band.reshape(-1, 3), axis=0, return_counts=True) + bg = cols[counts.argmax()] + diff = np.abs(band.astype(int) - bg.astype(int)).sum(axis=2) + ink_mask = diff > 120 + ink = band[ink_mask] + tc = tuple(int(v) for v in np.median(ink, axis=0)) if len(ink) else (0, 0, 0) + return tuple(int(v) for v in bg), tc, ink_mask, band + +def text_region(ink_mask, x_off=30): + # колонки с чернилами + colsum = ink_mask.sum(axis=0) + cols = np.where(colsum > 0)[0] + if len(cols) == 0: return None + # группируем в "кластеры" по разрывам > 15 px + groups = [] + start = cols[0]; prev = cols[0] + for c in cols[1:]: + if c - prev > 15: + groups.append((start, prev)); start = c + prev = c + groups.append((start, prev)) + # последняя группа - хоткей (короткая), если её ширина < 45 и групп > 1 + text_groups = groups + if len(groups) > 1 and (groups[-1][1] - groups[-1][0]) < 45: + text_groups = groups[:-1] + x0 = text_groups[0][0]; x1 = text_groups[-1][1] + rows = np.where(ink_mask[:, x0:x1+1].sum(axis=1) > 0)[0] + return (x0+x_off, rows.min()+y-8, x1+x_off, rows.max()+y-8), groups + +def iou_align(A, B, rng=10): + ha, wa = A.shape; hb, wb = B.shape; best = (-1, 0, 0) + for dy in range(-rng, rng+1): + for dx in range(-rng, rng+1): + y0 = max(0, dy); x0 = max(0, dx) + y1 = min(ha, hb+dy); x1 = min(wa, wb+dx) + if y1 <= y0 or x1 <= x0: continue + s1 = A[y0:y1, x0:x1]; s2 = B[y0-dy:y1-dy, x0-dx:x1-dx] + u = np.logical_or(s1, s2).sum() + if not u: continue + s = np.logical_and(s1, s2).sum()/u + if s > best[0]: best = (s, dx, dy) + return best + +for name, src, yA, yB in items: + a = np.array(Image.open(src).convert('RGB')) + img = Image.open(src).convert('RGB') + draw = ImageDraw.Draw(img) + print('==', name) + + for tag, y, old, new in (('A', yA, OLD_A, NEW_A), ('B', yB, OLD_B, NEW_B)): + bg, tc, ink_mask, band = analyze(a, y) + reg, groups = text_region(ink_mask) + if reg is None: + print(' ', tag, 'текст не найден'); continue + x0, y0, x1, y1 = reg + print(f' {tag}: bg={bg} ink={tc} text_bbox=({x0},{y0},{x1},{y1}) groups={groups}') + + # совмещаем отрисовку старого текста с картинкой + rend, rx, ry = render_mask(old) + sub = a[y0-2:y1+3, x0-2:x1+3] + d = np.abs(sub.astype(int) - np.array(bg).astype(int)).sum(axis=2) > 120 + s, dx, dy = iou_align(d, rend) + print(f' align IoU={s:.3f} dx={dx} dy={dy}') + + # точка, куда рисовать текст: (x0-2+dx - rx, y0-2+dy - ry) + px = x0 - 2 + dx - rx + py = y0 - 2 + dy - ry + + # стираем область текста + draw.rectangle([x0-3, y0-4, x1+3, y1+3], fill=bg) + # рисуем новый текст + draw.text((px, py), new, font=font(), fill=tc) + print(f' draw "{new}" at ({px},{py})') + + a2 = np.array(img) + # проверка: чернила в области B + Image.fromarray(a2).save(f'{OUT}/{name}.png') + print(' ->', f'{OUT}/{name}.png') +EOF diff --git a/build-scripts/integration/xor/xor-edit2.py.sh b/build-scripts/integration/xor/xor-edit2.py.sh new file mode 100644 index 0000000..8276a0e --- /dev/null +++ b/build-scripts/integration/xor/xor-edit2.py.sh @@ -0,0 +1,96 @@ +#!/bin/bash +python3 - <<'EOF' +from PIL import Image, ImageDraw, ImageFont +import numpy as np, os + +FONT = '/path/to/pf/PSD/fonts/Montserrat-VF.ttf' +OUT = '/path/to/pf/KRD/images' +os.makedirs(OUT, exist_ok=True) + +DARK = np.array([41, 53, 84]) +YELL = np.array([234, 224, 115]) +PAGE = np.array([233, 233, 233]) + +items = [ + ('legacy-2', '/path/to/pf/PSD/main/main2.bmp', 424, 481), + ('x64-2', '/path/to/pf/PSD/UEFI/x64/main/main2.bmp', 356, 416), + ('x86-2', '/path/to/pf/PSD/UEFI/x86/main/main2.bmp', 424, 481), +] +OLD_A = 'Grub2 FileManager (ISO образы)' +NEW_A = 'Ventoy (ISO образы)' +OLD_B = 'Kaspersky Rescue Disk 18' +NEW_B = 'Kaspersky Rescue Disk 24' + +def font(size=20, wght=550): + f = ImageFont.truetype(FONT, size) + f.set_variation_by_axes([wght]) + return f + +def render(text, color, size=20, wght=550, pad=60): + f = font(size, wght) + w, h = 1100, 140 + img = Image.new('RGB', (w, h), tuple(PAGE)) + ImageDraw.Draw(img).text((pad, 40), text, font=f, fill=tuple(int(v) for v in color)) + a = np.array(img).astype(int) + m = np.abs(a - PAGE).sum(axis=2) > 100 + ys, xs = np.where(m) + return m[ys.min():ys.max()+1, xs.min():xs.max()+1], xs.min()-pad, ys.min()-40 + +def iou_align(A, B, rng=12): + ha, wa = A.shape; hb, wb = B.shape; best = (-1, 0, 0) + for dy in range(-rng, rng+1): + for dx in range(-rng, rng+1): + y0 = max(0, dy); x0 = max(0, dx) + y1 = min(ha, hb+dy); x1 = min(wa, wb+dx) + if y1 <= y0 or x1 <= x0: continue + s1 = A[y0:y1, x0:x1]; s2 = B[y0-dy:y1-dy, x0-dx:x1-dx] + u = np.logical_or(s1, s2).sum() + if not u: continue + s = np.logical_and(s1, s2).sum()/u + if s > best[0]: best = (s, dx, dy) + return best + +for name, src, yA, yB in items: + base = Image.open(src).convert('RGB') + arr0 = np.array(base).astype(int) + img = base.copy() + draw = ImageDraw.Draw(img) + print('==', name) + + for tag, y, old, new in (('A', yA, OLD_A, NEW_A), ('B', yB, OLD_B, NEW_B)): + band = arr0[y-10:y+24, 20:1010] + # цвет полосы: сэмпл в середине строки + bar = arr0[y+2, 250] + # сколько пикселей рядом с тёмным/жёлтым в полосе + d_dark = np.abs(band - DARK).sum(axis=2) < 150 + d_yell = np.abs(band - YELL).sum(axis=2) < 150 + if d_yell.sum() > 50 and np.abs(bar - YELL).sum() > 100: + text_color, bar_color = YELL, bar + elif d_dark.sum() > 50 and np.abs(bar - DARK).sum() > 100: + text_color, bar_color = DARK, bar + else: + # текст того цвета, которого больше и который не совпадает с полосой + text_color = YELL if d_yell.sum() > d_dark.sum() else DARK + bar_color = bar + m = np.abs(band - text_color).sum(axis=2) < 150 + ys, xs = np.where(m) + if len(xs) == 0: + print(' ', tag, 'текст не найден'); continue + x0, x1 = xs.min()+20, xs.max()+20 + y0, y1 = ys.min()+y-10, ys.max()+y-10 + print(f' {tag}: bar={tuple(int(v) for v in bar_color)} text={tuple(int(v) for v in text_color)} bbox=({x0},{y0},{x1},{y1})') + + rend, rx, ry = render(old, text_color) + sub = np.abs(arr0[y0-2:y1+3, x0-2:x1+3] - text_color).sum(axis=2) < 150 + s, dx, dy = iou_align(sub, rend) + print(f' align IoU={s:.3f} dx={dx} dy={dy}') + px = x0 - 2 + dx - rx + py = y0 - 2 + dy - ry + + draw.rectangle([x0-3, y0-4, x1+3, y1+3], fill=tuple(int(v) for v in bar_color)) + draw.text((px, py), new, font=font(), fill=tuple(int(v) for v in text_color)) + print(f' draw "{new}" at ({px},{py})') + + img.save(f'{OUT}/{name}.png') + print(' ->', f'{OUT}/{name}.png') +EOF diff --git a/build-scripts/integration/xor/xor-edit3.py.sh b/build-scripts/integration/xor/xor-edit3.py.sh new file mode 100644 index 0000000..469272f --- /dev/null +++ b/build-scripts/integration/xor/xor-edit3.py.sh @@ -0,0 +1,104 @@ +#!/bin/bash +python3 - <<'EOF' +from PIL import Image, ImageDraw, ImageFont +import numpy as np, os + +FONT = '/path/to/pf/PSD/fonts/Montserrat-VF.ttf' +OUT = '/path/to/pf/KRD/images' +os.makedirs(OUT, exist_ok=True) + +DARK = np.array([41, 53, 84]); YELL = np.array([234, 224, 115]); PAGE = np.array([233, 233, 233]) +TOL = 55 + +items = [ + ('legacy-1', '/path/to/pf/PSD/main/main1.bmp', 424, 481), + ('legacy-2', '/path/to/pf/PSD/main/main2.bmp', 424, 481), + ('x64-1', '/path/to/pf/PSD/UEFI/x64/main/main1.bmp', 356, 416), + ('x64-2', '/path/to/pf/PSD/UEFI/x64/main/main2.bmp', 356, 416), + ('x86-1', '/path/to/pf/PSD/UEFI/x86/main/main1.bmp', 424, 481), + ('x86-2', '/path/to/pf/PSD/UEFI/x86/main/main2.bmp', 424, 481), +] +OLD_A, NEW_A = 'Grub2 FileManager (ISO образы)', 'Ventoy (ISO образы)' +OLD_B, NEW_B = 'Kaspersky Rescue Disk 18', 'Kaspersky Rescue Disk 24' + +def font(size=20, wght=550): + f = ImageFont.truetype(FONT, size); f.set_variation_by_axes([wght]); return f + +def render(text, color, size=20, wght=550, pad=60): + img = Image.new('RGB', (1100, 140), tuple(PAGE)) + ImageDraw.Draw(img).text((pad, 40), text, font=font(size, wght), fill=tuple(int(v) for v in color)) + a = np.array(img).astype(int) + m = np.sqrt(((a - PAGE) ** 2).sum(axis=2)) > TOL + ys, xs = np.where(m) + return m[ys.min():ys.max()+1, xs.min():xs.max()+1], xs.min()-pad, ys.min()-40 + +def iou_align(A, B, rng=12): + ha, wa = A.shape; hb, wb = B.shape; best = (-1, 0, 0) + for dy in range(-rng, rng+1): + for dx in range(-rng, rng+1): + y0 = max(0, dy); x0 = max(0, dx) + y1 = min(ha, hb+dy); x1 = min(wa, wb+dx) + if y1 <= y0 or x1 <= x0: continue + s1 = A[y0:y1, x0:x1]; s2 = B[y0-dy:y1-dy, x0-dx:x1-dx] + u = np.logical_or(s1, s2).sum() + if not u: continue + s = np.logical_and(s1, s2).sum()/u + if s > best[0]: best = (s, dx, dy) + return best + +for name, src, yA, yB in items: + base = Image.open(src).convert('RGB') + arr0 = np.array(base).astype(int) + img = base.copy(); draw = ImageDraw.Draw(img) + print('==', name) + for tag, y, old, new in (('A', yA, OLD_A, NEW_A), ('B', yB, OLD_B, NEW_B)): + bar = arr0[y+2, 250] + band = arr0[y-10:y+24, 20:470] # только зона текста (справа графика) + cnt = {} + for nm, col in (('dark', DARK), ('yellow', YELL)): + cnt[nm] = int((np.sqrt(((band - col) ** 2).sum(axis=2)) < TOL).sum()) + # выбираем цвет текста: тот, что не совпадает с полосой и его достаточно + if np.sqrt(((bar - YELL) ** 2).sum()) < TOL and cnt['dark'] > 30: + text_color, bar_color = DARK, bar + elif np.sqrt(((bar - DARK) ** 2).sum()) < TOL and cnt['yellow'] > 30: + text_color, bar_color = YELL, bar + else: + text_color = YELL if cnt['yellow'] >= cnt['dark'] else DARK + bar_color = PAGE if cnt['yellow'] < 30 and cnt['dark'] < 30 else bar + m = np.sqrt(((band - text_color) ** 2).sum(axis=2)) < TOL + ys, xs = np.where(m) + if len(xs) == 0: + print(' ', tag, 'текст не найден'); continue + # колонки с чернилами, группируем по разрывам; последняя короткая группа = хоткей + colsum = m.sum(axis=0) + cols = np.where(colsum >= 2)[0] + groups = [] + if len(cols): + s = cols[0]; prev = cols[0] + for c in cols[1:]: + if c - prev > 12: + groups.append((s, prev)); s = c + prev = c + groups.append((s, prev)) + if len(groups) > 1 and (groups[-1][1] - groups[-1][0]) < 60: + groups = groups[:-1] + if not groups: + print(' ', tag, 'текст не найден'); continue + gx0, gx1 = groups[0][0], groups[-1][1] + x0, x1 = gx0+20, gx1+20 + rowsub = m[:, gx0:gx1+1] + rowsum = rowsub.sum(axis=1); rows = np.where(rowsum >= 2)[0] + y0, y1 = rows.min()+y-10, rows.max()+y-10 + print(f' {tag}: bar={tuple(int(v) for v in bar_color)} text={tuple(int(v) for v in text_color)} bbox=({x0},{y0},{x1},{y1})') + + rend, rx, ry = render(old, text_color) + sub = np.sqrt(((arr0[y0-2:y1+3, x0-2:x1+3] - text_color) ** 2).sum(axis=2)) < TOL + s, dx, dy = iou_align(sub, rend) + px = x0 - 2 + dx - rx; py = y0 - 2 + dy - ry + print(f' align IoU={s:.3f} dx={dx} dy={dy} -> draw at ({px},{py})') + + draw.rectangle([x0-3, y0-4, x1+3, y1+3], fill=tuple(int(v) for v in bar_color)) + draw.text((px, py), new, font=font(), fill=tuple(int(v) for v in text_color)) + img.save(f'{OUT}/{name}.png') + print(' ->', f'{OUT}/{name}.png') +EOF diff --git a/build-scripts/integration/xor/xor-uefi-test.sh b/build-scripts/integration/xor/xor-uefi-test.sh new file mode 100644 index 0000000..e17e488 --- /dev/null +++ b/build-scripts/integration/xor/xor-uefi-test.sh @@ -0,0 +1,34 @@ +#!/bin/bash +# Проверка UEFI Xorboot: какие файлы меню он использует. +set -e +IMG=/root/xoruefi.img +rm -f "$IMG"; truncate -s 256M "$IMG" +mkfs.vfat -F 32 -n XORTEST "$IMG" >/dev/null 2>&1 +mkdir -p /mnt/xortest; mount -o loop "$IMG" /mnt/xortest +mkdir -p /mnt/xortest/EFI/BOOT +cp -f /mnt/f/efi/Paravis/Boot/xor/UEFI/bootx64.efi /mnt/xortest/EFI/BOOT/BOOTX64.EFI +mkdir -p /mnt/xortest/efi/Paravis/Boot +cp -r /mnt/f/efi/Paravis/Boot/xor /mnt/xortest/efi/Paravis/Boot/ +sync +echo "=== в образе:"; find /mnt/xortest/efi/Paravis/Boot/xor -maxdepth 2 | head -20 +umount /mnt/xortest + +rm -f /tmp/qx1.ppm /tmp/qxmon.sock +qemu-system-x86_64 -m 1024 -machine q35 \ + -drive if=pflash,format=raw,readonly=on,file=/usr/share/OVMF/OVMF_CODE_4M.fd \ + -drive if=pflash,format=raw,file=/usr/share/OVMF/OVMF_VARS_4M.fd \ + -drive file="$IMG",format=raw,if=ide \ + -device qemu-xhci -device usb-tablet -display none -vga std \ + -monitor unix:/tmp/qxmon.sock,server,nowait -daemonize +sleep 12 +python3 - <<'EOF' +import socket, time +s=socket.socket(socket.AF_UNIX); s.connect('/tmp/qxmon.sock'); time.sleep(0.3) +s.recv(65536); s.sendall(b'screendump /tmp/qx1.ppm\n'); time.sleep(1.5) +try: s.recv(65536) +except Exception: pass +s.sendall(b'quit\n') +EOF +sleep 2 +pkill -f 'qemu-system-x86_64.*xoruefi.img' 2>/dev/null || true +ls -l /tmp/qx1.ppm 2>/dev/null diff --git a/build-scripts/integration/xor/xor-uefi-test2.sh b/build-scripts/integration/xor/xor-uefi-test2.sh new file mode 100644 index 0000000..58b6f58 --- /dev/null +++ b/build-scripts/integration/xor/xor-uefi-test2.sh @@ -0,0 +1,42 @@ +#!/bin/bash +# UEFI Xorboot на образе с таблицей разделов (как флешка). +set -e +IMG=/root/xoruefi.img +rm -f "$IMG"; truncate -s 300M "$IMG" +# MBR + один раздел с 1 МиБ +printf 'label: dos\nstart=1MiB, type=0c, bootable\n' | sfdisk "$IMG" >/dev/null 2>&1 || { + parted -s "$IMG" mklabel msdos + parted -s "$IMG" mkpart primary fat32 1MiB 100% + parted -s "$IMG" set 1 boot on +} +LOOP=$(losetup -f --show -P "$IMG") +sleep 1 +mkfs.vfat -F 32 -n XORTEST "${LOOP}p1" >/dev/null 2>&1 +mkdir -p /mnt/xortest; mount "${LOOP}p1" /mnt/xortest +mkdir -p /mnt/xortest/EFI/BOOT +cp -f /mnt/f/efi/Paravis/Boot/xor/UEFI/bootx64.efi /mnt/xortest/EFI/BOOT/BOOTX64.EFI +mkdir -p /mnt/xortest/efi/Paravis/Boot +cp -r /mnt/f/efi/Paravis/Boot/xor /mnt/xortest/efi/Paravis/Boot/ +sync +umount /mnt/xortest +losetup -d "$LOOP" + +rm -f /tmp/qx2.ppm /tmp/qxmon2.sock +qemu-system-x86_64 -m 1024 -machine q35 \ + -drive if=pflash,format=raw,readonly=on,file=/usr/share/OVMF/OVMF_CODE_4M.fd \ + -drive if=pflash,format=raw,file=/usr/share/OVMF/OVMF_VARS_4M.fd \ + -drive file="$IMG",format=raw,if=ide \ + -device qemu-xhci -device usb-tablet -display none -vga std \ + -monitor unix:/tmp/qxmon2.sock,server,nowait -daemonize +sleep 12 +python3 - <<'EOF' +import socket, time +s=socket.socket(socket.AF_UNIX); s.connect('/tmp/qxmon2.sock'); time.sleep(0.3) +s.recv(65536); s.sendall(b'screendump /tmp/qx2.ppm\n'); time.sleep(1.5) +try: s.recv(65536) +except Exception: pass +s.sendall(b'quit\n') +EOF +sleep 2 +pkill -f 'qemu-system-x86_64.*xoruefi.img' 2>/dev/null || true +ls -l /tmp/qx2.ppm diff --git a/build-scripts/integration/xor/xor-uefi-test3.sh b/build-scripts/integration/xor/xor-uefi-test3.sh new file mode 100644 index 0000000..99e8245 --- /dev/null +++ b/build-scripts/integration/xor/xor-uefi-test3.sh @@ -0,0 +1,39 @@ +#!/bin/bash +# UEFI Xorboot: какие имена BMP он ищет (x64.xor + 1x64/2x64). +set -e +IMG=/root/xuefi2.img +rm -f "$IMG"; truncate -s 400M "$IMG" +printf 'label: dos\nstart=1MiB, type=0c, bootable\n' | sfdisk "$IMG" >/dev/null 2>&1 +LOOP=$(losetup -f --show -P "$IMG"); sleep 1 +mkfs.vfat -F 32 -n XORTEST "${LOOP}p1" >/dev/null 2>&1 +mkdir -p /mnt/xt2; mount "${LOOP}p1" /mnt/xt2 + +mkdir -p /mnt/xt2/EFI/BOOT +cp -f /mnt/f/efi/Paravis/Boot/xor/UEFI/bootx64.efi /mnt/xt2/EFI/BOOT/BOOTX64.EFI +cp -f /mnt/f/efi/Boot/x64.xor /mnt/xt2/EFI/BOOT/x64.xor +cp -f /mnt/f/efi/Boot/1x64.bmp /mnt/xt2/EFI/BOOT/1x64.bmp +cp -f /mnt/f/efi/Boot/2x64.bmp /mnt/xt2/EFI/BOOT/2x64.bmp +# ещё копии под именами из конфига — но НЕ кладём, чтобы понять, какие он ищет +sync +echo "=== в EFI/BOOT:"; ls -l /mnt/xt2/EFI/BOOT +umount /mnt/xt2; losetup -d "$LOOP" + +rm -f /tmp/qx3.ppm /tmp/qm3.sock +qemu-system-x86_64 -m 1024 -machine q35 \ + -drive if=pflash,format=raw,readonly=on,file=/usr/share/OVMF/OVMF_CODE_4M.fd \ + -drive if=pflash,format=raw,file=/usr/share/OVMF/OVMF_VARS_4M.fd \ + -drive file="$IMG",format=raw,if=ide \ + -device qemu-xhci -device usb-tablet -display none -vga std \ + -monitor unix:/tmp/qm3.sock,server,nowait -daemonize +sleep 12 +python3 - <<'EOF' +import socket, time +s=socket.socket(socket.AF_UNIX); s.connect('/tmp/qm3.sock'); time.sleep(0.3) +s.recv(65536); s.sendall(b'screendump /tmp/qx3.ppm\n'); time.sleep(1.5) +try: s.recv(65536) +except Exception: pass +s.sendall(b'quit\n') +EOF +sleep 2 +pkill -f 'qemu-system-x86_64.*xuefi2.img' 2>/dev/null || true +ls -l /tmp/qx3.ppm diff --git a/build-scripts/integration/xor/xor-verify.sh b/build-scripts/integration/xor/xor-verify.sh new file mode 100644 index 0000000..9d8b15a --- /dev/null +++ b/build-scripts/integration/xor/xor-verify.sh @@ -0,0 +1,22 @@ +#!/bin/bash +python3 - <<'EOF' +from PIL import Image +import numpy as np + +pairs = [ + ('legacy-1', '/mnt/f/efi/Paravis/Boot/xor/Main1.bmp', '/path/to/pf/KRD/images/legacy-1.png'), + ('legacy-2', '/mnt/f/efi/Paravis/Boot/xor/Main2.bmp', '/path/to/pf/KRD/images/legacy-2.png'), + ('x64-1', '/mnt/f/efi/Boot/1x64.bmp', '/path/to/pf/KRD/images/x64-1.png'), + ('x64-2', '/mnt/f/efi/Boot/2x64.bmp', '/path/to/pf/KRD/images/x64-2.png'), + ('x86-1', '/mnt/f/efi/Boot/1x86.bmp', '/path/to/pf/KRD/images/x86-1.png'), + ('x86-2', '/mnt/f/efi/Boot/2x86.bmp', '/path/to/pf/KRD/images/x86-2.png'), +] +for name, bmp, png in pairs: + a = np.array(Image.open(bmp).convert('RGB')) + b = np.array(Image.open(png).convert('RGB')) + same = a.shape == b.shape and np.array_equal(a, b) + diff = None if a.shape != b.shape else int(np.abs(a.astype(int)-b.astype(int)).max()) + print(f' {name:9s} bmp={a.shape} png={b.shape} equal={same} maxdiff={diff}') + if not same: + Image.fromarray(a).save(f'/path/to/pf/KRD/check-{name}.png') +EOF diff --git a/build-scripts/integration/xor/xor-x86-18.sh b/build-scripts/integration/xor/xor-x86-18.sh new file mode 100644 index 0000000..ae76dc8 --- /dev/null +++ b/build-scripts/integration/xor/xor-x86-18.sh @@ -0,0 +1,84 @@ +#!/bin/bash +# Только ia32-картинки: "Kaspersky Rescue Disk 18" + "Ventoy (ISO образы)". +python3 - <<'EOF' +from PIL import Image, ImageDraw, ImageFont +import numpy as np, os + +FONT = '/path/to/pf/PSD/fonts/Montserrat-VF.ttf' +OUT = '/path/to/pf/KRD/images' +DARK = np.array([41, 53, 84]); YELL = np.array([234, 224, 115]); PAGE = np.array([233, 233, 233]) +TOL = 55 +items = [ + ('x86-1', '/path/to/pf/PSD/UEFI/x86/main/main1.bmp', 424, 481), + ('x86-2', '/path/to/pf/PSD/UEFI/x86/main/main2.bmp', 424, 481), +] +OLD_A, NEW_A = 'Grub2 FileManager (ISO образы)', 'Ventoy (ISO образы)' +OLD_B, NEW_B = 'Kaspersky Rescue Disk 18', 'Kaspersky Rescue Disk 18' # 18 как есть + +def font(size=20, wght=550): + f = ImageFont.truetype(FONT, size); f.set_variation_by_axes([wght]); return f + +def render(text, color, size=20, wght=550, pad=60): + img = Image.new('RGB', (1100, 140), tuple(PAGE)) + ImageDraw.Draw(img).text((pad, 40), text, font=font(size, wght), fill=tuple(int(v) for v in color)) + a = np.array(img).astype(int) + m = np.sqrt(((a - PAGE) ** 2).sum(axis=2)) > TOL + ys, xs = np.where(m) + return m[ys.min():ys.max()+1, xs.min():xs.max()+1], xs.min()-pad, ys.min()-40 + +def iou_align(A, B, rng=12): + ha, wa = A.shape; hb, wb = B.shape; best = (-1, 0, 0) + for dy in range(-rng, rng+1): + for dx in range(-rng, rng+1): + y0 = max(0, dy); x0 = max(0, dx) + y1 = min(ha, hb+dy); x1 = min(wa, wb+dx) + if y1 <= y0 or x1 <= x0: continue + s1 = A[y0:y1, x0:x1]; s2 = B[y0-dy:y1-dy, x0-dx:x1-dx] + u = np.logical_or(s1, s2).sum() + if not u: continue + s = np.logical_and(s1, s2).sum()/u + if s > best[0]: best = (s, dx, dy) + return best + +for name, src, yA, yB in items: + base = Image.open(src).convert('RGB') + arr0 = np.array(base).astype(int) + img = base.copy(); draw = ImageDraw.Draw(img) + for tag, y, old, new in (('A', yA, OLD_A, NEW_A), ('B', yB, OLD_B, NEW_B)): + bar = arr0[y+2, 250] + band = arr0[y-10:y+24, 20:470] + cnt = {} + for nm, col in (('dark', DARK), ('yellow', YELL)): + cnt[nm] = int((np.sqrt(((band - col) ** 2).sum(axis=2)) < TOL).sum()) + if np.sqrt(((bar - YELL) ** 2).sum()) < TOL and cnt['dark'] > 30: + text_color, bar_color = DARK, bar + elif np.sqrt(((bar - DARK) ** 2).sum()) < TOL and cnt['yellow'] > 30: + text_color, bar_color = YELL, bar + else: + text_color = YELL if cnt['yellow'] >= cnt['dark'] else DARK + bar_color = PAGE if cnt['yellow'] < 30 and cnt['dark'] < 30 else bar + m = np.sqrt(((band - text_color) ** 2).sum(axis=2)) < TOL + colsum = m.sum(axis=0); cols = np.where(colsum >= 2)[0] + groups = [] + if len(cols): + s = cols[0]; prev = cols[0] + for c in cols[1:]: + if c - prev > 12: groups.append((s, prev)); s = c + prev = c + groups.append((s, prev)) + if len(groups) > 1 and (groups[-1][1] - groups[-1][0]) < 60: groups = groups[:-1] + if not groups: continue + gx0, gx1 = groups[0][0], groups[-1][1] + x0, x1 = gx0+20, gx1+20 + rowsum = m[:, gx0:gx1+1].sum(axis=1); rows = np.where(rowsum >= 2)[0] + y0, y1 = rows.min()+y-10, rows.max()+y-10 + rend, rx, ry = render(old, text_color) + sub = np.sqrt(((arr0[y0-2:y1+3, x0-2:x1+3] - text_color) ** 2).sum(axis=2)) < TOL + s, dx, dy = iou_align(sub, rend) + px = x0 - 2 + dx - rx; py = y0 - 2 + dy - ry + draw.rectangle([x0-3, y0-4, x1+3, y1+3], fill=tuple(int(v) for v in bar_color)) + draw.text((px, py), new, font=font(), fill=tuple(int(v) for v in text_color)) + print(f' {name} {tag}: "{new}" at ({px},{py}) IoU={s:.3f}') + img.save(f'{OUT}/{name}.png') + print(' ->', f'{OUT}/{name}.png') +EOF diff --git a/build-scripts/integration/xor/xor32-dbg.sh b/build-scripts/integration/xor/xor32-dbg.sh new file mode 100644 index 0000000..6362ffd --- /dev/null +++ b/build-scripts/integration/xor/xor32-dbg.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -e +IMG=/root/xor32.img +LOOP=$(losetup -f --show -P "$IMG"); sleep 1 +mount "${LOOP}p1" /mnt/x32p1 +cp -f /path/to/pf/KRD/images/krd32dbg.efi /mnt/x32p1/efi/Paravis/Boot/loaders/xb32/krd.efi +sync +umount /mnt/x32p1; losetup -d "$LOOP" +bash /path/to/pf/Ventoy/xor32-run.sh 7 30 dbg +python3 - <<'EOF' +import zlib, struct +def ppm2png(src, dst): + d = open(src, 'rb').read(); parts=[]; i=0 + while len(parts) < 4: + while d[i:i+1].isspace(): i += 1 + j = i + while not d[j:j+1].isspace(): j += 1 + parts.append(d[i:j]); i = j + i += 1 + w=int(parts[1]); h=int(parts[2]); px=d[i:i+w*h*3] + raw=b''.join(b'\x00'+px[y*w*3:(y+1)*w*3] for y in range(h)) + def ch(t,dd): + c=t+dd + return struct.pack('>I',len(dd))+c+struct.pack('>I',zlib.crc32(c)&0xffffffff) + png=b'\x89PNG\r\n\x1a\n'+ch(b'IHDR',struct.pack('>IIBBBBB',w,h,8,2,0,0,0))+ch(b'IDAT',zlib.compress(raw,9))+ch(b'IEND',b'') + open(dst,'wb').write(png); print(dst,w,h) +ppm2png('/tmp/x32-dbg.ppm','/path/to/pf/KRD/xor32-dbg.png') +EOF diff --git a/build-scripts/integration/xor/xor32-run.sh b/build-scripts/integration/xor/xor32-run.sh new file mode 100644 index 0000000..84390f2 --- /dev/null +++ b/build-scripts/integration/xor/xor32-run.sh @@ -0,0 +1,40 @@ +#!/bin/bash +# Запуск ia32 Xorboot и выбор пункта N (по умолчанию 6 = Ventoy). +set -e +IMG=/root/xor32.img +N=${1:-6} +WAIT=${2:-25} +TAG=${3:-v} + +rm -f /tmp/x32-$TAG.ppm /tmp/xm32-$TAG.sock +qemu-system-i386 -m 1024 -machine q35 \ + -drive if=pflash,format=raw,readonly=on,file=/usr/share/OVMF/OVMF32_CODE_4M.fd \ + -drive if=pflash,format=raw,file=/root/OVMF32_VARS.fd \ + -drive file="$IMG",format=raw,if=ide \ + -device qemu-xhci -device usb-tablet -display none -vga std \ + -monitor unix:/tmp/xm32-$TAG.sock,server,nowait -daemonize + +python3 - "$N" "$WAIT" "$TAG" <<'EOF' +import socket, time, sys +N = int(sys.argv[1]); WAIT = int(sys.argv[2]); TAG = sys.argv[3] +sock = f'/tmp/xm32-{TAG}.sock' +def mon(cmd, pause=0.25): + s = socket.socket(socket.AF_UNIX); s.connect(sock); time.sleep(0.2) + s.recv(65536); s.sendall((cmd+'\n').encode()); time.sleep(pause) + try: s.recv(65536) + except Exception: pass + s.close() +time.sleep(12) +# текущий пункт — 2-й; шагаем вниз до N +for _ in range(N-2): + mon('sendkey down') +time.sleep(0.5) +mon('sendkey ret') +time.sleep(WAIT) +mon(f'screendump /tmp/x32-{TAG}.ppm') +time.sleep(1) +mon('quit') +EOF +sleep 2 +pkill -f "qemu-system-i386.*xor32.img" 2>/dev/null || true +ls -l /tmp/x32-$TAG.ppm diff --git a/build-scripts/integration/xor/xor32-test1.sh b/build-scripts/integration/xor/xor32-test1.sh new file mode 100644 index 0000000..fe7d505 --- /dev/null +++ b/build-scripts/integration/xor/xor32-test1.sh @@ -0,0 +1,56 @@ +#!/bin/bash +# Тестовый образ для ia32 Xorboot: p1 = меню+KRD, p2 = Ventoy EFI. +set -e +IMG=/root/xor32.img +rm -f "$IMG"; truncate -s 1200M "$IMG" +printf 'label: dos\nstart=1MiB, size=1024MiB, type=0c, bootable\nstart=1025MiB, type=0e\n' | sfdisk "$IMG" >/dev/null 2>&1 +LOOP=$(losetup -f --show -P "$IMG"); sleep 1 +mkfs.vfat -F 32 -n PARAVIS "${LOOP}p1" >/dev/null 2>&1 +mkfs.vfat -F 16 -n VTOYEFI "${LOOP}p2" >/dev/null 2>&1 + +mkdir -p /mnt/x32p1 /mnt/x32p2 +mount "${LOOP}p1" /mnt/x32p1 +mount "${LOOP}p2" /mnt/x32p2 + +# --- p1: загрузчик xorboot ia32 + конфиг + картинки + переходники + KRD +mkdir -p /mnt/x32p1/EFI/BOOT /mnt/x32p1/efi/Boot +cp -f /mnt/f/efi/Paravis/Boot/xor/UEFI/bootia32.efi /mnt/x32p1/EFI/BOOT/BOOTIA32.EFI +cp -f /path/to/pf/KRD/images/xor/x86.xor /mnt/x32p1/efi/Boot/x86.xor +cp -f /mnt/f/efi/Boot/1x86.bmp /mnt/x32p1/efi/Boot/1x86.bmp +cp -f /mnt/f/efi/Boot/2x86.bmp /mnt/x32p1/efi/Boot/2x86.bmp +mkdir -p /mnt/x32p1/efi/Paravis/Boot/loaders/xb32 +cp -f /path/to/pf/KRD/images/ventoy32.efi /mnt/x32p1/efi/Paravis/Boot/loaders/xb32/ventoy.efi +cp -f /path/to/pf/KRD/images/krd32.efi /mnt/x32p1/efi/Paravis/Boot/loaders/xb32/krd.efi +mkdir -p /mnt/x32p1/efi/Paravis/KRD/live +cp -f /mnt/f/efi/Paravis/KRD/live/vmlinuz /mnt/x32p1/efi/Paravis/KRD/live/ +cp -f /mnt/f/efi/Paravis/KRD/live/initrd.img /mnt/x32p1/efi/Paravis/KRD/live/ + +# --- p2: Ventoy EFI (как G:) +mkdir -p /mnt/x32p2/EFI/BOOT /mnt/x32p2/grub /mnt/x32p2/ventoy +cp -f /mnt/g/EFI/BOOT/grubia32.efi /mnt/x32p2/EFI/BOOT/ +cp -r /mnt/g/grub/i386-efi /mnt/x32p2/grub/ +cp -f /mnt/g/ventoy/ventoy.cpio /mnt/g/ventoy/ventoy.cpio.orig /mnt/g/ventoy/vtoyjump32.exe /mnt/x32p2/ventoy/ 2>/dev/null || true + +sync +du -sh /mnt/x32p1 /mnt/x32p2 +umount /mnt/x32p1 /mnt/x32p2; losetup -d "$LOOP" + +rm -f /tmp/x32-*.ppm /tmp/xm32.sock +qemu-system-i386 -m 1024 -machine q35 \ + -drive if=pflash,format=raw,readonly=on,file=/usr/share/OVMF/OVMF32_CODE_4M.fd \ + -drive if=pflash,format=raw,file=/root/OVMF32_VARS.fd \ + -drive file="$IMG",format=raw,if=ide \ + -device qemu-xhci -device usb-tablet -display none -vga std \ + -monitor unix:/tmp/xm32.sock,server,nowait -daemonize +sleep 14 +python3 - <<'EOF' +import socket, time +s=socket.socket(socket.AF_UNIX); s.connect('/tmp/xm32.sock'); time.sleep(0.3) +s.recv(65536); s.sendall(b'screendump /tmp/x32-0.ppm\n'); time.sleep(1.5) +try: s.recv(65536) +except Exception: pass +s.sendall(b'quit\n') +EOF +sleep 2 +pkill -f 'qemu-system-i386.*xor32.img' 2>/dev/null || true +ls -l /tmp/x32-0.ppm diff --git a/build-scripts/layout/create-ventoy-bigp1.ps1 b/build-scripts/layout/create-ventoy-bigp1.ps1 new file mode 100644 index 0000000..1758110 --- /dev/null +++ b/build-scripts/layout/create-ventoy-bigp1.ps1 @@ -0,0 +1,268 @@ +#Requires -RunAsAdministrator +<# +.SYNOPSIS + Вариант B: один большой p1 для данных + p2 Ventoy + p3 14 ГБ для загрузки. + Диск полностью очищается. + +.DESCRIPTION + Создаёт: + p1 ~462 ГБ NTFS ESD + ISO + личные файлы (данные Ventoy) + p2 32 МБ FAT VTOYEFI + core.img + p3 14 ГБ FAT32 проект PF + Xorboot (активный раздел) + + Почему так: + * Ventoy требует p1 = данные, p2 = VTOYEFI сразу после p1; + * p3 FAT32 нужен для UEFI (прошивка не читает NTFS/exFAT); + * ESD install_10_x64.esd (4.26 ГиБ) и install_11.esd (4.44 ГиБ) + не влезают в FAT32, поэтому данные — на NTFS p1. + + Change_bootLoader.exe использует букву диска, с которого запущен, + поэтому его можно запускать с p3 — PBR ставится на p3, MBR на диск. + p3 помечается активным. + +.PARAMETER DiskNumber + Номер физического диска из Get-Disk. + +.PARAMETER BootSizeGB + Размер p3 (проект + загрузчик) в ГБ. По умолчанию 14. + +.PARAMETER DataFs + Файловая система p1: NTFS (по умолчанию) или exFAT. + +.PARAMETER ProjectDir + Папка PF (C:\PF\PF). + +.PARAMETER SkipProject + Не копировать PF на p3. + +.PARAMETER AllowNonUsb + Для USB-переходников, которые Windows показывает не как USB. + +.PARAMETER Force + Не спрашивать YES. + +.EXAMPLE + .\create-ventoy-bigp1.ps1 -DiskNumber 2 -WhatIf + +.EXAMPLE + .\create-ventoy-bigp1.ps1 -DiskNumber 2 -BootSizeGB 14 +#> +[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')] +param( + [Parameter(Mandatory = $true)] + [int]$DiskNumber, + + [int]$BootSizeGB = 14, + + [int]$TailReserveMB = 50, + + [ValidateSet('NTFS', 'exFAT')] + [string]$DataFs = 'NTFS', + + [string]$ProjectDir = 'C:\PF\PF', + + [string]$SourceDir = $PSScriptRoot, + + [switch]$SkipProject, + + [switch]$AllowNonUsb, + + [switch]$Force +) + +$ErrorActionPreference = 'Stop' + +$MiB = 1MB +$VentoySize = 32MB +$P1Offset = 1MB + +function Write-Step([string]$Text) { Write-Host "`n=== $Text ===" -ForegroundColor Cyan } +function Write-Warn([string]$Text) { Write-Host "WARN: $Text" -ForegroundColor Yellow } +function Write-Ok([string]$Text) { Write-Host "OK: $Text" -ForegroundColor Green } + +# --------------------------------------------------------------------------- +Write-Step "Проверка исходных файлов" +$vtoyefi = Join-Path $SourceDir 'vtoyefi' +$coreImg = Join-Path $SourceDir 'ventoy-1.1.18\boot\core.img' +if (-not (Test-Path $coreImg)) { $coreImg = Join-Path $SourceDir 'core.img' } +$grldr = Join-Path $SourceDir 'grldr-ventoy' + +if (-not (Test-Path (Join-Path $vtoyefi 'ventoy\ventoy.cpio'))) { throw "Не найден распакованный VTOYEFI: $vtoyefi" } +if (-not (Test-Path $coreImg)) { throw "Не найден core.img: $coreImg" } +if (-not $SkipProject -and -not (Test-Path $ProjectDir)) { throw "Не найдена папка проекта: $ProjectDir" } +Write-Ok "VTOYEFI: $vtoyefi" +Write-Ok "core.img: $coreImg" + +# --------------------------------------------------------------------------- +Write-Step "Проверка диска $DiskNumber" +if ($BootSizeGB -lt 14) { throw "BootSizeGB должен быть >= 14 (проект PF занимает 13.26 ГиБ)." } + +$disk = Get-Disk -Number $DiskNumber -ErrorAction Stop +if ($disk.IsBoot -or $disk.IsSystem) { throw "Диск $DiskNumber загрузочный/системный. Отказ." } +if (-not $AllowNonUsb -and $disk.BusType -notin @('USB', 'SD', 'MMC')) { + throw "Диск $DiskNumber имеет BusType '$($disk.BusType)', а не USB/SD. Отказ (тест: -AllowNonUsb)." +} + +$bootSize = [uint64]$BootSizeGB * 1GB +$tailReserve = [uint64]$TailReserveMB * 1MB + +# Считаем с конца: p3 фиксирован, p2 перед ним, p1 — всё остальное. +# Оставляем 50 МБ неразмеченного хвоста: некоторые USB-мостики +# (Realtek RTL9210B и др.) отдают в конце лишние МБ, которые Windows +# не даёт занять, и раздел «впритык» падает с Not enough capacity. +$p3Offset = [Math]::Floor(($disk.Size - $tailReserve - $bootSize) / 1MB) * 1MB +$p2Offset = $p3Offset - $VentoySize +$p1Size = $p2Offset - $P1Offset +$p3Size = $bootSize + +if ($p1Size -lt 1GB) { throw "Диск слишком мал: p1 получается меньше 1 ГБ." } +if ($p2Offset -le $P1Offset) { throw "Диск слишком мал для p2/p3." } +if (($p3Offset + $p3Size + $tailReserve) -gt $disk.Size) { throw "Внутренняя ошибка: p3 + хвост выходят за диск." } + +if (-not $SkipProject) { + $projBytes = [uint64]((Get-ChildItem -Path $ProjectDir -Recurse -File -ErrorAction Stop | Measure-Object Length -Sum).Sum) + $freeBytes = $bootSize - $projBytes + Write-Host ("PF: {0:N2} ГиБ; p3: {1:N2} ГиБ; останется: {2:N2} ГиБ" -f ($projBytes / 1GB), ($bootSize / 1GB), ($freeBytes / 1GB)) + if ($freeBytes -lt 256MB) { throw ("PF занимает {0:N2} ГиБ, p3 = {1} ГиБ. Увеличьте -BootSizeGB (16/18)." -f ($projBytes / 1GB), $BootSizeGB) } + if ($freeBytes -lt 1GB) { Write-Warn "На p3 меньше 1 ГиБ свободно; при ошибке robocopy увеличьте -BootSizeGB." } +} + +Write-Host ("Диск: {0}, {1:N1} ГиБ, {2}, BusType={3}" -f $disk.FriendlyName, ($disk.Size / 1GB), $disk.PartitionStyle, $disk.BusType) +Write-Host ("p1: {0:N1} ГиБ {1} — данные (ESD/ISO/личные), LBA 2048" -f ($p1Size / 1GB), $DataFs) +Write-Host ("p2: 32 МБ FAT — Ventoy, offset {0} (LBA {1})" -f $p2Offset, ($p2Offset / 512)) +Write-Host ("p3: {0:N1} ГиБ FAT32 — проект PF + Xorboot, активный, offset {1} (LBA {2})" -f ($p3Size / 1GB), $p3Offset, ($p3Offset / 512)) +Write-Host ("Хвост-резерв: {0:N1} МБ (неразмеченный, чтобы Windows не ругался на конец диска)" -f ($tailReserve / 1MB)) +Write-Host "План: диск будет полностью очищен." + +if (-not $PSCmdlet.ShouldProcess("Диск $DiskNumber", "ПОЛНОСТЬЮ ОЧИСТИТЬ: p1 данные + p2 Ventoy + p3 проект/загрузчик")) { + Write-Host "WhatIf: изменения не вносились." -ForegroundColor Yellow + return +} +if (-not $Force) { + $ans = Read-Host "Введите YES для полной очистки диска $DiskNumber ($($disk.FriendlyName))" + if ($ans -ne 'YES') { throw "Отменено пользователем." } +} + +# --------------------------------------------------------------------------- +Write-Step "Очистка и MBR" +Clear-Disk -Number $DiskNumber -RemoveData -RemoveOEM -Confirm:$false -ErrorAction Stop +Initialize-Disk -Number $DiskNumber -PartitionStyle MBR -ErrorAction Stop +Start-Sleep -Seconds 2 +Write-Ok "Диск очищен, MBR создан." + +# --------------------------------------------------------------------------- +Write-Step "p1: данные ($DataFs)" +$p1 = New-Partition -DiskNumber $DiskNumber -Offset $P1Offset -Size $p1Size -Alignment 1MB -AssignDriveLetter -ErrorAction Stop +Start-Sleep -Seconds 1 +$v1 = Get-Volume -Partition $p1 -ErrorAction Stop +Format-Volume -DriveLetter $v1.DriveLetter -FileSystem $DataFs -NewFileSystemLabel 'DATA' -Confirm:$false -Force -ErrorAction Stop +Start-Sleep -Seconds 1 +$v1 = Get-Volume -Partition $p1 -ErrorAction Stop +Write-Ok ("p1: {0}: offset={1} (LBA {2}), size={3:N1} ГиБ, {4}" -f $v1.DriveLetter, $p1.Offset, ($p1.Offset / 512), ($p1.Size / 1GB), $DataFs) + +# --------------------------------------------------------------------------- +Write-Step "p2: VTOYEFI 32 МБ" +$p2 = New-Partition -DiskNumber $DiskNumber -Offset $p2Offset -Size $VentoySize -Alignment 1MB -AssignDriveLetter -ErrorAction Stop +Start-Sleep -Seconds 1 +$v2 = Get-Volume -Partition $p2 -ErrorAction Stop +Format-Volume -DriveLetter $v2.DriveLetter -FileSystem FAT -NewFileSystemLabel 'VTOYEFI' -Confirm:$false -Force -ErrorAction Stop +Start-Sleep -Seconds 1 +$v2 = Get-Volume -Partition $p2 -ErrorAction Stop +Write-Ok ("p2: {0}: offset={1} (LBA {2}), size={3:N1} МБ" -f $v2.DriveLetter, $p2.Offset, ($p2.Offset / 512), ($p2.Size / 1MB)) + +# --------------------------------------------------------------------------- +Write-Step "p3: проект PF + загрузчик (FAT32, 14 ГБ)" +$p3 = New-Partition -DiskNumber $DiskNumber -Offset $p3Offset -Size $p3Size -Alignment 1MB -AssignDriveLetter -ErrorAction Stop +Start-Sleep -Seconds 1 +$v3 = Get-Volume -Partition $p3 -ErrorAction Stop +Format-Volume -DriveLetter $v3.DriveLetter -FileSystem FAT32 -NewFileSystemLabel 'PARAVIS' -AllocationUnitSize 4096 -Confirm:$false -Force -ErrorAction Stop +Start-Sleep -Seconds 1 +$v3 = Get-Volume -Partition $p3 -ErrorAction Stop +Write-Ok ("p3: {0}: offset={1} (LBA {2}), size={3:N1} ГиБ, FAT32" -f $v3.DriveLetter, $p3.Offset, ($p3.Offset / 512), ($p3.Size / 1GB)) + +# --------------------------------------------------------------------------- +Write-Step "Копирование проекта PF на p3" +if ($SkipProject) { + Write-Warn "Пропущено (-SkipProject)." +} else { + # Важно: не использовать Start-Process с "H:\" — обратный слэш перед + # закрывающей кавычкой ломает командную строку. Вызов через & и массив + # аргументов передаёт путь корректно. + $roboArgs = @( + $ProjectDir, + "$($v3.DriveLetter):\", + '/E', '/R:1', '/W:1', '/NFL', '/NDL', '/NJH', '/NJS' + ) + & robocopy.exe @roboArgs + $rc = $LASTEXITCODE + if ($rc -ge 8) { + throw ("robocopy завершился с кодом {0}. Код 8 — не все файлы (место/доступ), 16 — серьёзная ошибка. Если мало места — увеличьте -BootSizeGB (16/18)." -f $rc) + } + Write-Ok "Проект скопирован на $($v3.DriveLetter):" +} + +# --------------------------------------------------------------------------- +Write-Step "VTOYEFI на p2" +Copy-Item -Path (Join-Path $vtoyefi '*') -Destination "$($v2.DriveLetter):\" -Recurse -Force -ErrorAction Stop +if (-not (Test-Path "$($v2.DriveLetter):\ventoy\ventoy.cpio")) { throw "VTOYEFI скопирован не полностью." } +Copy-Item -Path $coreImg -Destination "$($v2.DriveLetter):\ventoy\core.img" -Force -ErrorAction Stop +Write-Ok "VTOYEFI + core.img -> $($v2.DriveLetter):" + +# --------------------------------------------------------------------------- +Write-Step "Артефакты на p3" +$projFolder = "$($v3.DriveLetter):\efi\Paravis\Ventoy" +New-Item -ItemType Directory -Path $projFolder -Force | Out-Null +Copy-Item -Path $coreImg -Destination (Join-Path $projFolder 'core.img') -Force +if (Test-Path $grldr) { + Copy-Item -Path $grldr -Destination (Join-Path $projFolder 'grldr-ventoy') -Force + $g4d = "$($v3.DriveLetter):\efi\Paravis\Boot\g4d" + if (Test-Path $g4d) { + Copy-Item -Path $grldr -Destination (Join-Path $g4d 'Ventoy') -Force + Write-Ok "grldr-ventoy -> $g4d\Ventoy" + } +} +Write-Ok "core.img и grldr-ventoy -> $projFolder" + +# --------------------------------------------------------------------------- +Write-Step "Подготовка p1 для данных" +New-Item -ItemType Directory -Path "$($v1.DriveLetter):\ISO" -Force | Out-Null +New-Item -ItemType Directory -Path "$($v1.DriveLetter):\WindowsESD" -Force | Out-Null +Write-Ok "Созданы $($v1.DriveLetter):\ISO и $($v1.DriveLetter):\WindowsESD" + +# --------------------------------------------------------------------------- +Write-Step "Активный раздел p3" +Set-Partition -DiskNumber $DiskNumber -PartitionNumber 3 -IsActive $true -ErrorAction Stop +Write-Ok "p3 помечен активным (с него грузится Xorboot/grub4dos/bootmgr)." + +# --------------------------------------------------------------------------- +Write-Step "Проверка" +Get-Partition -DiskNumber $DiskNumber | Sort-Object Offset | Format-Table PartitionNumber, DriveLetter, Offset, Size, Type -AutoSize +$c3 = Get-Partition -DiskNumber $DiskNumber -PartitionNumber 3 +if (-not $c3.IsActive) { Write-Warn "p3 не активен — проверьте." } + +Write-Step "Готово. Что делать дальше" +$msg = @" +Разметка: + p1 {0}: {1} данные: ISO + WindowsESD + личные файлы + p2 {2}: FAT 32 МБ VTOYEFI + p3 {3}: FAT32 14 ГБ проект PF, активный + +Далее: + 1) Запустите {3}:\Change_bootLoader.exe (можно из любой папки на p3) + и выберите Legacy + UEFI. Он возьмёт букву {3}:, поставит PBR на p3, + MBR — на диск. + 2) BIOS: Xorboot/grub4dos будет искать \efi\Paravis\Boot\... на p3. + Для Ventoy добавьте пункт на \efi\Paravis\Boot\g4d\Ventoy + (или find --set-root /ventoy/core.img; kernel /ventoy/core.img). + 3) UEFI: прошивка увидит FAT32 p3 и загрузит \efi\Boot\bootx64.efi (Xorboot). + В Xorboot добавьте Ventoy: p2 {2}: \EFI\BOOT\BOOTX64.EFI. + 4) Распакуйте 3_PF_WindowsESD.zip в {0}:\WindowsESD (NTFS, >4 ГиБ влезают). + 5) ISO кладите в {0}:\ISO — Ventoy сканирует p1 и увидит их без Vlnk. + +Важно: Ventoy стоит p2 сразу после p1, а p3 — после Ventoy, поэтому +Ventoy не последний раздел. Строго последним он быть не может, если +после него есть загрузочный p3. +"@ -f $v1.DriveLetter, $DataFs, $v2.DriveLetter, $v3.DriveLetter +Write-Host $msg -ForegroundColor Gray + +Write-Ok "Готово." diff --git a/build-scripts/layout/create-ventoy-usb.ps1 b/build-scripts/layout/create-ventoy-usb.ps1 new file mode 100644 index 0000000..744c3a7 --- /dev/null +++ b/build-scripts/layout/create-ventoy-usb.ps1 @@ -0,0 +1,241 @@ +#Requires -RunAsAdministrator +<# +.SYNOPSIS + Полная разметка USB-диска под проект Paravis + Ventoy + ESD. + ВНИМАНИЕ: диск полностью очищается. + +.DESCRIPTION + Создаёт: + p1 FAT32 проект PF + ISO (по умолчанию 20 ГБ) + p2 FAT 32 МБ VTOYEFI + core.img + p3 NTFS остаток диска под ESD + + p1 начинается с LBA 2048 (1 МБ), p2 — сразу после p1, p3 — сразу после p2. + Это штатная схема Ventoy: data=p1, VTOYEFI=p2. + + MBR-код затем ставится вашим Change_bootLoader.exe (скрипт его не запускает). + +.PARAMETER DiskNumber + Номер физического диска из Get-Disk (только USB, не системный). + +.PARAMETER P1SizeGB + Размер p1 в ГБ. По умолчанию 20. Для FAT32 Windows практический максимум 32. + +.PARAMETER ProjectDir + Папка с проектом PF (по умолчанию C:\PF\PF). + +.PARAMETER SkipProject + Не копировать проект PF на p1. + +.PARAMETER Force + Не спрашивать YES (для автоматизации). Всё равно проверяет, что диск USB. + +.EXAMPLE + .\create-ventoy-usb.ps1 -DiskNumber 2 -WhatIf + +.EXAMPLE + .\create-ventoy-usb.ps1 -DiskNumber 2 -P1SizeGB 32 +#> +[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')] +param( + [Parameter(Mandatory = $true)] + [int]$DiskNumber, + + [int]$P1SizeGB = 14, + + [string]$ProjectDir = 'C:\PF\PF', + + [string]$SourceDir = $PSScriptRoot, + + [switch]$SkipProject, + + [switch]$AllowNonUsb, + + [switch]$Force +) + +$ErrorActionPreference = 'Stop' + +$MiB = 1MB +$VentoySize = 32MB +$P1Offset = 1MB +$SectorSize = 512 + +function Write-Step([string]$Text) { Write-Host "`n=== $Text ===" -ForegroundColor Cyan } +function Write-Warn([string]$Text) { Write-Host "WARN: $Text" -ForegroundColor Yellow } +function Write-Ok([string]$Text) { Write-Host "OK: $Text" -ForegroundColor Green } + +# --------------------------------------------------------------------------- +Write-Step "Проверка исходных файлов" +$vtoyefi = Join-Path $SourceDir 'vtoyefi' +$coreImg = Join-Path $SourceDir 'ventoy-1.1.18\boot\core.img' +if (-not (Test-Path $coreImg)) { $coreImg = Join-Path $SourceDir 'core.img' } +$grldr = Join-Path $SourceDir 'grldr-ventoy' + +if (-not (Test-Path (Join-Path $vtoyefi 'ventoy\ventoy.cpio'))) { + throw "Не найден распакованный VTOYEFI: $vtoyefi" +} +if (-not (Test-Path $coreImg)) { throw "Не найден core.img: $coreImg" } +if (-not $SkipProject -and -not (Test-Path $ProjectDir)) { + throw "Не найдена папка проекта: $ProjectDir (или используйте -SkipProject)." +} +Write-Ok "VTOYEFI: $vtoyefi" +Write-Ok "core.img: $coreImg" + +# --------------------------------------------------------------------------- +Write-Step "Проверка диска $DiskNumber" +if ($P1SizeGB -lt 15) { throw "P1SizeGB должен быть >= 15." } +if ($P1SizeGB -gt 32) { Write-Warn "FAT32 больше 32 ГБ Windows может не отформатировать." } + +$disk = Get-Disk -Number $DiskNumber -ErrorAction Stop +if ($disk.IsBoot -or $disk.IsSystem) { throw "Диск $DiskNumber загрузочный/системный. Отказ." } +if (-not $AllowNonUsb -and $disk.BusType -notin @('USB', 'SD', 'MMC')) { + throw "Диск $DiskNumber имеет BusType '$($disk.BusType)', а не USB/SD. Отказ (для USB-переходников: -AllowNonUsb)." +} + +$p1Size = [uint64]$P1SizeGB * 1GB +$need = $P1Offset + $p1Size + $VentoySize + 1GB +if ($disk.Size -lt $need) { + throw ("Диск слишком мал: {0:N1} GB, нужно минимум {1:N1} GB." -f ($disk.Size / 1GB), ($need / 1GB)) +} + +# Проверяем, что проект PF влезает в p1, ДО очистки диска +if (-not $SkipProject) { + $projBytes = [uint64]((Get-ChildItem -Path $ProjectDir -Recurse -File -ErrorAction Stop | Measure-Object Length -Sum).Sum) + $freeBytes = $p1Size - $projBytes + Write-Host ("PF: {0:N2} GiB; p1: {1:N2} GiB; останется: {2:N2} GiB" -f ($projBytes / 1GB), ($p1Size / 1GB), ($freeBytes / 1GB)) + if ($freeBytes -lt 256MB) { + throw ("Проект PF занимает {0:N2} GiB, а p1 = {1} ГиБ. Увеличьте -P1SizeGB (например, 16 или 20)." -f ($projBytes / 1GB), $P1SizeGB) + } + if ($freeBytes -lt 1GB) { + Write-Warn "На p1 останется меньше 1 ГиБ. FAT32 может не принять проект из-за кластеров; при ошибке robocopy увеличьте -P1SizeGB до 16-20." + } +} + +Write-Host ("Диск: {0}, {1:N1} GB, {2}, BusType={3}" -f $disk.FriendlyName, ($disk.Size / 1GB), $disk.PartitionStyle, $disk.BusType) +Write-Host ("План: p1 FAT32 {0} ГБ с LBA 2048; p2 FAT 32 МБ сразу после p1; p3 NTFS — остаток ({1:N1} ГБ)." -f $P1SizeGB, (($disk.Size - $P1Offset - $p1Size - $VentoySize) / 1GB)) +Write-Host "План: диск будет полностью очищен. MBR-код поставите Change_bootLoader.exe после копирования." + +if (-not $PSCmdlet.ShouldProcess("Диск $DiskNumber", "ПОЛНОСТЬЮ ОЧИСТИТЬ и создать p1 FAT32 + p2 32MB VTOYEFI + p3 NTFS")) { + Write-Host "WhatIf: изменения не вносились." -ForegroundColor Yellow + return +} + +if (-not $Force) { + $ans = Read-Host "Введите YES для полной очистки диска $DiskNumber ($($disk.FriendlyName))" + if ($ans -ne 'YES') { throw "Отменено пользователем." } +} + +# --------------------------------------------------------------------------- +Write-Step "Очистка и инициализация MBR" +Clear-Disk -Number $DiskNumber -RemoveData -RemoveOEM -Confirm:$false -ErrorAction Stop +Initialize-Disk -Number $DiskNumber -PartitionStyle MBR -ErrorAction Stop +Start-Sleep -Seconds 2 +Write-Ok "Диск очищен, MBR создан." + +# --------------------------------------------------------------------------- +Write-Step "Создание p1 (FAT32, проект)" +$p1 = New-Partition -DiskNumber $DiskNumber -Offset $P1Offset -Size $p1Size -Alignment 1MB -AssignDriveLetter -ErrorAction Stop +Start-Sleep -Seconds 1 +$v1 = Get-Volume -Partition $p1 -ErrorAction Stop +Format-Volume -DriveLetter $v1.DriveLetter -FileSystem FAT32 -NewFileSystemLabel 'PARAVIS' -AllocationUnitSize 4096 -Confirm:$false -Force -ErrorAction Stop +Start-Sleep -Seconds 1 +$v1 = Get-Volume -Partition $p1 -ErrorAction Stop +Write-Ok ("p1: {0}: offset={1} (LBA {2}), size={3:N1} GB" -f $v1.DriveLetter, $p1.Offset, ($p1.Offset / 512), ($p1.Size / 1GB)) + +# --------------------------------------------------------------------------- +Write-Step "Создание p2 (VTOYEFI, 32 МБ)" +$p2Offset = $p1.Offset + $p1.Size +$p2 = New-Partition -DiskNumber $DiskNumber -Offset $p2Offset -Size $VentoySize -Alignment 1MB -AssignDriveLetter -ErrorAction Stop +Start-Sleep -Seconds 1 +$v2 = Get-Volume -Partition $p2 -ErrorAction Stop +Format-Volume -DriveLetter $v2.DriveLetter -FileSystem FAT -NewFileSystemLabel 'VTOYEFI' -Confirm:$false -Force -ErrorAction Stop +Start-Sleep -Seconds 1 +$v2 = Get-Volume -Partition $p2 -ErrorAction Stop +Write-Ok ("p2: {0}: offset={1} (LBA {2}), size={3:N1} MB" -f $v2.DriveLetter, $p2.Offset, ($p2.Offset / 512), ($p2.Size / 1MB)) + +# --------------------------------------------------------------------------- +Write-Step "Создание p3 (NTFS, ESD)" +$p3Offset = $p2.Offset + $p2.Size +$p3 = New-Partition -DiskNumber $DiskNumber -Offset $p3Offset -UseMaximumSize -Alignment 1MB -AssignDriveLetter -ErrorAction Stop +Start-Sleep -Seconds 1 +$v3 = Get-Volume -Partition $p3 -ErrorAction Stop +Format-Volume -DriveLetter $v3.DriveLetter -FileSystem NTFS -NewFileSystemLabel 'ESD' -Confirm:$false -Force -ErrorAction Stop +Start-Sleep -Seconds 1 +$v3 = Get-Volume -Partition $p3 -ErrorAction Stop +Write-Ok ("p3: {0}: offset={1} (LBA {2}), size={3:N1} GB" -f $v3.DriveLetter, $p3.Offset, ($p3.Offset / 512), ($p3.Size / 1GB)) + +# --------------------------------------------------------------------------- +Write-Step "Копирование проекта PF на p1" +if ($SkipProject) { + Write-Warn "Пропущено (-SkipProject)." +} else { + $rc = Start-Process -FilePath 'robocopy.exe' -ArgumentList @( + "`"$ProjectDir`"", "`"$($v1.DriveLetter):\`"", '/E', '/R:1', '/W:1', '/NFL', '/NDL', '/NJH', '/NJS' + ) -Wait -PassThru -NoNewWindow + if ($rc.ExitCode -ge 8) { throw "robocopy завершился с кодом $($rc.ExitCode)." } + Write-Ok "Проект скопирован на $($v1.DriveLetter):" +} + +# --------------------------------------------------------------------------- +Write-Step "Копирование VTOYEFI на p2" +Copy-Item -Path (Join-Path $vtoyefi '*') -Destination "$($v2.DriveLetter):\" -Recurse -Force -ErrorAction Stop +if (-not (Test-Path "$($v2.DriveLetter):\ventoy\ventoy.cpio")) { throw "VTOYEFI скопирован не полностью." } +Copy-Item -Path $coreImg -Destination "$($v2.DriveLetter):\ventoy\core.img" -Force -ErrorAction Stop +Write-Ok "VTOYEFI + core.img -> $($v2.DriveLetter):" + +# --------------------------------------------------------------------------- +Write-Step "Артефакты в папке проекта на p1" +$projFolder = "$($v1.DriveLetter):\efi\Paravis\Ventoy" +New-Item -ItemType Directory -Path $projFolder -Force | Out-Null +Copy-Item -Path $coreImg -Destination (Join-Path $projFolder 'core.img') -Force +if (Test-Path $grldr) { + Copy-Item -Path $grldr -Destination (Join-Path $projFolder 'grldr-ventoy') -Force + $g4d = "$($v1.DriveLetter):\efi\Paravis\Boot\g4d" + if (Test-Path $g4d) { + Copy-Item -Path $grldr -Destination (Join-Path $g4d 'Ventoy') -Force + Write-Ok "grldr-ventoy -> $g4d\Ventoy" + } +} +Write-Ok "core.img и grldr-ventoy -> $projFolder" + +# --------------------------------------------------------------------------- +Write-Step "Активный раздел p1" +Set-Partition -DiskNumber $DiskNumber -PartitionNumber 1 -IsActive $true -ErrorAction Stop +Write-Ok "p1 помечен активным." + +# --------------------------------------------------------------------------- +Write-Step "Проверка разметки" +$chk = Get-Partition -DiskNumber $DiskNumber | Sort-Object Offset +$chk | Format-Table PartitionNumber, DriveLetter, Offset, Size, Type -AutoSize +$c1 = $chk | Where-Object PartitionNumber -eq 1 +$c2 = $chk | Where-Object PartitionNumber -eq 2 +if ($c1.Offset -ne $P1Offset) { Write-Warn "p1 offset $($c1.Offset) != 1048576." } +if ($c2.Offset -ne ($c1.Offset + $c1.Size)) { Write-Warn "p2 не сразу после p1." } +if ($c2.Size -ne $VentoySize) { Write-Warn "p2 size $($c2.Size) != 33554432." } + +Write-Step "Готово. Что делать дальше" +$msg = @" +Разметка: + p1 {0}: FAT32 проект + ISO + p2 {1}: FAT 32 МБ VTOYEFI + p3 {2}: NTFS ESD + +Далее: + 1) Запустите {0}:\Change_bootLoader.exe и выберите нужные загрузчики + (Legacy + UEFI). Он поставит MBR/PBR. + 2) BIOS: добавьте пункт Xorboot на файл + \efi\Paravis\Boot\g4d\Ventoy + (или в menu.lst: find --set-root /ventoy/core.img; kernel /ventoy/core.img). + 3) UEFI: добавьте в Xorboot загрузку файла + p2 {1}: \EFI\BOOT\BOOTX64.EFI + 4) Распакуйте 3_PF_WindowsESD.zip на p3 {2}: (NTFS). + 5) ISO: Ventoy ищет их только на p1 {0}:. Если p1 заполнен проектом, + положите ISO на p3 {2}: и создайте на p1 файлы-ссылки .vlnk.iso + через VentoyVlnk.exe из пакета Ventoy. Ventoy покажет ссылки в меню. + +Если p1 позже переполнится — увеличьте P1SizeGB (до 32) и повторите разметку. +"@ -f $v1.DriveLetter, $v2.DriveLetter, $v3.DriveLetter +Write-Host $msg -ForegroundColor Gray + +Write-Ok "Готово." diff --git a/build-scripts/layout/deploy-all.ps1 b/build-scripts/layout/deploy-all.ps1 new file mode 100644 index 0000000..6a79751 --- /dev/null +++ b/build-scripts/layout/deploy-all.ps1 @@ -0,0 +1,43 @@ +# Deploy everything staged on D: to the flash (p1 GRUB2 loader + p2 Ventoy cfg). +$ErrorActionPreference = 'Stop' + +$src = 'C:\PF\ParavisGrub' +$g2 = 'F:\efi\Paravis\Boot\grub2' +$ven = 'C:\PF\Ventoy\vtoyefi\grub\grub.cfg' + +function Fail($m) { Write-Host "ERROR: $m"; exit 1 } + +if (-not (Test-Path 'F:\efi\Paravis\Boot')) { Fail 'p1 (F:) not available - VM may hold the disk' } +if (-not (Test-Path 'G:\grub\grub.cfg')) { Fail 'p2 (G:) not available - VM may hold the disk' } + +New-Item -ItemType Directory -Force "$g2\menu", "$g2\apps" | Out-Null + +# --- p1: our loader tree only +Copy-Item "$src\grub.cfg" "$g2\grub.cfg" -Force +Copy-Item "$src\menu\*.cfg" "$g2\menu\" -Force +Copy-Item "$src\apps\super.efi" "$g2\apps\super.efi" -Force +Copy-Item "$src\apps\memtest86p.efi" "$g2\apps\memtest86p.efi" -Force +foreach ($stale in 'memtest.efi','memtest86.efi') { + Remove-Item "$g2\apps\$stale" -Force -ErrorAction SilentlyContinue +} + +# --- p2: Ventoy config (language default + earlier patches), backup first +Copy-Item 'G:\grub\grub.cfg' 'C:\PF\Ventoy\backup\grub.cfg.before-ru-default' -Force +Copy-Item $ven 'G:\grub\grub.cfg' -Force + +# --- report +'=== p1 grub2 tree:' +Get-ChildItem $g2 -Recurse -File | Select-Object @{n='rel';e={$_.FullName.Replace("$g2\",'')}},Length | + Sort-Object rel | Format-Table -AutoSize + +'=== p2 ventoy cfg:' +'{0} bytes {1}' -f (Get-Item 'G:\grub\grub.cfg').Length, (Get-FileHash 'G:\grub\grub.cfg' -Algorithm SHA256).Hash.ToLower() +'{0} bytes {1}' -f (Get-Item $ven).Length, (Get-FileHash $ven -Algorithm SHA256).Hash.ToLower() +Select-String -Path 'G:\grub\grub.cfg' -Pattern 'vt_init_menu_lang' | ForEach-Object { ' ' + $_.Line.Trim() } + +'=== syntax:' +$checker = 'C:\PF\grub2-a1ive\grub\grub-script-check.exe' +Get-ChildItem "$g2\grub.cfg", "$g2\menu\*.cfg" | ForEach-Object { + & $checker $_.FullName + if ($LASTEXITCODE -eq 0) { " OK $($_.Name)" } else { " FAIL $($_.Name)" } +} diff --git a/build-scripts/layout/deploy-menu.ps1 b/build-scripts/layout/deploy-menu.ps1 new file mode 100644 index 0000000..0a34c3b --- /dev/null +++ b/build-scripts/layout/deploy-menu.ps1 @@ -0,0 +1,26 @@ +# Deploy Paravis GRUB menu + apps from D: staging to p1. +$src = 'C:\PF\ParavisGrub' +$dst = 'F:\efi\Paravis\Boot\grub2' + +New-Item -ItemType Directory -Force "$dst\menu" | Out-Null +New-Item -ItemType Directory -Force "$dst\apps" | Out-Null + +Copy-Item "$src\grub.cfg" "$dst\grub.cfg" -Force +Copy-Item "$src\menu\*.cfg" "$dst\menu\" -Force +Copy-Item "$src\apps\memtest86p.efi" "$dst\apps\memtest86p.efi" -Force +Remove-Item "$dst\apps\memtest86.efi" -Force -ErrorAction SilentlyContinue + +'--- deployed tree:' +Get-ChildItem $dst -Recurse -File | Select-Object @{n='rel';e={$_.FullName.Replace("$dst\",'')}},Length | Sort-Object rel | Format-Table -AutoSize + +'--- syntax check:' +$checker = 'C:\PF\grub2-a1ive\grub\grub-script-check.exe' +Get-ChildItem "$dst\grub.cfg", "$dst\menu\*.cfg" | ForEach-Object { + & $checker $_.FullName + if ($LASTEXITCODE -eq 0) { " OK $($_.Name)" } else { " FAIL $($_.Name)" } +} + +'--- main menu head:' +Get-Content "$dst\grub.cfg" -TotalCount 6 | ForEach-Object { ' ' + $_ } +'--- submenu timeouts:' +Get-ChildItem "$dst\menu\*.cfg" | ForEach-Object { ' {0,-14} {1}' -f $_.Name, ((Get-Content $_.FullName -TotalCount 1)) } diff --git a/build-scripts/layout/deploy-theme.ps1 b/build-scripts/layout/deploy-theme.ps1 new file mode 100644 index 0000000..1a4cbe2 --- /dev/null +++ b/build-scripts/layout/deploy-theme.ps1 @@ -0,0 +1,30 @@ +# Deploy GRUB2 theme + menus to p1. +$ErrorActionPreference = 'Stop' +$src = 'C:\PF\ParavisGrub' +$dst = 'F:\efi\Paravis\Boot\grub2' + +if (-not (Test-Path 'F:\efi\Paravis\Boot')) { 'p1 not available'; exit 1 } + +# themes +Remove-Item "$dst\theme" -Recurse -Force -ErrorAction SilentlyContinue +New-Item -ItemType Directory -Force "$dst\theme" | Out-Null +Copy-Item "$src\theme\*" "$dst\theme\" -Recurse -Force +Remove-Item "$dst\theme\*\preview.png" -Force -ErrorAction SilentlyContinue +Remove-Item "$dst\theme\main\sel_bar.png" -Force -ErrorAction SilentlyContinue + +# menus +Copy-Item "$src\grub.cfg" "$dst\grub.cfg" -Force +New-Item -ItemType Directory -Force "$dst\menu" | Out-Null +Copy-Item "$src\menu\*.cfg" "$dst\menu\" -Force + +'--- tree:' +Get-ChildItem $dst -Recurse -File | Select-Object @{n='rel';e={$_.FullName.Replace("$dst\",'')}},Length | + Sort-Object rel | Format-Table -AutoSize + +'--- syntax:' +$checker = 'C:\PF\grub2-a1ive\grub\grub-script-check.exe' +Get-ChildItem "$dst\grub.cfg", "$dst\menu\*.cfg" | ForEach-Object { + & $checker $_.FullName + if ($LASTEXITCODE -eq 0) { " OK $($_.Name)" } else { " FAIL $($_.Name)" } +} +'--- free on F: {0:N0} MB' -f ((Get-Volume -DriveLetter F).SizeRemaining / 1MB) diff --git a/build-scripts/layout/deploy-ventoy-lang.ps1 b/build-scripts/layout/deploy-ventoy-lang.ps1 new file mode 100644 index 0000000..8888a33 --- /dev/null +++ b/build-scripts/layout/deploy-ventoy-lang.ps1 @@ -0,0 +1,19 @@ +# Deploy the patched Ventoy grub.cfg (Russian default language) to p2. +$src = 'C:\PF\Ventoy\vtoyefi\grub\grub.cfg' +$dst = 'G:\grub\grub.cfg' +$bkp = 'C:\PF\Ventoy\backup\grub.cfg.before-ru-default' + +if (Test-Path $dst) { + Copy-Item $dst $bkp -Force + Copy-Item $src $dst -Force + 'disk : {0} bytes {1}' -f (Get-Item $dst).Length, (Get-FileHash $dst -Algorithm SHA256).Hash.ToLower() + 'source: {0} bytes {1}' -f (Get-Item $src).Length, (Get-FileHash $src -Algorithm SHA256).Hash.ToLower() + '--- check:' + Select-String -Path $dst -Pattern 'vt_init_menu_lang' | ForEach-Object { ' ' + $_.Line.Trim() } + '--- other patches still present:' + foreach ($s in 'VTOY_DATA_PART_IDX', 'ISO/Ventoy/ventoy.json', 'SSTR/BCD') { + ' {0}: {1}' -f $s, (Select-String -Path $dst -Pattern ([regex]::Escape($s)) | Measure-Object).Count + } +} else { + 'G: not available' +} diff --git a/build-scripts/layout/finish-relayout.ps1 b/build-scripts/layout/finish-relayout.ps1 new file mode 100644 index 0000000..d10f741 --- /dev/null +++ b/build-scripts/layout/finish-relayout.ps1 @@ -0,0 +1,247 @@ +#Requires -RunAsAdministrator +<# +.SYNOPSIS + Завершает переразметку USB: проверяет MBR/gap, возвращает файлы на p1/p2/p3. + +.DESCRIPTION + Нужен, если relayout-usb.ps1 упал после diskpart (например, на Close() + дескриптора PhysicalDrive) и файлы не были возвращены. + + Скрипт: + 1. проверяет геометрию: p1 14 ГиБ @1 МиБ active, p2 32 МиБ сразу за p1, + p3 = остаток; + 2. сверяет байты 0..445 MBR и gap-сектора 1..62 с бэкапом + C:\PF\Ventoy\backup\usb-mbr-*.bin и при необходимости возвращает их; + 3. копирует staging (E:\_usb_stage\PARAVIS) на p1; + 4. ставит VTOYEFI + core на p2; + 5. копирует ISO с E:\Downloads\ISO на p3 и \ISO\Ventoy (маркер); + 6. сверяет размеры/количество. + +.EXAMPLE + .\finish-relayout.ps1 -WhatIf + .\finish-relayout.ps1 +#> +[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')] +param( + [int]$BootSizeMB = 14336, + [string]$StageDir = 'E:\_usb_stage', + [string]$IsoSource = 'E:\Downloads\ISO', + [string]$VentoyDir = 'C:\PF\Ventoy', + [string]$BackupDir = 'C:\PF\Ventoy\backup', + [switch]$SkipMbr +) + +$ErrorActionPreference = 'Stop' + +function Write-Step([string]$t) { Write-Host "`n=== $t ===" -ForegroundColor Cyan } +function Write-Ok([string]$t) { Write-Host "OK: $t" -ForegroundColor Green } +function Write-Warn([string]$t) { Write-Host "WARN: $t" -ForegroundColor Yellow } + +function Invoke-Robocopy([string]$src, [string]$dst, [string[]]$extra = @()) { + $roboArgs = @($src, $dst, '/E', '/COPY:DAT', '/R:1', '/W:1', '/MT:8', '/NFL', '/NDL', '/NJH', '/NJS', '/NP') + $extra + $out = & robocopy.exe @roboArgs 2>&1 + $code = $LASTEXITCODE + if ($code -ge 8) { + $out | Select-Object -Last 30 | ForEach-Object { " $_" } + throw "robocopy вернул код $code ($src -> $dst)" + } + return $code +} + +function Get-DiskVolumeLabel([int]$num, [string]$label) { + foreach ($p in (Get-Partition -DiskNumber $num -ErrorAction SilentlyContinue)) { + $v = Get-Volume -Partition $p -ErrorAction SilentlyContinue + if ($v -and $v.FileSystemLabel -eq $label) { return $v } + } + return $null +} + +function Read-Raw([int]$num, [int]$len) { + $fs = [IO.FileStream]::new("\\.\PhysicalDrive$num", [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::ReadWrite) + try { + $buf = New-Object byte[] $len + $n = $fs.Read($buf, 0, $len) + if ($n -ne $len) { throw "Прочитано $n из $len байт." } + return ,$buf + } finally { + try { $fs.Close() } catch { } + } +} + +function Write-Raw([int]$num, [byte[]]$data, [long]$offset) { + $fs = [IO.FileStream]::new("\\.\PhysicalDrive$num", [IO.FileMode]::Open, [IO.FileAccess]::ReadWrite, [IO.FileShare]::ReadWrite, 4096, [IO.FileOptions]::WriteThrough) + try { + $fs.Position = $offset + $fs.Write($data, 0, $data.Length) + $fs.Flush($true) + } finally { + # Windows может инвалидировать хэндл после записи в сектор 0 — + # ошибка Close() не означает, что запись не выполнена. + try { $fs.Close() } catch { } + } +} + +function Test-Range([byte[]]$a, [byte[]]$b, [int]$offset, [int]$count) { + for ($i = 0; $i -lt $count; $i++) { + if ($a[$offset + $i] -ne $b[$offset + $i]) { return $false } + } + return $true +} + +# ------------------------------------------------------------------ диск +Write-Step "Поиск диска" +$efiVol = Get-Volume | Where-Object { $_.FileSystemLabel -eq 'VTOYEFI' } | Select-Object -First 1 +if (-not $efiVol -or -not $efiVol.DriveLetter) { throw "Не найден раздел VTOYEFI." } +$diskNum = (Get-Partition -DriveLetter $efiVol.DriveLetter).DiskNumber +$disk = Get-Disk -Number $diskNum +Write-Host (" Диск {0}: {1}, {2:N1} ГиБ, {3}" -f $diskNum, $disk.FriendlyName, ($disk.Size/1GB), $disk.PartitionStyle) + +$pProj = Get-DiskVolumeLabel $diskNum 'PARAVIS' +$pEfi = Get-DiskVolumeLabel $diskNum 'VTOYEFI' +$pData = Get-DiskVolumeLabel $diskNum 'DATA' +if (-not $pProj -or -not $pEfi -or -not $pData) { throw "Не найдены все три раздела (PARAVIS/VTOYEFI/DATA)." } +Write-Host (" PARAVIS={0}: VTOYEFI={1}: DATA={2}:" -f $pProj.DriveLetter, $pEfi.DriveLetter, $pData.DriveLetter) + +# ------------------------------------------------------------- геометрия +Write-Step "Проверка геометрии" +$geo = Get-Partition -DiskNumber $diskNum | Sort-Object Offset +$geo | Format-Table PartitionNumber, DriveLetter, Offset, Size, Type, IsActive -AutoSize | Out-String | Write-Host +if ($geo.Count -ne 3) { throw "Ожидалось 3 раздела, найдено $($geo.Count)." } +if ($geo[0].Offset -ne 1048576) { throw "p1 начинается не с 1 МиБ (Offset=$($geo[0].Offset))." } +if ($geo[0].Size -ne ($BootSizeMB * 1MB)) { throw "p1 неверного размера: $($geo[0].Size)." } +if ($geo[1].Offset -ne ($geo[0].Offset + $geo[0].Size)) { throw "p2 идёт не сразу за p1." } +if ($geo[1].Size -ne 33554432) { throw "p2 не 32 МБ: $($geo[1].Size)." } +if (-not $geo[0].IsActive) { throw "p1 не помечен active." } +Write-Ok "Геометрия корректна." + +# ---------------------------------------------------------------- MBR/gap +if ($SkipMbr) { + Write-Step "Проверка MBR пропущена (-SkipMbr)" +} else { + Write-Step "Проверка MBR Xorboot и gap-секторов" + $bkp = Get-ChildItem $BackupDir -Filter 'usb-mbr-*.bin' | Sort-Object LastWriteTime -Descending | Select-Object -First 1 + if (-not $bkp) { throw "Нет бэкапа MBR в $BackupDir." } + Write-Host (" бэкап: {0}" -f $bkp.FullName) + if ($bkp.Length -lt 65536) { throw "Бэкап короче 64 КиБ." } + $orig = [IO.File]::ReadAllBytes($bkp.FullName) + $cur = Read-Raw $diskNum 65536 + + $mbrOk = Test-Range $cur $orig 0 446 + $gapOk = Test-Range $cur $orig 512 31744 + Write-Host (" MBR code (0..445): {0}" -f $(if ($mbrOk) { 'совпадает с бэкапом' } else { 'ОТЛИЧАЕТСЯ' })) + Write-Host (" gap (сектора 1..62): {0}" -f $(if ($gapOk) { 'совпадает с бэкапом' } else { 'ОТЛИЧАЕТСЯ' })) + + if (-not $mbrOk -or -not $gapOk) { + if (-not $PSCmdlet.ShouldProcess("PhysicalDrive$diskNum", "Восстановить код MBR (0..445) и gap (512..32255) из бэкапа")) { + Write-Warn "WhatIf: MBR не изменялся." + } else { + if (-not $mbrOk) { + $buf = New-Object byte[] 446 + [Array]::Copy($orig, 0, $buf, 0, 446) + Write-Raw $diskNum $buf 0 + Write-Ok "Код MBR (0..445) восстановлен." + } + if (-not $gapOk) { + $buf = New-Object byte[] 31744 + [Array]::Copy($orig, 512, $buf, 0, 31744) + Write-Raw $diskNum $buf 512 + Write-Ok "Gap (сектора 1..62) восстановлен." + } + Start-Sleep -Seconds 2 + Update-HostStorageCache + + $cur2 = Read-Raw $diskNum 65536 + if (-not (Test-Range $cur2 $orig 0 446)) { throw "MBR после записи не совпал с бэкапом." } + if (-not (Test-Range $cur2 $orig 512 31744)) { throw "Gap после записи не совпал с бэкапом." } + Write-Ok "MBR и gap совпадают с бэкапом." + } + } else { + Write-Ok "MBR и gap уже в порядке (запись Xorboot выполнена)." + } +} + +# --------------------------------------------------------------- источники +Write-Step "Обновление букв после проверки MBR" +Update-HostStorageCache +Start-Sleep -Seconds 1 +$pProj = Get-DiskVolumeLabel $diskNum 'PARAVIS' +$pEfi = Get-DiskVolumeLabel $diskNum 'VTOYEFI' +$pData = Get-DiskVolumeLabel $diskNum 'DATA' +if (-not $pProj -or -not $pEfi -or -not $pData) { throw "Разделы пропали после работы с MBR." } +if (-not $pProj.DriveLetter -or -not $pEfi.DriveLetter -or -not $pData.DriveLetter) { + foreach ($p in (Get-Partition -DiskNumber $diskNum | Where-Object { -not $_.DriveLetter })) { + Add-PartitionAccessPath -DiskNumber $diskNum -PartitionNumber $p.PartitionNumber -AssignDriveLetter + } + Start-Sleep -Seconds 1 + $pProj = Get-DiskVolumeLabel $diskNum 'PARAVIS' + $pEfi = Get-DiskVolumeLabel $diskNum 'VTOYEFI' + $pData = Get-DiskVolumeLabel $diskNum 'DATA' +} +Write-Host (" PARAVIS={0}: VTOYEFI={1}: DATA={2}:" -f $pProj.DriveLetter, $pEfi.DriveLetter, $pData.DriveLetter) + +Write-Step "Проверка источников" +$stageProj = Join-Path $StageDir 'PARAVIS' +$stageIsoVentoy = Join-Path $StageDir 'ISO_Ventoy' +$vtoyefi = Join-Path $VentoyDir 'vtoyefi' +$coreImg = Join-Path $VentoyDir 'core-custom-layout-1.1.18.img' +if (-not (Test-Path $stageProj)) { throw "Нет staging: $stageProj" } +if (-not (Test-Path (Join-Path $vtoyefi 'ventoy\ventoy.cpio'))) { throw "Нет VTOYEFI: $vtoyefi" } +if (-not (Test-Path $coreImg)) { throw "Нет core: $coreImg" } +if (-not (Test-Path $IsoSource)) { throw "Нет ISO: $IsoSource" } +$isos = Get-ChildItem $IsoSource -File -Filter *.iso +$isoBytes = ($isos | Measure-Object Length -Sum).Sum +$projBytes = (Get-ChildItem $stageProj -Recurse -File -Force | Measure-Object Length -Sum).Sum +Write-Host (" проект: {0:N2} ГБ, ISO: {1} шт. / {2:N2} ГБ" -f ($projBytes/1GB), $isos.Count, ($isoBytes/1GB)) +if ($pProj.SizeRemaining -lt $projBytes) { throw "На p1 не хватает места." } +if ($pData.SizeRemaining -lt $isoBytes) { throw "На p3 не хватает места." } + +if (-not $PSCmdlet.ShouldProcess("${pProj.DriveLetter}: / ${pEfi.DriveLetter}: / ${pData.DriveLetter}:", "Вернуть проект, VTOYEFI и ISO")) { + Write-Warn "WhatIf: файлы не копировались." + return +} + +# ---------------------------------------------------------------- restore +Write-Step "Возврат проекта на p1" +Invoke-Robocopy $stageProj ("{0}:\" -f $pProj.DriveLetter) | Out-Null +Write-Ok "Проект восстановлен." + +Write-Step "VTOYEFI на p2" +Invoke-Robocopy $vtoyefi ("{0}:\" -f $pEfi.DriveLetter) | Out-Null +Copy-Item $coreImg ("{0}:\ventoy\core.img" -f $pEfi.DriveLetter) -Force +if (-not (Select-String -Path ("{0}:\grub\grub.cfg" -f $pEfi.DriveLetter) -Pattern 'VTOY-CUSTOM-LAYOUT' -Quiet)) { + throw "На p2 grub.cfg без VTOY-CUSTOM-LAYOUT." +} +if ((Get-Item ("{0}:\ventoy\core.img" -f $pEfi.DriveLetter)).Length -ne (Get-Item $coreImg).Length) { + throw "core.img на p2 неверного размера." +} +Write-Ok ("VTOYEFI + core ({0} Б)." -f (Get-Item $coreImg).Length) + +Write-Step "ISO и \ISO\Ventoy на p3" +Invoke-Robocopy $IsoSource ("{0}:\ISO" -f $pData.DriveLetter) | Out-Null +if (Test-Path $stageIsoVentoy) { + Invoke-Robocopy $stageIsoVentoy ("{0}:\ISO\Ventoy" -f $pData.DriveLetter) | Out-Null +} else { + New-Item -ItemType Directory -Force -Path ("{0}:\ISO\Ventoy\theme" -f $pData.DriveLetter) | Out-Null + [IO.File]::WriteAllText(("{0}:\ISO\Ventoy\NOT.DEL" -f $pData.DriveLetter), "Ventoy data partition marker`r`nDo not delete this file.`r`n") +} +if (-not (Test-Path ("{0}:\ISO\Ventoy\NOT.DEL" -f $pData.DriveLetter))) { throw "Маркер NOT.DEL не создан." } +Write-Ok "ISO и маркер на месте." + +# ---------------------------------------------------------------- verify +Write-Step "Проверка результата" +$isoDst = Get-ChildItem ("{0}:\ISO" -f $pData.DriveLetter) -File -Filter *.iso +$isoDstBytes = ($isoDst | Measure-Object Length -Sum).Sum +$projDst = Get-ChildItem ("{0}:\" -f $pProj.DriveLetter) -Recurse -File -Force -ErrorAction SilentlyContinue | + Where-Object { $_.FullName -notmatch '\\System Volume Information\\' -and $_.FullName -notmatch '\\\$RECYCLE\.BIN\\' } | + Measure-Object Length -Sum + +" ISO на p3: {0} шт., {1:N2} ГБ (источник {2:N2} ГБ)" -f $isoDst.Count, ($isoDstBytes/1GB), ($isoBytes/1GB) +" проект на p1: {0} файлов, {1:N2} ГБ (источник {2:N2} ГБ)" -f $projDst.Count, ($projDst.Sum/1GB), ($projBytes/1GB) +" core.img: {0} Б" -f (Get-Item ("{0}:\ventoy\core.img" -f $pEfi.DriveLetter)).Length + +if ($isoDst.Count -ne $isos.Count -or $isoDstBytes -ne $isoBytes) { Write-Warn "ISO: количество/размер не совпал!" } +if ($projDst.Sum -ne $projBytes) { Write-Warn "Проект: размер не совпал!" } + +Write-Step "Готово" +Write-Host "Проверяйте загрузку Xorboot -> Ventoy." -ForegroundColor Green +Write-Host "Если Xorboot не грузится — Change_bootLoader.exe -> Install XorBoot." -ForegroundColor Green diff --git a/build-scripts/layout/fix-vmware-boot.ps1 b/build-scripts/layout/fix-vmware-boot.ps1 new file mode 100644 index 0000000..9f777ac --- /dev/null +++ b/build-scripts/layout/fix-vmware-boot.ps1 @@ -0,0 +1,61 @@ +#Requires -RunAsAdministrator +<# +.SYNOPSIS + Готовит VMware VM к загрузке Ventoy с raw-диска: + сбрасывает NVRAM (boot-записи) и, при -SecureBoot Off, выключает SB в VM. + +.PARAMETER Vmx + Путь к .vmx. + +.PARAMETER SecureBoot + On/Off. По умолчанию Off (для первого теста; сертификат Ventoy в NVRAM VM + не импортирован, при On потребуется MokManager). +#> +[CmdletBinding()] +param( + [string]$Vmx = 'D:\Paravis\Documents\Virtual Machines\Windows 10\Windows 10.vmx', + [ValidateSet('On', 'Off')] + [string]$SecureBoot = 'Off' +) + +$ErrorActionPreference = 'Stop' +function Write-Step([string]$t) { Write-Host "`n=== $t ===" -ForegroundColor Cyan } +function Write-Ok([string]$t) { Write-Host "OK: $t" -ForegroundColor Green } +function Write-Warn([string]$t) { Write-Host "WARN: $t" -ForegroundColor Yellow } + +if (-not (Test-Path $Vmx)) { throw "Нет файла: $Vmx" } +$dir = Split-Path $Vmx + +$vmxProc = Get-Process -Name 'vmware-vmx' -ErrorAction SilentlyContinue +if ($vmxProc) { throw "VM запущена. Выключите её." } + +Write-Step "Бэкап VMX" +$bak = "$Vmx.bak-{0:yyyyMMdd-HHmmss}" -f (Get-Date) +Copy-Item $Vmx $bak -Force +Write-Ok $bak + +Write-Step "Secure Boot = $SecureBoot" +$txt = Get-Content $Vmx -Raw -Encoding UTF8 +if ($SecureBoot -eq 'Off') { + if ($txt -match 'uefi\.secureBoot\.enabled') { + $txt = $txt -replace 'uefi\.secureBoot\.enabled\s*=\s*"[^"]*"', 'uefi.secureBoot.enabled = "FALSE"' + } else { + $txt = $txt.TrimEnd() + "`nuefi.secureBoot.enabled = `"FALSE`"`n" + } +} else { + $txt = $txt -replace 'uefi\.secureBoot\.enabled\s*=\s*"[^"]*"', 'uefi.secureBoot.enabled = "TRUE"' +} +[IO.File]::WriteAllText($Vmx, $txt, (New-Object System.Text.UTF8Encoding($false))) +Write-Ok "записано" + +Write-Step "Сброс NVRAM" +Get-ChildItem $dir -Filter '*.nvram' | ForEach-Object { + $b = "$($_.FullName).bak-{0:yyyyMMdd-HHmmss}" -f (Get-Date) + Copy-Item $_.FullName $b -Force + Remove-Item $_.FullName -Force + Write-Ok ("удалён {0} (бэкап {1})" -f $_.Name, (Split-Path $b -Leaf)) +} + +Write-Step "Диски VM" +Select-String -Path $Vmx -Pattern '^(sata|nvme|scsi|ide).*(fileName|deviceType)|^firmware|secureBoot' | + Select-Object -ExpandProperty Line diff --git a/build-scripts/layout/fix-vmware-rawdisk.ps1 b/build-scripts/layout/fix-vmware-rawdisk.ps1 new file mode 100644 index 0000000..5755497 --- /dev/null +++ b/build-scripts/layout/fix-vmware-rawdisk.ps1 @@ -0,0 +1,70 @@ +#Requires -RunAsAdministrator +<# +.SYNOPSIS + Убирает из VMware VM второй raw-диск (nvme0:0), указывающий на тот же + \\.\PhysicalDrive2, что и sata0:0. Плюс чистит устаревшие .lck. + +.DESCRIPTION + VMware не может открыть один физический диск дважды — отсюда + "Операция с файлом \\.\PhysicalDrive2 не удалась". + + Скрипт: + 1. проверяет, что VM не запущена (нет процесса vmware-vmx); + 2. делает бэкап .vmx; + 3. удаляет строки nvme0.*; + 4. удаляет устаревшие каталоги *.lck; + 5. печатает оставшиеся диски. + +.PARAMETER Vmx + Путь к .vmx. По умолчанию "D:\Paravis\Documents\Virtual Machines\Windows 10\Windows 10.vmx". +#> +[CmdletBinding()] +param( + [string]$Vmx = 'D:\Paravis\Documents\Virtual Machines\Windows 10\Windows 10.vmx' +) + +$ErrorActionPreference = 'Stop' +function Write-Step([string]$t) { Write-Host "`n=== $t ===" -ForegroundColor Cyan } +function Write-Ok([string]$t) { Write-Host "OK: $t" -ForegroundColor Green } +function Write-Warn([string]$t) { Write-Host "WARN: $t" -ForegroundColor Yellow } + +if (-not (Test-Path $Vmx)) { throw "Нет файла: $Vmx" } +$dir = Split-Path $Vmx + +Write-Step "Проверка, что VM не запущена" +$vmxProc = Get-Process -Name 'vmware-vmx' -ErrorAction SilentlyContinue +if ($vmxProc) { + throw "VM запущена (vmware-vmx PID $($vmxProc.Id -join ',')). Выключите её и повторите." +} +Write-Ok "vmware-vmx не запущен." + +Write-Step "Бэкап" +$bak = "$Vmx.bak-{0:yyyyMMdd-HHmmss}" -f (Get-Date) +Copy-Item $Vmx $bak -Force +Write-Ok "бэкап: $bak" + +Write-Step "Удаление nvme0:* из VMX" +$lines = Get-Content $Vmx -Encoding UTF8 +$keep = $lines | Where-Object { $_ -notmatch '^nvme0' } +$removed = $lines.Count - $keep.Count +if ($removed -eq 0) { + Write-Warn "строк nvme0 не найдено — возможно, уже убрано." +} else { + $utf8 = New-Object System.Text.UTF8Encoding($false) + [IO.File]::WriteAllLines($Vmx, $keep, $utf8) + Write-Ok ("удалено строк: {0}" -f $removed) +} + +Write-Step "Удаление устаревших .lck" +Get-ChildItem $dir -Directory -Filter '*.lck' -ErrorAction SilentlyContinue | ForEach-Object { + Remove-Item $_.FullName -Recurse -Force -ErrorAction SilentlyContinue + Write-Ok ("удалён {0}" -f $_.Name) +} + +Write-Step "Текущие диски в VMX" +Select-String -Path $Vmx -Pattern 'present = "TRUE"|fileName|deviceType' | + Where-Object { $_.Line -match '^(sata|nvme|scsi|ide)' } | + Select-Object -ExpandProperty Line + +Write-Step "Готово" +Write-Host "Запускайте VM. Должен остаться один raw-диск (sata0:0 -> Windows 10-1.vmdk)." -ForegroundColor Green diff --git a/build-scripts/layout/insert-ventoy-p2.ps1 b/build-scripts/layout/insert-ventoy-p2.ps1 new file mode 100644 index 0000000..7819d2f --- /dev/null +++ b/build-scripts/layout/insert-ventoy-p2.ps1 @@ -0,0 +1,374 @@ +#Requires -RunAsAdministrator +<# +.SYNOPSIS + Вставляет 32-МБ раздел VTOYEFI между p1 (FAT32, проект) и p2 (NTFS, ESD), + переставляя записи разделов в MBR: ESD становится p3. + +.DESCRIPTION + Исходная схема (как в вашем README): + p1 FAT32 >=15 GB проект PF + ISO + p2 NTFS >=15 GB Windows ESD + Целевая схема: + p1 FAT32 проект (уменьшен на 32 МБ + 1 МБ запас) + p2 FAT 32 МБ VTOYEFI + /ventoy/core.img + p3 NTFS ESD тот же offset и размер, что были у p2 + + Данные ESD не перемещаются: меняется только номер записи в таблице MBR. + MBR-код (xorboot/grub4dos) не перезаписывается. + + Скрипт делает резервные копии сектора 0 в папку backup. + +.PARAMETER DiskNumber + Номер физического диска из Get-Disk. + +.PARAMETER SourceDir + Папка с vtoyefi, core.img, grldr-ventoy. + +.PARAMETER AllowNonUsb + Разрешить не-USB диск (только для тестов). + +.EXAMPLE + .\insert-ventoy-p2.ps1 -DiskNumber 2 -WhatIf + +.EXAMPLE + .\insert-ventoy-p2.ps1 -DiskNumber 2 +#> +[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')] +param( + [Parameter(Mandatory = $true)] + [int]$DiskNumber, + + [string]$SourceDir = $PSScriptRoot, + + [switch]$AllowNonUsb +) + +$ErrorActionPreference = 'Stop' + +$MiB = 1MB +$VentoySize = 32MB # 65536 * 512 +$P1Offset = 1MB # LBA 2048 +$Margin = 1MB # запас, чтобы p2 гарантированно не залез на ESD +$Label = 'VTOYEFI' +$BackupDir = Join-Path $SourceDir 'backup' +$SectorSize = 512 + +function Write-Step([string]$Text) { Write-Host "`n=== $Text ===" -ForegroundColor Cyan } +function Write-Warn([string]$Text) { Write-Host "WARN: $Text" -ForegroundColor Yellow } +function Write-Ok([string]$Text) { Write-Host "OK: $Text" -ForegroundColor Green } + +# --------------------------------------------------------------------------- +# Работа с сектором 0 через физический диск +# --------------------------------------------------------------------------- +function Read-DiskSector { + param([int]$Disk, [uint64]$Lba, [int]$Count = 1) + $path = "\\.\PhysicalDrive$Disk" + $fs = [IO.File]::Open($path, [IO.FileMode]::Open, [IO.FileAccess]::ReadWrite, [IO.FileShare]::ReadWrite) + try { + $fs.Seek([int64]($Lba * $SectorSize), [IO.SeekOrigin]::Begin) | Out-Null + $buf = New-Object byte[] ($Count * $SectorSize) + $read = 0 + while ($read -lt $buf.Length) { + $n = $fs.Read($buf, $read, $buf.Length - $read) + if ($n -le 0) { throw "Короткое чтение сектора $Lba" } + $read += $n + } + return ,$buf + } finally { + $fs.Dispose() + } +} + +function Write-DiskSector { + param([int]$Disk, [uint64]$Lba, [byte[]]$Data) + if ($Data.Length % $SectorSize -ne 0) { throw "Размер данных не кратен 512." } + $path = "\\.\PhysicalDrive$Disk" + $fs = [IO.File]::Open($path, [IO.FileMode]::Open, [IO.FileAccess]::ReadWrite, [IO.FileShare]::ReadWrite) + try { + $fs.Seek([int64]($Lba * $SectorSize), [IO.SeekOrigin]::Begin) | Out-Null + $fs.Write($Data, 0, $Data.Length) + $fs.Flush() + } finally { + $fs.Dispose() + } +} + +function Get-MbrEntry { + param([byte[]]$Mbr, [int]$Index) + $o = 446 + 16 * $Index + [pscustomobject]@{ + Index = $Index + Status = $Mbr[$o] + Type = $Mbr[$o + 4] + StartLba = [BitConverter]::ToUInt32($Mbr, $o + 8) + Sectors = [BitConverter]::ToUInt32($Mbr, $o + 12) + } +} + +function Test-FatType([byte]$Type) { + return ($Type -in @(0x01, 0x04, 0x06, 0x0B, 0x0C, 0x0E, 0xEF)) +} + +# --------------------------------------------------------------------------- +Write-Step "Проверка исходных файлов" +$vtoyefi = Join-Path $SourceDir 'vtoyefi' +$coreImg = Join-Path $SourceDir 'ventoy-1.1.18\boot\core.img' +if (-not (Test-Path $coreImg)) { $coreImg = Join-Path $SourceDir 'core.img' } +$grldr = Join-Path $SourceDir 'grldr-ventoy' + +foreach ($p in @($vtoyefi, $coreImg)) { + if (-not (Test-Path $p)) { throw "Не найден обязательный элемент: $p" } +} +if (-not (Test-Path (Join-Path $vtoyefi 'ventoy\ventoy.cpio'))) { + throw "В $vtoyefi нет ventoy\ventoy.cpio — это не распакованный VTOYEFI." +} +Write-Ok "VTOYEFI: $vtoyefi" +Write-Ok "core.img: $coreImg" + +# --------------------------------------------------------------------------- +Write-Step "Проверка диска $DiskNumber" +$disk = Get-Disk -Number $DiskNumber -ErrorAction Stop +if ($disk.IsBoot -or $disk.IsSystem) { throw "Диск $DiskNumber загрузочный/системный. Отказ." } +if (-not $AllowNonUsb -and $disk.BusType -notin @('USB', 'SD', 'MMC')) { + throw "Диск $DiskNumber имеет BusType '$($disk.BusType)', а не USB/SD. Отказ (тест: -AllowNonUsb)." +} +if ($disk.PartitionStyle -ne 'MBR') { + throw "Нужна MBR-разметка. Сейчас: $($disk.PartitionStyle)." +} + +$parts = @(Get-Partition -DiskNumber $DiskNumber | Sort-Object Offset) +if ($parts.Count -ne 2) { + $desc = ($parts | ForEach-Object { "p$($_.PartitionNumber) offset=$($_.Offset) size=$($_.Size)" }) -join '; ' + throw "Ожидались ровно 2 раздела (проект + ESD). Сейчас: $desc" +} + +$p1 = $parts | Where-Object { $_.PartitionNumber -eq 1 } +$esd = $parts | Where-Object { $_.PartitionNumber -eq 2 } +if (-not $p1 -or -not $esd) { throw "Не найдены p1 и p2." } +if ($p1.Offset -ne $P1Offset) { + Write-Warn ("p1 начинается с offset {0} (LBA {1}), Ventoy ожидает 2048." -f $p1.Offset, ($p1.Offset / 512)) + Write-Warn "Загрузка возможна, но с предупреждением 'NOT a standard Ventoy device'." +} +if ($esd.Offset -lt ($p1.Offset + $p1.Size)) { throw "p2 пересекается с p1." } + +$vol1 = Get-Volume -Partition $p1 -ErrorAction Stop +if (-not $vol1.DriveLetter) { throw "У p1 нет буквы диска." } +$volEsd = Get-Volume -Partition $esd -ErrorAction Stop +if (-not $volEsd.DriveLetter) { Write-Warn "У ESD-раздела нет буквы диска; это не мешает операции." } + +$p1End = $p1.Offset + $p1.Size +$gap = $esd.Offset - $p1End +if ($gap -lt 0) { throw "Отрицательный зазор между p1 и p2." } + +# Сколько нужно освободить в p1, чтобы перед ESD влезли 32 МБ + запас +$need = [Math]::Max(0, $VentoySize - $gap) +$shrink = if ($need -gt 0) { $need + $Margin } else { 0 } +$newP1Size = $p1.Size - $shrink +if ($newP1Size -le 0) { throw "p1 слишком мал." } +if ($shrink -gt 0 -and $vol1.SizeRemaining -lt $shrink) { + throw ("На p1 свободно {0:N1} MB, а освободить нужно {1:N1} MB." -f ($vol1.SizeRemaining / 1MB), ($shrink / 1MB)) +} + +Write-Host ("Диск: {0}, {1:N1} GB, MBR, BusType={2}" -f $disk.FriendlyName, ($disk.Size / 1GB), $disk.BusType) +Write-Host ("p1 : offset={0} (LBA {1}), size={2:N1} MB, {3}" -f $p1.Offset, ($p1.Offset / 512), ($p1.Size / 1MB), $vol1.DriveLetter) +Write-Host ("p2 : offset={0} (LBA {1}), size={2:N1} MB, ESD" -f $esd.Offset, ($esd.Offset / 512), ($esd.Size / 1MB)) +Write-Host ("Зазор между p1 и p2: {0:N1} MB" -f ($gap / 1MB)) +if ($shrink -gt 0) { + Write-Host ("План: уменьшить p1 на {0:N1} MB (с {1:N1} до {2:N1} MB), начало p1 не меняется." -f ($shrink / 1MB), ($p1.Size / 1MB), ($newP1Size / 1MB)) +} else { + Write-Host "План: свободного места уже достаточно, p1 не трогаем." +} +Write-Host "План: создать p3 = 32 МБ FAT (VTOYEFI) в зазоре, затем поменять местами записи MBR p2 и p3." +Write-Host "План: ESD останется на том же offset/размере, но станет p3. Данные ESD не перемещаются." + +if (-not $PSCmdlet.ShouldProcess("Диск $DiskNumber", "Вставить 32-МБ VTOYEFI между p1 и ESD и переставить записи MBR p2/p3")) { + Write-Host "WhatIf: изменения не вносились." -ForegroundColor Yellow + return +} + +# --------------------------------------------------------------------------- +Write-Step "Резервная копия MBR" +New-Item -ItemType Directory -Path $BackupDir -Force | Out-Null +$stamp = Get-Date -Format 'yyyyMMdd-HHmmss' +$mbrBefore = Read-DiskSector -Disk $DiskNumber -Lba 0 +$mbrBeforePath = Join-Path $BackupDir "mbr-before-$stamp.bin" +[IO.File]::WriteAllBytes($mbrBeforePath, $mbrBefore) +Write-Ok "MBR сохранён: $mbrBeforePath" + +$ventoyCreated = $false +$mbrSwapped = $false + +try { + # ----------------------------------------------------------------------- + if ($shrink -gt 0) { + Write-Step "Уменьшение p1 на $([Math]::Round($shrink / 1MB, 1)) MB" + Write-Warn "Windows может отказать, если данные p1 лежат в самом конце раздела. Сделайте бэкап." + Resize-Partition -DriveLetter $vol1.DriveLetter -Size $newP1Size -ErrorAction Stop + Start-Sleep -Seconds 2 + } + + $p1After = Get-Partition -DiskNumber $DiskNumber -PartitionNumber 1 + $p2Offset = $p1After.Offset + $p1After.Size + $p2End = $p2Offset + $VentoySize + + # Если Windows округлил размер p1 вверх и p2 залезает на ESD — добираем + if ($p2End -gt $esd.Offset) { + $excess = $p2End - $esd.Offset + Write-Warn ("p2 залезает на ESD на {0} байт; уменьшаю p1 ещё." -f $excess) + $target = $p1After.Size - $excess - $Margin + Resize-Partition -DriveLetter $vol1.DriveLetter -Size $target -ErrorAction Stop + Start-Sleep -Seconds 2 + $p1After = Get-Partition -DiskNumber $DiskNumber -PartitionNumber 1 + $p2Offset = $p1After.Offset + $p1After.Size + $p2End = $p2Offset + $VentoySize + } + if ($p2End -gt $esd.Offset) { throw "Не удалось освободить 32 МБ перед ESD." } + + Write-Ok ("p1: новый конец {0} (LBA {1})" -f ($p1After.Size + $p1After.Offset), (($p1After.Size + $p1After.Offset) / 512)) + Write-Ok ("Будущий p2: offset={0} (LBA {1}), конец={2} (LBA {3})" -f $p2Offset, ($p2Offset / 512), $p2End, ($p2End / 512)) + + # ----------------------------------------------------------------------- + Write-Step "Создание раздела 32 МБ в зазоре" + try { + $ventoy = New-Partition -DiskNumber $DiskNumber -Offset $p2Offset -Size $VentoySize -Alignment 512 -AssignDriveLetter -ErrorAction Stop + } catch { + Write-Warn "Не удалось создать с Alignment=512: $($_.Exception.Message)" + throw + } + $ventoyCreated = $true + if ($ventoy.PartitionNumber -ne 3) { throw "Ожидался номер раздела 3, получен $($ventoy.PartitionNumber)." } + if ($ventoy.Offset -ne $p2Offset) { throw "Windows сдвинул начало p3: $($ventoy.Offset) != $p2Offset." } + if ($ventoy.Size -ne $VentoySize) { throw "Размер p3 $($ventoy.Size) != $VentoySize." } + Write-Ok "p3 создан: offset=$($ventoy.Offset), size=$($ventoy.Size)" + + Start-Sleep -Seconds 1 + $ventoyVol = Get-Volume -Partition $ventoy -ErrorAction Stop + if (-not $ventoyVol.DriveLetter) { throw "У нового раздела нет буквы диска." } + + Write-Step "Форматирование p3 в FAT" + Format-Volume -DriveLetter $ventoyVol.DriveLetter -FileSystem FAT -NewFileSystemLabel $Label -Confirm:$false -Force -ErrorAction Stop + Start-Sleep -Seconds 1 + + Write-Step "Копирование VTOYEFI и core.img" + $p3Root = "$($ventoyVol.DriveLetter):\" + Copy-Item -Path (Join-Path $vtoyefi '*') -Destination $p3Root -Recurse -Force -ErrorAction Stop + if (-not (Test-Path (Join-Path $p3Root 'ventoy\ventoy.cpio'))) { throw "Не найден $p3Root\ventoy\ventoy.cpio" } + Copy-Item -Path $coreImg -Destination (Join-Path $p3Root 'ventoy\core.img') -Force -ErrorAction Stop + Write-Ok "VTOYEFI и core.img скопированы." + + # ----------------------------------------------------------------------- + Write-Step "Перестановка записей MBR p2 <-> p3" + $mbrPre = Read-DiskSector -Disk $DiskNumber -Lba 0 + $mbrPrePath = Join-Path $BackupDir "mbr-pre-swap-$stamp.bin" + [IO.File]::WriteAllBytes($mbrPrePath, $mbrPre) + Write-Ok "MBR до перестановки: $mbrPrePath" + + $e1 = Get-MbrEntry $mbrPre 0 + $e2 = Get-MbrEntry $mbrPre 1 + $e3 = Get-MbrEntry $mbrPre 2 + + if ($e1.StartLba -ne 2048) { Write-Warn "p1 start LBA = $($e1.StartLba), не 2048." } + if ($e2.StartLba -ne [uint32]($esd.Offset / 512) -or $e2.Sectors -ne [uint32]($esd.Size / 512)) { + throw "Запись p2 в MBR не совпадает с ESD (start=$($e2.StartLba), sectors=$($e2.Sectors))." + } + if ($e2.Type -eq 0x05 -or $e2.Type -eq 0x0F) { throw "ESD — расширенный/логический раздел; эта схема не поддерживается." } + if ($e3.StartLba -ne [uint32]($p2Offset / 512) -or $e3.Sectors -ne [uint32](65536)) { + throw "Запись p3 в MBR не совпадает с новым разделом (start=$($e3.StartLba), sectors=$($e3.Sectors))." + } + if (-not (Test-FatType $e3.Type)) { throw ("Тип p3 0x{0:X2} не похож на FAT." -f $e3.Type) } + + $mbrNew = [byte[]]$mbrPre.Clone() + for ($i = 0; $i -lt 16; $i++) { + $t = $mbrNew[462 + $i] + $mbrNew[462 + $i] = $mbrNew[478 + $i] + $mbrNew[478 + $i] = $t + } + # Если p1 активен, не даём флагу активности уехать на Ventoy/ESD + if ($mbrNew[446] -eq 0x80) { + $mbrNew[462] = 0x00 + $mbrNew[478] = 0x00 + } + Write-DiskSector -Disk $DiskNumber -Lba 0 -Data $mbrNew + $mbrSwapped = $true + Start-Sleep -Seconds 1 + + # ----------------------------------------------------------------------- + Write-Step "Проверка MBR после перестановки" + $mbrCheck = Read-DiskSector -Disk $DiskNumber -Lba 0 + $c1 = Get-MbrEntry $mbrCheck 0 + $c2 = Get-MbrEntry $mbrCheck 1 + $c3 = Get-MbrEntry $mbrCheck 2 + $ok = $true + if ($c2.StartLba -ne [uint32]($p2Offset / 512) -or $c2.Sectors -ne [uint32]65536) { $ok = $false } + if ($c3.StartLba -ne [uint32]($esd.Offset / 512) -or $c3.Sectors -ne [uint32]($esd.Size / 512)) { $ok = $false } + if ($c1.StartLba -ne $e1.StartLba -or $c1.Sectors -ne $e1.Sectors) { $ok = $false } + + if (-not $ok) { + Write-DiskSector -Disk $DiskNumber -Lba 0 -Data $mbrPre + throw "Проверка MBR не прошла; восстановлен MBR до перестановки ($mbrPrePath)." + } + Write-Ok "p2 = Ventoy (32 МБ), p3 = ESD (offset не изменился)." + + # Обновляем кэш Windows (может не сработать без переподключения) + try { Update-HostStorageCache -ErrorAction SilentlyContinue } catch { } + Start-Sleep -Seconds 1 + + # ----------------------------------------------------------------------- + Write-Step "Артефакты в папке проекта на p1" + $projFolder = Join-Path "$($vol1.DriveLetter):\" 'efi\Paravis\Ventoy' + New-Item -ItemType Directory -Path $projFolder -Force | Out-Null + Copy-Item -Path $coreImg -Destination (Join-Path $projFolder 'core.img') -Force + if (Test-Path $grldr) { + Copy-Item -Path $grldr -Destination (Join-Path $projFolder 'grldr-ventoy') -Force + $g4d = Join-Path "$($vol1.DriveLetter):\" 'efi\Paravis\Boot\g4d' + if (Test-Path $g4d) { + Copy-Item -Path $grldr -Destination (Join-Path $g4d 'Ventoy') -Force + Write-Ok "grldr-ventoy -> $g4d\Ventoy" + } + } + Write-Ok "core.img и grldr-ventoy -> $projFolder" + + # ----------------------------------------------------------------------- + Write-Step "Готово. Что делать дальше" + Write-Host @" +Разметка теперь: + p1 FAT32 проект + ISO (как раньше, уменьшен на 32-33 МБ) + p2 FAT 32 МБ VTOYEFI (новый) + p3 NTFS ESD (тот же offset/размер, буква диска обычно сохраняется) + +BIOS / grub4dos: + title Ventoy 1.1.18 (BIOS) + find --set-root /ventoy/core.img + kernel /ventoy/core.img + boot + +UEFI / Xorboot: + раздел p2 (VTOYEFI), файл \EFI\BOOT\BOOTX64.EFI + +Важно: + * ESD-раздел теперь p3. Если где-то был захардкожен номер "2" — поправьте на "3". + Буква диска и данные не менялись. + * После изменения таблицы разделов желательно переподключить флешку, + чтобы Windows перечитала MBR. + * Change_bootLoader.exe при необходимости запустите заново: p1 остался p1. + +Резервные копии MBR: + $mbrBeforePath + $mbrPrePath + +Откат (если передумаете): + 1) удалить p2 (Ventoy, 32 МБ) в diskpart — это НЕ ESD; + 2) расширить p1 обратно на 32-33 МБ; + 3) восстановить $mbrBeforePath в сектор 0 (ESD снова станет p2). +"@ -ForegroundColor Gray +} +catch { + Write-Host "" + Write-Warn "Ошибка: $($_.Exception.Message)" + Write-Host "Состояние: p1 мог быть уменьшен; новый раздел мог быть создан." -ForegroundColor Yellow + Write-Host "Резервные копии MBR: $BackupDir" -ForegroundColor Yellow + if ($mbrSwapped) { + Write-Host "MBR уже переставлялся — проверьте разделы перед продолжением." -ForegroundColor Yellow + } + throw +} diff --git a/build-scripts/layout/prepare-new-usb.ps1 b/build-scripts/layout/prepare-new-usb.ps1 new file mode 100644 index 0000000..0764b1b --- /dev/null +++ b/build-scripts/layout/prepare-new-usb.ps1 @@ -0,0 +1,271 @@ +#Requires -RunAsAdministrator +<# +.SYNOPSIS + Готовит НОВУЮ флешку (64 ГБ) под кастомную схему: + p1 = загрузочный FAT32 (PARAVIS) + Xorboot MBR, + p2 = VTOYEFI 32 МБ, + p3 = данные NTFS (DATA) с ISO. + +.DESCRIPTION + Диск полностью очищается (diskpart clean) — всё содержимое теряется. + Источники: + * проект : E:\_usb_stage\PARAVIS (staging со старого SSD) + * VTOYEFI : C:\PF\Ventoy\vtoyefi + core-custom-layout-1.1.18.img + * ISO : E:\Downloads\ISO + * маркер : E:\_usb_stage\ISO_Ventoy -> \ISO\Ventoy + + В конце ставится Xorboot MBR/PBR через bootice (/keep_dpt, /keep_bpb) + и проверяется, что код MBR совпадает с xmbr.bin. + +.EXAMPLE + .\prepare-new-usb.ps1 -WhatIf + .\prepare-new-usb.ps1 -DiskNumber 2 +#> +[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')] +param( + [int]$DiskNumber = 0, + [int]$BootSizeMB = 14336, + [int]$TailMB = 50, + [string]$StageDir = 'E:\_usb_stage', + [string]$IsoSource = 'E:\Downloads\ISO', + [string]$VentoyDir = 'C:\PF\Ventoy', + [string]$BackupDir = 'C:\PF\Ventoy\backup', + [string]$Serial = 'AA00000000000489', + [switch]$Force +) + +$ErrorActionPreference = 'Stop' + +function Write-Step([string]$t) { Write-Host "`n=== $t ===" -ForegroundColor Cyan } +function Write-Ok([string]$t) { Write-Host "OK: $t" -ForegroundColor Green } +function Write-Warn([string]$t) { Write-Host "WARN: $t" -ForegroundColor Yellow } + +function Invoke-Diskpart([string]$script) { + $tmp = Join-Path $env:TEMP ("dp_{0}.txt" -f ([guid]::NewGuid().ToString('N'))) + $script | Set-Content -Path $tmp -Encoding ASCII + $out = & diskpart.exe /s $tmp 2>&1 + Remove-Item $tmp -Force -ErrorAction SilentlyContinue + $out | ForEach-Object { " $_" } + if ($LASTEXITCODE -ne 0) { throw "diskpart завершился с кодом $LASTEXITCODE" } +} + +function Invoke-Robocopy([string]$src, [string]$dst, [string[]]$extra = @()) { + $roboArgs = @($src, $dst, '/E', '/COPY:DAT', '/R:1', '/W:1', '/MT:8', '/NFL', '/NDL', '/NJH', '/NJS', '/NP') + $extra + $out = & robocopy.exe @roboArgs 2>&1 + $code = $LASTEXITCODE + if ($code -ge 8) { + $out | Select-Object -Last 30 | ForEach-Object { " $_" } + throw "robocopy вернул код $code ($src -> $dst)" + } + return $code +} + +function Get-DiskVolumeLabel([int]$num, [string]$label) { + foreach ($p in (Get-Partition -DiskNumber $num -ErrorAction SilentlyContinue)) { + $v = Get-Volume -Partition $p -ErrorAction SilentlyContinue + if ($v -and $v.FileSystemLabel -eq $label) { return $v } + } + return $null +} + +function Read-Raw([int]$num, [int]$len) { + $fs = [IO.FileStream]::new("\\.\PhysicalDrive$num", [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::ReadWrite) + try { + $buf = New-Object byte[] $len + $n = $fs.Read($buf, 0, $len) + if ($n -ne $len) { throw "Прочитано $n из $len байт." } + return ,$buf + } finally { try { $fs.Close() } catch { } } +} + +# ------------------------------------------------------------------ диск +Write-Step "Выбор диска" +if ($DiskNumber -gt 0) { + $disk = Get-Disk -Number $DiskNumber +} else { + $cand = @(Get-Disk | Where-Object { + $_.BusType -eq 'USB' -and + $_.Size -ge 40GB -and $_.Size -le 100GB -and + -not $_.IsBoot -and -not $_.IsSystem + }) + if ($cand.Count -ne 1) { + $cand | Select-Object Number,FriendlyName,SerialNumber,@{n='GB';e={[math]::Round($_.Size/1GB,1)}} | Format-Table -AutoSize | Out-String | Write-Host + throw "Не удалось однозначно выбрать диск — укажите -DiskNumber." + } + $disk = $cand[0] +} + +if ($disk.BusType -ne 'USB') { throw "Диск $($disk.Number) не USB ($($disk.BusType))." } +if ($disk.IsBoot -or $disk.IsSystem) { throw "Это системный диск — отказ." } +if (-not $Force -and $Serial -and $disk.SerialNumber -and $disk.SerialNumber.Trim() -ne $Serial) { + throw ("Серийный номер '{0}' не совпал с ожидаемым '{1}'. Если уверены — -Force." -f $disk.SerialNumber, $Serial) +} + +$diskNum = $disk.Number +Write-Host (" Диск {0}: {1}, {2:N2} ГиБ ({3} МБ), {4}, serial={5}" -f $diskNum, $disk.FriendlyName, ($disk.Size/1GB), ([math]::Floor($disk.Size/1MB)), $disk.PartitionStyle, $disk.SerialNumber) +Write-Host " ВНИМАНИЕ: диск будет полностью очищен." -ForegroundColor Red +$cur = Get-Partition -DiskNumber $diskNum -ErrorAction SilentlyContinue +if ($cur) { + $cur | Select-Object PartitionNumber, DriveLetter, Offset, @{n='GB';e={[math]::Round($_.Size/1GB,2)}}, Type | Format-Table -AutoSize | Out-String | Write-Host +} + +# --------------------------------------------------------------- источники +Write-Step "Проверка источников" +$stageProj = Join-Path $StageDir 'PARAVIS' +$stageIsoVentoy = Join-Path $StageDir 'ISO_Ventoy' +$vtoyefi = Join-Path $VentoyDir 'vtoyefi' +$coreImg = Join-Path $VentoyDir 'core-custom-layout-1.1.18.img' + +if (-not (Test-Path $stageProj)) { throw "Нет staging проекта: $stageProj" } +if (-not (Test-Path (Join-Path $vtoyefi 'ventoy\ventoy.cpio'))) { throw "Нет VTOYEFI: $vtoyefi" } +if (-not (Test-Path $coreImg)) { throw "Нет core: $coreImg" } +if (-not (Test-Path $IsoSource)) { throw "Нет ISO: $IsoSource" } +if (-not (Test-Path $stageIsoVentoy)) { throw "Нет \ISO\Ventoy в staging: $stageIsoVentoy" } + +$isos = Get-ChildItem $IsoSource -File -Filter *.iso +$isoBytes = ($isos | Measure-Object Length -Sum).Sum +$projBytes = (Get-ChildItem $stageProj -Recurse -File -Force | Measure-Object Length -Sum).Sum +Write-Host (" проект: {0:N2} ГБ, ISO: {1} шт. / {2:N2} ГБ" -f ($projBytes/1GB), $isos.Count, ($isoBytes/1GB)) + +$p1Bytes = [int64]$BootSizeMB * 1MB +$p2Bytes = [int64]32 * 1MB +$p3Bytes = $disk.Size - $p1Bytes - $p2Bytes - ([int64]$TailMB * 1MB) +if ($p3Bytes -le 0) { throw "Диск слишком мал для выбранных размеров." } +Write-Host (" p1 {0:N2} ГиБ / p2 32 МиБ / p3 {1:N2} ГиБ" -f ($p1Bytes/1GB), ($p3Bytes/1GB)) +if ($projBytes -gt ($p1Bytes - 64MB)) { throw "Проект не помещается на p1." } +if ($isoBytes -gt ($p3Bytes - 256MB)) { throw "ISO не помещаются на p3." } + +if (-not $PSCmdlet.ShouldProcess("PhysicalDrive$diskNum ($($disk.FriendlyName))", "Стереть диск и создать: p1 ${BootSizeMB}MB FAT32 PARAVIS, p2 32MB VTOYEFI, p3 NTFS DATA")) { + Write-Warn "WhatIf: изменения не вносились." + return +} + +# ------------------------------------------------------------------ backup +New-Item -ItemType Directory -Force -Path $BackupDir | Out-Null +$bkpFile = Join-Path $BackupDir ("usb-new-{0}-{1:yyyyMMdd-HHmmss}.bin" -f $diskNum, (Get-Date)) +[IO.File]::WriteAllBytes($bkpFile, (Read-Raw $diskNum 65536)) +Write-Ok ("первые 64 КиБ сохранены: {0}" -f $bkpFile) + +# ------------------------------------------------------------- разметка +Write-Step "Разметка (diskpart clean)" +$p3MB = [math]::Floor($p3Bytes / 1MB) +$dp = @" +select disk $diskNum +clean +create partition primary size=$BootSizeMB +format fs=fat32 quick label=PARAVIS +active +assign +create partition primary size=32 +format fs=fat quick label=VTOYEFI +assign +create partition primary size=$p3MB +format fs=ntfs quick label=DATA +assign +exit +"@ +Invoke-Diskpart $dp +Write-Ok "Разделы созданы." + +Write-Step "Обновление таблицы устройств" +Update-HostStorageCache +Start-Sleep -Seconds 3 +$deadline = (Get-Date).AddSeconds(60) +do { + Update-HostStorageCache + $v1 = Get-DiskVolumeLabel $diskNum 'PARAVIS' + $v2 = Get-DiskVolumeLabel $diskNum 'VTOYEFI' + $v3 = Get-DiskVolumeLabel $diskNum 'DATA' + if ($v1 -and $v2 -and $v3) { break } + Start-Sleep -Seconds 2 +} while ((Get-Date) -lt $deadline) +if (-not ($v1 -and $v2 -and $v3)) { throw "Новые разделы не появились." } + +foreach ($p in (Get-Partition -DiskNumber $diskNum | Where-Object { -not $_.DriveLetter })) { + Add-PartitionAccessPath -DiskNumber $diskNum -PartitionNumber $p.PartitionNumber -AssignDriveLetter +} +Start-Sleep -Seconds 1 +Update-HostStorageCache + +$pProj = Get-DiskVolumeLabel $diskNum 'PARAVIS' +$pEfi = Get-DiskVolumeLabel $diskNum 'VTOYEFI' +$pData = Get-DiskVolumeLabel $diskNum 'DATA' +if (-not $pProj.DriveLetter -or -not $pEfi.DriveLetter -or -not $pData.DriveLetter) { + throw "Не всем разделам назначены буквы." +} +Write-Ok ("буквы: PARAVIS={0}: VTOYEFI={1}: DATA={2}:" -f $pProj.DriveLetter, $pEfi.DriveLetter, $pData.DriveLetter) + +$geo = Get-Partition -DiskNumber $diskNum | Sort-Object Offset +$geo | Format-Table PartitionNumber, DriveLetter, Offset, Size, Type, IsActive -AutoSize | Out-String | Write-Host +if ($geo[0].Offset -ne 1048576) { throw "p1 начинается не с 1 МиБ." } +if ($geo[0].Size -ne $p1Bytes) { throw "p1 неверного размера." } +if ($geo[1].Offset -ne ($geo[0].Offset + $geo[0].Size)) { throw "p2 не сразу за p1." } +if ($geo[1].Size -ne $p2Bytes) { throw "p2 не 32 МБ." } +if (-not $geo[0].IsActive) { throw "p1 не active." } +Write-Ok "Геометрия корректна." + +# ---------------------------------------------------------------- файлы +Write-Step "Проект -> p1" +Invoke-Robocopy $stageProj ("{0}:\" -f $pProj.DriveLetter) | Out-Null +Write-Ok "Проект скопирован." + +Write-Step "VTOYEFI -> p2" +Invoke-Robocopy $vtoyefi ("{0}:\" -f $pEfi.DriveLetter) | Out-Null +Copy-Item $coreImg ("{0}:\ventoy\core.img" -f $pEfi.DriveLetter) -Force +if (-not (Select-String -Path ("{0}:\grub\grub.cfg" -f $pEfi.DriveLetter) -Pattern 'VTOY-CUSTOM-LAYOUT' -Quiet)) { throw "grub.cfg без VTOY-CUSTOM-LAYOUT." } +Write-Ok ("VTOYEFI + core ({0} Б)" -f (Get-Item $coreImg).Length) + +Write-Step "ISO -> p3" +Invoke-Robocopy $IsoSource ("{0}:\ISO" -f $pData.DriveLetter) | Out-Null +Invoke-Robocopy $stageIsoVentoy ("{0}:\ISO\Ventoy" -f $pData.DriveLetter) | Out-Null +if (-not (Test-Path ("{0}:\ISO\Ventoy\NOT.DEL" -f $pData.DriveLetter))) { throw "Маркер NOT.DEL не создан." } +Write-Ok "ISO и маркер на месте." + +# --------------------------------------------------------------- Xorboot +Write-Step "Установка Xorboot (MBR + PBR)" +$bootice = ("{0}:\efi\Paravis\Boot\bootice.exe" -f $pProj.DriveLetter) +$xmbr = ("{0}:\efi\Paravis\Boot\xor\xmbr.bin" -f $pProj.DriveLetter) +$xpbr = ("{0}:\efi\Paravis\Boot\xor\xpbr.bin" -f $pProj.DriveLetter) +foreach ($f in @($bootice, $xmbr, $xpbr)) { if (-not (Test-Path $f)) { throw "Нет файла: $f" } } + +$dev = ("{0}:" -f $pProj.DriveLetter) +& $bootice "/DEVICE=$dev" /mbr /restore "/file=$xmbr" /keep_dpt /quiet | Out-Host +& $bootice "/DEVICE=$dev" /pbr /restore "/file=$xpbr" /keep_bpb /quiet | Out-Host +Start-Sleep -Seconds 1 +Write-Ok "bootice: MBR и PBR записаны." + +Write-Step "Проверка MBR" +$mbr = Read-Raw $diskNum 512 +$xmbrBytes = [IO.File]::ReadAllBytes($xmbr) + +# bootice с /keep_dpt сохраняет таблицу разделов (0x1BE..0x1FD) и подпись диска +# (0x1B8..0x1BB), поэтому сравниваем код до и после этого участка. +$same = $true +for ($i = 0; $i -lt 0x1B8; $i++) { if ($mbr[$i] -ne $xmbrBytes[$i]) { $same = $false; break } } +if ($same) { + for ($i = 0x1BC; $i -lt 0x1BE; $i++) { if ($mbr[$i] -ne $xmbrBytes[$i]) { $same = $false; break } } +} +if ($same) { + Write-Ok "Код MBR совпадает с xmbr.bin." +} else { + Write-Warn "Код MBR отличается от xmbr.bin — проверьте загрузку; при необходимости Change_bootLoader.exe -> Install XorBoot." +} +$sig = "{0:X2}{1:X2}" -f $mbr[510], $mbr[511] +Write-Host (" сигнатура MBR: {0}, active p1: {1}" -f $sig, $geo[0].IsActive) + +# ---------------------------------------------------------------- отчёт +Write-Step "Итог" +$isoDst = Get-ChildItem ("{0}:\ISO" -f $pData.DriveLetter) -File -Filter *.iso +$isoDstBytes = ($isoDst | Measure-Object Length -Sum).Sum +$projDst = Get-ChildItem ("{0}:\" -f $pProj.DriveLetter) -Recurse -File -Force -ErrorAction SilentlyContinue | + Where-Object { $_.FullName -notmatch '\\System Volume Information\\' } | Measure-Object Length -Sum + +" p1 {0}: {1:N2} ГБ, {2} файлов (источник {3:N2} ГБ)" -f $pProj.DriveLetter, ($projDst.Sum/1GB), $projDst.Count, ($projBytes/1GB) +" p2 {0}: core {1} Б" -f $pEfi.DriveLetter, (Get-Item ("{0}:\ventoy\core.img" -f $pEfi.DriveLetter)).Length +" p3 {0}: ISO {1} шт., {2:N2} ГБ (источник {3:N2} ГБ)" -f $pData.DriveLetter, $isoDst.Count, ($isoDstBytes/1GB), ($isoBytes/1GB) +if ($isoDst.Count -ne $isos.Count -or $isoDstBytes -ne $isoBytes) { Write-Warn "ISO: несовпадение с источником." } +if ($projDst.Sum -ne $projBytes) { Write-Warn "Проект: размер не совпал." } + +Write-Step "Готово" +Write-Host "Загружайтесь: Xorboot -> Ventoy." -ForegroundColor Green +Write-Host "Если Xorboot не появится — Change_bootLoader.exe -> Install XorBoot." -ForegroundColor Green diff --git a/build-scripts/layout/prepare-ventoy-partition.ps1 b/build-scripts/layout/prepare-ventoy-partition.ps1 new file mode 100644 index 0000000..6c1bac9 --- /dev/null +++ b/build-scripts/layout/prepare-ventoy-partition.ps1 @@ -0,0 +1,250 @@ +#Requires -RunAsAdministrator +<# +.SYNOPSIS + Подготавливает на флешке второй раздел 32 МБ (VTOYEFI) для Ventoy, + НЕ трогая MBR-код и первый раздел с проектом Paravis. + +.DESCRIPTION + Схема, которую требует стоковый Ventoy: + p1: начинается с LBA 2048 (1 МБ), содержит ваши файлы и ISO + p2: 65536 секторов (32 МБ), FAT, сразу после p1, содержит VTOYEFI + /ventoy/core.img + + Скрипт: + 1. проверяет, что диск USB, MBR, p1 — единственный/последний раздел; + 2. при необходимости уменьшает p1 на 32 МБ (плюс до 1 МБ на выравнивание; + файловая система, не начало!); + 3. создаёт p2 сразу после p1 и форматирует его в FAT; + 4. копирует туда распакованный VTOYEFI и core.img; + 5. кладёт core.img и grldr-ventoy в папку проекта на p1. + + MBR-загрузочный код (xorboot/grub4dos) не перезаписывается. + Таблица разделов обновляется штатными средствами Windows. + +.PARAMETER DiskNumber + Номер физического диска из Get-Disk. Например: 2. + +.PARAMETER SourceDir + Папка с распакованными материалами Ventoy (vtoyefi, ventoy-1.1.18, core.img). + +.PARAMETER AllowNonUsb + Разрешить не-USB диск (только для тестов на VHD; на реальной системе не используйте). + +.EXAMPLE + .\prepare-ventoy-partition.ps1 -DiskNumber 2 -WhatIf + +.EXAMPLE + .\prepare-ventoy-partition.ps1 -DiskNumber 2 +#> +[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')] +param( + [Parameter(Mandatory = $true)] + [int]$DiskNumber, + + [string]$SourceDir = $PSScriptRoot, + + [switch]$AllowNonUsb +) + +$ErrorActionPreference = 'Stop' + +$MiB = 1MB +$VentoySize = 32MB # 65536 * 512 +$P1Offset = 1MB # LBA 2048 — обязательное требование Ventoy +$Label = 'VTOYEFI' + +function Write-Step([string]$Text) { Write-Host "`n=== $Text ===" -ForegroundColor Cyan } +function Write-Warn([string]$Text) { Write-Host "WARN: $Text" -ForegroundColor Yellow } +function Write-Ok([string]$Text) { Write-Host "OK: $Text" -ForegroundColor Green } + +# --------------------------------------------------------------------------- +Write-Step "Проверка исходных файлов" +$vtoyefi = Join-Path $SourceDir 'vtoyefi' +$coreImg = Join-Path $SourceDir 'ventoy-1.1.18\boot\core.img' +if (-not (Test-Path $coreImg)) { $coreImg = Join-Path $SourceDir 'core.img' } +$grldr = Join-Path $SourceDir 'grldr-ventoy' + +foreach ($p in @($vtoyefi, $coreImg)) { + if (-not (Test-Path $p)) { throw "Не найден обязательный элемент: $p" } +} +if (-not (Test-Path (Join-Path $vtoyefi 'ventoy\ventoy.cpio'))) { + throw "В $vtoyefi нет ventoy\ventoy.cpio — это не распакованный VTOYEFI." +} +Write-Ok "VTOYEFI: $vtoyefi" +Write-Ok "core.img: $coreImg" + +# --------------------------------------------------------------------------- +Write-Step "Проверка диска $DiskNumber" +$disk = Get-Disk -Number $DiskNumber -ErrorAction Stop + +if ($disk.IsBoot -or $disk.IsSystem) { + throw "Диск $DiskNumber является загрузочным/системным. Отказ." +} +if (-not $AllowNonUsb -and $disk.BusType -notin @('USB', 'SD', 'MMC')) { + throw "Диск $DiskNumber имеет BusType '$($disk.BusType)', а не USB/SD. Отказ (для теста используйте -AllowNonUsb)." +} +if ($disk.PartitionStyle -ne 'MBR') { + throw "Диск должен быть MBR. Сейчас: $($disk.PartitionStyle). Legacy core.img Ventoy рассчитан на msdos-разметку." +} + +$parts = @(Get-Partition -DiskNumber $DiskNumber | Sort-Object Offset) +$p1 = $parts | Where-Object { $_.PartitionNumber -eq 1 } +if (-not $p1) { throw "На диске нет раздела 1." } + +$extra = @($parts | Where-Object { $_.PartitionNumber -ne 1 }) +if ($extra.Count -gt 0) { + $list = ($extra | ForEach-Object { "p$($_.PartitionNumber) offset=$($_.Offset) size=$($_.Size)" }) -join '; ' + throw "На диске уже есть другие разделы: $list. Нужен диск, где p1 — последний раздел (Ventoy требует p2 сразу после p1)." +} + +Write-Host ("Диск: {0}, {1:N1} GB, {2}, BusType={3}" -f $disk.FriendlyName, ($disk.Size/1GB), $disk.PartitionStyle, $disk.BusType) +Write-Host ("p1: offset={0} (LBA {1}), size={2:N1} MB" -f $p1.Offset, ($p1.Offset/512), ($p1.Size/1MB)) + +if ($p1.Offset -ne $P1Offset) { + Write-Warn ("p1 начинается с offset {0} (LBA {1}), а Ventoy ожидает 2048 (1 МБ)." -f $p1.Offset, ($p1.Offset/512)) + Write-Warn "Ventoy сможет загрузиться, но выведет предупреждение 'This is NOT a standard Ventoy device'." + Write-Warn "Правильнее пересобрать флешку с p1 на LBA 2048 (файлы проекта у вас есть в C:\PF\PF)." + if (-not $PSCmdlet.ShouldContinue("Продолжить несмотря на нестандартное начало p1?", "Нестандартная разметка")) { + throw "Отменено пользователем." + } +} + +$vol = Get-Volume -Partition $p1 -ErrorAction Stop +if (-not $vol.DriveLetter) { + throw "У раздела p1 нет буквы диска. Назначьте букву и повторите." +} +$p1Letter = $vol.DriveLetter + +$p1End = $p1.Offset + $p1.Size +$tailFree = $disk.Size - $p1End +if ($tailFree -lt 0) { throw "Некорректная геометрия: p1 выходит за пределы диска." } + +# p2 должен начинаться ровно в конце p1. Windows по умолчанию выравнивает +# новые разделы на 1 МБ, поэтому конец p1 тоже выравниваем на 1 МБ. +$align = 1MB +$maxP1End = [Math]::Floor(($disk.Size - $VentoySize) / $align) * $align +$targetP1End = [Math]::Min($p1End, $maxP1End) +$targetP1End = [Math]::Floor($targetP1End / $align) * $align +if ($targetP1End -le $p1.Offset) { throw "Недостаточно места: p1 нельзя уменьшить до 1-МБ границы." } + +$newP1Size = $targetP1End - $p1.Offset +$shrink = $p1.Size - $newP1Size +if ($shrink -lt 0) { throw "Внутренняя ошибка: p2 оказался бы внутри p1." } +if ($shrink -gt 0) { + if ($vol.SizeRemaining -lt $shrink) { + throw ("На p1 свободно {0:N1} MB, а для p2 нужно освободить {1:N1} MB. Освободите место на флешке." -f ($vol.SizeRemaining/1MB), ($shrink/1MB)) + } + if ($p1.Size -le $shrink) { throw "p1 слишком мал." } +} +$p2Offset = $targetP1End +$p2End = $p2Offset + $VentoySize +if ($p2End -gt $disk.Size) { throw "p2 не помещается на диск." } + +Write-Host ("План: p2 offset={0} (LBA {1}), size=32 MB, конец={2} (LBA {3})" -f $p2Offset, ($p2Offset/512), $p2End, ($p2End/512)) +if ($shrink -gt 0) { + Write-Host ("План: уменьшить p1 на {0:N1} MB (с {1:N1} MB до {2:N1} MB); начало p1 не меняется." -f ($shrink/1MB), ($p1.Size/1MB), ($newP1Size/1MB)) +} else { + Write-Host "План: p1 уже выровнен, p2 создаётся сразу после p1." +} + +if (-not $PSCmdlet.ShouldProcess("Диск $DiskNumber", "Уменьшить p1 при необходимости, создать p2 32MB, отформатировать FAT, скопировать VTOYEFI и core.img")) { + Write-Host "WhatIf: изменения не вносились." -ForegroundColor Yellow + return +} + +# --------------------------------------------------------------------------- +if ($shrink -gt 0) { + Write-Step "Уменьшение p1 на $([Math]::Round($shrink/1MB,1)) MB" + Write-Warn "Если p1 — FAT32/NTFS с данными у конца раздела, Windows может отказать. Файлы не удаляются, но сделайте бэкап." + Resize-Partition -DriveLetter $p1Letter -Size $newP1Size -ErrorAction Stop + Start-Sleep -Seconds 2 + Write-Ok "p1 уменьшен. Новый размер: $([Math]::Round($newP1Size/1MB,1)) MB" +} + +# --------------------------------------------------------------------------- +Write-Step "Создание p2 (32 MB) сразу после p1" +$p2 = New-Partition -DiskNumber $DiskNumber -Offset $p2Offset -Size $VentoySize -Alignment $align -AssignDriveLetter -ErrorAction Stop +Start-Sleep -Seconds 1 +$p2Vol = Get-Volume -Partition $p2 -ErrorAction Stop +Write-Ok "p2 создан: диск $($p2Vol.DriveLetter):, offset=$($p2.Offset), size=$($p2.Size)" + +Write-Step "Форматирование p2 в FAT (Ventoy допускает FAT12/16/32)" +Format-Volume -DriveLetter $p2Vol.DriveLetter -FileSystem FAT -NewFileSystemLabel $Label -Confirm:$false -Force -ErrorAction Stop +Start-Sleep -Seconds 1 + +# --------------------------------------------------------------------------- +Write-Step "Копирование VTOYEFI" +$p2Root = "$($p2Vol.DriveLetter):\" +Copy-Item -Path (Join-Path $vtoyefi '*') -Destination $p2Root -Recurse -Force -ErrorAction Stop +if (-not (Test-Path (Join-Path $p2Root 'ventoy\ventoy.cpio'))) { + throw "После копирования не найден $p2Root\ventoy\ventoy.cpio" +} +Write-Ok "VTOYEFI скопирован." + +Write-Step "Копирование core.img" +$coreDst = Join-Path $p2Root 'ventoy\core.img' +Copy-Item -Path $coreImg -Destination $coreDst -Force -ErrorAction Stop +Write-Ok "core.img -> $coreDst" + +# --------------------------------------------------------------------------- +Write-Step "Артефакты в папке проекта на p1" +$projFolder = Join-Path "$($p1Letter):\" 'efi\Paravis\Ventoy' +New-Item -ItemType Directory -Path $projFolder -Force | Out-Null +Copy-Item -Path $coreImg -Destination (Join-Path $projFolder 'core.img') -Force +if (Test-Path $grldr) { + Copy-Item -Path $grldr -Destination (Join-Path $projFolder 'grldr-ventoy') -Force + $g4d = Join-Path "$($p1Letter):\" 'efi\Paravis\Boot\g4d' + if (Test-Path $g4d) { + Copy-Item -Path $grldr -Destination (Join-Path $g4d 'Ventoy') -Force + Write-Ok "grldr-ventoy -> $g4d\Ventoy (для пункта Xorboot)" + } +} +Write-Ok "core.img и grldr-ventoy -> $projFolder" + +# --------------------------------------------------------------------------- +Write-Step "Проверка разметки" +$p1After = Get-Partition -DiskNumber $DiskNumber -PartitionNumber 1 +$p2After = Get-Partition -DiskNumber $DiskNumber -PartitionNumber 2 +$expectedP2Offset = $p1After.Offset + $p1After.Size +if ($p2After.Offset -ne $expectedP2Offset) { + Write-Warn ("p2 offset {0} != конец p1 {1}. Ventoy может отказаться." -f $p2After.Offset, $expectedP2Offset) +} else { + Write-Ok "p2 начинается ровно в конце p1." +} +if ($p2After.Size -ne $VentoySize) { + Write-Warn ("p2 size {0} != {1} (65536 секторов)." -f $p2After.Size, $VentoySize) +} else { + Write-Ok "p2 size = 32 MB (65536 секторов)." +} +if ($p1After.Offset -ne $P1Offset) { + Write-Warn ("p1 offset {0} != 1048576 (LBA 2048)." -f $p1After.Offset) +} else { + Write-Ok "p1 начинается с LBA 2048." +} + +Write-Step "Готово. Что делать дальше" +Write-Host @" +1) BIOS / grub4dos. Добавьте пункт в menu.lst (или загрузите файл \efi\Paravis\Boot\g4d\Ventoy): + + title Ventoy 1.1.18 (BIOS) + find --set-root /ventoy/core.img + kernel /ventoy/core.img + boot + +2) UEFI / Xorboot. Добавьте загрузку файла со второго раздела (p2): + + \EFI\BOOT\BOOTX64.EFI + + (Secure Boot: при первом запуске согласиться с MOK и выбрать + ENROLL_THIS_KEY_IN_MOKMANAGER.cer с p2.) + +3) ISO-файлы кладите на p1 (в любые папки). Ventoy ищет их на p1. + +4) Проверка разметки: + Get-Partition -DiskNumber $DiskNumber | Format-Table PartitionNumber,Offset,Size + Должно быть: p1 offset=1048576, p2 сразу после p1, p2 size=33554432. + +Откат: удалить p2 (Remove-Partition) и расширить p1 обратно: + Resize-Partition -DriveLetter $p1Letter -Size <старый_размер_p1> +"@ -ForegroundColor Gray + +Write-Ok "MBR-код не изменялся. Таблица разделов обновлена штатно." diff --git a/build-scripts/layout/relayout-usb.ps1 b/build-scripts/layout/relayout-usb.ps1 new file mode 100644 index 0000000..15ad9a4 --- /dev/null +++ b/build-scripts/layout/relayout-usb.ps1 @@ -0,0 +1,365 @@ +#Requires -RunAsAdministrator +<# +.SYNOPSIS + Пересоздаёт разметку USB-диска под кастомный Ventoy: + p1 = загрузочный FAT32 (PARAVIS), p2 = VTOYEFI 32 МБ, p3 = данные NTFS (DATA). + +.DESCRIPTION + Порядок работы: + 1. проверяет диск/разделы/источники; + 2. копирует проект с загрузочного раздела в E:\_usb_stage; + 3. сохраняет первые 64 КиБ диска (MBR Xorboot + gap); + 4. удаляет разделы 3,2,1 и создаёт новые (p1 14 ГиБ FAT32 active, + p2 32 МБ FAT VTOYEFI, p3 остаток NTFS DATA); + 5. возвращает на место байты 0..445 MBR (код Xorboot + подпись диска), + таблица разделов остаётся новой; проверяет сектора 1..62; + 6. возвращает проект на p1, VTOYEFI на p2, ISO с E:\Downloads\ISO на p3, + создаёт \ISO\Ventoy (маркер NOT.DEL, README, theme). + + Разметка НЕ стирается через diskpart clean — иначе пропал бы код Xorboot + в первых 63 секторах. + +.PARAMETER BootSizeMB + Размер p1 в МБ. По умолчанию 14336 (14 ГиБ). + +.PARAMETER TailMB + Неразмеченный хвост в МБ. По умолчанию 50. + +.PARAMETER StageDir + Куда временно копируется проект. По умолчанию E:\_usb_stage. + +.PARAMETER IsoSource + Откуда берутся ISO. По умолчанию E:\Downloads\ISO. + +.PARAMETER VentoyDir + Папка с vtoyefi и core-custom-layout-1.1.18.img. По умолчанию C:\PF\Ventoy. + +.PARAMETER SkipStage + Не копировать проект заново (уже лежит в StageDir). + +.EXAMPLE + .\relayout-usb.ps1 -WhatIf + .\relayout-usb.ps1 +#> +[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')] +param( + [int]$BootSizeMB = 14336, + [int]$TailMB = 50, + [int]$DiskNumber = 0, + [string]$StageDir = 'E:\_usb_stage', + [string]$IsoSource = 'E:\Downloads\ISO', + [string]$VentoyDir = 'C:\PF\Ventoy', + [string]$BackupDir = 'C:\PF\Ventoy\backup', + [switch]$SkipStage, + [switch]$Force +) + +$ErrorActionPreference = 'Stop' + +function Write-Step([string]$t) { Write-Host "`n=== $t ===" -ForegroundColor Cyan } +function Write-Ok([string]$t) { Write-Host "OK: $t" -ForegroundColor Green } +function Write-Warn([string]$t) { Write-Host "WARN: $t" -ForegroundColor Yellow } + +function Invoke-Diskpart([string]$script) { + $tmp = Join-Path $env:TEMP ("dp_{0}.txt" -f ([guid]::NewGuid().ToString('N'))) + $script | Set-Content -Path $tmp -Encoding ASCII + $out = & diskpart.exe /s $tmp 2>&1 + Remove-Item $tmp -Force -ErrorAction SilentlyContinue + $out | ForEach-Object { " $_" } + if ($LASTEXITCODE -ne 0) { throw "diskpart завершился с кодом $LASTEXITCODE" } +} + +function Invoke-Robocopy([string]$src, [string]$dst, [string[]]$extra = @()) { + $roboArgs = @($src, $dst, '/E', '/COPY:DAT', '/R:1', '/W:1', '/MT:8', '/NFL', '/NDL', '/NJH', '/NJS', '/NP') + $extra + $out = & robocopy.exe @roboArgs 2>&1 + $code = $LASTEXITCODE + if ($code -ge 8) { + $out | Select-Object -Last 30 | ForEach-Object { " $_" } + throw "robocopy вернул код $code ($src -> $dst)" + } + return $code +} + +function Open-Physical([int]$num) { + for ($i = 0; $i -lt 6; $i++) { + try { + return [IO.FileStream]::new("\\.\PhysicalDrive$num", [IO.FileMode]::Open, [IO.FileAccess]::ReadWrite, [IO.FileShare]::ReadWrite, 4096, [IO.FileOptions]::WriteThrough) + } catch { + Start-Sleep -Seconds 2 + } + } + throw "Не удалось открыть \\.\PhysicalDrive$num (занят другим процессом?)." +} + +function Get-DiskVolumeLabel([int]$num, [string]$label) { + foreach ($p in (Get-Partition -DiskNumber $num -ErrorAction SilentlyContinue)) { + $v = Get-Volume -Partition $p -ErrorAction SilentlyContinue + if ($v -and $v.FileSystemLabel -eq $label) { return $v } + } + return $null +} + +# ------------------------------------------------------------------ 1. диск +Write-Step "Поиск диска" +if ($DiskNumber -gt 0) { + $diskNum = $DiskNumber + Write-Host (" диск задан явно: {0}" -f $diskNum) +} else { + $efiVol = Get-Volume | Where-Object { $_.FileSystemLabel -eq 'VTOYEFI' } | Select-Object -First 1 + if ($efiVol -and $efiVol.DriveLetter) { + $diskNum = (Get-Partition -DriveLetter $efiVol.DriveLetter).DiskNumber + } else { + $cand = @(Get-Disk | Where-Object { $_.BusType -eq 'USB' -and $_.PartitionStyle -eq 'MBR' -and $_.Size -eq 512110190592 }) + if ($cand.Count -ne 1) { throw "Не удалось однозначно определить диск. Укажите -DiskNumber (см. Get-Disk)." } + $diskNum = $cand[0].Number + Write-Warn "Метка VTOYEFI не найдена, диск выбран по размеру/типу." + } +} +$disk = Get-Disk -Number $diskNum + +$projVol = Get-DiskVolumeLabel $diskNum 'PARAVIS' +$dataVol = Get-DiskVolumeLabel $diskNum 'DATA' +$efiVol = Get-DiskVolumeLabel $diskNum 'VTOYEFI' +if (-not $SkipStage) { + if (-not $projVol -or -not $projVol.DriveLetter) { throw "Не найден раздел PARAVIS." } + if (-not $dataVol -or -not $dataVol.DriveLetter) { throw "Не найден раздел DATA." } +} + +Write-Host (" Диск {0}: {1}, {2:N1} ГиБ, {3}, USB={4}" -f $diskNum, $disk.FriendlyName, ($disk.Size/1GB), $disk.PartitionStyle, $disk.BusType) +Write-Host (" PARAVIS = {0} DATA = {1} VTOYEFI = {2}" -f $(if($projVol){$projVol.DriveLetter}else{'-'}), $(if($dataVol){$dataVol.DriveLetter}else{'-'}), $(if($efiVol){$efiVol.DriveLetter}else{'-'})) + +if ($disk.PartitionStyle -ne 'MBR') { throw "Ожидалась MBR-разметка, найдена $($disk.PartitionStyle)." } +if (-not $Force -and $disk.Size -ne 512110190592) { + throw ("Неожиданный размер диска {0} (ожидался 512110190592). Если уверены — -Force." -f $disk.Size) +} + +$parts = Get-Partition -DiskNumber $diskNum | Sort-Object Offset +if (-not $SkipStage -and $parts.Count -ne 3) { throw "Ожидалось 3 раздела, найдено $($parts.Count)." } + +# --------------------------------------------------------------- 2. источники +Write-Step "Проверка источников" +if (-not (Test-Path $IsoSource)) { throw "Нет папки с ISO: $IsoSource" } +$isos = Get-ChildItem $IsoSource -File -Filter *.iso +if ($isos.Count -eq 0) { throw "В $IsoSource нет ISO." } +$isoBytes = ($isos | Measure-Object Length -Sum).Sum +Write-Host (" ISO: {0} шт., {1:N2} ГБ" -f $isos.Count, ($isoBytes/1GB)) + +$vtoyefi = Join-Path $VentoyDir 'vtoyefi' +$coreImg = Join-Path $VentoyDir 'core-custom-layout-1.1.18.img' +if (-not (Test-Path (Join-Path $vtoyefi 'ventoy\ventoy.cpio'))) { throw "Нет VTOYEFI: $vtoyefi" } +if (-not (Test-Path $coreImg)) { throw "Нет core: $coreImg" } +if (-not (Select-String -Path (Join-Path $vtoyefi 'grub\grub.cfg') -Pattern 'VTOY-CUSTOM-LAYOUT' -Quiet)) { + throw "grub.cfg в vtoyefi не содержит кастомный поиск раздела (VTOY-CUSTOM-LAYOUT)." +} + +# ------------------------------------------------------------------ 3. stage +$stageProj = Join-Path $StageDir 'PARAVIS' +$stageIsoVentoy = Join-Path $StageDir 'ISO_Ventoy' + +$projSrcSize = $null +if ($projVol -and $projVol.DriveLetter) { + $projSrcSize = (Get-ChildItem ("{0}:\" -f $projVol.DriveLetter) -Recurse -File -Force -ErrorAction SilentlyContinue | + Where-Object { $_.FullName -notmatch '\\System Volume Information\\' -and $_.FullName -notmatch '\\\$RECYCLE\.BIN\\' -and $_.Name -ne 'ventoy.log' } | + Measure-Object Length -Sum) +} + +if (-not $SkipStage -and (Test-Path $stageProj)) { + $existing = Get-ChildItem $stageProj -Recurse -File -Force -ErrorAction SilentlyContinue | Measure-Object Length -Sum + if ($null -eq $projSrcSize -or $existing.Sum -eq $projSrcSize.Sum) { + Write-Step "Staging уже готов (размер совпадает) — копирование пропущено" + $SkipStage = $true + } +} + +if ($SkipStage) { + Write-Step "Staging пропущен (-SkipStage)" +} else { + if (-not $projVol -or -not $projVol.DriveLetter) { throw "Нет раздела PARAVIS для staging (укажите -SkipStage, если staging уже готов)." } + $stageRoot = [IO.Path]::GetPathRoot($StageDir).TrimEnd('\').TrimEnd(':') + $free = (Get-Volume | Where-Object { $_.DriveLetter -and ([string]$_.DriveLetter) -eq $stageRoot } | Select-Object -First 1).SizeRemaining + if ($free -lt ($projSrcSize.Sum + 2GB)) { + throw ("На {0} недостаточно места: нужно {1:N1} ГБ, свободно {2:N1} ГБ." -f $stageRoot, (($projSrcSize.Sum+2GB)/1GB), ($free/1GB)) + } + + Write-Step "Копирование загрузочного раздела в staging" + Write-Host (" {0:N2} ГБ -> {1}" -f ($projSrcSize.Sum/1GB), $stageProj) + if (Test-Path $stageProj) { Remove-Item $stageProj -Recurse -Force } + Invoke-Robocopy ("{0}:\" -f $projVol.DriveLetter) $stageProj @('/XD', 'System Volume Information', '$RECYCLE.BIN', '/XF', 'ventoy.log') | Out-Null + + $stageSize = (Get-ChildItem $stageProj -Recurse -File -Force | Measure-Object Length -Sum) + Write-Host (" скопировано: {0:N2} ГБ, {1} файлов" -f ($stageSize.Sum/1GB), $stageSize.Count) + if ($stageSize.Sum -ne $projSrcSize.Sum) { + throw ("Размер копии не совпал: {0} != {1}. Разметка НЕ менялась." -f $stageSize.Sum, $projSrcSize.Sum) + } + Write-Ok "Проект скопирован и сверен." + + if (Test-Path ("{0}:\ISO\Ventoy" -f $dataVol.DriveLetter)) { + if (Test-Path $stageIsoVentoy) { Remove-Item $stageIsoVentoy -Recurse -Force } + Invoke-Robocopy ("{0}:\ISO\Ventoy" -f $dataVol.DriveLetter) $stageIsoVentoy | Out-Null + Write-Ok "\ISO\Ventoy сохранён в staging." + } +} + +# ------------------------------------------------------------- 4. bkp + wipe +if (-not $PSCmdlet.ShouldProcess("PhysicalDrive$diskNum", "Переразметить: p1 ${BootSizeMB}MB FAT32, p2 32MB FAT VTOYEFI, p3 NTFS DATA")) { + Write-Warn "WhatIf: изменения не вносились." + return +} + +New-Item -ItemType Directory -Force -Path $BackupDir | Out-Null +$mbrFile = Join-Path $BackupDir ("usb-mbr-{0:yyyyMMdd-HHmmss}.bin" -f (Get-Date)) + +Write-Step "Сохранение первых 64 КиБ диска" +$head = New-Object byte[] 65536 +$fs = Open-Physical $diskNum +try { + $read = $fs.Read($head, 0, $head.Length) + if ($read -ne $head.Length) { throw "Прочитано $read байт вместо 65536." } +} finally { try { $fs.Close() } catch { } } +[IO.File]::WriteAllBytes($mbrFile, $head) +Write-Ok ("MBR/gap сохранены: {0}" -f $mbrFile) + +Write-Step "Снятие букв (best effort)" +foreach ($l in @($projVol.DriveLetter, $dataVol.DriveLetter, $efiVol.DriveLetter)) { + if ($l) { & mountvol.exe ("{0}:" -f $l) /p 2>$null | Out-Null } +} + +Write-Step "Переразметка (diskpart)" +$totalMB = [math]::Floor($disk.Size / 1MB) +$p3MB = $totalMB - $BootSizeMB - 32 - $TailMB +if ($p3MB -lt 1024) { throw "Слишком маленький диск для выбранных размеров." } +$dp = @" +select disk $diskNum +select partition 3 +delete partition override +select partition 2 +delete partition override +select partition 1 +delete partition override +create partition primary size=$BootSizeMB +format fs=fat32 quick label=PARAVIS +active +assign +create partition primary size=32 +format fs=fat quick label=VTOYEFI +assign +create partition primary size=$p3MB +format fs=ntfs quick label=DATA +assign +exit +"@ +Invoke-Diskpart $dp +Write-Ok "Разделы созданы и отформатированы." + +Write-Step "Возврат кода MBR Xorboot (байты 0..445)" +$fs = Open-Physical $diskNum +try { + $fs.Position = 0 + $fs.Write($head, 0, 446) + $fs.Flush() + + # сектора 1..62 (gap Xorboot) не должны были измениться + $fs.Position = 512 + $gap = New-Object byte[] 31744 + $n = $fs.Read($gap, 0, $gap.Length) + $gapOk = $true + for ($i = 0; $i -lt $n; $i++) { if ($gap[$i] -ne $head[512 + $i]) { $gapOk = $false; break } } + if (-not $gapOk) { + Write-Warn "Gap-сектора изменились — восстанавливаю сектора 1..62." + $fs.Position = 512 + $fs.Write($head, 512, 31744) + $fs.Flush() + } else { + Write-Ok "Gap-сектора (1..62) не тронуты." + } +} finally { + # после записи в сектор 0 Windows инвалидирует хэндл — ошибка Close() не критична + try { $fs.Close() } catch { } +} + +Write-Step "Обновление таблицы устройств" +Update-HostStorageCache +Start-Sleep -Seconds 3 +$deadline = (Get-Date).AddSeconds(60) +do { + Update-HostStorageCache + $v1 = Get-DiskVolumeLabel $diskNum 'PARAVIS' + $v2 = Get-DiskVolumeLabel $diskNum 'VTOYEFI' + $v3 = Get-DiskVolumeLabel $diskNum 'DATA' + if ($v1 -and $v2 -and $v3) { break } + Start-Sleep -Seconds 2 +} while ((Get-Date) -lt $deadline) +if (-not ($v1 -and $v2 -and $v3)) { throw "Новые разделы не появились в системе. Проверьте 'Управление дисками'." } + +foreach ($p in (Get-Partition -DiskNumber $diskNum | Where-Object { -not $_.DriveLetter })) { + Add-PartitionAccessPath -DiskNumber $diskNum -PartitionNumber $p.PartitionNumber -AssignDriveLetter +} +Start-Sleep -Seconds 1 +Update-HostStorageCache + +$pProj = Get-DiskVolumeLabel $diskNum 'PARAVIS' +$pEfi = Get-DiskVolumeLabel $diskNum 'VTOYEFI' +$pData = Get-DiskVolumeLabel $diskNum 'DATA' +if (-not $pProj.DriveLetter -or -not $pEfi.DriveLetter -or -not $pData.DriveLetter) { + throw "Не всем новым разделам назначены буквы. Откройте «Управление дисками» и назначьте вручную, затем запустите скрипт с -SkipStage." +} +Write-Ok ("новые буквы: PARAVIS={0}: VTOYEFI={1}: DATA={2}:" -f $pProj.DriveLetter, $pEfi.DriveLetter, $pData.DriveLetter) + +$geo = Get-Partition -DiskNumber $diskNum | Sort-Object Offset +$geo | Format-Table PartitionNumber, DriveLetter, Offset, Size, Type, IsActive -AutoSize | Out-String | Write-Host +if ($geo[0].Offset -ne 1048576) { throw "p1 начинается не с 1 МиБ (Offset=$($geo[0].Offset)) — разметка неверная." } +if ($geo[0].Size -ne ($BootSizeMB * 1MB)) { throw "p1 неверного размера: $($geo[0].Size)." } +if ($geo[1].Offset -ne ($geo[0].Offset + $geo[0].Size)) { throw "p2 идёт не сразу за p1." } +if ($geo[1].Size -ne 33554432) { throw "p2 не 32 МБ: $($geo[1].Size)." } +if (-not $geo[0].IsActive) { throw "p1 не помечен active." } +Write-Ok "Геометрия разделов корректна." + +# --------------------------------------------------------------- 5. restore +Write-Step "Возврат проекта на p1" +Invoke-Robocopy $stageProj ("{0}:\" -f $pProj.DriveLetter) | Out-Null +Write-Ok "Проект восстановлен." + +Write-Step "VTOYEFI на p2" +Invoke-Robocopy $vtoyefi ("{0}:\" -f $pEfi.DriveLetter) | Out-Null +Copy-Item $coreImg ("{0}:\ventoy\core.img" -f $pEfi.DriveLetter) -Force +if (-not (Select-String -Path ("{0}:\grub\grub.cfg" -f $pEfi.DriveLetter) -Pattern 'VTOY-CUSTOM-LAYOUT' -Quiet)) { + throw "На p2 лежит grub.cfg без VTOY-CUSTOM-LAYOUT." +} +Write-Ok ("VTOYEFI + core ({0} Б) на месте." -f (Get-Item $coreImg).Length) + +Write-Step "ISO и \ISO\Ventoy на p3" +Invoke-Robocopy $IsoSource ("{0}:\ISO" -f $pData.DriveLetter) | Out-Null +if (Test-Path $stageIsoVentoy) { + Invoke-Robocopy $stageIsoVentoy ("{0}:\ISO\Ventoy" -f $pData.DriveLetter) | Out-Null +} else { + New-Item -ItemType Directory -Force -Path ("{0}:\ISO\Ventoy\theme" -f $pData.DriveLetter) | Out-Null + [IO.File]::WriteAllText(("{0}:\ISO\Ventoy\NOT.DEL" -f $pData.DriveLetter), "Ventoy data partition marker`r`nDo not delete this file.`r`n") +} +if (-not (Test-Path ("{0}:\ISO\Ventoy\NOT.DEL" -f $pData.DriveLetter))) { throw "Маркер NOT.DEL не создан." } +Write-Ok "ISO и маркер на месте." + +# ---------------------------------------------------------------- 6. verify +Write-Step "Проверка результата" +$isoDst = Get-ChildItem ("{0}:\ISO" -f $pData.DriveLetter) -File -Filter *.iso +$isoDstBytes = ($isoDst | Measure-Object Length -Sum).Sum +$projDst = Get-ChildItem ("{0}:\" -f $pProj.DriveLetter) -Recurse -File -Force -ErrorAction SilentlyContinue | + Where-Object { $_.FullName -notmatch '\\System Volume Information\\' -and $_.FullName -notmatch '\\\$RECYCLE\.BIN\\' } | + Measure-Object Length -Sum + +" ISO на p3: {0} шт., {1:N2} ГБ (источник {2:N2} ГБ)" -f $isoDst.Count, ($isoDstBytes/1GB), ($isoBytes/1GB) +if ($projSrcSize) { + " проект на p1: {0} файлов, {1:N2} ГБ (источник {2:N2} ГБ)" -f $projDst.Count, ($projDst.Sum/1GB), ($projSrcSize.Sum/1GB) +} else { + " проект на p1: {0} файлов, {1:N2} ГБ" -f $projDst.Count, ($projDst.Sum/1GB) +} +" core.img: {0} Б" -f (Get-Item ("{0}:\ventoy\core.img" -f $pEfi.DriveLetter)).Length + +if ($isoDst.Count -ne $isos.Count -or $isoDstBytes -ne $isoBytes) { Write-Warn "Количество/размер ISO не совпал с источником!" } +if ($projSrcSize -and $projDst.Sum -ne $projSrcSize.Sum) { Write-Warn "Размер проекта не совпал с источником!" } + +Write-Step "Готово" +Write-Host "Дальше:" -ForegroundColor Green +Write-Host " 1. Проверить загрузку Xorboot -> Ventoy." +Write-Host " 2. Если Xorboot не грузится — запустить Change_bootLoader.exe с загрузочного раздела (Install XorBoot)." +Write-Host " 3. Staging можно удалить: $StageDir" +Write-Host (" Бэкап MBR/gap: {0}" -f $mbrFile) diff --git a/build-scripts/layout/restore-ventoy-p2.ps1 b/build-scripts/layout/restore-ventoy-p2.ps1 new file mode 100644 index 0000000..f8c9ff3 --- /dev/null +++ b/build-scripts/layout/restore-ventoy-p2.ps1 @@ -0,0 +1,120 @@ +#Requires -RunAsAdministrator +<# +.SYNOPSIS + Восстанавливает VTOYEFI (p2) из C:\PF\Ventoy без изменения разделов и MBR. + +.DESCRIPTION + Копирует полный VTOYEFI 1.1.18 (с кастомным grub.cfg: раздел с ISO + определяется по маркеру /ISO/Ventoy/NOT.DEL) и патченный core.img + (409 448 Б: MBR check и geometry check отключены, номер раздела данных + берётся из VTOY_DATA_PART_IDX). Полезно, если p2 очищен или нужно + вернуть рабочую конфигурацию после экспериментов. + +.PARAMETER DriveLetter + Буква раздела VTOYEFI. По умолчанию G. + +.PARAMETER SourceDir + Папка C:\PF\Ventoy. + +.PARAMETER CoreImg + Патченный core. По умолчанию core-custom-layout-1.1.18.img. + +.PARAMETER Force + Не проверять метку VTOYEFI. +#> +[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')] +param( + [char]$DriveLetter = 'G', + [string]$SourceDir = 'C:\PF\Ventoy', + [string]$CoreImg = '', + [switch]$Force +) + +$ErrorActionPreference = 'Stop' + +function Write-Step([string]$Text) { Write-Host "`n=== $Text ===" -ForegroundColor Cyan } +function Write-Warn([string]$Text) { Write-Host "WARN: $Text" -ForegroundColor Yellow } +function Write-Ok([string]$Text) { Write-Host "OK: $Text" -ForegroundColor Green } + +$vtoyefi = Join-Path $SourceDir 'vtoyefi' +if (-not $CoreImg) { $CoreImg = Join-Path $SourceDir 'core-custom-layout-1.1.18.img' } + +if (-not (Test-Path (Join-Path $vtoyefi 'ventoy\ventoy.cpio'))) { throw "Не найден VTOYEFI: $vtoyefi" } +if (-not (Test-Path $CoreImg)) { throw "Не найден core: $CoreImg" } + +Write-Step "Проверка раздела ${DriveLetter}:" +try { + $vol = Get-Volume -DriveLetter $DriveLetter -ErrorAction Stop +} catch { + throw "Раздел ${DriveLetter}: не найден. Если диск offline/readonly — отключите USB от VMware или выключите VM, затем повторите." +} +if (-not $Force -and $vol.FileSystemLabel -ne 'VTOYEFI') { + throw "Метка раздела '$($vol.FileSystemLabel)', а не VTOYEFI. Если уверены — используйте -Force." +} +if ($vol.FileSystem -notmatch 'FAT') { throw "Раздел ${DriveLetter}: не FAT." } + +$free = (Get-ChildItem -Recurse -File $vtoyefi | Measure-Object Length -Sum).Sum + (Get-Item $CoreImg).Length +Write-Host ("Нужно ~{0:N1} МБ, свободно {1:N1} МБ" -f ($free/1MB), ($vol.SizeRemaining/1MB)) +if ($vol.SizeRemaining -lt $free) { throw "На разделе недостаточно места." } + +if (-not $PSCmdlet.ShouldProcess("${DriveLetter}:", "Очистить VTOYEFI и скопировать Ventoy 1.1.18 + патченный core")) { + Write-Host "WhatIf: изменения не вносились." -ForegroundColor Yellow + return +} + +Write-Step "Очистка ${DriveLetter}:" +Get-ChildItem -Force "${DriveLetter}:\" | Remove-Item -Recurse -Force -ErrorAction Stop +Write-Ok "Очищено." + +Write-Step "Копирование VTOYEFI 1.1.18" +Copy-Item -Path (Join-Path $vtoyefi '*') -Destination "${DriveLetter}:\" -Recurse -Force -ErrorAction Stop +if (-not (Test-Path "${DriveLetter}:\ventoy\ventoy.cpio")) { throw "Копирование VTOYEFI не удалось." } +Write-Ok "VTOYEFI скопирован." + +Write-Step "Копирование патченного core" +Copy-Item -Path $CoreImg -Destination "${DriveLetter}:\ventoy\core.img" -Force -ErrorAction Stop +Write-Ok ("core.img -> {0}:\ventoy\core.img ({1} Б)" -f $DriveLetter, (Get-Item $CoreImg).Length) + +Write-Step "Проверка кастомного grub.cfg" +$cfgPath = "${DriveLetter}:\grub\grub.cfg" +if ((Get-Content -Path $cfgPath -Raw -ErrorAction SilentlyContinue) -match 'VTOY-CUSTOM-LAYOUT') { + Write-Ok "grub.cfg: поиск раздела ISO по маркеру /ISO/Ventoy/NOT.DEL включён." +} else { + Write-Warn "grub.cfg без кастомного поиска раздела — Ventoy будет искать ISO на p1." +} +if (-not (Test-Path "${DriveLetter}:\grub\grub.cfg.orig")) { + Write-Warn "Резервная копия grub.cfg.orig на разделе отсутствует (не критично)." +} + +Write-Step "Проверка патча vtoyjump (MBR check в PE)" +function Test-ByteAt([string]$Path, [long]$Offset, [byte[]]$Expected) { + if (-not (Test-Path $Path)) { return $false } + $fs = [IO.File]::OpenRead($Path) + try { + $fs.Position = $Offset + $buf = New-Object byte[] $Expected.Length + $n = $fs.Read($buf, 0, $buf.Length) + } finally { $fs.Close() } + if ($n -ne $Expected.Length) { return $false } + for ($i = 0; $i -lt $Expected.Length; $i++) { if ($buf[$i] -ne $Expected[$i]) { return $false } } + return $true +} + +$jumpChecks = @( + @{ File = 'vtoyjump64.exe'; Offset = 0x810E; Bytes = [byte[]](0xB3, 0x01, 0x90); Name = 'mov $1,%bl; nop' }, + @{ File = 'vtoyjump32.exe'; Offset = 0x6FEB; Bytes = [byte[]](0x90, 0x90); Name = 'nop nop' }, + @{ File = 'vtoyjump32.exe'; Offset = 0x6FF3; Bytes = [byte[]](0x90, 0x90, 0x90, 0x90, 0x90, 0x90); Name = 'nop x6' } +) +foreach ($c in $jumpChecks) { + $path = Join-Path "${DriveLetter}:\ventoy" $c.File + if (Test-ByteAt $path $c.Offset $c.Bytes) { + Write-Ok ("{0} @0x{1:X}: патч на месте ({2})" -f $c.File, $c.Offset, $c.Name) + } else { + Write-Warn ("{0} @0x{1:X}: патч MBR check НЕ применён — ISO в PE не смонтируется!" -f $c.File, $c.Offset) + } +} + +Write-Step "Готово" +Get-Item "${DriveLetter}:\grub\grub.cfg", "${DriveLetter}:\grub\fonts\unicode.pf2", "${DriveLetter}:\ventoy\core.img", "${DriveLetter}:\EFI\BOOT\BOOTX64.EFI" | + Select-Object FullName, Length | Format-Table -AutoSize +Write-Host "Теперь можно загружать Xorboot -> Ventoy (1.1.18, MBR check отключён в core и в vtoyjump)." -ForegroundColor Green diff --git a/build-scripts/layout/stage-all.sh b/build-scripts/layout/stage-all.sh new file mode 100644 index 0000000..46e2004 --- /dev/null +++ b/build-scripts/layout/stage-all.sh @@ -0,0 +1,26 @@ +#!/bin/bash +# Build memtest86+ (if needed), sign it, generate menus — everything on D:. +set -e +K=/path/to/pf/Ventoy/keys +D=/path/to/pf/ParavisGrub +A=$D/apps +mkdir -p "$A" "$D/menu" + +if [ ! -f /tmp/mt86p/build/x86_64/mt86plus ]; then + echo "=== cloning + building memtest86+" + rm -rf /tmp/mt86p + git clone --depth 1 -q https://github.com/memtest86plus/memtest86plus.git /tmp/mt86p + ( cd /tmp/mt86p/build/x86_64 && make -j8 >/tmp/mt86_build.log 2>&1 ) || { tail -20 /tmp/mt86_build.log; exit 1; } +fi + +MT=/tmp/mt86p/build/x86_64/mt86plus +echo "=== memtest86+ : $(stat -c %s "$MT") bytes" +cp -f "$MT" "$A/_mt.efi" +sbsign --key "$K/ventoy.key" --cert "$K/ventoy.crt" --output "$A/memtest86p.efi" "$A/_mt.efi" >/dev/null +sbverify --cert "$K/ventoy.crt" "$A/memtest86p.efi" >/dev/null && echo " signed OK" +rm -f "$A/_mt.efi" +ls -l "$A/memtest86p.efi" + +echo "=== generating menus" +python3 "$D/gen_menu.py" "$D" +ls -l "$D" "$D/menu" diff --git a/build-scripts/layout/stage-menu.sh b/build-scripts/layout/stage-menu.sh new file mode 100644 index 0000000..e9044fa --- /dev/null +++ b/build-scripts/layout/stage-menu.sh @@ -0,0 +1,21 @@ +#!/bin/bash +set -e +K=/path/to/pf/Ventoy/keys +D=/path/to/pf/ParavisGrub +A=$D/apps +mkdir -p "$A" "$D/menu" + +echo "=== memtest86+ 9.10 -> signed (staged on D:)" +if [ -f /tmp/mt86p/build/x86_64/mt86plus ]; then + cp -f /tmp/mt86p/build/x86_64/mt86plus "$A/mt86plus.raw.efi" + sbsign --key "$K/ventoy.key" --cert "$K/ventoy.crt" --output "$A/memtest86p.efi" "$A/mt86plus.raw.efi" + sbverify --cert "$K/ventoy.crt" "$A/memtest86p.efi" + rm -f "$A/mt86plus.raw.efi" + ls -l "$A/memtest86p.efi" +else + echo " !! build missing in /tmp (wsl restarted?)" +fi + +echo "=== generate menu files" +python3 "$D/gen_menu.py" "$D" +ls -l "$D" "$D/menu" "$A" diff --git a/build-scripts/layout/stage-theme.sh b/build-scripts/layout/stage-theme.sh new file mode 100644 index 0000000..96ec05b --- /dev/null +++ b/build-scripts/layout/stage-theme.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -e +python3 /path/to/pf/ParavisGrub/build_all.py +echo "=== staged:" +ls -l /path/to/pf/ParavisGrub/theme /path/to/pf/ParavisGrub/theme/main +grep -n 'loadfont\|set theme\|set timeout\|set default' /path/to/pf/ParavisGrub/grub.cfg | head diff --git a/build-scripts/layout/switch-uefi-loader.ps1 b/build-scripts/layout/switch-uefi-loader.ps1 new file mode 100644 index 0000000..417f7f4 --- /dev/null +++ b/build-scripts/layout/switch-uefi-loader.ps1 @@ -0,0 +1,44 @@ +# Install the Paravis GRUB2 UEFI loader as the active first/second stage on p1. +# EFI\BOOT\bootx64.efi = shim (MS), EFI\BOOT\fbx64.efi = our signed GRUB2 (+.sbat) +param( + [ValidateSet('grub2','xorboot','ventoy')] + [string]$Loader = 'grub2' +) + +$p1 = 'F:' +$boot = "$p1\EFI\BOOT" +$bkp = 'C:\PF\Ventoy\backup\uefi-loaders' +New-Item -ItemType Directory -Force $bkp | Out-Null + +function Save-Current([string]$tag) { + Get-ChildItem $boot -File -ErrorAction SilentlyContinue | Where-Object { $_.Extension -eq '.efi' } | ForEach-Object { + Copy-Item $_.FullName (Join-Path $bkp "$tag-$($_.Name)") -Force + } +} + +Save-Current 'current' + +switch ($Loader) { + 'grub2' { + Copy-Item 'G:\EFI\BOOT\BOOTX64.EFI' "$boot\bootx64.efi" -Force + Copy-Item 'C:\PF\ParavisGrub\grubx64.efi' "$boot\fbx64.efi" -Force + Copy-Item 'G:\EFI\BOOT\mmx64.efi' "$boot\mmx64.efi" -Force + Copy-Item 'C:\PF\ParavisGrub\grub.cfg' "$p1\efi\Paravis\Boot\grub2\grub.cfg" -Force + } + 'xorboot' { + Copy-Item 'C:\PF\Ventoy\backup\xorboot-uefi\bootx64.efi.orig' "$boot\bootx64.efi" -Force + foreach ($f in 'fbx64.efi','mmx64.efi') { + if (Test-Path "$boot\$f") { Remove-Item "$boot\$f" -Force } + } + } + 'ventoy' { + # firmware entry should point at p2 (VTOYEFI); nothing to do on p1 + Write-Host 'Ventoy is booted directly from p2 (VTOYEFI) - select that entry in firmware' + } +} + +Get-ChildItem $boot -File -Filter '*.efi' | Sort-Object Name | ForEach-Object { + $s = Get-AuthenticodeSignature $_.FullName + $subj = if ($s.SignerCertificate) { ($s.SignerCertificate.Subject -replace '^CN=([^,]+).*', '$1') } else { '-' } + "{0,-14} {1,9} {2,-12} {3}" -f $_.Name, $_.Length, $s.Status, $subj +} diff --git a/build-scripts/theme-tools/crop-text.sh b/build-scripts/theme-tools/crop-text.sh new file mode 100644 index 0000000..b713f90 --- /dev/null +++ b/build-scripts/theme-tools/crop-text.sh @@ -0,0 +1,11 @@ +#!/bin/bash +python3 - <<'EOF' +from PIL import Image +im = Image.open('/mnt/f/efi/Paravis/Boot/xor/Main1.bmp').convert('RGB') +crop = im.crop((40, 470, 480, 510)) +crop = crop.resize((crop.width*3, crop.height*3), Image.LANCZOS) +crop.save('/path/to/pf/KRD/crop-kaspersky.png') +crop2 = im.crop((40, 412, 480, 452)).resize((440*3, 40*3), Image.LANCZOS) +crop2.save('/path/to/pf/KRD/crop-gfm.png') +print('ok') +EOF diff --git a/build-scripts/theme-tools/font-check-cyr.sh b/build-scripts/theme-tools/font-check-cyr.sh new file mode 100644 index 0000000..9ef79c0 --- /dev/null +++ b/build-scripts/theme-tools/font-check-cyr.sh @@ -0,0 +1,49 @@ +#!/bin/bash +python3 - <<'EOF' +import numpy as np +from PIL import Image, ImageDraw, ImageFont + +bmp = Image.open('/mnt/f/efi/Paravis/Boot/xor/Main1.bmp').convert('L') + +def cmp(cropbox, text, path, size, stroke=0): + crop = bmp.crop(cropbox) + A = np.array(crop) < 128 + ys, xs = np.where(A) + T = A[ys.min():ys.max()+1, xs.min():xs.max()+1] + f = ImageFont.truetype(path, size) + img = Image.new('L', (800, 100), 255) + ImageDraw.Draw(img).text((20, 20), text, font=f, fill=0, stroke_width=stroke, stroke_fill=0) + m = np.array(img) < 128 + ys2, xs2 = np.where(m) + B = m[ys2.min():ys2.max()+1, xs2.min():xs2.max()+1] + ha, wa = T.shape; hb, wb = B.shape; best = 0 + for dy in range(-4, 5): + for dx in range(-5, 6): + y0 = max(0, dy); x0 = max(0, dx) + y1 = min(ha, hb+dy); x1 = min(wa, wb+dx) + if y1 <= y0 or x1 <= x0: continue + s1 = T[y0:y1, x0:x1]; s2 = B[y0-dy:y1-dy, x0-dx:x1-dx] + u = np.logical_or(s1, s2).sum() + if u: best = max(best, np.logical_and(s1, s2).sum()/u) + return T.shape, B.shape, best + +tests = [ + ('Перезагрузка (R)', (44, 620, 240, 650)), + ('Super Grub2 (поиск и запуск ОС)', (44, 126, 470, 155)), +] +fonts = { + 'SegoeUI-Semibold23': ('/mnt/c/Windows/Fonts/seguisb.ttf', 23), + 'SegoeUI-Bold22': ('/mnt/c/Windows/Fonts/segoeuib.ttf', 22), + 'SegoeUI23': ('/mnt/c/Windows/Fonts/segoeui.ttf', 23), + 'Ubuntu23': ('/mnt/d/GIT/aspia_no2fa-3.0/vcpkg4aspia/buildtrees/harfbuzz/src/14.2.1-f76ca539fc.clean/test/subset/data/fonts/Ubuntu-Regular.ttf', 23), + 'Roboto23': ('/mnt/d/GIT/aspia_no2fa-3.0/vcpkg4aspia/buildtrees/harfbuzz/src/14.2.1-f76ca539fc.clean/test/subset/data/fonts/Roboto-Regular.ttf', 23), +} +for t, box in tests: + print('==', t) + for name,(path,size) in fonts.items(): + try: + ts, bs, s = cmp(box, t, path, size) + print(f' {name:22s} target={ts} rendered={bs} IoU={s:.3f}') + except Exception as e: + print(' ', name, 'err', e) +EOF diff --git a/build-scripts/theme-tools/font-convert.sh b/build-scripts/theme-tools/font-convert.sh new file mode 100644 index 0000000..203a938 --- /dev/null +++ b/build-scripts/theme-tools/font-convert.sh @@ -0,0 +1,25 @@ +#!/bin/bash +F=/path/to/pf/PSD/fonts/Montserrat-SemiBold.ttf +echo "=== сигнатура:" +xxd -l 16 "$F" +pip install --quiet fonttools brotli >/dev/null 2>&1 +python3 - <<'EOF' +from fontTools.ttLib import TTFont +import os +src = '/path/to/pf/PSD/fonts/Montserrat-SemiBold.ttf' +with open(src, 'rb') as fh: + sig = fh.read(4) +print('sig:', sig) +dst = '/path/to/pf/PSD/fonts/Montserrat-SemiBold.ttf' +if sig in (b'wOFF', b'wOF2'): + f = TTFont(src) + f.flavor = None + out = '/path/to/pf/PSD/fonts/Montserrat-SemiBold.ttf' + f.save(out) + print('converted ->', out, os.path.getsize(out), 'bytes') +elif sig in (b'\x00\x01\x00\x00', b'true', b'OTTO'): + print('already ttf/otf') +else: + print('unknown') +EOF +ls -l /path/to/pf/PSD/fonts/ \ No newline at end of file diff --git a/build-scripts/theme-tools/font-info.sh b/build-scripts/theme-tools/font-info.sh new file mode 100644 index 0000000..c15f6f8 --- /dev/null +++ b/build-scripts/theme-tools/font-info.sh @@ -0,0 +1,14 @@ +#!/bin/bash +set -e +python3 -m pip install --quiet --break-system-packages fonttools 2>/dev/null || true +python3 - <<'EOF' +from fontTools.ttLib import TTFont +p='/tmp/Montserrat.ttf' +f=TTFont(p) +print('family:', f['name'].getDebugName(1), '| subfamily:', f['name'].getDebugName(2)) +if 'fvar' in f: + for a in f['fvar'].axes: + print(' axis', a.axisTag, a.minValue, a.defaultValue, a.maxValue) +else: + print(' static font') +EOF diff --git a/build-scripts/theme-tools/font-match.py.sh b/build-scripts/theme-tools/font-match.py.sh new file mode 100644 index 0000000..a07808b --- /dev/null +++ b/build-scripts/theme-tools/font-match.py.sh @@ -0,0 +1,74 @@ +#!/bin/bash +pip install --quiet pillow numpy >/dev/null 2>&1 +python3 - <<'EOF' +import numpy as np +from PIL import Image, ImageDraw, ImageFont +import glob, os + +# 1. Кроп надписи с картинки +bmp = Image.open('/mnt/f/efi/Paravis/Boot/xor/Main1.bmp').convert('L') +crop = bmp.crop((44, 476, 316, 506)) # с запасом вокруг текста +a = np.array(crop) +target = (a < 128) # тёмный текст +ys, xs = np.where(target) +print('target ink bbox:', xs.min(), xs.max(), ys.min(), ys.max(), 'pixels:', target.sum()) + +text = 'Kaspersky Rescue Disk 18' + +def render(font_path, size): + try: + f = ImageFont.truetype(font_path, size) + except Exception: + return None + img = Image.new('L', (600, 80), 255) + d = ImageDraw.Draw(img) + try: + d.text((10, 10), text, font=f, fill=0) + except Exception: + return None + m = np.array(img) < 128 + if not m.any(): + return None + ys, xs = np.where(m) + return m[ys.min():ys.max()+1, xs.min():xs.max()+1] + +def score(A, B): + # A: target crop, B: rendered mask; пробуем сдвиги + best = -1 + ha, wa = A.shape; hb, wb = B.shape + for dy in range(-3, 4): + for dx in range(-3, 4): + # размещаем B в A со сдвигом + y0 = max(0, dy); x0 = max(0, dx) + y1 = min(ha, hb + dy); x1 = min(wa, wb + dx) + if y1 <= y0 or x1 <= x0: continue + sub = A[y0:y1, x0:x1] + subB = B[y0-dy:y1-dy, x0-dx:x1-dx] + inter = np.logical_and(sub, subB).sum() + union = np.logical_or(sub, subB).sum() + if union == 0: continue + s = inter / union + if s > best: best = s + return best + +# цель обрезаем по чернилам для корректного сравнения +ys, xs = np.where(target) +T = target[ys.min():ys.max()+1, xs.min():xs.max()+1] + +results = [] +fonts = glob.glob('/mnt/c/Windows/Fonts/*.ttf') + glob.glob('/mnt/c/Windows/Fonts/*.otf') +for fp in fonts: + for size in (20, 21, 21.63, 22, 23): + B = render(fp, size) + if B is None: continue + if abs(B.shape[1] - T.shape[1]) > 12: # грубый отсев по ширине + continue + s = score(T, B) + if s > 0: + results.append((s, os.path.basename(fp), size, B.shape)) + +results.sort(reverse=True) +print('--- top-15:') +for s, name, size, shape in results[:15]: + print(f' {s:.3f} {name:32s} size={size:<5} shape={shape}') +EOF diff --git a/build-scripts/theme-tools/font-match2.sh b/build-scripts/theme-tools/font-match2.sh new file mode 100644 index 0000000..982b357 --- /dev/null +++ b/build-scripts/theme-tools/font-match2.sh @@ -0,0 +1,83 @@ +#!/bin/bash +python3 - <<'EOF' +import numpy as np, glob +from PIL import Image, ImageDraw, ImageFont + +bmp = Image.open('/mnt/f/efi/Paravis/Boot/xor/Main1.bmp').convert('L') +crop = bmp.crop((44, 476, 316, 506)) +A = np.array(crop) < 128 +ys, xs = np.where(A) +T = A[ys.min():ys.max()+1, xs.min():xs.max()+1] +TH, TW = T.shape +print('target', TW, 'x', TH) + +fonts = { + 'Roboto': '/mnt/d/GIT/aspia_no2fa-3.0/vcpkg4aspia/buildtrees/harfbuzz/src/14.2.1-f76ca539fc.clean/test/subset/data/fonts/Roboto-Regular.ttf', + 'SourceSansPro': '/mnt/d/GIT/aspia_no2fa-3.0/vcpkg4aspia/buildtrees/harfbuzz/src/14.2.1-f76ca539fc.clean/test/subset/data/fonts/SourceSansPro-Regular.otf', + 'Ubuntu': '/mnt/d/GIT/aspia_no2fa-3.0/vcpkg4aspia/buildtrees/harfbuzz/src/14.2.1-f76ca539fc.clean/test/subset/data/fonts/Ubuntu-Regular.ttf', + 'SegoeUI-Semibold': '/mnt/c/Windows/Fonts/seguisb.ttf', + 'SegoeUI-Bold': '/mnt/c/Windows/Fonts/segoeuib.ttf', + 'SegoeUI': '/mnt/c/Windows/Fonts/segoeui.ttf', +} +text = 'Kaspersky Rescue Disk 18' + +def render(path, size): + try: + f = ImageFont.truetype(path, size) + except Exception: + return None + img = Image.new('L', (700, 100), 255) + d = ImageDraw.Draw(img) + try: + d.text((20, 20), text, font=f, fill=0) + except Exception: + return None + m = np.array(img) < 128 + if not m.any(): return None + ys, xs = np.where(m) + return m[ys.min():ys.max()+1, xs.min():xs.max()+1] + +def iou(A, B): + ha, wa = A.shape; hb, wb = B.shape + best = 0 + for dy in range(-3, 4): + for dx in range(-4, 5): + y0 = max(0, dy); x0 = max(0, dx) + y1 = min(ha, hb+dy); x1 = min(wa, wb+dx) + if y1 <= y0 or x1 <= x0: continue + s1 = A[y0:y1, x0:x1]; s2 = B[y0-dy:y1-dy, x0-dx:x1-dx] + u = np.logical_or(s1, s2).sum() + if u: best = max(best, np.logical_and(s1, s2).sum()/u) + return best + +rows = [('ORIGINAL', crop)] +for name, path in fonts.items(): + best = (0, None, None) + for size10 in range(190, 260, 5): + size = size10/10.0 + B = render(path, size) + if B is None: continue + if abs(B.shape[1]-TW) > 10: continue + s = iou(T, B) + if s > best[0]: best = (s, size, B) + if best[1]: + print(f'{name:18s} size={best[1]:.1f} IoU={best[0]:.3f}') + im = Image.new('RGB', (272, 30), (233,233,233)) + try: + f = ImageFont.truetype(path, best[1]) + ImageDraw.Draw(im).text((6, 2), text, font=f, fill=(41,55,84)) + except Exception: + pass + rows.append((f'{name} {best[1]}', im)) + +scale = 3 +out = Image.new('RGB', (272*scale, sum(r[1].height*scale+6 for r in rows)+10), (255,255,255)) +y = 5 +d = ImageDraw.Draw(out) +for name, im in rows: + im2 = im.resize((im.width*scale, im.height*scale), Image.LANCZOS) + out.paste(im2, (0, y)); d.text((272*scale-200, y+2), name, fill=(0,0,0)) + y += im2.height+6 +out.save('/path/to/pf/KRD/font-candidates2.png') +print('saved') +EOF diff --git a/build-scripts/theme-tools/font-preview.sh b/build-scripts/theme-tools/font-preview.sh new file mode 100644 index 0000000..dda8f27 --- /dev/null +++ b/build-scripts/theme-tools/font-preview.sh @@ -0,0 +1,45 @@ +#!/bin/bash +python3 - <<'EOF' +from PIL import Image, ImageDraw, ImageFont + +text = 'Kaspersky Rescue Disk 18' +orig = Image.open('/mnt/f/efi/Paravis/Boot/xor/Main1.bmp').convert('RGB').crop((44, 476, 316, 506)) + +cands = [ + ('Segoe UI Semibold', '/mnt/c/Windows/Fonts/seguisb.ttf', 23), + ('Segoe UI Bold', '/mnt/c/Windows/Fonts/segoeuib.ttf', 22), + ('Segoe UI', '/mnt/c/Windows/Fonts/segoeui.ttf', 23), + ('Arial Bold', '/mnt/c/Windows/Fonts/arialbd.ttf', 21), + ('Tahoma Bold', '/mnt/c/Windows/Fonts/tahomabd.ttf', 21), + ('Verdana Bold', '/mnt/c/Windows/Fonts/verdanab.ttf', 20), + ('Calibri Bold', '/mnt/c/Windows/Fonts/calibrib.ttf', 23), + ('Trebuchet Bold', '/mnt/c/Windows/Fonts/trebucbd.ttf', 22), + ('Franklin Gothic', '/mnt/c/Windows/Fonts/framd.ttf', 22), + ('PhagsPa Bold', '/mnt/c/Windows/Fonts/phagspab.ttf', 22), +] + +rows = [('ORIGINAL', orig)] +for name, path, size in cands: + try: + f = ImageFont.truetype(path, size) + except Exception as e: + print('skip', name, e); continue + img = Image.new('RGB', (272, 30), (233, 233, 233)) + d = ImageDraw.Draw(img) + d.text((6, 2), text, font=f, fill=(41, 55, 84)) + rows.append((name, img)) + +scale = 3 +W = 272 * scale +H = sum(r[1].height * scale + 6 for r in rows) + 10 +out = Image.new('RGB', (W, H), (255, 255, 255)) +y = 5 +d2 = ImageDraw.Draw(out) +for name, im in rows: + im2 = im.resize((im.width*scale, im.height*scale), Image.LANCZOS) + out.paste(im2, (0, y)) + d2.text((W-190, y+2), name, fill=(0, 0, 0)) + y += im2.height + 6 +out.save('/path/to/pf/KRD/font-candidates.png') +print('saved') +EOF diff --git a/build-scripts/theme-tools/font-scan.sh b/build-scripts/theme-tools/font-scan.sh new file mode 100644 index 0000000..aa14bf9 --- /dev/null +++ b/build-scripts/theme-tools/font-scan.sh @@ -0,0 +1,60 @@ +#!/bin/bash +python3 - <<'EOF' +import numpy as np, glob, os +from PIL import Image, ImageDraw, ImageFont + +bmp = Image.open('/mnt/f/efi/Paravis/Boot/xor/Main1.bmp').convert('L') +crop = bmp.crop((44, 620, 240, 650)) +A = np.array(crop) < 128 +ys, xs = np.where(A) +T = A[ys.min():ys.max()+1, xs.min():xs.max()+1] +TH, TW = T.shape +print('target', TW, TH) + +texts = [('Перезагрузка (R)', (44, 620, 240, 650), T)] + +def render(path, text, size, stroke=0): + try: + f = ImageFont.truetype(path, size) + img = Image.new('L', (900, 120), 255) + ImageDraw.Draw(img).text((20, 20), text, font=f, fill=0, stroke_width=stroke, stroke_fill=0) + except Exception: + return None + m = np.array(img) < 128 + if not m.any(): return None + ys, xs = np.where(m) + return m[ys.min():ys.max()+1, xs.min():xs.max()+1] + +def iou(A, B): + ha, wa = A.shape; hb, wb = B.shape; best = 0 + for dy in range(-4, 5): + for dx in range(-5, 6): + y0 = max(0, dy); x0 = max(0, dx) + y1 = min(ha, hb+dy); x1 = min(wa, wb+dx) + if y1 <= y0 or x1 <= x0: continue + s1 = A[y0:y1, x0:x1]; s2 = B[y0-dy:y1-dy, x0-dx:x1-dx] + u = np.logical_or(s1, s2).sum() + if u: best = max(best, np.logical_and(s1, s2).sum()/u) + return best + +fonts = glob.glob('/mnt/c/Windows/Fonts/*.ttf') + glob.glob('/mnt/c/Windows/Fonts/*.otf') +fonts += glob.glob('/mnt/d/GIT/aspia_no2fa-3.0/vcpkg4aspia/buildtrees/harfbuzz/src/*/test/subset/data/fonts/*.ttf') +fonts += glob.glob('/mnt/d/GIT/aspia_no2fa-3.0/vcpkg4aspia/buildtrees/harfbuzz/src/*/test/subset/data/fonts/*.otf') + +res = [] +for fp in fonts: + for size10 in range(200, 245, 5): + size = size10/10.0 + B = render(fp, 'Перезагрузка (R)', size) + if B is None or abs(B.shape[1]-TW) > 6: continue + s = iou(T, B) + res.append((s, os.path.basename(fp), size, B.shape[1])) +res.sort(reverse=True) +seen = set(); out = [] +for s, n, size, w in res: + if n in seen: continue + seen.add(n); out.append((s, n, size, w)) + if len(out) >= 20: break +for s, n, size, w in out: + print(f' {s:.3f} {n:34s} size={size:<5} w={w}') +EOF diff --git a/build-scripts/theme-tools/font-tune.sh b/build-scripts/theme-tools/font-tune.sh new file mode 100644 index 0000000..2deade8 --- /dev/null +++ b/build-scripts/theme-tools/font-tune.sh @@ -0,0 +1,45 @@ +#!/bin/bash +python3 - <<'EOF' +import numpy as np +from PIL import Image, ImageDraw, ImageFont + +bmp = Image.open('/mnt/f/efi/Paravis/Boot/xor/Main1.bmp').convert('L') +crop = bmp.crop((44, 476, 316, 506)) +A = np.array(crop) < 128 +ys, xs = np.where(A); T = A[ys.min():ys.max()+1, xs.min():xs.max()+1] + +text = 'Kaspersky Rescue Disk 18' +path = '/mnt/c/Windows/Fonts/seguisb.ttf' + +def render(size, stroke): + f = ImageFont.truetype(path, size) + img = Image.new('L', (700, 100), 255) + d = ImageDraw.Draw(img) + d.text((20, 20), text, font=f, fill=0, stroke_width=stroke, stroke_fill=0) + m = np.array(img) < 128 + ys, xs = np.where(m) + return m[ys.min():ys.max()+1, xs.min():xs.max()+1] + +def iou(A, B): + ha, wa = A.shape; hb, wb = B.shape; best = 0 + for dy in range(-4, 5): + for dx in range(-5, 6): + y0 = max(0, dy); x0 = max(0, dx) + y1 = min(ha, hb+dy); x1 = min(wa, wb+dx) + if y1 <= y0 or x1 <= x0: continue + s1 = A[y0:y1, x0:x1]; s2 = B[y0-dy:y1-dy, x0-dx:x1-dx] + u = np.logical_or(s1, s2).sum() + if u: best = max(best, np.logical_and(s1, s2).sum()/u) + return best + +best = (-1,) +for size10 in range(215, 245, 5): + for stroke10 in range(0, 9, 2): + size = size10/10.0; stroke = stroke10/10.0 + B = render(size, stroke) + if abs(B.shape[1]-T.shape[1]) > 8: continue + s = iou(T, B) + print(f' size={size:.1f} stroke={stroke:.1f} w={B.shape[1]} IoU={s:.3f}') + if s > best[0]: best = (s, size, stroke) +print('BEST:', best) +EOF diff --git a/build-scripts/theme-tools/get-montserrat.sh b/build-scripts/theme-tools/get-montserrat.sh new file mode 100644 index 0000000..e2c1d5d --- /dev/null +++ b/build-scripts/theme-tools/get-montserrat.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -e +cd /tmp +# Montserrat (SemiBold) — шрифт из макета +if [ ! -f /tmp/Montserrat-SemiBold.ttf ]; then + curl -sSL --max-time 300 -o /tmp/Montserrat.ttf \ + "https://github.com/google/fonts/raw/main/ofl/montserrat/Montserrat%5Bwght%5D.ttf" || true + curl -sSL --max-time 300 -o /tmp/Montserrat-SemiBold.ttf \ + "https://github.com/google/fonts/raw/main/ofl/montserrat/static/Montserrat-SemiBold.ttf" || true +fi +ls -l /tmp/Montserrat-SemiBold.ttf 2>/dev/null || echo " semibold download failed" +file /tmp/Montserrat-SemiBold.ttf 2>/dev/null | head -1 diff --git a/build-scripts/theme-tools/make-pf2.sh b/build-scripts/theme-tools/make-pf2.sh new file mode 100644 index 0000000..fcee015 --- /dev/null +++ b/build-scripts/theme-tools/make-pf2.sh @@ -0,0 +1,16 @@ +#!/bin/bash +set -e +T=/path/to/pf/ParavisGrub/theme/main +mkdir -p "$T" + +echo "=== instantiate Montserrat 600 (SemiBold) + pf2" +python3 - <<'EOF' +from fontTools.ttLib import TTFont +from fontTools.varLib.instancer import instantiateVariableFont +f = TTFont('/tmp/Montserrat.ttf') +inst = instantiateVariableFont(f, {'wght': 600}) +inst.save('/tmp/Montserrat-SemiBold.ttf') +print(' saved /tmp/Montserrat-SemiBold.ttf') +EOF +grub-mkfont -s 17 -o "$T/paravis.pf2" /tmp/Montserrat-SemiBold.ttf +ls -l "$T/paravis.pf2" diff --git a/build-scripts/theme-tools/montserrat-check.sh b/build-scripts/theme-tools/montserrat-check.sh new file mode 100644 index 0000000..c83d0fc --- /dev/null +++ b/build-scripts/theme-tools/montserrat-check.sh @@ -0,0 +1,53 @@ +#!/bin/bash +python3 - <<'EOF' +import numpy as np +from PIL import Image, ImageDraw, ImageFont + +bmp = Image.open('/mnt/f/efi/Paravis/Boot/xor/Main1.bmp').convert('L') +crop = bmp.crop((44, 476, 316, 506)) +A = np.array(crop) < 128 +ys, xs = np.where(A); T = A[ys.min():ys.max()+1, xs.min():xs.max()+1] +print('target', T.shape) + +text = 'Kaspersky Rescue Disk 18' +path = '/path/to/pf/PSD/fonts/Montserrat-SemiBold.ttf' + +def render(size): + f = ImageFont.truetype(path, size) + img = Image.new('L', (700, 100), 255) + ImageDraw.Draw(img).text((20, 20), text, font=f, fill=0) + m = np.array(img) < 128 + ys, xs = np.where(m) + return m[ys.min():ys.max()+1, xs.min():xs.max()+1] + +def iou(A, B): + ha, wa = A.shape; hb, wb = B.shape; best = 0 + for dy in range(-4, 5): + for dx in range(-5, 6): + y0 = max(0, dy); x0 = max(0, dx) + y1 = min(ha, hb+dy); x1 = min(wa, wb+dx) + if y1 <= y0 or x1 <= x0: continue + s1 = A[y0:y1, x0:x1]; s2 = B[y0-dy:y1-dy, x0-dx:x1-dx] + u = np.logical_or(s1, s2).sum() + if u: best = max(best, np.logical_and(s1, s2).sum()/u) + return best + +best = (0,) +for size10 in range(190, 245, 5): + size = size10/10.0 + B = render(size) + s = iou(T, B) + print(f' size={size:<5} w={B.shape[1]:<4} h={B.shape[0]:<3} IoU={s:.3f}') + if s > best[0]: best = (s, size) + +print('BEST', best) +# картинка-сравнение +im = Image.new('RGB', (272, 30), (233,233,233)) +ImageDraw.Draw(im).text((6, 2), text, font=ImageFont.truetype(path, best[1]), fill=(41,55,84)) +orig = Image.open('/mnt/f/efi/Paravis/Boot/xor/Main1.bmp').convert('RGB').crop((44, 476, 316, 506)) +out = Image.new('RGB', (272*3, 30*3*2+20), (255,255,255)) +out.paste(orig.resize((orig.width*3, orig.height*3), Image.LANCZOS), (0,0)) +out.paste(im.resize((im.width*3, im.height*3), Image.LANCZOS), (0,30*3+10)) +out.save('/path/to/pf/KRD/montserrat-check.png') +print('saved') +EOF diff --git a/build-scripts/theme-tools/montserrat-check2.sh b/build-scripts/theme-tools/montserrat-check2.sh new file mode 100644 index 0000000..3aad261 --- /dev/null +++ b/build-scripts/theme-tools/montserrat-check2.sh @@ -0,0 +1,61 @@ +#!/bin/bash +python3 - <<'EOF' +import numpy as np +from PIL import Image, ImageDraw, ImageFont + +path = '/path/to/pf/PSD/fonts/Montserrat-VF.ttf' +bmp = Image.open('/mnt/f/efi/Paravis/Boot/xor/Main1.bmp').convert('L') +crop = bmp.crop((44, 476, 316, 506)) +A = np.array(crop) < 128 +ys, xs = np.where(A); T = A[ys.min():ys.max()+1, xs.min():xs.max()+1] +print('target', T.shape) + +text = 'Kaspersky Rescue Disk 18' + +def render(size, wght): + f = ImageFont.truetype(path, size) + try: + f.set_variation_by_axes([wght]) + except Exception as e: + print('var err', e); return None + img = Image.new('L', (700, 100), 255) + ImageDraw.Draw(img).text((20, 20), text, font=f, fill=0) + m = np.array(img) < 128 + ys, xs = np.where(m) + return m[ys.min():ys.max()+1, xs.min():xs.max()+1] + +def iou(A, B): + ha, wa = A.shape; hb, wb = B.shape; best = 0 + for dy in range(-4, 5): + for dx in range(-5, 6): + y0 = max(0, dy); x0 = max(0, dx) + y1 = min(ha, hb+dy); x1 = min(wa, wb+dx) + if y1 <= y0 or x1 <= x0: continue + s1 = A[y0:y1, x0:x1]; s2 = B[y0-dy:y1-dy, x0-dx:x1-dx] + u = np.logical_or(s1, s2).sum() + if u: best = max(best, np.logical_and(s1, s2).sum()/u) + return best + +best = (0,) +for wght in (500, 550, 600, 650, 700): + for size10 in range(190, 240, 5): + size = size10/10.0 + B = render(size, wght) + if B is None: continue + s = iou(T, B) + if abs(B.shape[1]-T.shape[1]) < 8: + print(f' w={wght} size={size:<5} w_px={B.shape[1]:<4} IoU={s:.3f}') + if s > best[0]: best = (s, size, wght) +print('BEST', best) + +s, size, wght = best +im = Image.new('RGB', (272, 30), (233,233,233)) +f = ImageFont.truetype(path, size); f.set_variation_by_axes([wght]) +ImageDraw.Draw(im).text((6, 2), text, font=f, fill=(41,55,84)) +orig = Image.open('/mnt/f/efi/Paravis/Boot/xor/Main1.bmp').convert('RGB').crop((44, 476, 316, 506)) +out = Image.new('RGB', (272*3, 30*3*2+20), (255,255,255)) +out.paste(orig.resize((orig.width*3, orig.height*3), Image.LANCZOS), (0,0)) +out.paste(im.resize((im.width*3, im.height*3), Image.LANCZOS), (0,30*3+10)) +out.save('/path/to/pf/KRD/montserrat-check.png') +print('saved') +EOF diff --git a/build-scripts/theme-tools/pf2dump.py b/build-scripts/theme-tools/pf2dump.py new file mode 100644 index 0000000..a5e9a42 --- /dev/null +++ b/build-scripts/theme-tools/pf2dump.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python3 +import struct, sys + +d = open(sys.argv[1], 'rb').read() +print('size', len(d), 'head', d[:16]) +pos = 12 +while pos + 8 <= len(d) and pos < 200000: + name = d[pos:pos+4] + if not all(65 <= c <= 90 for c in name): + print(' stop at', pos, name) + break + ln_be = struct.unpack('>I', d[pos+4:pos+8])[0] + ln_le = struct.unpack(' len(d): + break diff --git a/build-scripts/theme-tools/pf2test.py b/build-scripts/theme-tools/pf2test.py new file mode 100644 index 0000000..2d37992 --- /dev/null +++ b/build-scripts/theme-tools/pf2test.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python3 +import struct + +PATH = '/path/to/pf/ParavisGrub/theme/paravis.pf2' +d = open(PATH, 'rb').read() + +pos = 12 +sec = {} +while pos + 8 <= len(d): + name = d[pos:pos+4] + if not all(65 <= c <= 90 for c in name): + break + length = struct.unpack('>I', d[pos+4:pos+8])[0] + body_start = pos + 8 + if length == 0xFFFFFFFF: + body = d[body_start:] + pos = len(d) + else: + body = d[body_start:body_start + length] + pos = body_start + length + sec[name] = body + +chix, data = sec[b'CHIX'], sec[b'DATA'] +print('chix', len(chix), 'data', len(data), 'entries', len(chix) / 9) + +def parse(order): + widths = {} + for i in range(len(chix) // 9): + e = chix[i * 9:(i + 1) * 9] + code = int.from_bytes(e[0:4], order) + off = int.from_bytes(e[5:9], 'big') + rec = data[off:off + 16] + if len(rec) < 16: + continue + w, h, xo, yo, dw, dh, dxo, dyo = struct.unpack('>HHhhhhhh', rec) + widths[chr(code) if code < 0x110000 else '?'] = dw + return widths + +for order in ('big', 'little'): + w = parse(order) + sample = {c: w.get(c) for c in ' A1('} + codes = sorted(ord(c) for c in w if c != '?') + print(order, 'glyphs', len(w), 'sample', sample, + 'range', hex(codes[0]) if codes else '-', hex(codes[-1]) if codes else '-') diff --git a/build-scripts/theme-tools/pf2width.py b/build-scripts/theme-tools/pf2width.py new file mode 100644 index 0000000..383f377 --- /dev/null +++ b/build-scripts/theme-tools/pf2width.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python3 +"""Exact text width from a GRUB pf2 font (what GRUB itself uses).""" +import struct + + +def load_pf2(path): + data = open(path, 'rb').read() + if data[:4] != b'FILE': + raise ValueError('not a pf2 file') + pos = 12 + sec = {} + while pos + 8 <= len(data): + name = data[pos:pos + 4] + length = struct.unpack('>I', data[pos + 4:pos + 8])[0] + sec[name] = data[pos + 8:pos + 8 + length] + pos += 8 + length + + chix = sec.get(b'CHIX', b'') + dat = sec.get(b'DATA', b'') + widths = {} + for i in range(len(chix) // 8): + code, off = struct.unpack('>II', chix[i * 8:(i + 1) * 8]) + rec = dat[off:off + 16] + if len(rec) < 16: + continue + _w, _h, _xo, _yo, dw, _dh, _dxo, _dyo = struct.unpack('>HHhhhhhh', rec) + widths[chr(code)] = dw + return widths + + +if __name__ == '__main__': + import sys + w = load_pf2(sys.argv[1]) + for ch in ' Aa1(9)': + print(repr(ch), w.get(ch)) + print('space width:', w.get(' '), '| glyphs:', len(w)) + print('thin spaces:', w.get('\u2009'), w.get('\u200a'), w.get('\u00a0')) diff --git a/build-scripts/theme-tools/psd-dump.py b/build-scripts/theme-tools/psd-dump.py new file mode 100644 index 0000000..7199d8d --- /dev/null +++ b/build-scripts/theme-tools/psd-dump.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python3 +"""Dump PSD structure with text content / fonts / geometry.""" +import sys +from psd_tools import PSDImage + +path = sys.argv[1] if len(sys.argv) > 1 else '/path/to/pf/PSD/UEFI/x64/main/main.psd' +psd = PSDImage.open(path) +print('canvas %dx%d' % (psd.width, psd.height)) + + +def walk(layer, depth=0): + pad = ' ' * depth + kind = layer.kind + name = (layer.name or '') + bbox = layer.bbox + vis = 'vis' if layer.visible else 'HID' + extra = '' + try: + if kind == 'type': + eng = layer.engine_dict or {} + txt = None + try: + txt = layer.text + except Exception: + pass + style = (eng.get('StyleRun') or {}).get('RunArray') or [] + font = size = None + if style: + rs = style[0].get('StyleSheet', {}).get('StyleSheetData', {}) + font = rs.get('Font') + size = rs.get('FontSize') + extra = ' text=%r font=%s size=%s' % ((txt or '')[:40], font, size) + except Exception as e: + extra = ' <%s>' % e + print('%s%-10s %-30s %-24s %s%s' % (pad, kind, name[:30], str(bbox), vis, extra)) + if kind == 'group': + for ch in layer: + walk(ch, depth + 1) + + +for l in psd: + walk(l) diff --git a/build-scripts/theme-tools/psd-dump.sh b/build-scripts/theme-tools/psd-dump.sh new file mode 100644 index 0000000..81c1036 --- /dev/null +++ b/build-scripts/theme-tools/psd-dump.sh @@ -0,0 +1,37 @@ +#!/bin/bash +pip install --quiet psd-tools 2>/dev/null || pip3 install --quiet psd-tools 2>/dev/null +python3 - <<'EOF' +from psd_tools import PSDImage +import os + +files = [ + ('legacy', '/path/to/pf/PSD/main/main.psd'), + ('uefi-x64', '/path/to/pf/PSD/UEFI/x64/main/main.psd'), + ('uefi-x86', '/path/to/pf/PSD/UEFI/x86/main/main.psd'), +] +for tag, path in files: + print('='*70) + print(tag, path, os.path.getsize(path), 'bytes') + psd = PSDImage.open(path) + print(' size:', psd.width, 'x', psd.height, 'layers:', len(list(psd.descendants()))) + for layer in psd.descendants(): + if layer.kind == 'type': + try: + eng = layer.engine_dict + rd = eng.get('ResourceDict', {}) + fonts = eng.get('FontSet', []) + fname = None + sz = None + for f in fonts: + fname = f.get('Name') + st = eng.get('StyleRun', {}).get('RunArray', []) + for s in st: + ss = s.get('StyleSheet', {}).get('StyleSheetData', {}) + sz = ss.get('FontSize') + col = ss.get('FillColor', {}).get('Values') + print(' TEXT:', repr(layer.text[:60])) + print(' font:', fname, ' size:', sz, ' color:', col) + print(' bbox:', layer.bbox) + except Exception as e: + print(' layer err:', e) +EOF diff --git a/build-scripts/theme-tools/psd-export.py b/build-scripts/theme-tools/psd-export.py new file mode 100644 index 0000000..b60a6ac --- /dev/null +++ b/build-scripts/theme-tools/psd-export.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +"""Export background / highlight from the PSD design (UEFI x64 main).""" +import os +from psd_tools import PSDImage + +SRC = '/path/to/pf/PSD/UEFI/x64/main/main.psd' +OUT = '/path/to/pf/ParavisGrub/theme/main' +os.makedirs(OUT, exist_ok=True) + +KEEP_TEXT = {'Главное Меню', 'Дополнительное Меню', '© Paravis.RU', 'Paravis Flash'} + + +def hide_item_text(layer): + """Hide menu-item text layers, keep headers/decoration.""" + for ch in layer: + if ch.kind == 'type' and (ch.name or '') not in KEEP_TEXT: + ch.visible = False + elif ch.kind == 'group': + hide_item_text(ch) + + +psd = PSDImage.open(SRC) +for layer in psd: + nm = layer.name or '' + if nm.startswith('ТЕКСТ_БЕЗ_ОБВОДКИ'): + for ch in layer: + ch.visible = False + elif nm.startswith('ТЕКСТ_С_ОБВОДКОЙ'): + hide_item_text(layer) + +img = psd.composite() +img.save(os.path.join(OUT, 'background.png')) +print('background.png', img.size) + +# --- highlight bar: take F2 (item 1) from the hidden "ВЫДЕЛЕНЫЕ_ПУНКТЫ" group +psd2 = PSDImage.open(SRC) +sel = None +for layer in psd2.descendants(): + if (layer.name or '').strip() in ('F2', 'F3') and layer.kind == 'pixel': + if layer.name.strip() == 'F2': + sel = layer +if sel is None: + print('highlight layer not found') +else: + bar = sel.topil() + bar.save(os.path.join(OUT, 'sel_bar.png')) + print('sel_bar.png', bar.size, 'bbox', sel.bbox) diff --git a/build-scripts/theme-tools/psd-font.py b/build-scripts/theme-tools/psd-font.py new file mode 100644 index 0000000..cc3d3c9 --- /dev/null +++ b/build-scripts/theme-tools/psd-font.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 +from psd_tools import PSDImage + +psd = PSDImage.open('/path/to/pf/PSD/UEFI/x64/main/main.psd') +names = set() +for layer in psd.descendants(): + if layer.kind != 'type': + continue + try: + rd = layer.resource_dict or {} + for fs in rd.get('FontSet', []) or []: + n = fs.get('Name') if hasattr(fs, 'get') else getattr(fs, 'Name', None) + if n: + names.add(n) + except Exception as e: + pass +print('fonts in document:', sorted(names) or 'not found') + +# fallback: raw resource block scan +try: + from psd_tools.constants import Resource + for k, v in psd.image_resources.items(): + if 'Font' in str(k): + print('resource', k, str(v)[:400]) +except Exception as e: + print('image_resources:', e) diff --git a/build-scripts/theme-tools/psd-fonts.sh b/build-scripts/theme-tools/psd-fonts.sh new file mode 100644 index 0000000..5cd5c6d --- /dev/null +++ b/build-scripts/theme-tools/psd-fonts.sh @@ -0,0 +1,36 @@ +#!/bin/bash +python3 - <<'EOF' +from psd_tools import PSDImage +import os + +for tag, path in [ + ('legacy', '/path/to/pf/PSD/main/main.psd'), + ('uefi-x64', '/path/to/pf/PSD/UEFI/x64/main/main.psd'), + ('uefi-x86', '/path/to/pf/PSD/UEFI/x86/main/main.psd'), +]: + print('='*60); print(tag) + psd = PSDImage.open(path) + fonts = set() + for layer in psd.descendants(): + if layer.kind != 'type': + continue + try: + eng = layer.engine_dict + for f in eng.get('FontSet', []): + fonts.add(f.get('Name')) + except Exception: + pass + print(' fonts:', sorted(fonts)) + # один пример для каждой из интересующих строк + for layer in psd.descendants(): + if layer.kind == 'type' and layer.text and ('Grub2' in layer.text or 'Kaspersky' in layer.text): + eng = layer.engine_dict + fs = [f.get('Name') for f in eng.get('FontSet', [])] + runs = eng.get('StyleRun', {}).get('RunArray', []) + info = [] + for r in runs: + d = r.get('StyleSheet', {}).get('StyleSheetData', {}) + info.append((d.get('Font'), d.get('FontSize'), d.get('FillColor', {}).get('Values'))) + print(' text:', repr(layer.text[:55])) + print(' fonts=', fs, ' runs=', info, ' bbox=', layer.bbox) +EOF diff --git a/build-scripts/theme-tools/psd-layers.sh b/build-scripts/theme-tools/psd-layers.sh new file mode 100644 index 0000000..38dfc7d --- /dev/null +++ b/build-scripts/theme-tools/psd-layers.sh @@ -0,0 +1,13 @@ +#!/bin/bash +set -e +echo "=== install psd-tools" +pip3 install --quiet psd-tools 2>/dev/null || pip3 install --quiet --break-system-packages psd-tools +python3 - <<'EOF' +from psd_tools import PSDImage +p = PSDImage.open('/path/to/pf/PSD/UEFI/x64/main/main.psd') +print('canvas: %dx%d mode=%s' % (p.width, p.height, p.color_mode)) +print('layers (top-level):') +for i, l in enumerate(p): + print(' %2d %-28s type=%-8s visible=%-5s bbox=%s opacity=%s' % ( + i, (l.name or '')[:28], l.kind, l.visible, l.bbox, l.opacity)) +EOF diff --git a/build-scripts/theme-tools/psd-raw.sh b/build-scripts/theme-tools/psd-raw.sh new file mode 100644 index 0000000..16c5371 --- /dev/null +++ b/build-scripts/theme-tools/psd-raw.sh @@ -0,0 +1,18 @@ +#!/bin/bash +python3 - <<'EOF' +from psd_tools import PSDImage +psd = PSDImage.open('/path/to/pf/PSD/main/main.psd') +for layer in psd.descendants(): + if layer.kind == 'type' and layer.text and 'Kaspersky' in layer.text: + eng = layer.engine_dict + print('keys:', list(eng.keys())) + fs = eng.get('FontSet') + print('FontSet type:', type(fs), 'len:', len(fs) if fs else 0) + if fs: + for f in fs[:5]: + print(' entry keys:', list(f.keys())) + print(' ', {k: (v if not isinstance(v, list) else v[:6]) for k, v in f.items()}) + rd = eng.get('ResourceDict') + print('ResourceDict keys:', list(rd.keys()) if rd else None) + break +EOF diff --git a/build-scripts/theme-tools/psd-sub-dump.py b/build-scripts/theme-tools/psd-sub-dump.py new file mode 100644 index 0000000..39937f3 --- /dev/null +++ b/build-scripts/theme-tools/psd-sub-dump.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python3 +from psd_tools import PSDImage +import sys + +for p in sys.argv[1:]: + print('=' * 20, p.split('/')[-1]) + psd = PSDImage.open(p) + for layer in psd: + print(' group %-30s vis=%s bbox=%s' % ((layer.name or '')[:30], layer.visible, layer.bbox)) + for ch in layer: + if ch.kind == 'type': + print(' type %-32s vis=%s bbox=%s' % ((ch.name or '')[:32], ch.visible, ch.bbox)) + elif ch.kind == 'pixel': + print(' pixel %-32s vis=%s bbox=%s' % ((ch.name or '')[:32], ch.visible, ch.bbox)) + else: + print(' %-6s %-32s vis=%s' % (ch.kind, (ch.name or '')[:32], ch.visible)) diff --git a/build-scripts/theme-tools/psd-theme.py b/build-scripts/theme-tools/psd-theme.py new file mode 100644 index 0000000..dd81270 --- /dev/null +++ b/build-scripts/theme-tools/psd-theme.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python3 +"""Build the GRUB theme for the main menu from the PSD design.""" +import os +from psd_tools import PSDImage +from PIL import Image + +SRC = '/path/to/pf/PSD/UEFI/x64/main/main.psd' +OUT = '/path/to/pf/ParavisGrub/theme/main' +os.makedirs(OUT, exist_ok=True) + +KEEP = {'главное меню', 'дополнительное меню', '© paravis.ru', 'paravis flash'} + +psd = PSDImage.open(SRC) + + +def keep_headers(layer): + for ch in layer: + if ch.kind == 'type' and (ch.name or '').strip().lower() not in KEEP: + ch.visible = False + elif ch.kind == 'group': + keep_headers(ch) + + +for layer in psd: + nm = (layer.name or '') + if nm.startswith('ТЕКСТ_БЕЗ_ОБВОДКИ'): + for ch in layer: + ch.visible = False + elif nm.startswith('ТЕКСТ_С_ОБВОДКОЙ'): + keep_headers(layer) + +bg = psd.composite() +bg.save(os.path.join(OUT, 'background.png')) +print('background:', bg.size) + +# --- highlight bar -> 9-slice (w / c / e) +bar = Image.open(os.path.join(OUT, 'sel_bar.png')).convert('RGBA') +W, H = bar.size +cap_w = 28 +cap_e = 84 +bar.crop((0, 0, cap_w, H)).save(os.path.join(OUT, 'sel_w.png')) +bar.crop((W - cap_e, 0, W, H)).save(os.path.join(OUT, 'sel_e.png')) +# center: 1px column from the flat middle, replicated +mid = bar.crop((W // 2, 0, W // 2 + 1, H)) +mid.resize((4, H)).save(os.path.join(OUT, 'sel_c.png')) +print('sel slices: w=%dx%d c=4x%d e=%dx%d' % (cap_w, H, H, cap_e, H)) + +# --- font info +fonts = set() +for layer in psd.descendants(): + if layer.kind == 'type': + try: + eng = layer.engine_dict or {} + for run in (eng.get('StyleRun') or {}).get('RunArray') or []: + f = run.get('StyleSheet', {}).get('StyleSheetData', {}).get('Font') + if f is not None: + fonts.add(f) + except Exception: + pass +print('font indices used:', sorted(fonts)) +try: + fs = psd.font_set + for i in sorted(fonts): + print(' font[%s]:' % i, fs[i] if i < len(fs) else '?') +except Exception as e: + print(' font_set unreadable:', e)