forked from Drewsif/PiShrink
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathpishrink
executable file
·91 lines (73 loc) · 2.09 KB
/
pishrink
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
#!/bin/bash
usage() { echo "Usage: $0 imagefile.img [newimagefile.img]"; exit -1; }
#Args
img="$1"
#Usage checks
if [[ -z "$img" ]]; then
usage
fi
if [[ ! -f "$img" ]]; then
echo "ERROR: $img is not a file..."
exit -2
fi
#Check that what we need is installed
for command in tune2fs e2fsck resize2fs; do
which $command 2>&1 >/dev/null
if (( $? != 0 )); then
echo "ERROR: $command is not installed."
exit -4
fi
done
#Copy to new file if requested
if [ -n "$2" ]; then
echo "Copying $1 to $2..."
cp "$1" "$2"
if (( $? != 0 )); then
echo "ERROR: Could not copy file..."
exit -5
fi
img="$2"
fi
#Gather info
beforesize=$(ls -lh "$img" | tr -s " " | cut -d " " -f 5)
partnum=$(fdisk "$img" | grep Linux | cut -d ":" -f1 | tr -d " ")
partstart=$(fdisk -d "$img" | grep 0x83 | cut -d "," -f1)
loopback=$(hdiutil attach -nomount "$img" | grep Linux | cut -d " " -f1)
tune2fs_output=$(tune2fs -l "$loopback")
currentsize=$(echo "$tune2fs_output" | grep '^Block count:' | tr -d ' ' | cut -d ':' -f 2)
blocksize=$(echo "$tune2fs_output" | grep '^Block size:' | tr -d ' ' | cut -d ':' -f 2)
#Make sure filesystem is ok, force yes on all questions
e2fsck -y -f "$loopback"
minsize=$(resize2fs -P "$loopback" | cut -d ':' -f 2 | tr -d ' ')
# add 200 MB of extra space, the system may need it to run, minsize is in blocks unit
minsize=$(($minsize + 200 * 1048576 / $blocksize))
if [[ $minsize -gt $currentsize ]]; then
echo "ERROR: Image already shrunk to smallest size"
exit -6
fi
#Shrink filesystem
resize2fs -p "$loopback" $minsize
if [[ $? != 0 ]]; then
echo "ERROR: resize2fs failed..."
hdiutil detach $loopback
exit -7
fi
sleep 1
#Shrink partition
hdiutil detach $loopback
# fdisk uses a block size of 512 Bytes!
partnewsize=$(($minsize * $blocksize / 512))
newpartend=$(($partstart + $partnewsize))
# now use fdisk to change the partition
fdisk -e "$img" <<EOF2
e $partnum
$newpartend
w
q
EOF2
sleep 1
#Truncate the file
endresult=$(($newpartend * 512))
truncate -s $endresult "$img"
aftersize=$(ls -lh "$img" | tr -s " " | cut -d " " -f 5)
echo "Shrunk $img from $beforesize to $aftersize"