You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

99 lines
2.1 KiB

  1. #!/bin/sh
  2. . /lib/functions.sh
  3. . /lib/upgrade/common.sh
  4. . /usr/share/libubox/jshn.sh
  5. OWRT_VOLUMES=owrt-volumes
  6. get_partition_by_name_gpt() {
  7. local dev="$1"
  8. local part parts node name
  9. json_load "$(sfdisk -J "/dev/$dev" 2>/dev/null)"
  10. json_select "partitiontable" || return
  11. json_select "partitions" || return
  12. json_get_keys parts
  13. for part in $parts; do
  14. json_select "$part"
  15. json_get_vars node name
  16. if [ "$2" = "$name" ]; then
  17. echo "$node"
  18. break
  19. fi
  20. json_select ..
  21. done
  22. }
  23. part_fixup() {
  24. echo "write" | sfdisk --force -q -w never $1
  25. }
  26. get_free_area() {
  27. local found=
  28. sfdisk -q -F "$1" 2>/dev/null | while read start end sectors size; do
  29. case $start in
  30. *"Unpartitioned"* | *"Units:"* | *"Sector"* | *"Start"* )
  31. continue
  32. ;;
  33. [0-9]*)
  34. case "$size" in
  35. *"M")
  36. [ "${size%%M}" -lt 100 ] && continue
  37. ;;
  38. *"G" | *"T")
  39. ;;
  40. *"k" | *"b")
  41. continue
  42. ;;
  43. esac
  44. [ "$found" ] || echo "start=$start, size=$((end - start))"
  45. found=1
  46. ;;
  47. esac
  48. done
  49. }
  50. create_lvm_part() {
  51. local disk=$1
  52. local freepart
  53. freepart="$(get_free_area $disk)"
  54. if [ "$freepart" ]; then
  55. echo "$freepart, type=lvm, name=$OWRT_VOLUMES" | sfdisk --force -w never -a $disk
  56. partx -a $disk 1>/dev/null 2>/dev/null || true
  57. return 0
  58. else
  59. return 1
  60. fi
  61. }
  62. lvm_init() {
  63. lvm pvcreate -f $1
  64. lvm vgcreate "$2" $1
  65. lvm vgs
  66. }
  67. autopart_init() {
  68. local diskdev
  69. local lvmpart
  70. local diskserial diskhash
  71. export_bootdevice && export_partdevice diskdev 0
  72. [ "$diskdev" ] || return
  73. [ -e "/sys/class/block/$diskdev/device/serial" ] && diskserial="$(cat /sys/class/block/$diskdev/device/serial)"
  74. [ -e "/sys/class/block/$diskdev/device/cid" ] && diskserial="$diskserial$(cat /sys/class/block/$diskdev/device/cid)"
  75. [ "$diskserial" ] || diskserial="$(cat /proc/sys/kernel/random/uuid)"
  76. diskhash="$(echo $diskserial | sha256sum | cut -d' ' -f1)"
  77. part_fixup /dev/$diskdev
  78. create_lvm_part /dev/$diskdev || return
  79. lvmpart=$(get_partition_by_name_gpt $diskdev $OWRT_VOLUMES)
  80. [ "$lvmpart" ] || return
  81. lvm_init $lvmpart "${OWRT_VOLUMES}-${diskhash:0:16}"
  82. }
  83. autopart_init
  84. exit 0