Merge pull request #20349 from turris-cz/unbound-1171
[feed/packages.git] / utils / uvol / files / autopart.defaults
1 #!/bin/sh
2
3 . /lib/functions.sh
4 . /lib/upgrade/common.sh
5 . /usr/share/libubox/jshn.sh
6
7 OWRT_VOLUMES=owrt-volumes
8
9 load_partitions() {
10 local dev="$1"
11 json_init
12 json_load "$(sfdisk -J "$dev" 2>/dev/null)"
13 json_select "partitiontable" || return 1
14 return 0
15 }
16
17 get_partition_by_name_gpt() {
18 local label part parts node name
19 json_get_vars label
20 [ "$label" = "gpt" ] || return
21 json_select "partitions" || return
22 json_get_keys parts
23 for part in $parts; do
24 json_select "$part"
25 json_get_vars node name
26 if [ "$1" = "$name" ]; then
27 echo "$node"
28 break
29 fi
30 json_select ..
31 done
32 json_select ..
33 }
34
35 get_partition_by_type_mbr() {
36 local label part parts node type
37 json_get_vars label
38 [ "$label" = "dos" ] || return
39 json_select "partitions" || return
40 json_get_keys parts
41 for part in $parts; do
42 json_select "$part"
43 json_get_vars node type
44 if [ "$1" = "$type" ]; then
45 echo "$node"
46 break
47 fi
48 json_select ..
49 done
50 json_select ..
51 }
52
53 part_fixup() {
54 echo "write" | sfdisk --force -q -w never "$1" 1>/dev/null 2>/dev/null
55 }
56
57 get_free_area() {
58 local found=
59 sfdisk --bytes -q -F "$1" 2>/dev/null | while read -r start end sectors size; do
60 case $start in
61 *"Unpartitioned"* | *"Units:"* | *"Sector"* | *"Start"* )
62 continue
63 ;;
64 [0-9]*)
65 [ "$size" -lt $((100 * 1024 * 1024)) ] && continue
66 [ "$found" ] || echo "start=$start, size=$sectors"
67 found=1
68 ;;
69 esac
70 done
71 }
72
73 create_lvm_part() {
74 local disk="$1"
75 local freepart
76
77 freepart="$(get_free_area "$disk")"
78 if [ "$freepart" ]; then
79 echo "$freepart, type=lvm, name=$OWRT_VOLUMES" | sfdisk --force -w never -a "$disk" || return 1
80 partx -a "$disk" 1>/dev/null 2>/dev/null || true
81 return 0
82 else
83 return 1
84 fi
85 }
86
87 lvm_init() {
88 lvm pvcreate -f "$1"
89 lvm vgcreate "$2" "$1"
90 lvm vgs
91 }
92
93 autopart_init() {
94 local diskdev
95 local lvmpart
96 local diskserial diskhash
97
98 export_bootdevice && export_partdevice diskdev 0
99
100 [ "$diskdev" ] || return
101
102 [ -e "/sys/class/block/$diskdev/device/serial" ] && diskserial="$(cat "/sys/class/block/$diskdev/device/serial")"
103 [ -e "/sys/class/block/$diskdev/device/cid" ] && diskserial="$diskserial$(cat "/sys/class/block/$diskdev/device/cid")"
104 [ "$diskserial" ] || diskserial="$(cat /proc/sys/kernel/random/uuid)"
105 diskhash="$(echo "$diskserial" | sha256sum | cut -d' ' -f1)"
106
107 part_fixup "/dev/$diskdev"
108 create_lvm_part "/dev/$diskdev" || return
109 load_partitions "/dev/$diskdev" || return
110 lvmpart="$(get_partition_by_name_gpt "$OWRT_VOLUMES")"
111 [ "$lvmpart" ] || lvmpart="$(get_partition_by_type_mbr "8e")"
112 [ "$lvmpart" ] || return
113
114 lvm_init "$lvmpart" "${OWRT_VOLUMES}-${diskhash:0:16}"
115 }
116
117 autopart_init
118 exit 0