Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- #
- # optimage.sh <foo.img>
- #
- # repackages filesystem images for improved compression
- # all modifications to the images are non-destructive
- # method shown from and explained by [mbm]
- #
- # created by CEnnis91 (2012)
- #
- if [ $(whoami) != "root" ]; then
- echo "Error: You must run as root!"
- exit 1
- fi
- fsimg=$(readlink -f "$1")
- if [ ! -f "$fsimg" ]; then
- echo "Error: File does not exist!"
- exit 1
- fi
- fstype=$(file "$fsimg" | grep -io "ext[2-4]")
- if [ -z "$fstype" ]; then
- echo "Error: Invalid file type!"
- exit 1
- fi
- fsname=$(basename "$fsimg" | sed 's|^\(.*\)[.].*$|\1|')
- blkcount=$(tune2fs -l "$fsimg" | grep "Block count" | sed 's|[^0-9]*\(.*\)|\1|')
- blksize=$(tune2fs -l "$fsimg" | grep "Block size" | sed 's|[^0-9]*\(.*\)|\1|')
- tmpdir=$(mktemp -d)
- tmplog=$(mktemp)
- exec 3>&1 > $tmplog 2>&1
- trap "rm -r $tmpdir" 0 1 2 3 15
- trap "echo 'Something went wrong! Read $tmplog for details.' >&3; exit 0" ERR
- echo "Creating blank image..." >&3
- mv "$fsimg" "$fsimg.old"
- dd if=/dev/zero of="$fsimg" bs=$blksize count=$blkcount
- mke2fs -F -b $blksize -T "$fstype" "$fsimg"
- mkdir -p "$tmpdir/$fsname" "$tmpdir/old_$fsname"
- echo "Copying data over..." >&3
- mount -o loop "$fsimg" "$tmpdir/$fsname"
- mount -o loop "$fsimg.old" "$tmpdir/old_$fsname"
- cp -af "$tmpdir/old_$fsname"/* "$tmpdir/$fsname"
- umount "$tmpdir/$fsname/"
- umount "$tmpdir/old_$fsname/"
- owner=$(ls -al "$fsimg.old" | cut -d " " -f 3-4 | sed 's/ /:/g')
- chown "$owner" "$fsimg"
- echo "Success!" >&3
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement