mybin

my ~/bin
git clone https://a3nm.net/git/mybin/
Log | Files | Refs | README

commit 3134bfaf878aed2f16206a111d44bd820561c94e
parent c6ed0b4850f394d46a5d4bf9aa5cc0063a814d74
Author: Antoine Amarilli <a3nm@a3nm.net>
Date:   Sun,  4 Oct 2015 01:33:09 +0200

shrinkimg

Diffstat:
shrinkimg | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 80 insertions(+), 0 deletions(-)

diff --git a/shrinkimg b/shrinkimg @@ -0,0 +1,80 @@ +#!/bin/bash + +# shrink the (possibly compressed) ext[2-4] disk image $1 +# and compress it to $2, overwriting it + +if [ "$#" -ne 2 ] || ! [ -f "$1" ]; then + echo "Usage: $0 INPUT.img(.xz|.gz|) OUTPUT.img.xz" >&2 + exit 8 +fi + +FILE="$1" +OUT="$2" +DIR=$(dirname $(readlink -f "$OUT")) +# create temporary file in directory of output +TEMP=$(mktemp -p "$DIR") +OSIZE=$(du -h "$FILE" | cut -f1) + +TYPE=$(file "$FILE" | cut -d ':' -f2) + +echo "creating $TEMP" + +case $TYPE in + *'XZ compressed'*) + pv -N "unxz" "$FILE" | xz -dc >$TEMP + ;; + *'gzip compressed'*) + pv -N "gunzip" "$FILE" | gzip -dc >$TEMP + ;; + *'ext'[2-4]' filesystem data'*) + pv -N "cp" "$FILE" >$TEMP + ;; + *) + echo "unknown type for $FILE: $TYPE" + echo "aborting" + exit 1 + ;; +esac + +TYPE2=$(file "$TEMP" | cut -d ':' -f2) + +case $TYPE2 in + *'ext'[2-4]' filesystem data'*) + # do nothing + ;; + *) + echo "unknown type after decompressing to $TEMP: $TYPE2" + echo "aborting WITHOUT removing $TEMP" + exit 1 + ;; +esac + +OSPACE=$(du -h "$TEMP" |cut -f1) + +chronic e2fsck -fn "$TEMP" || { + echo "e2fsck errors in $TEMP, please fix" + echo "aborting WITHOUT removing $TEMP" + exit 2 +} +chronic resize2fs -M "$TEMP" || { + echo "error when resizing $TEMP"; + echo "aborting WITHOUT removing $TEMP" + exit 3 +} + +NSPACE=$(du -h "$TEMP" |cut -f1) + +(pv -N "xz" "$TEMP" | xz -9c >"$OUT") || { + echo "error when compressing $TEMP, please fix"; + echo "aborting WITHOUT removing $TEMP" + exit 4 +} +rm $TEMP + +NSIZE=$(du -h "$OUT" | cut -f1) + +echo "successfully shrunk $FILE to $OUT" +echo "uncompressed apparent size went from $OSPACE bytes to $NSPACE bytes" +echo "compressed apparent size went from $OSIZE bytes to $NSIZE bytes" +exit 0 +