You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

431 lines
11 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. #!/bin/bash
  2. version="v0.1.2"
  3. CURRENT_DIR="$(pwd)"
  4. SCRIPTNAME="${0##*/}"
  5. MYNAME="${SCRIPTNAME%.*}"
  6. LOGFILE="${CURRENT_DIR}/${SCRIPTNAME%.*}.log"
  7. REQUIRED_TOOLS="parted losetup tune2fs md5sum e2fsck resize2fs"
  8. ZIPTOOLS=("gzip xz")
  9. declare -A ZIP_PARALLEL_TOOL=( [gzip]="pigz" [xz]="xz" ) # parallel zip tool to use in parallel mode
  10. declare -A ZIP_PARALLEL_OPTIONS=( [gzip]="-f9" [xz]="-T0" ) # options for zip tools in parallel mode
  11. declare -A ZIPEXTENSIONS=( [gzip]="gz" [xz]="xz" ) # extensions of zipped files
  12. function info() {
  13. echo "$SCRIPTNAME: $1 ..."
  14. }
  15. function error() {
  16. echo -n "$SCRIPTNAME: ERROR occurred in line $1: "
  17. shift
  18. echo "$@"
  19. }
  20. function cleanup() {
  21. if losetup "$loopback" &>/dev/null; then
  22. losetup -d "$loopback"
  23. fi
  24. if [ "$debug" = true ]; then
  25. local old_owner=$(stat -c %u:%g "$src")
  26. chown "$old_owner" "$LOGFILE"
  27. fi
  28. }
  29. function logVariables() {
  30. if [ "$debug" = true ]; then
  31. echo "Line $1" >> "$LOGFILE"
  32. shift
  33. local v var
  34. for var in "$@"; do
  35. eval "v=\$$var"
  36. echo "$var: $v" >> "$LOGFILE"
  37. done
  38. fi
  39. }
  40. function checkFilesystem() {
  41. info "Checking filesystem"
  42. e2fsck -pf "$loopback"
  43. (( $? < 4 )) && return
  44. info "Filesystem error detected!"
  45. info "Trying to recover corrupted filesystem"
  46. e2fsck -y "$loopback"
  47. (( $? < 4 )) && return
  48. if [[ $repair == true ]]; then
  49. info "Trying to recover corrupted filesystem - Phase 2"
  50. e2fsck -fy -b 32768 "$loopback"
  51. (( $? < 4 )) && return
  52. fi
  53. error $LINENO "Filesystem recoveries failed. Giving up..."
  54. exit 9
  55. }
  56. function set_autoexpand() {
  57. #Make pi expand rootfs on next boot
  58. mountdir=$(mktemp -d)
  59. partprobe "$loopback"
  60. mount "$loopback" "$mountdir"
  61. if [ ! -d "$mountdir/etc" ]; then
  62. info "/etc not found, autoexpand will not be enabled"
  63. umount "$mountdir"
  64. return
  65. fi
  66. if [[ -f "$mountdir/etc/rc.local" ]] && [[ "$(md5sum "$mountdir/etc/rc.local" | cut -d ' ' -f 1)" != "1c579c7d5b4292fd948399b6ece39009" ]]; then
  67. echo "Creating new /etc/rc.local"
  68. if [ -f "$mountdir/etc/rc.local" ]; then
  69. mv "$mountdir/etc/rc.local" "$mountdir/etc/rc.local.bak"
  70. fi
  71. #####Do not touch the following lines#####
  72. cat <<\EOF1 > "$mountdir/etc/rc.local"
  73. #!/bin/bash
  74. do_expand_rootfs() {
  75. ROOT_PART=$(mount | sed -n 's|^/dev/\(.*\) on / .*|\1|p')
  76. PART_NUM=${ROOT_PART#mmcblk0p}
  77. if [ "$PART_NUM" = "$ROOT_PART" ]; then
  78. echo "$ROOT_PART is not an SD card. Don't know how to expand"
  79. return 0
  80. fi
  81. # Get the starting offset of the root partition
  82. PART_START=$(parted /dev/mmcblk0 -ms unit s p | grep "^${PART_NUM}" | cut -f 2 -d: | sed 's/[^0-9]//g')
  83. [ "$PART_START" ] || return 1
  84. # Return value will likely be error for fdisk as it fails to reload the
  85. # partition table because the root fs is mounted
  86. fdisk /dev/mmcblk0 <<EOF
  87. p
  88. d
  89. $PART_NUM
  90. n
  91. p
  92. $PART_NUM
  93. $PART_START
  94. p
  95. w
  96. EOF
  97. cat <<EOF > /etc/rc.local &&
  98. #!/bin/sh
  99. echo "Expanding /dev/$ROOT_PART"
  100. resize2fs /dev/$ROOT_PART
  101. rm -f /etc/rc.local; cp -f /etc/rc.local.bak /etc/rc.local; /etc/rc.local
  102. EOF
  103. reboot
  104. exit
  105. }
  106. raspi_config_expand() {
  107. /usr/bin/env raspi-config --expand-rootfs
  108. if [[ $? != 0 ]]; then
  109. return -1
  110. else
  111. rm -f /etc/rc.local; cp -f /etc/rc.local.bak /etc/rc.local; /etc/rc.local
  112. reboot
  113. exit
  114. fi
  115. }
  116. raspi_config_expand
  117. echo "WARNING: Using backup expand..."
  118. sleep 5
  119. do_expand_rootfs
  120. echo "ERROR: Expanding failed..."
  121. sleep 5
  122. if [[ -f /etc/rc.local.bak ]]; then
  123. cp -f /etc/rc.local.bak /etc/rc.local
  124. /etc/rc.local
  125. fi
  126. exit 0
  127. EOF1
  128. #####End no touch zone#####
  129. chmod +x "$mountdir/etc/rc.local"
  130. fi
  131. umount "$mountdir"
  132. }
  133. help() {
  134. local help
  135. read -r -d '' help << EOM
  136. Usage: $0 [-adhrspvzZ] imagefile.img [newimagefile.img]
  137. -s Don't expand filesystem when image is booted the first time
  138. -v Be verbose
  139. -r Use advanced filesystem repair option if the normal one fails
  140. -z Compress image after shrinking with gzip
  141. -Z Compress image after shrinking with xz
  142. -a Compress image in parallel using multiple cores
  143. -p Remove logs, apt archives, dhcp leases and ssh hostkeys
  144. -d Write debug messages in a debug log file
  145. EOM
  146. echo "$help"
  147. exit 1
  148. }
  149. should_skip_autoexpand=false
  150. debug=false
  151. repair=false
  152. parallel=false
  153. verbose=false
  154. prep=false
  155. ziptool=""
  156. while getopts ":adhprsvzZ" opt; do
  157. case "${opt}" in
  158. a) parallel=true;;
  159. d) debug=true;;
  160. h) help;;
  161. p) prep=true;;
  162. r) repair=true;;
  163. s) should_skip_autoexpand=true ;;
  164. v) verbose=true;;
  165. z) ziptool="gzip";;
  166. Z) ziptool="xz";;
  167. *) help;;
  168. esac
  169. done
  170. shift $((OPTIND-1))
  171. if [ "$debug" = true ]; then
  172. info "Creating log file $LOGFILE"
  173. rm "$LOGFILE" &>/dev/null
  174. exec 1> >(stdbuf -i0 -o0 -e0 tee -a "$LOGFILE" >&1)
  175. exec 2> >(stdbuf -i0 -o0 -e0 tee -a "$LOGFILE" >&2)
  176. fi
  177. echo "${0##*/} $version"
  178. #Args
  179. src="$1"
  180. img="$1"
  181. #Usage checks
  182. if [[ -z "$img" ]]; then
  183. help
  184. fi
  185. if [[ ! -f "$img" ]]; then
  186. error $LINENO "$img is not a file..."
  187. exit 2
  188. fi
  189. if (( EUID != 0 )); then
  190. error $LINENO "You need to be running as root."
  191. exit 3
  192. fi
  193. # set locale to POSIX(English) temporarily
  194. # these locale settings only affect the script and its sub processes
  195. export LANGUAGE=POSIX
  196. export LC_ALL=POSIX
  197. export LANG=POSIX
  198. # check selected compression tool is supported and installed
  199. if [[ -n $ziptool ]]; then
  200. if [[ ! " ${ZIPTOOLS[@]} " =~ $ziptool ]]; then
  201. error $LINENO "$ziptool is an unsupported ziptool."
  202. exit 17
  203. else
  204. if [[ $parallel == true && $ziptool == "gzip" ]]; then
  205. REQUIRED_TOOLS="$REQUIRED_TOOLS pigz"
  206. else
  207. REQUIRED_TOOLS="$REQUIRED_TOOLS $ziptool"
  208. fi
  209. fi
  210. fi
  211. #Check that what we need is installed
  212. for command in $REQUIRED_TOOLS; do
  213. command -v $command >/dev/null 2>&1
  214. if (( $? != 0 )); then
  215. error $LINENO "$command is not installed."
  216. exit 4
  217. fi
  218. done
  219. #Copy to new file if requested
  220. if [ -n "$2" ]; then
  221. f="$2"
  222. if [[ -n $ziptool && "${f##*.}" == "${ZIPEXTENSIONS[$ziptool]}" ]]; then # remove zip extension if zip requested because zip tool will complain about extension
  223. f="${f%.*}"
  224. fi
  225. info "Copying $1 to $f..."
  226. cp --reflink=auto --sparse=always "$1" "$f"
  227. if (( $? != 0 )); then
  228. error $LINENO "Could not copy file..."
  229. exit 5
  230. fi
  231. old_owner=$(stat -c %u:%g "$1")
  232. chown "$old_owner" "$f"
  233. img="$f"
  234. fi
  235. # cleanup at script exit
  236. trap cleanup EXIT
  237. #Gather info
  238. info "Gathering data"
  239. beforesize="$(ls -lh "$img" | cut -d ' ' -f 5)"
  240. parted_output="$(parted -ms "$img" unit B print)"
  241. rc=$?
  242. if (( $rc )); then
  243. error $LINENO "parted failed with rc $rc"
  244. info "Possibly invalid image. Run 'parted $img unit B print' manually to investigate"
  245. exit 6
  246. fi
  247. partnum="$(echo "$parted_output" | tail -n 1 | cut -d ':' -f 1)"
  248. partstart="$(echo "$parted_output" | tail -n 1 | cut -d ':' -f 2 | tr -d 'B')"
  249. if [ -z "$(parted -s "$img" unit B print | grep "$partstart" | grep logical)" ]; then
  250. parttype="primary"
  251. else
  252. parttype="logical"
  253. fi
  254. loopback="$(losetup -f --show -o "$partstart" "$img")"
  255. tune2fs_output="$(tune2fs -l "$loopback")"
  256. rc=$?
  257. if (( $rc )); then
  258. echo "$tune2fs_output"
  259. error $LINENO "tune2fs failed. Unable to shrink this type of image"
  260. exit 7
  261. fi
  262. currentsize="$(echo "$tune2fs_output" | grep '^Block count:' | tr -d ' ' | cut -d ':' -f 2)"
  263. blocksize="$(echo "$tune2fs_output" | grep '^Block size:' | tr -d ' ' | cut -d ':' -f 2)"
  264. logVariables $LINENO beforesize parted_output partnum partstart parttype tune2fs_output currentsize blocksize
  265. #Check if we should make pi expand rootfs on next boot
  266. if [ "$parttype" == "logical" ]; then
  267. echo "WARNING: PiShrink does not yet support autoexpanding of this type of image"
  268. elif [ "$should_skip_autoexpand" = false ]; then
  269. set_autoexpand
  270. else
  271. echo "Skipping autoexpanding process..."
  272. fi
  273. if [[ $prep == true ]]; then
  274. info "Syspreping: Removing logs, apt archives, dhcp leases and ssh hostkeys"
  275. mountdir=$(mktemp -d)
  276. mount "$loopback" "$mountdir"
  277. rm -rvf $mountdir/var/cache/apt/archives/* $mountdir/var/lib/dhcpcd5/* $mountdir/var/log/* $mountdir/var/tmp/* $mountdir/tmp/* $mountdir/etc/ssh/*_host_*
  278. umount "$mountdir"
  279. fi
  280. #Make sure filesystem is ok
  281. checkFilesystem
  282. if ! minsize=$(resize2fs -P "$loopback"); then
  283. rc=$?
  284. error $LINENO "resize2fs failed with rc $rc"
  285. exit 10
  286. fi
  287. minsize=$(cut -d ':' -f 2 <<< "$minsize" | tr -d ' ')
  288. logVariables $LINENO currentsize minsize
  289. if [[ $currentsize -eq $minsize ]]; then
  290. error $LINENO "Image already shrunk to smallest size"
  291. exit 11
  292. fi
  293. #Add some free space to the end of the filesystem
  294. extra_space=$(($currentsize - $minsize))
  295. logVariables $LINENO extra_space
  296. for space in 5000 1000 100; do
  297. if [[ $extra_space -gt $space ]]; then
  298. minsize=$(($minsize + $space))
  299. break
  300. fi
  301. done
  302. logVariables $LINENO minsize
  303. #Shrink filesystem
  304. info "Shrinking filesystem"
  305. resize2fs -p "$loopback" $minsize
  306. rc=$?
  307. if (( $rc )); then
  308. error $LINENO "resize2fs failed with rc $rc"
  309. mount "$loopback" "$mountdir"
  310. mv "$mountdir/etc/rc.local.bak" "$mountdir/etc/rc.local"
  311. umount "$mountdir"
  312. losetup -d "$loopback"
  313. exit 12
  314. fi
  315. sleep 1
  316. #Shrink partition
  317. partnewsize=$(($minsize * $blocksize))
  318. newpartend=$(($partstart + $partnewsize))
  319. logVariables $LINENO partnewsize newpartend
  320. parted -s -a minimal "$img" rm "$partnum"
  321. rc=$?
  322. if (( $rc )); then
  323. error $LINENO "parted failed with rc $rc"
  324. exit 13
  325. fi
  326. parted -s "$img" unit B mkpart "$parttype" "$partstart" "$newpartend"
  327. rc=$?
  328. if (( $rc )); then
  329. error $LINENO "parted failed with rc $rc"
  330. exit 14
  331. fi
  332. #Truncate the file
  333. info "Shrinking image"
  334. endresult=$(parted -ms "$img" unit B print free)
  335. rc=$?
  336. if (( $rc )); then
  337. error $LINENO "parted failed with rc $rc"
  338. exit 15
  339. fi
  340. endresult=$(tail -1 <<< "$endresult" | cut -d ':' -f 2 | tr -d 'B')
  341. logVariables $LINENO endresult
  342. truncate -s "$endresult" "$img"
  343. rc=$?
  344. if (( $rc )); then
  345. error $LINENO "trunate failed with rc $rc"
  346. exit 16
  347. fi
  348. # handle compression
  349. if [[ -n $ziptool ]]; then
  350. options=""
  351. envVarname="${MYNAME^^}_${ziptool^^}" # PISHRINK_GZIP or PISHRINK_XZ environment variables allow to override all options for gzip or xz
  352. [[ $parallel == true ]] && options="${ZIP_PARALLEL_OPTIONS[$ziptool]}"
  353. [[ -v $envVarname ]] && options="${!envVarname}" # if environment variable defined use these options
  354. [[ $verbose == true ]] && options="$options -v" # add verbose flag if requested
  355. if [[ $parallel == true ]]; then
  356. parallel_tool="${ZIP_PARALLEL_TOOL[$ziptool]}"
  357. info "Using $parallel_tool on the shrunk image"
  358. if ! $parallel_tool ${options} "$img"; then
  359. rc=$?
  360. error $LINENO "$parallel_tool failed with rc $rc"
  361. exit 18
  362. fi
  363. else # sequential
  364. info "Using $ziptool on the shrunk image"
  365. if ! $ziptool ${options} "$img"; then
  366. rc=$?
  367. error $LINENO "$ziptool failed with rc $rc"
  368. exit 19
  369. fi
  370. fi
  371. img=$img.${ZIPEXTENSIONS[$ziptool]}
  372. fi
  373. aftersize=$(ls -lh "$img" | cut -d ' ' -f 5)
  374. logVariables $LINENO aftersize
  375. info "Shrunk $img from $beforesize to $aftersize"