41_snapshots-btrfs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. #! /usr/bin/env bash
  2. #
  3. # Written by: Antynea
  4. # BTC donation address: 1Lbvz244WA8xbpHek9W2Y12cakM6rDe5Rt
  5. # Github: https://github.com/Antynea/grub-btrfs
  6. #
  7. # Purpose:
  8. # Improves Grub by adding "btrfs snapshots" to the Grub menu.
  9. # You can boot your system on a "snapshot" from the Grub menu.
  10. # Supports manual snapshots, snapper, timeshift ...
  11. # Warning : booting on read-only snapshots can be tricky.
  12. # (Read about it, https://github.com/Antynea/grub-btrfs#warning-booting-on-read-only-snapshots-can-be-tricky)
  13. #
  14. # What this script does:
  15. # - Automatically List snapshots existing on root partition (btrfs).
  16. # - Automatically Detect if "/boot" is in separate partition.
  17. # - Automatically Detect kernel, initramfs and intel/amd microcode in "/boot" directory on snapshots.
  18. # - Automatically Create corresponding "menuentry" in grub.cfg.
  19. # - Automatically detect the type/tags and descriptions/comments of snapper/timeshift snapshots.
  20. # - Automatically generate grub.cfg if you use the provided systemd service.
  21. #
  22. # Installation:
  23. # - Refer to https://github.com/Antynea/grub-btrfs#%EF%B8%8F-installation
  24. #
  25. # Customization:
  26. # You have the possibility to modify many parameters in /etc/default/grub-btrfs/config.
  27. # Read more here https://github.com/Antynea/grub-btrfs#installation- an in the manpage
  28. # 'man grub-btrfs'
  29. #
  30. # Automatically update Grub
  31. # If you would like grub-btrfs menu to automatically update when a snapshot is created or deleted:
  32. # - Refer to https://github.com/Antynea/grub-btrfs#-automatically-update-grub-upon-snapshot.
  33. #
  34. # Special thanks for assistance and contributions:
  35. # - My friends
  36. # - All contributors on Github
  37. #
  38. set -e
  39. sysconfdir="/etc"
  40. grub_btrfs_config="${sysconfdir}/default/grub-btrfs/config"
  41. [[ -f "$grub_btrfs_config" ]] && . "$grub_btrfs_config"
  42. [[ -f "${sysconfdir}/default/grub" ]] && . "${sysconfdir}/default/grub"
  43. ## Error Handling
  44. print_error()
  45. {
  46. local err_msg="$*"
  47. local bug_report="If you think an error has occurred, please file a bug report at \"https://github.com/Antynea/grub-btrfs\""
  48. printf "%s\n" "${err_msg}" "${bug_report}" >&2 ;
  49. exit 0
  50. }
  51. # parse arguments
  52. while getopts :V-: opt; do
  53. case "$opt" in
  54. -)
  55. case "${OPTARG}" in
  56. version)
  57. printf "Version %s\n" "${GRUB_BTRFS_VERSION}" >&2 ;
  58. exit 0
  59. ;;
  60. esac;;
  61. V)
  62. printf "Version %s\n" "${GRUB_BTRFS_VERSION}" >&2 ;
  63. exit 0
  64. ;;
  65. *)
  66. printf "Unknown flag, exiting...\n"
  67. exit 0
  68. ;;
  69. esac
  70. done
  71. ## Exit the script, if:
  72. [[ "${GRUB_BTRFS_DISABLE,,}" == "true" ]] && print_error "GRUB_BTRFS_DISABLE is set to true (default=false)"
  73. if ! type btrfs >/dev/null 2>&1; then print_error "btrfs-progs isn't installed"; fi
  74. [[ -f "${GRUB_BTRFS_MKCONFIG_LIB:-/usr/share/grub/grub-mkconfig_lib}" ]] && . "${GRUB_BTRFS_MKCONFIG_LIB:-/usr/share/grub/grub-mkconfig_lib}" || print_error "grub-mkconfig_lib couldn't be found"
  75. [[ "$(btrfs filesystem df / 2>&1)" == *"not a btrfs filesystem"* ]] && print_error "Root filesystem isn't btrfs"
  76. printf "Detecting snapshots ...\n" >&2 ;
  77. ## Submenu name
  78. distro=$(awk -F "=" '/^NAME=/ {gsub(/"/, "", $2); print $2}' /etc/os-release)
  79. #submenuname=${GRUB_BTRFS_SUBMENUNAME:-"${distro:-Linux} snapshots"}
  80. submenuname=${GRUB_BTRFS_SUBMENUNAME:-"スナップショット"}
  81. ## Limit snapshots to show in the Grub menu (default=50)
  82. limit_snap_show="${GRUB_BTRFS_LIMIT:-50}"
  83. ## How to sort snapshots list
  84. btrfs_subvolume_sort="--sort=${GRUB_BTRFS_SUBVOLUME_SORT:-"-rootid"}"
  85. ## Customize GRUB directory, where "grub.cfg" file is saved
  86. grub_directory=${GRUB_BTRFS_GRUB_DIRNAME:-"/boot/grub"}
  87. ## Customize BOOT directory, where kernels/initrams/microcode is saved.
  88. boot_directory=${GRUB_BTRFS_BOOT_DIRNAME:-"/boot"}
  89. ## Customize GRUB-BTRFS.cfg directory, where "grub-btrfs.cfg" file is saved
  90. grub_btrfs_directory=${GRUB_BTRFS_GBTRFS_DIRNAME:-${grub_directory}}
  91. ## Customize directory where "grub-btrfs.cfg" file is searched for by grub
  92. grub_btrfs_search_directory=${GRUB_BTRFS_GBTRFS_SEARCH_DIRNAME:-"\${prefix}"}
  93. ## Password protection management for submenu
  94. # Protection support for submenu (--unrestricted)
  95. case "${GRUB_BTRFS_DISABLE_PROTECTION_SUBMENU,,}" in
  96. true) unrestricted_access_submenu="--unrestricted ";;
  97. *) unrestricted_access_submenu=""
  98. esac
  99. # Authorized users (--users foo,bar)
  100. if [ -n "${GRUB_BTRFS_PROTECTION_AUTHORIZED_USERS}" ] ; then
  101. protection_authorized_users="--users ${GRUB_BTRFS_PROTECTION_AUTHORIZED_USERS} "
  102. fi
  103. ## Probe informations of Root and Boot devices
  104. # Probe info "Root partition"
  105. root_device=$(${grub_probe} --target=device /) # Root device
  106. root_uuid=$(${grub_probe} --device ${root_device} --target="fs_uuid" 2>/dev/null) # UUID of the root device
  107. root_uuid_subvolume=$(btrfs subvolume show / 2>/dev/null) || print_error "UUID of the root subvolume is not available"; # If UUID of root subvolume is not available, then exit
  108. root_uuid_subvolume=$(awk -F":" 'match($1, /(^[ \t]+UUID)/) {sub(/^[ \t]+/, "", $2); print $2}' <<< "$root_uuid_subvolume") # UUID of the root subvolume
  109. # Probe info "Boot partition"
  110. boot_device=$(${grub_probe} --target=device ${boot_directory}) # Boot device
  111. boot_uuid=$(${grub_probe} --device ${boot_device} --target="fs_uuid" 2>/dev/null) # UUID of the boot device
  112. boot_uuid_subvolume=$(btrfs subvolume show "$boot_directory" 2>/dev/null) || boot_uuid_subvolume=" UUID: $root_uuid_subvolume"; # If boot folder isn't a subvolume, then UUID=root_uuid_subvolume
  113. boot_uuid_subvolume=$(awk -F":" 'match($1, /(^[ \t]+UUID)/) {sub(/^[ \t]+/, "", $2); print $2}' <<< "$boot_uuid_subvolume") # UUID of the boot subvolume
  114. boot_hs=$(${grub_probe} --device ${boot_device} --target="hints_string" 2>/dev/null) # hints string
  115. boot_fs=$(${grub_probe} --device ${boot_device} --target="fs" 2>/dev/null) # Type filesystem of boot device
  116. ## Parameters passed to the kernel
  117. kernel_parameters="$GRUB_CMDLINE_LINUX $GRUB_CMDLINE_LINUX_DEFAULT $GRUB_BTRFS_SNAPSHOT_KERNEL_PARAMETERS"
  118. ## Mount point location
  119. grub_btrfs_mount_point=$(mktemp -dt grub-btrfs.XXXXXXXXXX)
  120. ## Class for theme
  121. CLASS="--class snapshots --class gnu-linux --class gnu --class os"
  122. ## save IFS
  123. oldIFS=$IFS
  124. ## Detect uuid requirement (lvm,btrfs...)
  125. check_uuid_required() {
  126. if [ "${root_uuid}" = "" ] || [ "${GRUB_DISABLE_LINUX_UUID}" = "true" ] \
  127. || ! test -e "/dev/disk/by-uuid/${root_uuid}" \
  128. || ( test -e "${root_device}" && uses_abstraction "${root_device}" lvm ); then
  129. LINUX_ROOT_DEVICE=${root_device}
  130. else
  131. LINUX_ROOT_DEVICE=UUID=${root_uuid}
  132. fi
  133. }
  134. ## Detect rootflags
  135. detect_rootflags()
  136. {
  137. local fstabflags=$(grep -oE '^\s*[^#][[:graph:]]+\s+/\s+btrfs\s+[[:graph:]]+' "${grub_btrfs_mount_point}/${snap_dir_name_trim}/etc/fstab" \
  138. | sed -E 's/^.*[[:space:]]([[:graph:]]+)$/\1/;s/,?subvol(id)?=[^,$]+//g;s/^,//')
  139. rootflags="rootflags=${fstabflags:+$fstabflags,}${GRUB_BTRFS_ROOTFLAGS:+$GRUB_BTRFS_ROOTFLAGS,}"
  140. }
  141. unmount_grub_btrfs_mount_point()
  142. {
  143. if [[ -d "$grub_btrfs_mount_point" ]]; then
  144. local wait=true
  145. local wait_max=0
  146. printf "Unmount %s .." "$grub_btrfs_mount_point" >&2;
  147. while $wait; do
  148. if grep -qs "$grub_btrfs_mount_point" /proc/mounts; then
  149. wait_max=$((1+wait_max))
  150. if umount "$grub_btrfs_mount_point" >/dev/null 2>&1; then
  151. wait=false # umount successful
  152. printf " Success\n" >&2;
  153. elif [[ $wait_max = 10 ]]; then
  154. printf "\nWarning: Unable to unmount %s in %s\n" "$root_device" "$grub_btrfs_mount_point" >&2;
  155. break;
  156. else
  157. printf "." >&2 ; # output to show that the script is alive
  158. sleep 2 # wait 2 seconds before retry
  159. fi
  160. else
  161. wait=false # not mounted
  162. printf " Success\n" >&2;
  163. fi
  164. done
  165. if [[ "$wait" != true ]]; then
  166. if ! rm -d "$grub_btrfs_mount_point" >/dev/null 2>&1; then
  167. printf "Unable to delete %s: Device or ressource is busy\n" "$grub_btrfs_mount_point" >&2;
  168. fi
  169. fi
  170. fi
  171. }
  172. ## Create entry
  173. entry()
  174. {
  175. echo "$@" >> "$grub_btrfs_directory/grub-btrfs.new"
  176. }
  177. ## menu entries
  178. make_menu_entries()
  179. {
  180. ## \" required for snap,kernels,init,microcode with space in their name
  181. entry "submenu '${title_menu}' {
  182. submenu '${title_submenu}' { echo }"
  183. for k in "${name_kernel[@]}"; do
  184. [[ ! -f "${boot_dir}"/"${k}" ]] && continue;
  185. kversion=${k#*"-"}
  186. for i in "${name_initramfs[@]}"; do
  187. if [[ "${name_initramfs}" != "x" ]] ; then
  188. # prefix_i=${i%%"-"*}
  189. suffix_i=${i#*"-"}
  190. # alt_suffix_i=${i##*"-"}
  191. if [ "${kversion}" = "${suffix_i}" ]; then i="${i}";
  192. elif [ "${kversion}.img" = "${suffix_i}" ]; then i="${i}";
  193. elif [ "${kversion}-fallback.img" = "${suffix_i}" ]; then i="${i}";
  194. elif [ "${kversion}.gz" = "${suffix_i}" ]; then i="${i}";
  195. else continue;
  196. fi
  197. for u in "${name_microcode[@]}"; do
  198. if [[ "${name_microcode}" != "x" ]] ; then
  199. entry "
  200. menuentry ' "${k}" & "${i}" & "${u}"' ${CLASS} "\$menuentry_id_option" 'gnulinux-snapshots-$boot_uuid' {"
  201. else
  202. entry "
  203. menuentry ' "${k}" & "${i}"' ${CLASS} "\$menuentry_id_option" 'gnulinux-snapshots-$boot_uuid' {"
  204. fi
  205. entry "\
  206. if [ x\$feature_all_video_module = xy ]; then
  207. insmod all_video
  208. fi
  209. set gfxpayload=keep
  210. insmod ${boot_fs}
  211. if [ x\$feature_platform_search_hint = xy ]; then
  212. search --no-floppy --fs-uuid --set=root ${boot_hs} ${boot_uuid}
  213. else
  214. search --no-floppy --fs-uuid --set=root ${boot_uuid}
  215. fi
  216. echo 'Loading Snapshot: "${snap_date_trim}" "${snap_dir_name_trim}"'
  217. echo 'Loading Kernel: "${k}" ...'
  218. linux \"${boot_dir_root_grub}/"${k}"\" root="${LINUX_ROOT_DEVICE}" ${kernel_parameters} ${rootflags}subvol=\""${snap_dir_name_trim}"\""
  219. if [[ "${name_microcode}" != "x" ]] ; then
  220. entry "\
  221. echo 'Loading Microcode & Initramfs: "${u}" "${i}" ...'
  222. initrd \"${boot_dir_root_grub}/"${u}"\" \"${boot_dir_root_grub}/"${i}"\""
  223. else
  224. entry "\
  225. echo 'Loading Initramfs: "${i}" ...'
  226. initrd \"${boot_dir_root_grub}/"${i}"\""
  227. fi
  228. entry " }"
  229. count_warning_menuentries=$((1+count_warning_menuentries))
  230. done
  231. else
  232. for u in "${name_microcode[@]}"; do
  233. if [[ "${name_microcode}" != "x" ]] ; then
  234. entry "
  235. menuentry ' "${k}" & "${u}"' ${CLASS} "\$menuentry_id_option" 'gnulinux-snapshots-$boot_uuid' {"
  236. else
  237. entry "
  238. menuentry ' "${k}"' ${CLASS} "\$menuentry_id_option" 'gnulinux-snapshots-$boot_uuid' {"
  239. fi
  240. entry "\
  241. if [ x\$feature_all_video_module = xy ]; then
  242. insmod all_video
  243. fi
  244. set gfxpayload=keep
  245. insmod ${boot_fs}
  246. if [ x\$feature_platform_search_hint = xy ]; then
  247. search --no-floppy --fs-uuid --set=root ${boot_hs} ${boot_uuid}
  248. else
  249. search --no-floppy --fs-uuid --set=root ${boot_uuid}
  250. fi
  251. echo 'Loading Snapshot: "${snap_date_trim}" "${snap_dir_name_trim}"'
  252. echo 'Loading Kernel: "${k}" ...'
  253. linux \"${boot_dir_root_grub}/"${k}"\" root="${LINUX_ROOT_DEVICE}" ${kernel_parameters} ${rootflags}subvol=\""${snap_dir_name_trim}"\""
  254. if [[ "${name_microcode}" != "x" ]] ; then
  255. entry "\
  256. echo 'Loading Microcode: "${u}" ...'
  257. initrd \"${boot_dir_root_grub}/"${u}"\""
  258. fi
  259. entry " }"
  260. count_warning_menuentries=$((1+count_warning_menuentries))
  261. done
  262. fi
  263. done
  264. done
  265. entry "}"
  266. }
  267. ## Trim a string from leading and trailing whitespaces
  268. trim() {
  269. local var="$*"
  270. var="${var#"${var%%[![:space:]]*}"}"
  271. var="${var%"${var##*[![:space:]]}"}"
  272. echo -n "$var"
  273. }
  274. ## List of snapshots on filesystem
  275. snapshot_list()
  276. {
  277. local snapper_info="info.xml"
  278. local timeshift_info="info.json"
  279. local date_snapshots=()
  280. local path_snapshots=()
  281. local type_snapshots=()
  282. local description_snapshots=()
  283. IFS=$'\n'
  284. for snap in $(btrfs subvolume list -sa "${btrfs_subvolume_sort}" /); do # Parse btrfs snapshots
  285. IFS=$oldIFS
  286. snap=(${snap})
  287. local path_snapshot=${snap[@]:13:${#snap[@]}}
  288. if [ "$path_snapshot" = "DELETED" ]; then continue; fi # Discard deleted snapshots
  289. [[ ${path_snapshot%%"/"*} == "<FS_TREE>" ]] && path_snapshot=${path_snapshot#*"/"} # Remove the "<FS_TREE>" string at the beginning of the path
  290. # ignore specific path during run "grub-mkconfig"
  291. if [ -n "${GRUB_BTRFS_IGNORE_SPECIFIC_PATH}" ] ; then
  292. for isp in "${GRUB_BTRFS_IGNORE_SPECIFIC_PATH[@]}" ; do
  293. [[ "${path_snapshot}" == "${isp}" ]] && continue 2;
  294. done
  295. fi
  296. if [ -n "${GRUB_BTRFS_IGNORE_PREFIX_PATH}" ] ; then
  297. for isp in "${GRUB_BTRFS_IGNORE_PREFIX_PATH[@]}" ; do
  298. [[ "${path_snapshot}" == "${isp}"/* ]] && continue 2;
  299. done
  300. fi
  301. [[ ! -d "$grub_btrfs_mount_point/$path_snapshot/boot" ]] && continue; # Discard snapshots without /boot folder
  302. # Parse Snapper & timeshift informations
  303. local type_snapshot="N/A"
  304. local description_snapshot="N/A"
  305. if [[ -s "$grub_btrfs_mount_point/${path_snapshot%"/"*}/$snapper_info" ]] ; then
  306. type_snapshot=$(awk -F"<|>" 'match($2, /^type/) {print $3}' "$grub_btrfs_mount_point/${path_snapshot%"/"*}/$snapper_info") # search matching string beginning "type"
  307. description_snapshot=$(awk -F"<|>" 'match($2, /^description/) {print $3}' "$grub_btrfs_mount_point/${path_snapshot%"/"*}/$snapper_info") # search matching string beginning "description"
  308. elif [[ -s "$grub_btrfs_mount_point/${path_snapshot%"/"*}/$timeshift_info" ]] ; then
  309. type_snapshot=$(awk -F" : " 'match($1, /^[ \t]+"tags"/) {gsub(/"|,/,"");print $2}' "$grub_btrfs_mount_point/${path_snapshot%"/"*}/$timeshift_info") # search matching string beginning "tags"
  310. description_snapshot=$(awk -F" : " 'match($1, /^[ \t]+"comments"/) {gsub(/"|,/,"");print $2}' "$grub_btrfs_mount_point/${path_snapshot%"/"*}/$timeshift_info") # search matching string beginning "comments"
  311. fi
  312. [[ -z "$type_snapshot" ]] && type_snapshot=("N/A")
  313. [[ -z "$description_snapshot" ]] && description_snapshot=("N/A")
  314. # ignore specific {type,tag,description} of snapshot during run "grub-mkconfig"
  315. if [ -n "${GRUB_BTRFS_IGNORE_SNAPSHOT_TYPE}" ] ; then
  316. for ist in "${GRUB_BTRFS_IGNORE_SNAPSHOT_TYPE[@]}" ; do
  317. [[ "${type_snapshot}" == "${ist}" ]] && continue 2;
  318. done
  319. fi
  320. if [ -n "${GRUB_BTRFS_IGNORE_SNAPSHOT_DESCRIPTION}" ] ; then
  321. for isd in "${GRUB_BTRFS_IGNORE_SNAPSHOT_DESCRIPTION[@]}" ; do
  322. [[ "${description_snapshot}" == "${isd}" ]] && continue 2;
  323. done
  324. fi
  325. local date_snapshot="${snap[@]:10:2}"
  326. date_snapshots+=("$date_snapshot")
  327. path_snapshots+=("$path_snapshot")
  328. type_snapshots+=("$type_snapshot")
  329. description_snapshots+=("$description_snapshot")
  330. done
  331. # Find max length of a snapshot date, needed for pretty formatting
  332. local max_date_length=0
  333. for i in "${date_snapshots[@]}"; do
  334. local length="${#i}"
  335. [[ "$length" -gt "$max_date_length" ]] && max_date_length=$length
  336. done
  337. # Find max length of a snapshot name, needed for pretty formatting
  338. local max_path_length=0
  339. for i in "${path_snapshots[@]}"; do
  340. local length="${#i}"
  341. [[ "$length" -gt "$max_path_length" ]] && max_path_length=$length
  342. done
  343. # Find max length of a snapshot type, needed for pretty formatting
  344. local max_type_length=0
  345. for i in "${type_snapshots[@]}"; do
  346. local length="${#i}"
  347. [[ "$length" -gt "$max_type_length" ]] && max_type_length=$length
  348. done
  349. # Find max length of a snapshot description, needed for pretty formatting
  350. local max_description_length=0
  351. for i in "${description_snapshots[@]}"; do
  352. local length="${#i}"
  353. [[ "$length" -gt "$max_description_length" ]] && max_description_length=$length
  354. done
  355. for i in "${!path_snapshots[@]}"; do
  356. printf -v entry "%-${max_date_length}s | %-${max_path_length}s | %-${max_type_length}s | %-${max_description_length}s |" "${date_snapshots[$i]}" "${path_snapshots[$i]}" "${type_snapshots[$i]}" "${description_snapshots[$i]}"
  357. echo "$entry"
  358. done
  359. IFS=$oldIFS
  360. }
  361. ## Parse snapshots in snapshot_list
  362. parse_snapshot_list()
  363. {
  364. snap_date=" $(echo "$item" | cut -d'|' -f1)" # column_1, first space is necessary for pretty formatting
  365. snap_date_trim="$(trim "$snap_date")"
  366. snap_dir_name="$(echo "$item" | cut -d'|' -f2)" # column_2
  367. snap_dir_name_trim="$(trim "$snap_dir_name")"
  368. snap_snapshot="$snap_dir_name" # Used by "title_format" function
  369. snap_type="$(echo "$item" | cut -d'|' -f3)" # column_3
  370. snap_description="$(echo "$item" | cut -d'|' -f4)" # column_4
  371. }
  372. ## Detect kernels in "boot_directory"
  373. detect_kernel()
  374. {
  375. list_kernel=()
  376. # Original kernel (auto-detect)
  377. for okernel in "${boot_dir}"/vmlinuz-* \
  378. "${boot_dir}"/vmlinux-* \
  379. "${boot_dir}"/kernel-* ; do
  380. [[ ! -f "${okernel}" ]] && continue;
  381. list_kernel+=("$okernel")
  382. done
  383. # Custom name kernel in "GRUB_BTRFS_NKERNEL"
  384. if [ -n "${GRUB_BTRFS_NKERNEL}" ] ; then
  385. for ckernel in "${boot_dir}/${GRUB_BTRFS_NKERNEL[@]}" ; do
  386. [[ ! -f "${ckernel}" ]] && continue;
  387. list_kernel+=("$ckernel")
  388. done
  389. fi
  390. }
  391. ## Detect initramfs in "boot_directory"
  392. detect_initramfs()
  393. {
  394. list_initramfs=()
  395. # Original initramfs (auto-detect)
  396. for oinitramfs in "${boot_dir}"/initrd.img-* \
  397. "${boot_dir}"/initramfs-* \
  398. "${boot_dir}"/initrd-* ; do
  399. [[ ! -f "${oinitramfs}" ]] && continue;
  400. list_initramfs+=("$oinitramfs")
  401. done
  402. # Custom name initramfs in "GRUB_BTRFS_NINIT"
  403. if [ -n "${GRUB_BTRFS_NINIT}" ] ; then
  404. for cinitramfs in "${boot_dir}/${GRUB_BTRFS_NINIT[@]}" ; do
  405. [[ ! -f "${cinitramfs}" ]] && continue;
  406. list_initramfs+=("$cinitramfs")
  407. done
  408. fi
  409. if [ -z "${list_initramfs}" ]; then list_initramfs=(x); fi
  410. }
  411. ## Detect microcode in "boot_directory"
  412. detect_microcode()
  413. {
  414. list_ucode=()
  415. # Original intel/amd microcode (auto-detect)
  416. # See "https://www.gnu.org/software/grub/manual/grub/html_node/Simple-configuration.html"
  417. for oiucode in "${boot_dir}"/intel-uc.img \
  418. "${boot_dir}"/intel-ucode.img \
  419. "${boot_dir}"/amd-uc.img \
  420. "${boot_dir}"/amd-ucode.img \
  421. "${boot_dir}"/early_ucode.cpio \
  422. "${boot_dir}"/microcode.cpio; do
  423. [[ ! -f "${oiucode}" ]] && continue;
  424. list_ucode+=("$oiucode")
  425. done
  426. # Custom name microcode in "GRUB_BTRFS_CUSTOM_MICROCODE"
  427. if [ -n "${GRUB_BTRFS_CUSTOM_MICROCODE}" ] ; then
  428. for cucode in "${boot_dir}/${GRUB_BTRFS_CUSTOM_MICROCODE[@]}" ; do
  429. [[ ! -f "${cucode}" ]] && continue
  430. list_ucode+=("$cucode")
  431. done
  432. fi
  433. if [ -z "${list_ucode}" ]; then list_ucode=(x); fi
  434. }
  435. ## Title format in Grub-menu
  436. declare -A title_column=( [date]=Date [snapshot]=Snapshot [type]=Type [description]=Description ) # Column title that appears in the header
  437. title_format()
  438. {
  439. title_menu="|" # "|" is for visuals only
  440. title_submenu="|" # "|" is for visuals only
  441. [[ -z "${GRUB_BTRFS_TITLE_FORMAT}" ]] && GRUB_BTRFS_TITLE_FORMAT=("date" "snapshot" "type" "description"); # Default parameters
  442. for key in "${!GRUB_BTRFS_TITLE_FORMAT[@]}"; do
  443. [[ ${GRUB_BTRFS_TITLE_FORMAT[$key],,} != "${title_column[${GRUB_BTRFS_TITLE_FORMAT[$key]}],,}" ]] && continue; # User used wrong parameter
  444. declare -n var="snap_${GRUB_BTRFS_TITLE_FORMAT[$key],,}" # $var is a indirect variable
  445. if [[ "${#var}" -lt "${#title_column[${GRUB_BTRFS_TITLE_FORMAT[$key],,}]}" ]]; then # Add extra spaces if length of $var is smaller than the length of column, needed for pretty formatting
  446. printf -v var "%-$(((${#title_column[${GRUB_BTRFS_TITLE_FORMAT[$key],,}]}-${#var})+${#var}))s" "${var}";
  447. fi
  448. var="$(sed "s/'//g" <(echo "${var}"))"
  449. title_menu+="${var}|"
  450. title_submenu+=" $(trim "${var}") |"
  451. done
  452. }
  453. # Adds a header to the grub-btrfs.cfg file
  454. header_menu()
  455. {
  456. local header_entry=""
  457. [[ -z "${GRUB_BTRFS_TITLE_FORMAT}" ]] && GRUB_BTRFS_TITLE_FORMAT=("date" "snapshot" "type" "description"); # Default parameters
  458. for key in "${!GRUB_BTRFS_TITLE_FORMAT[@]}"; do
  459. [[ ${GRUB_BTRFS_TITLE_FORMAT[$key],,} != "${title_column[${GRUB_BTRFS_TITLE_FORMAT[$key]}],,}" ]] && continue; # User used wrong parameter
  460. declare -n var="snap_${GRUB_BTRFS_TITLE_FORMAT[$key],,}" # $var is a indirect variable
  461. # Center alignment, needed for pretty formatting
  462. local lenght_title_column_left=$((${#var}-${#title_column[${GRUB_BTRFS_TITLE_FORMAT[$key],,}]}))
  463. ((lenght_title_column_left%2)) && lenght_title_column_left=$((lenght_title_column_left+1)); # If the difference is an odd number, add an extra space
  464. lenght_title_column_left=$((((lenght_title_column_left/2)+${#title_column[${GRUB_BTRFS_TITLE_FORMAT[$key],,}]})));
  465. local lenght_title_column_right=$(((${#var}-lenght_title_column_left)+1)) #+1 is necessary for extra "|" character
  466. header_entry+=$(printf "%${lenght_title_column_left}s%${lenght_title_column_right}s" "${title_column[${GRUB_BTRFS_TITLE_FORMAT[$key],,}]}" "|") # Final "|" is for visuals only
  467. done
  468. sed -i "1imenuentry '|${header_entry}' { echo }" "$grub_btrfs_directory/grub-btrfs.new" # First "|" is for visuals only
  469. }
  470. ## List of kernels, initramfs and microcode in snapshots
  471. boot_bounded()
  472. {
  473. # Initialize menu entries
  474. IFS=$'\n'
  475. for item in $(snapshot_list); do
  476. [[ ${limit_snap_show} -le 0 ]] && break; # fix: limit_snap_show=0
  477. IFS=$oldIFS
  478. parse_snapshot_list
  479. boot_dir="$grub_btrfs_mount_point/$snap_dir_name_trim$boot_directory"
  480. detect_kernel
  481. if [ -z "${list_kernel}" ]; then continue; fi
  482. name_kernel=("${list_kernel[@]##*"/"}")
  483. detect_initramfs
  484. name_initramfs=("${list_initramfs[@]##*"/"}")
  485. detect_microcode
  486. name_microcode=("${list_ucode[@]##*"/"}")
  487. detect_rootflags
  488. title_format
  489. boot_dir_root_grub="$(make_system_path_relative_to_its_root "${boot_dir}")" # convert "boot_directory" to root of GRUB (e.g /boot become /)
  490. make_menu_entries
  491. # show snapshot found during run "grub-mkconfig"
  492. if [[ "${GRUB_BTRFS_SHOW_SNAPSHOTS_FOUND:-"true"}" = "true" ]]; then
  493. printf "Found snapshot: %s\n" "$item" >&2 ;
  494. fi
  495. # Limit snapshots found during run "grub-mkconfig"
  496. count_limit_snap=$((1+count_limit_snap))
  497. [[ $count_limit_snap -ge $limit_snap_show ]] && break;
  498. done
  499. IFS=$oldIFS
  500. }
  501. boot_separate()
  502. {
  503. boot_dir="${boot_directory}"
  504. boot_dir_root_grub="$(make_system_path_relative_to_its_root "${boot_dir}")" # convert "boot_directory" to root of GRUB (e.g /boot become /)
  505. detect_kernel
  506. if [ -z "${list_kernel}" ]; then print_error "Kernels not found."; fi
  507. name_kernel=("${list_kernel[@]##*"/"}")
  508. detect_initramfs
  509. name_initramfs=("${list_initramfs[@]##*"/"}")
  510. detect_microcode
  511. name_microcode=("${list_ucode[@]##*"/"}")
  512. # Initialize menu entries
  513. IFS=$'\n'
  514. for item in $(snapshot_list); do
  515. [[ ${limit_snap_show} -le 0 ]] && break; # fix: limit_snap_show=0
  516. IFS=$oldIFS
  517. parse_snapshot_list
  518. detect_rootflags
  519. title_format
  520. make_menu_entries
  521. # show snapshot found during run "grub-mkconfig"
  522. if [[ "${GRUB_BTRFS_SHOW_SNAPSHOTS_FOUND:-"true"}" = "true" ]]; then
  523. printf "Found snapshot: %s\n" "$item" >&2 ;
  524. fi
  525. # Limit snapshots found during run "grub-mkconfig"
  526. count_limit_snap=$((1+count_limit_snap))
  527. [[ $count_limit_snap -ge $limit_snap_show ]] && break;
  528. done
  529. IFS=$oldIFS
  530. }
  531. rm -f "$grub_btrfs_directory/grub-btrfs.new"
  532. true > "$grub_btrfs_directory/grub-btrfs.new" # Create a "grub-btrfs.new" file in "grub_btrfs_directory"
  533. # Create a backup of the "$grub_btrfs_directory/grub-btrfs.cfg" file if exist
  534. if [ -e "$grub_btrfs_directory/grub-btrfs.cfg" ]; then
  535. mv -f "$grub_btrfs_directory/grub-btrfs.cfg" "$grub_btrfs_directory/grub-btrfs.cfg.bkp"
  536. fi
  537. # Create mount point then mounting
  538. [[ ! -d $grub_btrfs_mount_point ]] && mkdir -p "$grub_btrfs_mount_point"
  539. mount -o ro,subvolid=5 /dev/disk/by-uuid/"$root_uuid" "$grub_btrfs_mount_point/" > /dev/null
  540. trap "unmount_grub_btrfs_mount_point" EXIT # unmounting mount point on EXIT signal
  541. count_warning_menuentries=0 # Count menuentries
  542. count_limit_snap=0 # Count snapshots
  543. check_uuid_required
  544. # Detects if /boot is a separate partition
  545. [[ "${GRUB_BTRFS_OVERRIDE_BOOT_PARTITION_DETECTION,,}" == "true" ]] && printf "Override boot partition detection : enable \n" >&2 && boot_separate;
  546. if [[ "$root_uuid" != "$boot_uuid" ]] || [[ "$root_uuid_subvolume" != "$boot_uuid_subvolume" ]]; then boot_separate ; else boot_bounded ; fi
  547. # Make a submenu in GRUB (grub.cfg)
  548. cat << EOF
  549. if [ ! -e "${grub_btrfs_search_directory}/grub-btrfs.cfg" ]; then
  550. echo ""
  551. else
  552. submenu '${submenuname}' ${protection_authorized_users}${unrestricted_access_submenu}{
  553. configfile "${grub_btrfs_search_directory}/grub-btrfs.cfg"
  554. }
  555. fi
  556. EOF
  557. # Show warn, menuentries exceeds 250 entries
  558. [[ $count_warning_menuentries -ge 250 ]] && printf "Generated %s total GRUB entries. You might experience issues loading snapshots menu in GRUB.\n" "${count_warning_menuentries}" >&2 ;
  559. # Show total found snapshots
  560. if [[ "${GRUB_BTRFS_SHOW_TOTAL_SNAPSHOTS_FOUND:-"true"}" = "true" && -n "${count_limit_snap}" && "${count_limit_snap}" != "0" ]]; then
  561. printf "Found %s snapshot(s)\n" "${count_limit_snap}" >&2 ;
  562. fi
  563. # if no snapshot found, delete the "$grub_btrfs_directory/grub-btrfs.new" file and the "$grub_btrfs_directory/grub-btrfs.cfg.bkp" file and exit
  564. if [[ "${count_limit_snap}" = "0" || -z "${count_limit_snap}" ]]; then
  565. rm -f "$grub_btrfs_directory/grub-btrfs.new" "$grub_btrfs_directory/grub-btrfs.cfg.bkp"
  566. print_error "No snapshots found."
  567. fi
  568. # Move "grub-btrfs.new" to "grub-btrfs.cfg"
  569. header_menu
  570. if "${bindir}/${GRUB_BTRFS_SCRIPT_CHECK:-grub-script-check}" "$grub_btrfs_directory/grub-btrfs.new"; then
  571. cat "$grub_btrfs_directory/grub-btrfs.new" > "$grub_btrfs_directory/grub-btrfs.cfg"
  572. rm -f "$grub_btrfs_directory/grub-btrfs.new" "$grub_btrfs_directory/grub-btrfs.cfg.bkp"
  573. else
  574. if [ -e "$grub_btrfs_directory/grub-btrfs.cfg.bkp" ]; then
  575. mv -f "$grub_btrfs_directory/grub-btrfs.cfg.bkp" "$grub_btrfs_directory/grub-btrfs.cfg"
  576. fi
  577. print_error "Syntax errors were detected in generated ${grub_btrfs_directory}/grub-btrfs.new file. The old grub-btrfs.cfg file (if present) have been restored."
  578. fi
  579. # warn when this script is run but there is no entry in grub.cfg
  580. grep "snapshots-btrfs" "${grub_directory}/grub.cfg" >/dev/null 2>&1 || printf "\nWARNING: '%s' needs to run at least once to generate the snapshots (sub)menu entry in grub the main menu. \
  581. After that this script can run alone to generate the snapshot entries.\n\n" "${GRUB_BTRFS_MKCONFIG:-grub-mkconfig}" >&2 ;