mkswap-qemu.sh
1 |
#! /usr/bin/env bash |
---|---|
2 |
|
3 |
set -e |
4 |
|
5 |
output="$1" |
6 |
size="$2" |
7 |
|
8 |
if [ -z "${output}" -o -z "${size}" ]; then |
9 |
echo "Usage: mkswap-qemu <output> <sizeInMB> <mkswapArgs>..." >&2 |
10 |
|
11 |
exit 1 |
12 |
fi |
13 |
|
14 |
if [ $[${size} / 1] != "${size}" ] 2>/dev/null; then |
15 |
echo "Invalid size specified: ${size}" >&2 |
16 |
|
17 |
exit 1 |
18 |
fi |
19 |
|
20 |
shift; shift |
21 |
mkswap_args=("$@") |
22 |
|
23 |
tmpfile1='' |
24 |
tmpfile2='' |
25 |
|
26 |
function cleanup() { |
27 |
rm -f "${tmpfile1}" "${tmpfile2}" |
28 |
} |
29 |
|
30 |
trap cleanup EXIT |
31 |
|
32 |
tmpfile1="$(mktemp)" |
33 |
tmpfile2="$(mktemp)" |
34 |
pagesize="$(getconf PAGESIZE)" |
35 |
|
36 |
dd if=/dev/zero of="${tmpfile1}" bs=$[1024*1024] seek=$[${size} - 1] count=1 2>/dev/null |
37 |
|
38 |
mkswap "${mkswap_args[@]}" "${tmpfile1}" |
39 |
|
40 |
dd if="${tmpfile1}" bs="${pagesize}" count=1 of="${tmpfile2}" 2>/dev/null |
41 |
|
42 |
case "${output}" in |
43 |
rbd:*) |
44 |
output_format='raw' |
45 |
;; |
46 |
*.qcow2) |
47 |
output_format='qcow2' |
48 |
;; |
49 |
*) |
50 |
# Default: raw |
51 |
output_format='raw' |
52 |
;; |
53 |
esac |
54 |
|
55 |
qemu-img convert -O "${output_format}" -f raw "${tmpfile2}" "${output}" |
56 |
qemu-img resize -f "${output_format}" "${output}" "${size}M" |
57 |
|
58 |
exit 0 |