+ tail -n +3 <<< "$ptable" | while read line; do
+ part_num=$(cut -d':' -f1 <<< "$line")
+ if [ $(is_extended_partition "$dev" "$part_num") == "yes" ]; then
+ echo "$line"
+ return 0
+ fi
+ done
+ echo ""
+}
+
+get_logical_partitions() {
+ local ptable="$1"
+
+ tail -n +3 <<< "$ptable" | while read line; do
+ part_num=$(cut -d':' -f1 <<< "$line")
+ if [ $part_num -ge 5 ]; then
+ echo "$line"
+ fi
+ done
+
+ return 0
+}
+
+get_last_primary_partition() {
+ local ptable="$1"
+ local dev=$(echo "ptable" | sed -n 2p | cut -d':' -f1)
+
+ for i in 4 3 2 1; do
+ if output=$(grep "^$i:" <<< "$ptable"); then
+ echo "$output"
+ return 0
+ fi
+ done
+ echo ""
+}
+
+get_partition_to_resize() {
+ local dev="$1"
+
+ table=$(get_partition_table "$dev")
+
+ if [ $(get_partition_count "$table") -eq 0 ]; then
+ return 0
+ fi
+
+ table_type=$(get_partition_table_type "$table")
+ last_part=$(get_last_partition "$table")
+ last_part_num=$(cut -d: -f1 <<< "$last_part")
+
+ if [ "$table_type" == "msdos" -a $last_part_num -gt 4 ]; then
+ extended=$(get_extended_partition "$table")
+ last_primary=$(get_last_primary_partition "$table")
+ ext_num=$(cut -d: -f1 <<< "$extended")
+ prim_num=$(cut -d: -f1 <<< "$last_primary")
+
+ if [ "$ext_num" != "$last_prim_num" ]; then
+ echo "$last_prim_num"
+ else
+ echo "$last_part_num"
+ fi
+ else
+ echo "$last_part_num"
+ fi
+}
+
+create_partition() {
+ local device="$1"
+ local part="$2"
+ local ptype="$3"
+
+ declare -a fields
+ IFS=":;" read -ra fields <<< "$part"
+ local id="${fields[0]}"
+ local start="${fields[1]}"
+ local end="${fields[2]}"
+ local size="${fields[3]}"
+ local fs="${fields[4]}"
+ local name="${fields[5]}"
+ local flags="${fields[6]//,/ }"
+
+ $PARTED -s -m -- $device mkpart "$ptype" $fs "$start" "$end"
+ for flag in $flags; do
+ $PARTED -s -m $device set "$id" "$flag" on
+ done
+}
+
+enlarge_partition() {
+ local device="$1"
+ local part="$2"
+ local ptype="$3"
+ local new_end="$4"
+
+ if [ -z "$new_end" ]; then
+ new_end=$(cut -d: -f 3 <<< "$(get_last_free_sector "$device")")
+ fi
+
+ declare -a fields
+ IFS=":;" read -ra fields <<< "$part"
+ fields[2]="$new_end"
+
+ local new_part=""
+ for ((i = 0; i < ${#fields[*]}; i = i + 1)); do
+ new_part="$new_part":"${fields[$i]}"
+ done
+ new_part=${new_part:1}
+
+ # If this is an extended partition, removing it will also remove the
+ # logical partitions it contains. We need to save them for later.
+ if [ "$ptype" = "extended" ]; then
+ local table="$(get_partition_table "$device")"
+ local logical="$(get_logical_partitions "$table")"
+ fi
+
+ id=${fields[0]}
+ $PARTED -s -m "$device" rm "$id"
+ create_partition "$device" "$new_part" "$ptype"
+
+ if [ "$ptype" = "extended" ]; then
+ # Recreate logical partitions
+ echo "$logical" | while read logical_part; do
+ create_partition "$device" "$logical_part" "logical"
+ done
+ fi