CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
orangepi-xunlong

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

GitHub Repository: orangepi-xunlong/orangepi-build
Path: blob/next/scripts/debootstrap.sh
Views: 3960
1
#!/bin/bash
2
#
3
# Copyright (c) 2013-2021 Igor Pecovnik, igor.pecovnik@gma**.com
4
#
5
# This file is licensed under the terms of the GNU General Public
6
# License version 2. This program is licensed "as is" without any
7
# warranty of any kind, whether express or implied.
8
9
10
# Functions:
11
12
# debootstrap_ng
13
# create_rootfs_cache
14
# prepare_partitions
15
# update_initramfs
16
# create_image
17
18
19
20
21
# debootstrap_ng
22
#
23
debootstrap_ng()
24
{
25
display_alert "Starting rootfs and image building process for" "${BRANCH} ${BOARD} ${RELEASE} ${DESKTOP_APPGROUPS_SELECTED:-null} ${DESKTOP_ENVIRONMENT:-null} ${BUILD_MINIMAL}" "info"
26
27
[[ $ROOTFS_TYPE != ext4 ]] && display_alert "Assuming $BOARD $BRANCH kernel supports $ROOTFS_TYPE" "" "wrn"
28
29
# trap to unmount stuff in case of error/manual interruption
30
trap unmount_on_exit INT TERM EXIT
31
32
# stage: clean and create directories
33
rm -rf $SDCARD $MOUNT
34
mkdir -p $SDCARD $MOUNT $DEST/images $EXTER/cache/rootfs
35
36
# stage: verify tmpfs configuration and mount
37
# CLI needs ~1.5GiB, desktop - ~3.5GiB
38
# calculate and set tmpfs mount to use 9/10 of available RAM+SWAP
39
local phymem=$(( (($(awk '/MemTotal/ {print $2}' /proc/meminfo) + $(awk '/SwapTotal/ {print $2}' /proc/meminfo))) / 1024 * 9 / 10 )) # MiB
40
if [[ $BUILD_DESKTOP == yes ]]; then local tmpfs_max_size=3500; else local tmpfs_max_size=1500; fi # MiB
41
if [[ $FORCE_USE_RAMDISK == no ]]; then local use_tmpfs=no
42
elif [[ $FORCE_USE_RAMDISK == yes || $phymem -gt $tmpfs_max_size ]]; then
43
local use_tmpfs=yes
44
fi
45
[[ -n $FORCE_TMPFS_SIZE ]] && phymem=$FORCE_TMPFS_SIZE
46
47
[[ $use_tmpfs == yes ]] && mount -t tmpfs -o size=${phymem}M tmpfs $SDCARD
48
49
# stage: prepare basic rootfs: unpack cache or create from scratch
50
create_rootfs_cache
51
52
call_extension_method "pre_install_distribution_specific" "config_pre_install_distribution_specific" << 'PRE_INSTALL_DISTRIBUTION_SPECIFIC'
53
*give config a chance to act before install_distribution_specific*
54
Called after `create_rootfs_cache` (_prepare basic rootfs: unpack cache or create from scratch_) but before `install_distribution_specific` (_install distribution and board specific applications_).
55
PRE_INSTALL_DISTRIBUTION_SPECIFIC
56
57
# stage: install kernel and u-boot packages
58
# install distribution and board specific applications
59
60
if [[ ${RELEASE} == "raspi" ]]; then
61
install_opi_specific
62
else
63
install_distribution_specific
64
install_common
65
66
# install locally built packages or install pre-built packages from orangepi
67
[[ $EXTERNAL_NEW == compile || $EXTERNAL_NEW == prebuilt ]] && chroot_installpackages_local
68
69
#[[ $EXTERNAL_NEW == prebuilt ]] && chroot_installpackages "yes"
70
71
# stage: user customization script
72
# NOTE: installing too many packages may fill tmpfs mount
73
customize_image
74
75
# remove packages that are no longer needed. Since we have intrudoced uninstall feature, we might want to clean things that are no longer needed
76
display_alert "No longer needed packages" "purge" "info"
77
chroot $SDCARD /bin/bash -c "apt-get autoremove -y" >/dev/null 2>&1
78
79
# create list of installed packages for debug purposes
80
chroot $SDCARD /bin/bash -c "dpkg --get-selections" | grep -v deinstall | awk '{print $1}' | cut -f1 -d':' > $DEST/${LOG_SUBPATH}/installed-packages-${RELEASE}$([[ ${BUILD_MINIMAL} == yes ]] && echo "-minimal")$([[ ${BUILD_DESKTOP} == yes ]] && echo "-desktop").list 2>&1
81
82
fi
83
84
# clean up / prepare for making the image
85
umount_chroot "$SDCARD"
86
post_debootstrap_tweaks
87
88
if [[ $ROOTFS_TYPE == fel ]]; then
89
FEL_ROOTFS=$SDCARD/
90
display_alert "Starting FEL boot" "$BOARD" "info"
91
source $SRC/scripts/fel-load.sh
92
else
93
prepare_partitions
94
create_image
95
fi
96
97
# stage: unmount tmpfs
98
umount $SDCARD 2>&1
99
if [[ $use_tmpfs = yes ]]; then
100
while grep -qs "$SDCARD" /proc/mounts
101
do
102
umount $SDCARD
103
sleep 5
104
done
105
fi
106
rm -rf $SDCARD
107
108
# remove exit trap
109
trap - INT TERM EXIT
110
} #############################################################################
111
112
bootstrap(){
113
local BOOTSTRAP_CMD=debootstrap
114
local BOOTSTRAP_ARGS=()
115
116
export CAPSH_ARG="--drop=cap_setfcap"
117
export http_proxy=${APT_PROXY}
118
119
BOOTSTRAP_ARGS+=(--arch arm64)
120
BOOTSTRAP_ARGS+=(--include gnupg)
121
#BOOTSTRAP_ARGS+=(--components "main,contrib,non-free")
122
BOOTSTRAP_ARGS+=(--components "main")
123
BOOTSTRAP_ARGS+=(--exclude=info)
124
BOOTSTRAP_ARGS+=(--include=ca-certificates)
125
BOOTSTRAP_ARGS+=("$@")
126
printf -v BOOTSTRAP_STR '%q ' "${BOOTSTRAP_ARGS[@]}"
127
128
${BOOTSTRAP_CMD} $BOOTSTRAP_STR || true
129
}
130
export -f bootstrap
131
132
# create_rootfs_cache
133
#
134
# unpacks cached rootfs for $RELEASE or creates one
135
#
136
create_rootfs_cache()
137
{
138
139
local packages_hash=$(get_package_list_hash "$ROOTFSCACHE_VERSION")
140
local cache_type="cli"
141
[[ ${BUILD_DESKTOP} == yes ]] && local cache_type="xfce-desktop"
142
[[ -n ${DESKTOP_ENVIRONMENT} ]] && local cache_type="${DESKTOP_ENVIRONMENT}"
143
[[ ${BUILD_MINIMAL} == yes ]] && local cache_type="minimal"
144
local cache_name=${RELEASE}-${cache_type}-${ARCH}.$packages_hash.tar.lz4
145
local cache_fname=${EXTER}/cache/rootfs/${cache_name}
146
local display_name=${RELEASE}-${cache_type}-${ARCH}.${packages_hash:0:3}...${packages_hash:29}.tar.lz4
147
148
if [[ -f $cache_fname && "$ROOT_FS_CREATE_ONLY" != "force" ]]; then
149
local date_diff=$(( ($(date +%s) - $(stat -c %Y $cache_fname)) / 86400 ))
150
display_alert "Extracting $display_name" "$date_diff days old" "info"
151
pv -p -b -r -c -N "[ .... ] $display_name" "$cache_fname" | lz4 -dc | tar xp --xattrs -C $SDCARD/
152
[[ $? -ne 0 ]] && rm $cache_fname && exit_with_error "Cache $cache_fname is corrupted and was deleted. Restart."
153
rm $SDCARD/etc/resolv.conf
154
echo "nameserver $NAMESERVER" >> $SDCARD/etc/resolv.conf
155
create_sources_list "$RELEASE" "$SDCARD/"
156
elif [[ $RELEASE == "raspi" ]]; then
157
display_alert "local not found" "Creating new rootfs cache for $RELEASE" "info"
158
159
cd $SDCARD # this will prevent error sh: 0: getcwd() failed
160
161
bootstrap bullseye "$SDCARD" "https://mirrors.ustc.edu.cn/debian/"
162
163
mount_chroot "$SDCARD"
164
165
display_alert "Diverting" "initctl/start-stop-daemon" "info"
166
# policy-rc.d script prevents starting or reloading services during image creation
167
printf '#!/bin/sh\nexit 101' > $SDCARD/usr/sbin/policy-rc.d
168
LC_ALL=C LANG=C chroot $SDCARD /bin/bash -c "dpkg-divert --quiet --local --rename --add /sbin/initctl" &> /dev/null
169
LC_ALL=C LANG=C chroot $SDCARD /bin/bash -c "dpkg-divert --quiet --local --rename --add /sbin/start-stop-daemon" &> /dev/null
170
printf '#!/bin/sh\necho "Warning: Fake start-stop-daemon called, doing nothing"' > $SDCARD/sbin/start-stop-daemon
171
printf '#!/bin/sh\necho "Warning: Fake initctl called, doing nothing"' > $SDCARD/sbin/initctl
172
chmod 755 $SDCARD/usr/sbin/policy-rc.d
173
chmod 755 $SDCARD/sbin/initctl
174
chmod 755 $SDCARD/sbin/start-stop-daemon
175
176
install_raspi_specific
177
178
umount_chroot "$SDCARD"
179
180
tar cp --xattrs --directory=$SDCARD/ --exclude='./dev/*' --exclude='./proc/*' --exclude='./run/*' --exclude='./tmp/*' \
181
--exclude='./sys/*' . | pv -p -b -r -s $(du -sb $SDCARD/ | cut -f1) -N "$display_name" | lz4 -5 -c > $cache_fname
182
else
183
display_alert "local not found" "Creating new rootfs cache for $RELEASE" "info"
184
185
# stage: debootstrap base system
186
if [[ $NO_APT_CACHER != yes ]]; then
187
# apt-cacher-ng apt-get proxy parameter
188
local apt_extra="-o Acquire::http::Proxy=\"http://${APT_PROXY_ADDR:-localhost:3142}\""
189
local apt_mirror="http://${APT_PROXY_ADDR:-localhost:3142}/$APT_MIRROR"
190
else
191
local apt_mirror="http://$APT_MIRROR"
192
fi
193
194
# fancy progress bars
195
[[ -z $OUTPUT_DIALOG ]] && local apt_extra_progress="--show-progress -o DPKG::Progress-Fancy=1"
196
197
# Ok so for eval+PIPESTATUS.
198
# Try this on your bash shell:
199
# ONEVAR="testing" eval 'bash -c "echo value once $ONEVAR && false && echo value twice $ONEVAR"' '| grep value' '| grep value' ; echo ${PIPESTATUS[*]}
200
# Notice how PIPESTATUS has only one element. and it is always true, although we failed explicitly with false in the middle of the bash.
201
# That is because eval itself is considered a single command, no matter how many pipes you put in there, you'll get a single value, the return code of the LAST pipe.
202
# Lets export the value of the pipe inside eval so we know outside what happened:
203
# ONEVAR="testing" eval 'bash -e -c "echo value once $ONEVAR && false && echo value twice $ONEVAR"' '| grep value' '| grep value' ';EVALPIPE=(${PIPESTATUS[@]})' ; echo ${EVALPIPE[*]}
204
205
local release_version=${RELEASE}
206
207
if [[ ${RELEASE} == "sid" ]]; then
208
release_version=unstable
209
apt_mirror="https://snapshot.debian.org/archive/debian-ports/20221225T084846Z"
210
DEBOOTSTRAP_OPTION="--no-check-gpg --no-merged-usr"
211
PACKAGE_LIST_EXCLUDE="usr-is-merged"
212
fi
213
214
display_alert "Installing base system" "Stage 1/2" "info"
215
cd $SDCARD # this will prevent error sh: 0: getcwd() failed
216
217
eval 'debootstrap --variant=minbase --include=${DEBOOTSTRAP_LIST// /,} ${PACKAGE_LIST_EXCLUDE:+ --exclude=${PACKAGE_LIST_EXCLUDE// /,}} \
218
--arch=$ARCH --components=${DEBOOTSTRAP_COMPONENTS} $DEBOOTSTRAP_OPTION --foreign ${release_version} $SDCARD/ ${apt_mirror}' \
219
${PROGRESS_LOG_TO_FILE:+' | tee -a $DEST/${LOG_SUBPATH}/debootstrap.log'} \
220
${OUTPUT_DIALOG:+' | dialog --backtitle "$backtitle" --progressbox "Debootstrap (stage 1/2)..." $TTY_Y $TTY_X'} \
221
${OUTPUT_VERYSILENT:+' >/dev/null 2>/dev/null'} ';EVALPIPE=(${PIPESTATUS[@]})'
222
223
[[ ${EVALPIPE[0]} -ne 0 || ! -f $SDCARD/debootstrap/debootstrap ]] && exit_with_error "Debootstrap base system for ${BRANCH} ${BOARD} ${RELEASE} ${DESKTOP_APPGROUPS_SELECTED} ${DESKTOP_ENVIRONMENT} ${BUILD_MINIMAL} first stage failed"
224
225
cp /usr/bin/$QEMU_BINARY $SDCARD/usr/bin/
226
227
mkdir -p $SDCARD/usr/share/keyrings/
228
cp /usr/share/keyrings/*-archive-keyring.gpg $SDCARD/usr/share/keyrings/
229
230
display_alert "Installing base system" "Stage 2/2" "info"
231
eval 'LC_ALL=C LANG=C chroot $SDCARD /bin/bash -e -c "/debootstrap/debootstrap --second-stage"' \
232
${PROGRESS_LOG_TO_FILE:+' | tee -a $DEST/${LOG_SUBPATH}/debootstrap.log'} \
233
${OUTPUT_DIALOG:+' | dialog --backtitle "$backtitle" --progressbox "Debootstrap (stage 2/2)..." $TTY_Y $TTY_X'} \
234
${OUTPUT_VERYSILENT:+' >/dev/null 2>/dev/null'} ';EVALPIPE=(${PIPESTATUS[@]})'
235
236
[[ ${EVALPIPE[0]} -ne 0 || ! -f $SDCARD/bin/bash ]] && exit_with_error "Debootstrap base system for ${BRANCH} ${BOARD} ${RELEASE} ${DESKTOP_APPGROUPS_SELECTED} ${DESKTOP_ENVIRONMENT} ${BUILD_MINIMAL} second stage failed"
237
238
mount_chroot "$SDCARD"
239
240
if [[ ${RELEASE} == "sid" ]]; then
241
mkdir -p $SDCARD/etc/apt/apt.conf.d/
242
echo "Acquire::Check-Valid-Until no;" > $SDCARD/etc/apt/apt.conf.d/99-no-check-valid-until
243
wget -qnc -P ${EXTER}/cache/debs/ https://snapshot.debian.org/archive/debian-ports/20220616T194833Z/pool-riscv64/main/i/icu/libicu71_71.1-3_riscv64.deb
244
cp -v ${EXTER}/cache/debs/libicu71_71.1-3_riscv64.deb $SDCARD/
245
LC_ALL=C LANG=C chroot $SDCARD /bin/bash -c "dpkg -i /libicu71_71.1-3_riscv64.deb" &> /dev/null
246
fi
247
248
display_alert "Diverting" "initctl/start-stop-daemon" "info"
249
# policy-rc.d script prevents starting or reloading services during image creation
250
printf '#!/bin/sh\nexit 101' > $SDCARD/usr/sbin/policy-rc.d
251
LC_ALL=C LANG=C chroot $SDCARD /bin/bash -c "dpkg-divert --quiet --local --rename --add /sbin/initctl" &> /dev/null
252
LC_ALL=C LANG=C chroot $SDCARD /bin/bash -c "dpkg-divert --quiet --local --rename --add /sbin/start-stop-daemon" &> /dev/null
253
printf '#!/bin/sh\necho "Warning: Fake start-stop-daemon called, doing nothing"' > $SDCARD/sbin/start-stop-daemon
254
printf '#!/bin/sh\necho "Warning: Fake initctl called, doing nothing"' > $SDCARD/sbin/initctl
255
chmod 755 $SDCARD/usr/sbin/policy-rc.d
256
chmod 755 $SDCARD/sbin/initctl
257
chmod 755 $SDCARD/sbin/start-stop-daemon
258
259
# stage: configure language and locales
260
display_alert "Configuring locales" "$DEST_LANG" "info"
261
262
[[ -f $SDCARD/etc/locale.gen ]] && sed -i "s/^# $DEST_LANG/$DEST_LANG/" $SDCARD/etc/locale.gen
263
eval 'LC_ALL=C LANG=C chroot $SDCARD /bin/bash -c "locale-gen $DEST_LANG"' ${OUTPUT_VERYSILENT:+' >/dev/null 2>/dev/null'}
264
eval 'LC_ALL=C LANG=C chroot $SDCARD /bin/bash -c "update-locale LANG=$DEST_LANG LANGUAGE=$DEST_LANG LC_MESSAGES=$DEST_LANG"' \
265
${OUTPUT_VERYSILENT:+' >/dev/null 2>/dev/null'}
266
267
if [[ -f $SDCARD/etc/default/console-setup ]]; then
268
sed -e 's/CHARMAP=.*/CHARMAP="UTF-8"/' -e 's/FONTSIZE=.*/FONTSIZE="8x16"/' \
269
-e 's/CODESET=.*/CODESET="guess"/' -i $SDCARD/etc/default/console-setup
270
eval 'LC_ALL=C LANG=C chroot $SDCARD /bin/bash -c "setupcon --save --force"'
271
fi
272
273
# stage: create apt-get sources list
274
create_sources_list "$RELEASE" "$SDCARD/"
275
276
# add armhf arhitecture to arm64, unless configured not to do so.
277
if [[ "a${ARMHF_ARCH}" != "askip" ]]; then
278
[[ $ARCH == arm64 ]] && eval 'LC_ALL=C LANG=C chroot $SDCARD /bin/bash -c "dpkg --add-architecture armhf"'
279
fi
280
281
# this should fix resolvconf installation failure in some cases
282
chroot $SDCARD /bin/bash -c 'echo "resolvconf resolvconf/linkify-resolvconf boolean false" | debconf-set-selections'
283
284
# stage: update packages list
285
display_alert "Updating package list" "$RELEASE" "info"
286
eval 'LC_ALL=C LANG=C chroot $SDCARD /bin/bash -e -c "apt-get -q -y $apt_extra update"' \
287
${PROGRESS_LOG_TO_FILE:+' | tee -a $DEST/${LOG_SUBPATH}/debootstrap.log'} \
288
${OUTPUT_DIALOG:+' | dialog --backtitle "$backtitle" --progressbox "Updating package lists..." $TTY_Y $TTY_X'} \
289
${OUTPUT_VERYSILENT:+' >/dev/null 2>/dev/null'} ';EVALPIPE=(${PIPESTATUS[@]})'
290
291
[[ ${EVALPIPE[0]} -ne 0 ]] && display_alert "Updating package lists" "failed" "wrn"
292
293
# stage: upgrade base packages from xxx-updates and xxx-backports repository branches
294
display_alert "Upgrading base packages" "Orange Pi" "info"
295
eval 'LC_ALL=C LANG=C chroot $SDCARD /bin/bash -e -c "DEBIAN_FRONTEND=noninteractive apt-get -y -q \
296
$apt_extra $apt_extra_progress upgrade"' \
297
${PROGRESS_LOG_TO_FILE:+' | tee -a $DEST/${LOG_SUBPATH}/debootstrap.log'} \
298
${OUTPUT_DIALOG:+' | dialog --backtitle "$backtitle" --progressbox "Upgrading base packages..." $TTY_Y $TTY_X'} \
299
${OUTPUT_VERYSILENT:+' >/dev/null 2>/dev/null'} ';EVALPIPE=(${PIPESTATUS[@]})'
300
301
# Myy: Dividing the desktop packages installation steps into multiple
302
# ones. We first install the "ADDITIONAL_PACKAGES" in order to get
303
# access to software-common-properties installation.
304
# THEN we add the APT sources and install the Desktop packages.
305
# TODO : Find a way to add APT sources WITHOUT software-common-properties
306
307
[[ ${EVALPIPE[0]} -ne 0 ]] && display_alert "Upgrading base packages" "failed" "wrn"
308
309
# stage: install additional packages
310
display_alert "Installing the main packages for" "Orange Pi" "info"
311
eval 'LC_ALL=C LANG=C chroot $SDCARD /bin/bash -e -c "DEBIAN_FRONTEND=noninteractive apt-get -y -q \
312
$apt_extra $apt_extra_progress --no-install-recommends install $PACKAGE_MAIN_LIST"' \
313
${PROGRESS_LOG_TO_FILE:+' | tee -a $DEST/${LOG_SUBPATH}/debootstrap.log'} \
314
${OUTPUT_DIALOG:+' | dialog --backtitle "$backtitle" --progressbox "Installing Orange Pi main packages..." $TTY_Y $TTY_X'} \
315
${OUTPUT_VERYSILENT:+' >/dev/null 2>/dev/null'} ';EVALPIPE=(${PIPESTATUS[@]})'
316
317
[[ ${PIPESTATUS[0]} -ne 0 ]] && exit_with_error "Installation of Orange Pi main packages for ${BRANCH} ${BOARD} ${RELEASE} ${DESKTOP_APPGROUPS_SELECTED} ${DESKTOP_ENVIRONMENT} ${BUILD_MINIMAL} failed"
318
319
if [[ $BUILD_DESKTOP == "yes" ]]; then
320
# FIXME Myy : Are we keeping this only for Desktop users,
321
# or should we extend this to CLI users too ?
322
# There might be some clunky boards that require Debian packages from
323
# specific repos...
324
display_alert "Adding apt sources for Desktop packages"
325
add_desktop_package_sources
326
327
local apt_desktop_install_flags=""
328
if [[ ! -z ${DESKTOP_APT_FLAGS_SELECTED+x} ]]; then
329
for flag in ${DESKTOP_APT_FLAGS_SELECTED}; do
330
apt_desktop_install_flags+=" --install-${flag}"
331
done
332
else
333
# Myy : Using the previous default option, if the variable isn't defined
334
# And ONLY if it's not defined !
335
apt_desktop_install_flags+=" --no-install-recommends"
336
fi
337
338
display_alert "Installing the desktop packages for" "Orange Pi" "info"
339
eval 'LC_ALL=C LANG=C chroot $SDCARD /bin/bash -e -c "DEBIAN_FRONTEND=noninteractive apt-get -y -q \
340
$apt_extra $apt_extra_progress install ${apt_desktop_install_flags} $PACKAGE_LIST_DESKTOP"' \
341
${PROGRESS_LOG_TO_FILE:+' | tee -a $DEST/${LOG_SUBPATH}/debootstrap.log'} \
342
${OUTPUT_DIALOG:+' | dialog --backtitle "$backtitle" --progressbox "Installing Orange Pi desktop packages..." $TTY_Y $TTY_X'} \
343
${OUTPUT_VERYSILENT:+' >/dev/null 2>/dev/null'} ';EVALPIPE=(${PIPESTATUS[@]})'
344
345
[[ ${PIPESTATUS[0]} -ne 0 ]] && exit_with_error "Installation of Orange Pi desktop packages for ${BRANCH} ${BOARD} ${RELEASE} ${DESKTOP_APPGROUPS_SELECTED} ${DESKTOP_ENVIRONMENT} ${BUILD_MINIMAL} failed"
346
fi
347
348
install_docker
349
[[ ${BOARDFAMILY} == "starfive2" ]] && jh7110_install_libs
350
351
# Remove packages from packages.uninstall
352
353
display_alert "Uninstall packages" "$PACKAGE_LIST_UNINSTALL" "info"
354
eval 'LC_ALL=C LANG=C chroot $SDCARD /bin/bash -e -c "DEBIAN_FRONTEND=noninteractive apt-get -y -qq \
355
$apt_extra $apt_extra_progress purge $PACKAGE_LIST_UNINSTALL"' \
356
${PROGRESS_LOG_TO_FILE:+' >> $DEST/${LOG_SUBPATH}/debootstrap.log'} \
357
${OUTPUT_DIALOG:+' | dialog --backtitle "$backtitle" --progressbox "Removing packages.uninstall packages..." $TTY_Y $TTY_X'} \
358
${OUTPUT_VERYSILENT:+' >/dev/null 2>/dev/null'} ';EVALPIPE=(${PIPESTATUS[@]})'
359
360
[[ ${EVALPIPE[0]} -ne 0 ]] && exit_with_error "Installation of Orange Pi packages failed"
361
362
# stage: purge residual packages
363
display_alert "Purging residual packages for" "Orange Pi" "info"
364
PURGINGPACKAGES=$(chroot $SDCARD /bin/bash -c "dpkg -l | grep \"^rc\" | awk '{print \$2}' | tr \"\n\" \" \"")
365
eval 'LC_ALL=C LANG=C chroot $SDCARD /bin/bash -e -c "DEBIAN_FRONTEND=noninteractive apt-get -y -q \
366
$apt_extra $apt_extra_progress remove --purge $PURGINGPACKAGES"' \
367
${PROGRESS_LOG_TO_FILE:+' | tee -a $DEST/${LOG_SUBPATH}/debootstrap.log'} \
368
${OUTPUT_DIALOG:+' | dialog --backtitle "$backtitle" --progressbox "Purging residual Orange Pi packages..." $TTY_Y $TTY_X'} \
369
${OUTPUT_VERYSILENT:+' >/dev/null 2>/dev/null'} ';EVALPIPE=(${PIPESTATUS[@]})'
370
371
[[ ${EVALPIPE[0]} -ne 0 ]] && exit_with_error "Purging of residual Orange Pi packages failed"
372
373
# stage: remove downloaded packages
374
chroot $SDCARD /bin/bash -c "apt-get -y autoremove; apt-get clean"
375
376
# DEBUG: print free space
377
local freespace=$(LC_ALL=C df -h)
378
echo $freespace >> $DEST/${LOG_SUBPATH}/debootstrap.log
379
display_alert "Free SD cache" "$(echo -e "$freespace" | grep $SDCARD | awk '{print $5}')" "info"
380
display_alert "Mount point" "$(echo -e "$freespace" | grep $MOUNT | head -1 | awk '{print $5}')" "info"
381
382
# create list of installed packages for debug purposes
383
chroot $SDCARD /bin/bash -c "dpkg --get-selections" | grep -v deinstall | awk '{print $1}' | cut -f1 -d':' > ${cache_fname}.list 2>&1
384
385
# creating xapian index that synaptic runs faster
386
if [[ $BUILD_DESKTOP == yes ]]; then
387
display_alert "Recreating Synaptic search index" "Please wait" "info"
388
chroot $SDCARD /bin/bash -c "[[ -f /usr/sbin/update-apt-xapian-index ]] && /usr/sbin/update-apt-xapian-index -u"
389
fi
390
391
# this is needed for the build process later since resolvconf generated file in /run is not saved
392
rm $SDCARD/etc/resolv.conf
393
echo "nameserver $NAMESERVER" >> $SDCARD/etc/resolv.conf
394
395
# stage: make rootfs cache archive
396
display_alert "Ending debootstrap process and preparing cache" "$RELEASE" "info"
397
sync
398
# the only reason to unmount here is compression progress display
399
# based on rootfs size calculation
400
umount_chroot "$SDCARD"
401
402
tar cp --xattrs --directory=$SDCARD/ --exclude='./dev/*' --exclude='./proc/*' --exclude='./run/*' --exclude='./tmp/*' \
403
--exclude='./sys/*' --exclude='./home/*' --exclude='./root/*' . | pv -p -b -r -s $(du -sb $SDCARD/ | cut -f1) -N "$display_name" | lz4 -5 -c > $cache_fname
404
405
# sign rootfs cache archive that it can be used for web cache once. Internal purposes
406
if [[ -n "${GPG_PASS}" && "${SUDO_USER}" ]]; then
407
[[ -n ${SUDO_USER} ]] && sudo chown -R ${SUDO_USER}:${SUDO_USER} "${DEST}"/images/
408
echo "${GPG_PASS}" | sudo -H -u ${SUDO_USER} bash -c "gpg --passphrase-fd 0 --armor --detach-sign --pinentry-mode loopback --batch --yes ${cache_fname}" || exit 1
409
fi
410
411
# needed for backend to keep current only
412
touch $cache_fname.current
413
414
fi
415
416
# used for internal purposes. Faster rootfs cache rebuilding
417
if [[ -n "$ROOT_FS_CREATE_ONLY" ]]; then
418
umount --lazy "$SDCARD"
419
rm -rf $SDCARD
420
421
display_alert "Rootfs build done" "@host" "info"
422
display_alert "Target directory" "${EXTER}/cache/rootfs" "info"
423
display_alert "File name" "${cache_name}" "info"
424
425
# remove exit trap
426
trap - INT TERM EXIT
427
exit
428
fi
429
430
mount_chroot "$SDCARD"
431
} #############################################################################
432
433
# prepare_partitions
434
#
435
# creates image file, partitions and fs
436
# and mounts it to local dir
437
# FS-dependent stuff (boot and root fs partition types) happens here
438
#
439
prepare_partitions() {
440
display_alert "Preparing image file for rootfs" "$BOARD $RELEASE" "info"
441
442
# possible partition combinations
443
# /boot: none, ext4, ext2, fat (BOOTFS_TYPE)
444
# root: ext4, btrfs, f2fs, nfs (ROOTFS_TYPE)
445
446
# declare makes local variables by default if used inside a function
447
# NOTE: mountopts string should always start with comma if not empty
448
449
# array copying in old bash versions is tricky, so having filesystems as arrays
450
# with attributes as keys is not a good idea
451
declare -A parttype mkopts mkopts_label mkfs mountopts
452
453
parttype[ext4]=ext4
454
parttype[ext2]=ext2
455
parttype[fat]=fat16
456
parttype[f2fs]=ext4 # not a copy-paste error
457
parttype[btrfs]=btrfs
458
parttype[xfs]=xfs
459
# parttype[nfs] is empty
460
461
# metadata_csum and 64bit may need to be disabled explicitly when migrating to newer supported host OS releases
462
if [[ $HOSTRELEASE =~ buster|bullseye|bookworm|bionic|focal|jammy|noble|kinetic|sid ]]; then
463
mkopts[ext4]="-q -m 2 -O ^64bit,^metadata_csum"
464
fi
465
# mkopts[fat] is empty
466
mkopts[ext2]='-q'
467
# mkopts[f2fs] is empty
468
mkopts[btrfs]='-m dup'
469
# mkopts[xfs] is empty
470
# mkopts[nfs] is empty
471
472
mkopts_label[ext4]='-L '
473
mkopts_label[ext2]='-L '
474
mkopts_label[fat]='-n '
475
mkopts_label[f2fs]='-l '
476
mkopts_label[btrfs]='-L '
477
mkopts_label[xfs]='-L '
478
# mkopts_label[nfs] is empty
479
480
mkfs[ext4]=ext4
481
mkfs[ext2]=ext2
482
mkfs[fat]=vfat
483
mkfs[f2fs]=f2fs
484
mkfs[btrfs]=btrfs
485
mkfs[xfs]=xfs
486
# mkfs[nfs] is empty
487
488
mountopts[ext4]=',commit=600,errors=remount-ro'
489
# mountopts[ext2] is empty
490
# mountopts[fat] is empty
491
# mountopts[f2fs] is empty
492
mountopts[btrfs]=',commit=600'
493
# mountopts[xfs] is empty
494
# mountopts[nfs] is empty
495
496
# default BOOTSIZE to use if not specified
497
DEFAULT_BOOTSIZE=1024 # MiB
498
# size of UEFI partition. 0 for no UEFI. Don't mix UEFISIZE>0 and BOOTSIZE>0
499
UEFISIZE=${UEFISIZE:-0}
500
BIOSSIZE=${BIOSSIZE:-0}
501
UEFI_MOUNT_POINT=${UEFI_MOUNT_POINT:-/boot/efi}
502
UEFI_FS_LABEL="${UEFI_FS_LABEL:-opi_efi}"
503
ROOT_FS_LABEL="${ROOT_FS_LABEL:-opi_root}"
504
BOOT_FS_LABEL="${BOOT_FS_LABEL:-opi_boot}"
505
506
call_extension_method "pre_prepare_partitions" "prepare_partitions_custom" << 'PRE_PREPARE_PARTITIONS'
507
*allow custom options for mkfs*
508
Good time to change stuff like mkfs opts, types etc.
509
PRE_PREPARE_PARTITIONS
510
511
# stage: determine partition configuration
512
local next=1
513
# Check if we need UEFI partition
514
if [[ $UEFISIZE -gt 0 ]]; then
515
# Check if we need BIOS partition
516
[[ $BIOSSIZE -gt 0 ]] && local biospart=$((next++))
517
local uefipart=$((next++))
518
fi
519
# Check if we need boot partition
520
if [[ -n $BOOTFS_TYPE || $ROOTFS_TYPE != ext4 || $CRYPTROOT_ENABLE == yes ]]; then
521
local bootpart=$((next++))
522
local bootfs=${BOOTFS_TYPE:-ext4}
523
[[ -z $BOOTSIZE || $BOOTSIZE -le 8 ]] && BOOTSIZE=${DEFAULT_BOOTSIZE}
524
else
525
BOOTSIZE=0
526
fi
527
# Check if we need root partition
528
[[ $ROOTFS_TYPE != nfs ]] &&
529
local rootpart=$((next++))
530
531
# stage: calculate rootfs size
532
export rootfs_size=$(du -sm $SDCARD/ | cut -f1) # MiB
533
display_alert "Current rootfs size" "$rootfs_size MiB" "info"
534
535
call_extension_method "prepare_image_size" "config_prepare_image_size" << 'PREPARE_IMAGE_SIZE'
536
*allow dynamically determining the size based on the $rootfs_size*
537
Called after `${rootfs_size}` is known, but before `${FIXED_IMAGE_SIZE}` is taken into account.
538
A good spot to determine `FIXED_IMAGE_SIZE` based on `rootfs_size`.
539
UEFISIZE can be set to 0 for no UEFI partition, or to a size in MiB to include one.
540
Last chance to set `USE_HOOK_FOR_PARTITION`=yes and then implement create_partition_table hook_point.
541
PREPARE_IMAGE_SIZE
542
543
if [[ -n $FIXED_IMAGE_SIZE && $FIXED_IMAGE_SIZE =~ ^[0-9]+$ ]]; then
544
display_alert "Using user-defined image size" "$FIXED_IMAGE_SIZE MiB" "info"
545
local sdsize=$FIXED_IMAGE_SIZE
546
# basic sanity check
547
if [[ $ROOTFS_TYPE != nfs && $sdsize -lt $rootfs_size ]]; then
548
exit_with_error "User defined image size is too small" "$sdsize <= $rootfs_size"
549
fi
550
else
551
local imagesize=$(($rootfs_size + $OFFSET + $BOOTSIZE + $UEFISIZE + $EXTRA_ROOTFS_MIB_SIZE)) # MiB
552
# Hardcoded overhead +25% is needed for desktop images,
553
# for CLI it could be lower. Align the size up to 4MiB
554
if [[ $BUILD_DESKTOP == yes ]]; then
555
local sdsize=$(bc -l <<< "scale=0; ((($imagesize * 1.35) / 1 + 0) / 4 + 1) * 4")
556
else
557
local sdsize=$(bc -l <<< "scale=0; ((($imagesize * 1.30) / 1 + 0) / 4 + 1) * 4")
558
fi
559
fi
560
561
# stage: create blank image
562
display_alert "Creating blank image for rootfs" "$sdsize MiB" "info"
563
if [[ $FAST_CREATE_IMAGE == yes ]]; then
564
truncate --size=${sdsize}M ${SDCARD}.raw # sometimes results in fs corruption, revert to previous know to work solution
565
sync
566
else
567
dd if=/dev/zero bs=1M status=none count=$sdsize | pv -p -b -r -s $(($sdsize * 1024 * 1024)) -N "[ .... ] dd" | dd status=none of=${SDCARD}.raw
568
fi
569
570
# stage: create partition table
571
display_alert "Creating partitions" "${bootfs:+/boot: $bootfs }root: $ROOTFS_TYPE" "info"
572
if [[ "${USE_HOOK_FOR_PARTITION}" == "yes" ]]; then
573
{
574
[[ "$IMAGE_PARTITION_TABLE" == "msdos" ]] &&
575
echo "label: dos" ||
576
echo "label: $IMAGE_PARTITION_TABLE"
577
} | sfdisk ${SDCARD}.raw >> "${DEST}/${LOG_SUBPATH}/install.log" 2>&1 ||
578
exit_with_error "Create partition table fail. Please check" "${DEST}/${LOG_SUBPATH}/install.log"
579
580
call_extension_method "create_partition_table" <<- 'CREATE_PARTITION_TABLE'
581
*only called when USE_HOOK_FOR_PARTITION=yes to create the complete partition table*
582
Finally, we can get our own partition table. You have to partition ${SDCARD}.raw
583
yourself. Good luck.
584
CREATE_PARTITION_TABLE
585
else
586
{
587
[[ "$IMAGE_PARTITION_TABLE" == "msdos" ]] &&
588
echo "label: dos" ||
589
echo "label: $IMAGE_PARTITION_TABLE"
590
591
local next=$OFFSET
592
if [[ -n "$biospart" ]]; then
593
# gpt: BIOS boot
594
local type="21686148-6449-6E6F-744E-656564454649"
595
echo "$biospart : name=\"bios\", start=${next}MiB, size=${BIOSSIZE}MiB, type=${type}"
596
local next=$(($next + $BIOSSIZE))
597
fi
598
if [[ -n "$uefipart" ]]; then
599
# dos: EFI (FAT-12/16/32)
600
# gpt: EFI System
601
[[ "$IMAGE_PARTITION_TABLE" != "gpt" ]] &&
602
local type="ef" ||
603
local type="C12A7328-F81F-11D2-BA4B-00A0C93EC93B"
604
echo "$uefipart : name=\"efi\", start=${next}MiB, size=${UEFISIZE}MiB, type=${type}"
605
local next=$(($next + $UEFISIZE))
606
fi
607
if [[ -n "$bootpart" ]]; then
608
# Linux extended boot
609
[[ "$IMAGE_PARTITION_TABLE" != "gpt" ]] &&
610
local type="ea" ||
611
local type="BC13C2FF-59E6-4262-A352-B275FD6F7172"
612
if [[ -n "$rootpart" ]]; then
613
echo "$bootpart : name=\"bootfs\", start=${next}MiB, size=${BOOTSIZE}MiB, type=${type}"
614
local next=$(($next + $BOOTSIZE))
615
else
616
# no `size` argument mean "as much as possible"
617
echo "$bootpart : name=\"bootfs\", start=${next}MiB, type=${type}"
618
fi
619
fi
620
if [[ -n "$rootpart" ]]; then
621
# dos: Linux
622
# gpt: Linux filesystem
623
[[ "$IMAGE_PARTITION_TABLE" != "gpt" ]] &&
624
local type="83" ||
625
local type="0FC63DAF-8483-4772-8E79-3D69D8477DE4"
626
# no `size` argument mean "as much as possible"
627
echo "$rootpart : name=\"rootfs\", start=${next}MiB, type=${type}"
628
fi
629
} | sfdisk ${SDCARD}.raw >> "${DEST}/${LOG_SUBPATH}/install.log" 2>&1 ||
630
exit_with_error "Partition fail. Please check" "${DEST}/${LOG_SUBPATH}/install.log"
631
fi
632
633
call_extension_method "post_create_partitions" <<- 'POST_CREATE_PARTITIONS'
634
*called after all partitions are created, but not yet formatted*
635
POST_CREATE_PARTITIONS
636
637
# stage: mount image
638
# lock access to loop devices
639
exec {FD}> /var/lock/orangepi-debootstrap-losetup
640
flock -x $FD
641
642
LOOP=$(losetup -f)
643
[[ -z $LOOP ]] && exit_with_error "Unable to find free loop device"
644
645
check_loop_device "$LOOP"
646
647
losetup $LOOP ${SDCARD}.raw
648
649
# loop device was grabbed here, unlock
650
flock -u $FD
651
652
partprobe $LOOP
653
654
# stage: create fs, mount partitions, create fstab
655
rm -f $SDCARD/etc/fstab
656
if [[ -n $rootpart ]]; then
657
local rootdevice="${LOOP}p${rootpart}"
658
659
if [[ $CRYPTROOT_ENABLE == yes ]]; then
660
display_alert "Encrypting root partition with LUKS..." "cryptsetup luksFormat $rootdevice" ""
661
echo -n $CRYPTROOT_PASSPHRASE | cryptsetup luksFormat $CRYPTROOT_PARAMETERS $rootdevice -
662
echo -n $CRYPTROOT_PASSPHRASE | cryptsetup luksOpen $rootdevice $ROOT_MAPPER -
663
display_alert "Root partition encryption complete." "" "ext"
664
# TODO: pass /dev/mapper to Docker
665
rootdevice=/dev/mapper/$ROOT_MAPPER # used by `mkfs` and `mount` commands
666
fi
667
668
check_loop_device "$rootdevice"
669
display_alert "Creating rootfs" "$ROOTFS_TYPE on $rootdevice"
670
mkfs.${mkfs[$ROOTFS_TYPE]} ${mkopts[$ROOTFS_TYPE]} ${mkopts_label[$ROOTFS_TYPE]:+${mkopts_label[$ROOTFS_TYPE]}"$ROOT_FS_LABEL"} $rootdevice >> "${DEST}"/${LOG_SUBPATH}/install.log 2>&1
671
[[ $ROOTFS_TYPE == ext4 ]] && tune2fs -o journal_data_writeback $rootdevice > /dev/null
672
if [[ $ROOTFS_TYPE == btrfs && $BTRFS_COMPRESSION != none ]]; then
673
local fscreateopt="-o compress-force=${BTRFS_COMPRESSION}"
674
fi
675
mount ${fscreateopt} $rootdevice $MOUNT/
676
# create fstab (and crypttab) entry
677
if [[ $CRYPTROOT_ENABLE == yes ]]; then
678
# map the LUKS container partition via its UUID to be the 'cryptroot' device
679
echo "$ROOT_MAPPER UUID=$(blkid -s UUID -o value ${LOOP}p${rootpart}) none luks" >> $SDCARD/etc/crypttab
680
local rootfs=$rootdevice # used in fstab
681
else
682
local rootfs="UUID=$(blkid -s UUID -o value $rootdevice)"
683
fi
684
echo "$rootfs / ${mkfs[$ROOTFS_TYPE]} defaults,noatime${mountopts[$ROOTFS_TYPE]} 0 1" >> $SDCARD/etc/fstab
685
else
686
# update_initramfs will fail if /lib/modules/ doesn't exist
687
mount --bind --make-private $SDCARD $MOUNT/
688
echo "/dev/nfs / nfs defaults 0 0" >> $SDCARD/etc/fstab
689
fi
690
if [[ -n $bootpart ]]; then
691
display_alert "Creating /boot" "$bootfs on ${LOOP}p${bootpart}"
692
check_loop_device "${LOOP}p${bootpart}"
693
mkfs.${mkfs[$bootfs]} ${mkopts[$bootfs]} ${mkopts_label[$bootfs]:+${mkopts_label[$bootfs]}"$BOOT_FS_LABEL"} ${LOOP}p${bootpart} >> "${DEST}"/${LOG_SUBPATH}/install.log 2>&1
694
mkdir -p $MOUNT/boot/
695
mount ${LOOP}p${bootpart} $MOUNT/boot/
696
echo "UUID=$(blkid -s UUID -o value ${LOOP}p${bootpart}) /boot ${mkfs[$bootfs]} defaults${mountopts[$bootfs]} 0 2" >> $SDCARD/etc/fstab
697
fi
698
if [[ -n $uefipart ]]; then
699
display_alert "Creating EFI partition" "FAT32 ${UEFI_MOUNT_POINT} on ${LOOP}p${uefipart} label ${UEFI_FS_LABEL}"
700
check_loop_device "${LOOP}p${uefipart}"
701
mkfs.fat -F32 -n "${UEFI_FS_LABEL}" ${LOOP}p${uefipart} >> "${DEST}"/debug/install.log 2>&1
702
mkdir -p "${MOUNT}${UEFI_MOUNT_POINT}"
703
mount ${LOOP}p${uefipart} "${MOUNT}${UEFI_MOUNT_POINT}"
704
echo "UUID=$(blkid -s UUID -o value ${LOOP}p${uefipart}) ${UEFI_MOUNT_POINT} vfat defaults 0 2" >> $SDCARD/etc/fstab
705
fi
706
echo "tmpfs /tmp tmpfs defaults,nosuid 0 0" >> $SDCARD/etc/fstab
707
708
call_extension_method "format_partitions" <<- 'FORMAT_PARTITIONS'
709
*if you created your own partitions, this would be a good time to format them*
710
The loop device is mounted, so ${LOOP}p1 is it's first partition etc.
711
FORMAT_PARTITIONS
712
713
# stage: adjust boot script or boot environment
714
if [[ -f $SDCARD/boot/orangepiEnv.txt ]]; then
715
if [[ $CRYPTROOT_ENABLE == yes ]]; then
716
echo "rootdev=$rootdevice cryptdevice=UUID=$(blkid -s UUID -o value ${LOOP}p${rootpart}):$ROOT_MAPPER" >> $SDCARD/boot/orangepiEnv.txt
717
else
718
echo "rootdev=$rootfs" >> $SDCARD/boot/orangepiEnv.txt
719
fi
720
echo "rootfstype=$ROOTFS_TYPE" >> $SDCARD/boot/orangepiEnv.txt
721
elif [[ $rootpart != 1 ]] && [[ $SRC_EXTLINUX != yes ]]; then
722
local bootscript_dst=${BOOTSCRIPT##*:}
723
sed -i 's/mmcblk0p1/mmcblk0p2/' $SDCARD/boot/$bootscript_dst
724
sed -i -e "s/rootfstype=ext4/rootfstype=$ROOTFS_TYPE/" \
725
-e "s/rootfstype \"ext4\"/rootfstype \"$ROOTFS_TYPE\"/" $SDCARD/boot/$bootscript_dst
726
fi
727
728
# if we have boot.ini = remove orangepiEnv.txt and add UUID there if enabled
729
if [[ -f $SDCARD/boot/boot.ini ]]; then
730
sed -i -e "s/rootfstype \"ext4\"/rootfstype \"$ROOTFS_TYPE\"/" $SDCARD/boot/boot.ini
731
if [[ $CRYPTROOT_ENABLE == yes ]]; then
732
local rootpart="UUID=$(blkid -s UUID -o value ${LOOP}p${rootpart})"
733
sed -i 's/^setenv rootdev .*/setenv rootdev "\/dev\/mapper\/'$ROOT_MAPPER' cryptdevice='$rootpart':'$ROOT_MAPPER'"/' $SDCARD/boot/boot.ini
734
else
735
sed -i 's/^setenv rootdev .*/setenv rootdev "'$rootfs'"/' $SDCARD/boot/boot.ini
736
fi
737
if [[ $LINUXFAMILY != meson64 ]]; then
738
[[ -f $SDCARD/boot/orangepiEnv.txt ]] && rm $SDCARD/boot/orangepiEnv.txt
739
fi
740
fi
741
742
# if we have a headless device, set console to DEFAULT_CONSOLE
743
if [[ -n $DEFAULT_CONSOLE && -f $SDCARD/boot/orangepiEnv.txt ]]; then
744
if grep -lq "^console=" $SDCARD/boot/orangepiEnv.txt; then
745
sed -i "s/^console=.*/console=$DEFAULT_CONSOLE/" $SDCARD/boot/orangepiEnv.txt
746
else
747
echo "console=$DEFAULT_CONSOLE" >> $SDCARD/boot/orangepiEnv.txt
748
fi
749
fi
750
751
# recompile .cmd to .scr if boot.cmd exists
752
753
if [[ -f $SDCARD/boot/boot.cmd ]]; then
754
if [ -z $BOOTSCRIPT_OUTPUT ]; then BOOTSCRIPT_OUTPUT=boot.scr; fi
755
mkimage -C none -A arm -T script -d $SDCARD/boot/boot.cmd $SDCARD/boot/$BOOTSCRIPT_OUTPUT > /dev/null 2>&1
756
fi
757
758
# create extlinux config
759
if [[ -f $SDCARD/boot/extlinux/extlinux.conf ]]; then
760
echo " append root=$rootfs $SRC_CMDLINE $MAIN_CMDLINE" >> $SDCARD/boot/extlinux/extlinux.conf
761
[[ -f $SDCARD/boot/orangepiEnv.txt ]] && rm $SDCARD/boot/orangepiEnv.txt
762
fi
763
764
}
765
766
# update_initramfs
767
#
768
# this should be invoked as late as possible for any modifications by
769
# customize_image (userpatches) and prepare_partitions to be reflected in the
770
# final initramfs
771
#
772
# especially, this needs to be invoked after /etc/crypttab has been created
773
# for cryptroot-unlock to work:
774
# https://serverfault.com/questions/907254/cryproot-unlock-with-dropbear-timeout-while-waiting-for-askpass
775
#
776
# since Debian buster, it has to be called within create_image() on the $MOUNT
777
# path instead of $SDCARD (which can be a tmpfs and breaks cryptsetup-initramfs).
778
#
779
update_initramfs()
780
{
781
local chroot_target=$1
782
local target_dir=$(
783
find ${chroot_target}/lib/modules/ -maxdepth 1 -type d -name "*${VER}*"
784
)
785
if [ "$target_dir" != "" ]; then
786
update_initramfs_cmd="update-initramfs -uv -k $(basename $target_dir)"
787
else
788
exit_with_error "No kernel installed for the version" "${VER}"
789
fi
790
display_alert "Updating initramfs..." "$update_initramfs_cmd" ""
791
cp /usr/bin/$QEMU_BINARY $chroot_target/usr/bin/
792
mount_chroot "$chroot_target/"
793
794
chroot $chroot_target /bin/bash -c "$update_initramfs_cmd" >> $DEST/${LOG_SUBPATH}/install.log 2>&1 || {
795
display_alert "Updating initramfs FAILED, see:" "$DEST/${LOG_SUBPATH}/install.log" "err"
796
exit 23
797
}
798
display_alert "Updated initramfs." "for details see: $DEST/${LOG_SUBPATH}/install.log" "info"
799
800
display_alert "Re-enabling" "initramfs-tools hook for kernel"
801
chroot $chroot_target /bin/bash -c "chmod -v +x /etc/kernel/postinst.d/initramfs-tools" >> "${DEST}"/${LOG_SUBPATH}/install.log 2>&1
802
803
umount_chroot "$chroot_target/"
804
rm $chroot_target/usr/bin/$QEMU_BINARY
805
806
} #############################################################################
807
808
# create_image
809
#
810
# finishes creation of image from cached rootfs
811
#
812
create_image()
813
{
814
# stage: create file name
815
if [[ $SELECTED_CONFIGURATION == "cli_standard" ]]; then
816
IMAGE_TYPE=server
817
elif [[ $SELECTED_CONFIGURATION == "cli_minimal" ]]; then
818
IMAGE_TYPE=minimal
819
else
820
IMAGE_TYPE=desktop
821
fi
822
823
local version="${BOARD^}_${REVISION}_${DISTRIBUTION,}_${RELEASE}_${IMAGE_TYPE}"${DESKTOP_ENVIRONMENT:+_$DESKTOP_ENVIRONMENT}"_linux$(grab_version "$LINUXSOURCEDIR")"
824
825
if [[ ${RELEASE} == "raspi" ]]; then
826
local version="${BOARD^}_${REVISION}_raspios_bullseye_${IMAGE_TYPE}"${DESKTOP_ENVIRONMENT:+_$DESKTOP_ENVIRONMENT}"_linux$(grab_version "$LINUXSOURCEDIR")"
827
fi
828
829
[[ $ROOTFS_TYPE == nfs ]] && version=${version}_nfsboot
830
831
destimg=$DEST/images/${version}
832
rm -rf $destimg
833
mkdir -p $destimg
834
835
if [[ $ROOTFS_TYPE != nfs ]]; then
836
display_alert "Copying files to" "/"
837
echo -e "\nCopying files to [/]" >>"${DEST}"/${LOG_SUBPATH}/install.log
838
rsync -aHWXh \
839
--exclude="/boot/*" \
840
--exclude="/dev/*" \
841
--exclude="/proc/*" \
842
--exclude="/run/*" \
843
--exclude="/tmp/*" \
844
--exclude="/sys/*" \
845
--info=progress0,stats1 $SDCARD/ $MOUNT/ >> "${DEST}"/${LOG_SUBPATH}/install.log 2>&1
846
else
847
display_alert "Creating rootfs archive" "rootfs.tgz" "info"
848
tar cp --xattrs --directory=$SDCARD/ --exclude='./boot/*' --exclude='./dev/*' --exclude='./proc/*' --exclude='./run/*' --exclude='./tmp/*' \
849
--exclude='./sys/*' . | pv -p -b -r -s $(du -sb $SDCARD/ | cut -f1) -N "rootfs.tgz" | gzip -c > $destimg/${version}-rootfs.tgz
850
fi
851
852
# stage: rsync /boot
853
display_alert "Copying files to" "/boot"
854
echo -e "\nCopying files to [/boot]" >>"${DEST}"/${LOG_SUBPATH}/install.log
855
if [[ $(findmnt --target $MOUNT/boot -o FSTYPE -n) == vfat ]]; then
856
# fat32
857
rsync -rLtWh \
858
--info=progress0,stats1 \
859
--log-file="${DEST}"/${LOG_SUBPATH}/install.log $SDCARD/boot $MOUNT >> "${DEST}"/${LOG_SUBPATH}/install.log 2>&1
860
else
861
# ext4
862
rsync -aHWXh \
863
--info=progress0,stats1 \
864
--log-file="${DEST}"/${LOG_SUBPATH}/install.log $SDCARD/boot $MOUNT >> "${DEST}"/${LOG_SUBPATH}/install.log 2>&1
865
fi
866
867
call_extension_method "pre_update_initramfs" "config_pre_update_initramfs" << 'PRE_UPDATE_INITRAMFS'
868
*allow config to hack into the initramfs create process*
869
Called after rsync has synced both `/root` and `/root` on the target, but before calling `update_initramfs`.
870
PRE_UPDATE_INITRAMFS
871
872
# stage: create final initramfs
873
[[ -n $KERNELSOURCE ]] && {
874
update_initramfs $MOUNT
875
}
876
877
# DEBUG: print free space
878
local freespace=$(LC_ALL=C df -h)
879
echo $freespace >> $DEST/${LOG_SUBPATH}/debootstrap.log
880
display_alert "Free SD cache" "$(echo -e "$freespace" | grep $SDCARD | awk '{print $5}')" "info"
881
display_alert "Mount point" "$(echo -e "$freespace" | grep $MOUNT | head -1 | awk '{print $5}')" "info"
882
883
# stage: write u-boot
884
write_uboot $LOOP
885
886
# fix wrong / permissions
887
chmod 755 $MOUNT
888
889
call_extension_method "pre_umount_final_image" "config_pre_umount_final_image" << 'PRE_UMOUNT_FINAL_IMAGE'
890
*allow config to hack into the image before the unmount*
891
Called before unmounting both `/root` and `/boot`.
892
PRE_UMOUNT_FINAL_IMAGE
893
894
# unmount /boot/efi first, then /boot, rootfs third, image file last
895
sync
896
[[ $UEFISIZE != 0 ]] && umount -l "${MOUNT}${UEFI_MOUNT_POINT}"
897
[[ $BOOTSIZE != 0 ]] && umount -l $MOUNT/boot
898
[[ $ROOTFS_TYPE != nfs ]] && umount -l $MOUNT
899
[[ $CRYPTROOT_ENABLE == yes ]] && cryptsetup luksClose $ROOT_MAPPER
900
901
call_extension_method "post_umount_final_image" "config_post_umount_final_image" << 'POST_UMOUNT_FINAL_IMAGE'
902
*allow config to hack into the image after the unmount*
903
Called after unmounting both `/root` and `/boot`.
904
POST_UMOUNT_FINAL_IMAGE
905
906
# to make sure its unmounted
907
while grep -Eq '(${MOUNT}|${DESTIMG})' /proc/mounts
908
do
909
display_alert "Wait for unmount" "${MOUNT}" "info"
910
sleep 5
911
done
912
913
losetup -d $LOOP
914
rm -rf --one-file-system $DESTIMG $MOUNT
915
916
mkdir -p $DESTIMG
917
mv ${SDCARD}.raw $DESTIMG/${version}.img
918
919
FINALDEST=${destimg}
920
921
# custom post_build_image_modify hook to run before fingerprinting and compression
922
[[ $(type -t post_build_image_modify) == function ]] && display_alert "Custom Hook Detected" "post_build_image_modify" "info" && post_build_image_modify "${DESTIMG}/${version}.img"
923
924
if [[ $BUILD_ALL != yes ]]; then
925
926
if [[ $COMPRESS_OUTPUTIMAGE == "" || $COMPRESS_OUTPUTIMAGE == no ]]; then
927
COMPRESS_OUTPUTIMAGE="sha,gpg,img"
928
elif [[ $COMPRESS_OUTPUTIMAGE == yes ]]; then
929
COMPRESS_OUTPUTIMAGE="sha,gpg,7z"
930
fi
931
932
if [[ $COMPRESS_OUTPUTIMAGE == *gz* ]]; then
933
display_alert "Compressing" "${DESTIMG}/${version}.img.gz" "info"
934
pigz -3 < $DESTIMG/${version}.img > $DESTIMG/${version}.img.gz
935
compression_type=".gz"
936
fi
937
938
if [[ $COMPRESS_OUTPUTIMAGE == *xz* ]]; then
939
display_alert "Compressing" "${DESTIMG}/${version}.img.xz" "info"
940
# compressing consumes a lot of memory we don't have. Waiting for previous packing job to finish helps to run a lot more builds in parallel
941
available_cpu=$(grep -c 'processor' /proc/cpuinfo)
942
[[ ${BUILD_ALL} == yes ]] && available_cpu=$(( $available_cpu * 30 / 100 )) # lets use 20% of resources in case of build-all
943
[[ ${available_cpu} -gt 8 ]] && available_cpu=8 # using more cpu cores for compressing is pointless
944
available_mem=$(LC_ALL=c free | grep Mem | awk '{print $4/$2 * 100.0}' | awk '{print int($1)}') # in percentage
945
# build optimisations when memory drops below 5%
946
if [[ ${BUILD_ALL} == yes && ( ${available_mem} -lt 15 || $(ps -uax | grep "pixz" | wc -l) -gt 4 )]]; then
947
while [[ $(ps -uax | grep "pixz" | wc -l) -gt 2 ]]
948
do echo -en "#"
949
sleep 20
950
done
951
fi
952
pixz -7 -p ${available_cpu} -f $(expr ${available_cpu} + 2) < $DESTIMG/${version}.img > ${DESTIMG}/${version}.img.xz
953
compression_type=".xz"
954
fi
955
956
if [[ $COMPRESS_OUTPUTIMAGE == *img* || $COMPRESS_OUTPUTIMAGE == *7z* ]]; then
957
# mv $DESTIMG/${version}.img ${FINALDEST}/${version}.img || exit 1
958
compression_type=""
959
fi
960
961
if [[ $COMPRESS_OUTPUTIMAGE == *sha* ]]; then
962
cd ${DESTIMG}
963
display_alert "SHA256 calculating" "${version}.img${compression_type}" "info"
964
sha256sum -b ${version}.img${compression_type} > ${version}.img${compression_type}.sha
965
fi
966
967
if [[ $COMPRESS_OUTPUTIMAGE == *gpg* ]]; then
968
cd ${DESTIMG}
969
if [[ -n $GPG_PASS ]]; then
970
display_alert "GPG signing" "${version}.img${compression_type}" "info"
971
[[ -n ${SUDO_USER} ]] && sudo chown -R ${SUDO_USER}:${SUDO_USER} "${DESTIMG}"/
972
echo "${GPG_PASS}" | sudo -H -u ${SUDO_USER} bash -c "gpg --passphrase-fd 0 --armor --detach-sign --pinentry-mode loopback --batch --yes ${DESTIMG}/${version}.img${compression_type}" || exit 1
973
#else
974
# display_alert "GPG signing skipped - no GPG_PASS" "${version}.img" "wrn"
975
fi
976
fi
977
978
#fingerprint_image "${DESTIMG}/${version}.img${compression_type}.txt" "${version}"
979
980
if [[ $COMPRESS_OUTPUTIMAGE == *7z* ]]; then
981
display_alert "Compressing" "${DESTIMG}/${version}.7z" "info"
982
7za a -t7z -bd -m0=lzma2 -mx=3 -mfb=64 -md=32m -ms=on \
983
${DESTIMG}/${version}.7z ${version}.key ${version}.img* >/dev/null 2>&1
984
find ${DESTIMG}/ -type \
985
f \( -name "${version}.img" -o -name "${version}.img.asc" -o -name "${version}.img.txt" -o -name "${version}.img.sha" \) -print0 \
986
>/dev/null 2>&1
987
fi
988
989
fi
990
#display_alert "Done building" "${DESTIMG}/${version}.img" "info"
991
display_alert "Done building" "${FINALDEST}/${version}.img" "info"
992
993
# call custom post build hook
994
[[ $(type -t post_build_image) == function ]] && post_build_image "${DESTIMG}/${version}.img"
995
996
# move artefacts from temporally directory to its final destination
997
[[ -n $compression_type ]] && rm $DESTIMG/${version}.img
998
mv $DESTIMG/${version}* ${FINALDEST}
999
rm -rf $DESTIMG
1000
1001
# write image to SD card
1002
if [[ $(lsblk "$CARD_DEVICE" 2>/dev/null) && -f ${FINALDEST}/${version}.img ]]; then
1003
1004
# make sha256sum if it does not exists. we need it for comparisson
1005
if [[ -f "${FINALDEST}/${version}".img.sha ]]; then
1006
local ifsha=$(cat ${FINALDEST}/${version}.img.sha | awk '{print $1}')
1007
else
1008
local ifsha=$(sha256sum -b "${FINALDEST}/${version}".img | awk '{print $1}')
1009
fi
1010
1011
display_alert "Writing image" "$CARD_DEVICE ${readsha}" "info"
1012
1013
# write to SD card
1014
pv -p -b -r -c -N "[ .... ] dd" ${FINALDEST}/${version}.img | dd of=$CARD_DEVICE bs=1M iflag=fullblock oflag=direct status=none
1015
1016
call_extension_method "post_write_sdcard" <<- 'POST_BUILD_IMAGE'
1017
*run after writing img to sdcard*
1018
After the image is written to `$CARD_DEVICE`, but before verifying it.
1019
You can still set SKIP_VERIFY=yes to skip verification.
1020
POST_BUILD_IMAGE
1021
1022
if [[ "${SKIP_VERIFY}" != "yes" ]]; then
1023
# read and compare
1024
display_alert "Verifying. Please wait!"
1025
local ofsha=$(dd if=$CARD_DEVICE count=$(du -b ${FINALDEST}/${version}.img | cut -f1) status=none iflag=count_bytes oflag=direct | sha256sum | awk '{print $1}')
1026
if [[ $ifsha == $ofsha ]]; then
1027
display_alert "Writing verified" "${version}.img" "info"
1028
else
1029
display_alert "Writing failed" "${version}.img" "err"
1030
fi
1031
fi
1032
elif [[ `systemd-detect-virt` == 'docker' && -n $CARD_DEVICE ]]; then
1033
# display warning when we want to write sd card under Docker
1034
display_alert "Can't write to $CARD_DEVICE" "Enable docker privileged mode in config-docker.conf" "wrn"
1035
fi
1036
1037
} #############################################################################
1038
1039