#!/bin/sh MIN_DISK_SPACE_MB=1000 list_disks() { lsblk -o NAME -r -d -n } main() { local disks=$(list_disks) local found_free_space=0 local found_device="" for device_name in ${disks}; do local device="/dev/${device_name}" echo "Checking disk '$device'..." local disk_free_space="$(parted $device unit MB print free 2>/dev/null | grep 'Free Space' | tail -n1 | awk '{ print $3 }')" disk_free_space=${disk_free_space%MB} disk_free_space=$(printf '%.0f' "${disk_free_space:-0}") echo "Free space on disk: ${disk_free_space}" if [ ! -z "${disk_free_space}" ]; then if [ ${disk_free_space} -gt ${found_free_space} ]; then found_free_space=${disk_free_space} found_device=${device} fi fi done if [ -z "${found_device}" ] || [ ${MIN_DISK_SPACE_MB} -gt ${found_free_space} ]; then echo "No device with sufficient remaining disk space, exiting." exit 1 fi echo "Creating new partition on '${found_device}' with remaining disk free space" local last_partition_end_mb=$(parted "$found_device" unit MB print | awk '/^ [0-9]+ / {start=$3} END {print int(start)}') if [ "${last_partition_end_mb}" != "0" ]; then parted -s "${found_device}" -f -a opt mkpart primary "${last_partition_end_mb}MB" '100%' else parted -s "${found_device}" -f -a opt mkpart primary '0%' '100%' fi sync local last_partition_number=$(parted ${found_device} print | grep -o -e '^ [0-9]*' | awk '{print $1}' | tail -n 1) local new_partition_device=$(lsblk -r -n -o PARTN,NAME ${found_device} | awk -v partition_number="${last_partition_number}" '$1 == partition_number {print $2}') mkfs.ext4 -F /dev/${new_partition_device} if [ $? -ne 0 ]; then echo "Could not initialize filesystem on new partition !" exit 1 fi local new_partition_uuid=$(lsblk -r -n -o PARTN,UUID ${found_device} | awk -v partition_number="${last_partition_number}" '$1 == partition_number {print $2}') if [ -z "${new_partition_uuid}" ]; then echo "Could not find partition with number '${last_partition_number}' !" exit 1 fi umount -f /data rm -rf /data mkdir -p /data uci add fstab mount uci set fstab.@mount[-1].target='/data' uci set fstab.@mount[-1].uuid=${new_partition_uuid} uci set fstab.@mount[-1].enabled='1' uci commit fstab reload_config } main