-
Notifications
You must be signed in to change notification settings - Fork 2
/
shrink-vm
executable file
·105 lines (86 loc) · 2.48 KB
/
shrink-vm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#!/bin/bash
# SPDX-FileCopyrightText: 2016 - 2023 sudorook <[email protected]>
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <https://www.gnu.org/licenses/>.
set -euo pipefail
ROOT="$(dirname "${0}")"
source "${ROOT}"/globals
! check_command qemu-img && exit 3
#
# Functions
#
function abort() {
if [ -f "${1}.bak" ]; then
mv -f "${1}.bak" "${1}"
fi
}
function do_shrink() {
if test -r "${1}"; then
if ! [[ "$(file -b "${1}")" =~ QCOW ]]; then
echo -e $'\033[1;31m'"ERROR: ${1@Q} is not a QCOW2 file. Exiting."$'\033[0m' 1>&2
exit 3
fi
else
echo -e $'\033[1;31m'"ERROR: Cannot read ${1@Q}. Exiting."$'\033[0m' 1>&2
fi
echo -e $'\033[1;32m'"Shrinking..."$'\033[0m'
mv -f "${1}" "${1}.bak"
qemu-img convert -O qcow2 "${1}.bak" "${1}"
chmod --reference="${1}.bak" "${1}"
chown --reference="${1}.bak" "${1}"
rm -f "${1}.bak"
}
FUNCTION=$(declare -f do_shrink)
#
# Globals
#
QCOW2="${1}"
# Check inputs and requirements.
if ! [ -f "${QCOW2}" ]; then
show_error "ERROR: ${QCOW2@Q} doesn't exist. Exiting."
exit 3
fi
OWNER="$(stat "${QCOW2}" -c "%U")"
#
# Main
#
trap 'abort ${QCOW2}' INT TERM ERR
OLD_SIZE=$(du -h "${QCOW2}" | cut -f1)
case "${OWNER}" in
"${USER}")
do_shrink "${QCOW2}"
;;
root | qemu | libvirt-qemu)
show_info "${QCOW2@Q} owned by ${OWNER@Q}. Trying sudo..."
sudo bash -c "${FUNCTION} && do_shrink ${QCOW2}"
;;
nobody | kvm)
show_error "ERROR: Cannot edit running instance. Exiting."
exit 3
;;
*)
if [[ "$(users)" =~ (^|[[:space:]])${OWNER}($|[[:space:]]) ]]; then
show_warning "${QCOW2@Q} owned by ${OWNER}. Trying su..."
su "${OWNER}" - bash -c "${FUNCTION} && do_shrink ${QCOW2}"
else
show_error "User ${OWNER@Q} not recognized. Exiting."
exit 3
fi
;;
esac
NEW_SIZE=$(du -h "${QCOW2}" | cut -f1)
show_success "Compressed ${QCOW2@Q} from ${OLD_SIZE} to ${NEW_SIZE}."
sync