#!/bin/sh # resize-uec-image Usage() { cat <&2; } fail() { [ $# -eq 0 ] || error "$@"; exit 1; } human2bytes() { # converts size suitable for input to resize2fs to bytes # s:512 byte sectors, K:kilobytes, M:megabytes, G:gigabytes # none: block size of the image local input=${1} defunit=${2:-1024} local unit count; case "$input" in *s) count=${input%s}; unit=512;; *K) count=${input%K}; unit=1024;; *M) count=${input%M}; unit=$((1024*1024));; *G) count=${input%G}; unit=$((1024*1024*1024));; *) count=${input} ; unit=${2:-1024};; esac _RET=$((${count}*${unit})) } [ "$1" = "-h" -o "$1" = "--help" ] && { Usage; exit 0; } [ $# -eq 3 -o $# -eq 2 ] || { Usage 1>&2; exit 1; } old="$1" size="$2" new="${3:-${old}}" human2bytes "${size}" && new_size=${_RET} || fail "failed to understand ${size}" if [ ! "${old}" -ef "${new}" ]; then file_out=$(file "${old}") || fail "failed to read ${old} with 'file'" case "${file_out}" in *gzip\ compressed*) zcat -f "$old" | cp --sparse=always /dev/stdin "$new";; *) cp --sparse=always "${old}" "${new}";; esac [ $? -eq 0 ] || fail "failed to cp ${old} -> ${new}" fi ls_out=$(ls -l "${new}") && old_size=$(echo "${ls_out}" | awk '{print $5}') || fail "failed to get size of ${new_img}" e2fsck -fp "$new" || fail "failed to fsck ${new}" if [ "${old_size}" -lt "${new_size}" ]; then truncate "--size=$size" "$new" || fail "failed to change size of ${new}" fi resize2fs "$new" "$size" || fail "failed to resize ${new} -> ${size}" if [ "${old_size}" -gt "${new_size}" ]; then truncate "--size=$size" "$new" || fail "failed to change size of ${new}" fi exit 0