~ubuntu-on-ec2/ubuntu-on-ec2/uec-tools

« back to all changes in this revision

Viewing changes to resize-uec-image

  • Committer: Scott Moser
  • Date: 2009-10-09 16:58:15 UTC
  • Revision ID: smoser@canonical.com-20091009165815-yg44tqe98uy9qgff
initial revision of resize-uec-image

versions of this script first appeared from mdz on ubuntu-devel, then
were modified by smoser and uploaded to bug 439868.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/bin/sh
 
2
# resize-uec-image
 
3
 
 
4
Usage() {
 
5
        cat <<EOF
 
6
Usage: ${0##*/} image size [output]
 
7
   Resize a UEC image to a new size.
 
8
   if output is given, do not modify 'image', but create new file 'output'
 
9
 
 
10
   New size is specified per resize2fs(8), e.g. "1G" for 1 gigabyte
 
11
EOF
 
12
        return 0
 
13
}
 
14
 
 
15
error() { echo "$@" 1>&2; }
 
16
fail() { [ $# -eq 0 ] || error "$@"; exit 1; }
 
17
 
 
18
human2bytes() {
 
19
   # converts size suitable for input to resize2fs to bytes
 
20
   # s:512 byte sectors, K:kilobytes, M:megabytes, G:gigabytes
 
21
   # none: block size of the image
 
22
   local input=${1} defunit=${2:-1024}
 
23
   local unit count;
 
24
   case "$input" in
 
25
      *s) count=${input%s}; unit=512;;
 
26
      *K) count=${input%K}; unit=1024;;
 
27
      *M) count=${input%M}; unit=$((1024*1024));;
 
28
      *G) count=${input%G}; unit=$((1024*1024*1024));;
 
29
      *)  count=${input}  ; unit=${2:-1024};;
 
30
   esac
 
31
   _RET=$((${count}*${unit}))
 
32
}
 
33
 
 
34
[ "$1" = "-h" -o "$1" = "--help" ] && { Usage; exit 0; }
 
35
 
 
36
[ $# -eq 3 -o $# -eq 2 ] || { Usage 1>&2; exit 1; }
 
37
 
 
38
old="$1"
 
39
size="$2"
 
40
new="${3:-${old}}"
 
41
 
 
42
human2bytes "${size}" && new_size=${_RET} ||
 
43
   fail "failed to understand ${size}"
 
44
 
 
45
if [ ! "${old}" -ef "${new}" ]; then
 
46
   file_out=$(file "${old}") || fail "failed to read ${old} with 'file'"
 
47
   case "${file_out}" in
 
48
      *gzip\ compressed*)
 
49
         zcat -f "$old" | cp --sparse=always /dev/stdin "$new";;
 
50
      *) cp --sparse=always "${old}" "${new}";;
 
51
   esac
 
52
   [ $? -eq 0 ] || fail "failed to cp ${old} -> ${new}"
 
53
fi
 
54
 
 
55
ls_out=$(ls -l "${new}") &&
 
56
   old_size=$(echo "${ls_out}" | awk '{print $5}') ||
 
57
   fail "failed to get size of ${new_img}"
 
58
 
 
59
e2fsck -fp "$new" || fail "failed to fsck ${new}"
 
60
 
 
61
if [ "${old_size}" -lt "${new_size}" ]; then
 
62
   truncate "--size=$size" "$new" || fail "failed to change size of ${new}"
 
63
fi
 
64
 
 
65
resize2fs "$new" "$size" || fail "failed to resize ${new} -> ${size}"
 
66
 
 
67
if [ "${old_size}" -gt "${new_size}" ]; then
 
68
   truncate "--size=$size" "$new" || fail "failed to change size of ${new}"
 
69
fi
 
70
 
 
71
exit 0