Project

General

Profile

Download (75.1 KB) Statistics
| Branch: | Tag: | Revision:
1
#!/bin/sh
2
#
3
# builder_common.sh
4
#
5
# Copyright (c) 2004-2015 Electric Sheep Fencing, LLC
6
# Copyright (C) 2014 Ermal Luçi
7
# All rights reserved.
8
#
9
# NanoBSD portions of the code
10
# Copyright (c) 2005 Poul-Henning Kamp.
11
# and copied from nanobsd.sh
12
# All rights reserved.
13
#
14
# FreeSBIE portions of the code
15
# Copyright (c) 2005 Dario Freni
16
# and copied from FreeSBIE project
17
# All rights reserved.
18
#
19
# Redistribution and use in source and binary forms, with or without
20
# modification, are permitted provided that the following conditions
21
# are met:
22
#
23
# 1. Redistributions of source code must retain the above copyright
24
#    notice, this list of conditions and the following disclaimer.
25
#
26
# 2. Redistributions in binary form must reproduce the above copyright
27
#    notice, this list of conditions and the following disclaimer in the
28
#    documentation and/or other materials provided with the distribution.
29
#
30
# THIS SOFTWARE IS PROVIDED BY THE pfSense PROJECT ``AS IS'' AND ANY
31
# EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
33
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE pfSense PROJECT OR
34
# ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36
# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
38
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
41
# OF THE POSSIBILITY OF SUCH DAMAGE.
42
# Redistribution and use in source and binary forms, with or without
43
# modification, are permitted provided that the following conditions are met:
44
#
45

    
46
if [ -z "${IMAGES_FINAL_DIR}" -o "${IMAGES_FINAL_DIR}" = "/" ]; then
47
	echo "IMAGES_FINAL_DIR is not defined"
48
	print_error_pfS
49
fi
50

    
51
lc() {
52
	echo "${1}" | tr '[[:upper:]]' '[[:lower:]]'
53
}
54

    
55
git_last_commit() {
56
	export CURRENT_COMMIT=$(git -C ${BUILDER_ROOT} log -1 --format='%H')
57
	export CURRENT_AUTHOR=$(git -C ${BUILDER_ROOT} log -1 --format='%an')
58
	echo ">>> Last known commit $CURRENT_AUTHOR - $CURRENT_COMMIT"
59
	echo "$CURRENT_COMMIT" > $SCRATCHDIR/build_commit_info.txt
60
}
61

    
62
# Create core pkg repository
63
core_pkg_create_repo() {
64
	if [ ! -d "${CORE_PKG_REAL_PATH}/All" ]; then
65
		return
66
	fi
67

    
68
	############ ATTENTION ##############
69
	#
70
	# For some reason pkg-repo fail without / in the end of directory name
71
	# so removing it will break command
72
	#
73
	# https://github.com/freebsd/pkg/issues/1364
74
	#
75
	echo -n ">>> Creating core packages repository... "
76
	if pkg repo -q "${CORE_PKG_REAL_PATH}/"; then
77
		echo "Done!"
78
	else
79
		echo "Failed!"
80
		print_error_pfS
81
	fi
82

    
83
	# Use the same directory structure as poudriere does to avoid
84
	# breaking snapshot repositories during rsync
85
	ln -sf $(basename ${CORE_PKG_REAL_PATH}) ${CORE_PKG_PATH}/.latest
86
	ln -sf .latest/All ${CORE_PKG_PATH}/All
87
	ln -sf .latest/digests.txz ${CORE_PKG_PATH}/digests.txz
88
	ln -sf .latest/meta.txz ${CORE_PKG_PATH}/meta.txz
89
	ln -sf .latest/packagesite.txz ${CORE_PKG_PATH}/packagesite.txz
90
}
91

    
92
# Create core pkg (base, kernel)
93
core_pkg_create() {
94
	local _template="${1}"
95
	local _flavor="${2}"
96
	local _version="${3}"
97
	local _root="${4}"
98
	local _filter="${5}"
99

    
100
	[ -d "${CORE_PKG_TMP}" ] \
101
		&& rm -rf ${CORE_PKG_TMP}
102

    
103
	local _templates_path=${BUILDER_TOOLS}/templates/core_pkg/${_template}
104
	local _template_metadir=${_templates_path}/metadir
105
	local _metadir=${CORE_PKG_TMP}/${_template}_metadir
106

    
107
	if [ ! -d ${_template_metadir} ]; then
108
		echo "ERROR: Template dir not found for pkg ${_template}"
109
		exit
110
	fi
111

    
112
	mkdir -p ${CORE_PKG_TMP}
113

    
114
	cp -r ${_template_metadir} ${_metadir}
115

    
116
	local _manifest=${_metadir}/+MANIFEST
117
	local _plist=${CORE_PKG_TMP}/${_template}_plist
118
	local _exclude_plist=${CORE_PKG_TMP}/${_template}_exclude_plist
119

    
120
	if [ -f "${_templates_path}/pkg-plist" ]; then
121
		cp ${_templates_path}/pkg-plist ${_plist}
122
	else
123
		if [ -n "${_filter}" ]; then
124
			_filter="-name ${_filter}"
125
		fi
126
		(cd ${_root} && find . ${_filter} -type f -or -type l | sed 's,^.,,' | sort -u) > ${_plist}
127
	fi
128

    
129
	if [ -f "${_templates_path}/exclude_plist" ]; then
130
		cp ${_templates_path}/exclude_plist ${_exclude_plist}
131
	else
132
		touch ${_exclude_plist}
133
	fi
134

    
135
	sed \
136
		-i '' \
137
		-e "s,%%PRODUCT_NAME%%,${PRODUCT_NAME},g" \
138
		-e "s,%%PRODUCT_URL%%,${PRODUCT_URL},g" \
139
		-e "s,%%FLAVOR%%,${_flavor:+-}${_flavor},g" \
140
		-e "s,%%FLAVOR_DESC%%,${_flavor:+ (${_flavor})},g" \
141
		-e "s,%%VERSION%%,${_version},g" \
142
		${_metadir}/* \
143
		${_plist} \
144
		${exclude_plist}
145

    
146
	if [ -f "${_exclude_plist}" ]; then
147
		sort -u ${_exclude_plist} > ${_plist}.exclude
148
		mv ${_plist} ${_plist}.tmp
149
		comm -23 ${_plist}.tmp ${_plist}.exclude > ${_plist}
150
		rm -f ${_plist}.tmp ${plist}.exclude
151
	fi
152

    
153
	# Add license information
154
	local _portname=$(sed '/^name: /!d; s,^[^"]*",,; s,",,' ${_metadir}/+MANIFEST)
155
	local _licenses_dir="/usr/local/share/licenses/${_portname}-${_version}"
156
	mkdir -p ${_root}${_licenses_dir}
157
	cp ${BUILDER_ROOT}/license.txt ${_root}${_licenses_dir}/ESF
158
	echo "This package has a single license: ESF (Electric Sheep Fencing License)." \
159
		> ${_root}${_licenses_dir}/LICENSE
160
	cat <<EOF >${_root}${_licenses_dir}/catalog.mk
161
_LICENSE=ESF
162
_LICENSE_NAME=Electric Sheep Fencing License
163
_LICENSE_PERMS=dist-mirror dist-sell pkg-mirror pkg-sell auto-accept
164
_LICENSE_GROUPS=
165
_LICENSE_DISTFILES=
166
EOF
167
	cat <<EOF >>${_plist}
168
${_licenses_dir}/catalog.mk
169
${_licenses_dir}/LICENSE
170
${_licenses_dir}/ESF
171
EOF
172

    
173
	mkdir -p ${CORE_PKG_REAL_PATH}/All
174
	if ! pkg create -o ${CORE_PKG_REAL_PATH}/All -p ${_plist} -r ${_root} -m ${_metadir}; then
175
		echo ">>> ERROR: Error building package ${_template} ${_flavor}"
176
		print_error_pfS
177
	fi
178
}
179

    
180
# This routine will output that something went wrong
181
print_error_pfS() {
182
	echo
183
	echo "####################################"
184
	echo "Something went wrong, check errors!" >&2
185
	echo "####################################"
186
	echo
187
	echo "NOTE: a lot of times you can run './build.sh --clean-builder' to resolve."
188
	echo
189
	if [ "$1" != "" ]; then
190
		echo $1
191
	fi
192
	[ -n "${LOGFILE}" -a -f "${LOGFILE}" ] && \
193
		echo "Log saved on ${LOGFILE}" && \
194
		tail -n20 ${LOGFILE} >&2
195
	echo
196
	kill $$
197
	exit 1
198
}
199

    
200
# This routine will verify that the kernel has been
201
# installed OK to the staging area.
202
ensure_kernel_exists() {
203
	if [ ! -f "$1/boot/kernel/kernel.gz" ]; then
204
		echo ">>> ERROR: Could not locate $1/boot/kernel.gz"
205
		print_error_pfS
206
	fi
207
	KERNEL_SIZE=$(stat -f "%z" $1/boot/kernel/kernel.gz)
208
	if [ "$KERNEL_SIZE" -lt 3500 ]; then
209
		echo ">>> ERROR: Kernel $1/boot/kernel.gz appears to be smaller than it should be: $KERNEL_SIZE"
210
		print_error_pfS
211
	fi
212
}
213

    
214
get_pkg_name() {
215
	echo "${PRODUCT_NAME}-${1}-${CORE_PKG_VERSION}"
216
}
217

    
218
# This routine builds all related kernels
219
build_all_kernels() {
220
	# Set KERNEL_BUILD_PATH if it has not been set
221
	if [ -z "${KERNEL_BUILD_PATH}" ]; then
222
		KERNEL_BUILD_PATH=$SCRATCHDIR/kernels
223
		echo ">>> KERNEL_BUILD_PATH has not been set. Setting to ${KERNEL_BUILD_PATH}!"
224
	fi
225

    
226
	[ -d "${KERNEL_BUILD_PATH}" ] \
227
		&& rm -rf ${KERNEL_BUILD_PATH}
228

    
229
	# Build embedded kernel
230
	for BUILD_KERNEL in $BUILD_KERNELS; do
231
		unset KERNCONF
232
		unset KERNEL_DESTDIR
233
		unset KERNELCONF
234
		unset KERNEL_NAME
235
		export KERNCONF=$BUILD_KERNEL
236
		export KERNEL_DESTDIR="$KERNEL_BUILD_PATH/$BUILD_KERNEL"
237
		export KERNELCONF="${FREEBSD_SRC_DIR}/sys/${TARGET}/conf/$BUILD_KERNEL"
238
		export KERNEL_NAME=${BUILD_KERNEL}
239

    
240
		LOGFILE="${BUILDER_LOGS}/kernel.${KERNCONF}.${TARGET}.log"
241
		echo ">>> Building $BUILD_KERNEL kernel."  | tee -a ${LOGFILE}
242

    
243
		if [ ! -e "${FREEBSD_SRC_DIR}/sys/${TARGET}/conf/${BUILD_KERNEL}" ]; then
244
			echo ">>> ERROR: Could not find $KERNELCONF"
245
			print_error_pfS
246
		fi
247

    
248
		if [ -n "${NO_BUILDKERNEL}" -a -f "${CORE_PKG_REAL_PATH}/All/$(get_pkg_name kernel-${KERNEL_NAME}).txz" ]; then
249
			echo ">>> NO_BUILDKERNEL set, skipping build" | tee -a ${LOGFILE}
250
			continue
251
		fi
252

    
253
		export SRC_CONF=${SRC_CONF}
254
		buildkernel
255

    
256
		echo ">>> Staging $BUILD_KERNEL kernel..." | tee -a ${LOGFILE}
257
		installkernel
258

    
259
		ensure_kernel_exists $KERNEL_DESTDIR
260

    
261
		echo -n ">>> Creating pkg of $KERNEL_NAME-debug kernel to staging area... "  | tee -a ${LOGFILE}
262
		core_pkg_create kernel-debug ${KERNEL_NAME} ${CORE_PKG_VERSION} ${KERNEL_DESTDIR} \*.symbols
263
		find ${KERNEL_DESTDIR} -name '*.symbols' -type f -delete
264
		echo " Done" | tee -a ${LOGFILE}
265

    
266
		echo -n ">>> Creating pkg of $KERNEL_NAME kernel to staging area... "  | tee -a ${LOGFILE}
267
		core_pkg_create kernel ${KERNEL_NAME} ${CORE_PKG_VERSION} ${KERNEL_DESTDIR}
268

    
269
		rm -rf $KERNEL_DESTDIR 2>&1 1>/dev/null
270

    
271
		echo " Done" | tee -a ${LOGFILE}
272
	done
273
}
274

    
275
install_default_kernel() {
276
	if [ -z "${1}" ]; then
277
		echo ">>> ERROR: install_default_kernel called without a kernel config name"| tee -a ${LOGFILE}
278
		print_error_pfS
279
	fi
280

    
281
	export KERNEL_NAME="${1}"
282

    
283
	echo -n ">>> Installing kernel to be used by image ${KERNEL_NAME}..." | tee -a ${LOGFILE}
284

    
285
	# Copy kernel package to chroot, otherwise pkg won't find it to install
286
	if ! pkg_chroot_add ${FINAL_CHROOT_DIR} kernel-${KERNEL_NAME}; then
287
		echo ">>> ERROR: Error installing kernel package $(get_pkg_name kernel-${KERNEL_NAME}).txz" | tee -a ${LOGFILE}
288
		print_error_pfS
289
	fi
290

    
291
	# Lock kernel to avoid user end up removing it for any reason
292
	pkg_chroot ${FINAL_CHROOT_DIR} lock -q -y $(get_pkg_name kernel-${KERNEL_NAME})
293

    
294
	if [ ! -f $FINAL_CHROOT_DIR/boot/kernel/kernel.gz ]; then
295
		echo ">>> ERROR: No kernel installed on $FINAL_CHROOT_DIR and the resulting image will be unusable. STOPPING!" | tee -a ${LOGFILE}
296
		print_error_pfS
297
	fi
298
	mkdir -p $FINAL_CHROOT_DIR/pkgs
299
	if [ -z "${2}" -o -n "${INSTALL_EXTRA_KERNELS}" ]; then
300
		cp ${CORE_PKG_REAL_PATH}/All/$(get_pkg_name kernel-${KERNEL_NAME}).txz $FINAL_CHROOT_DIR/pkgs
301
		if [ -n "${INSTALL_EXTRA_KERNELS}" ]; then
302
			for _EXTRA_KERNEL in $INSTALL_EXTRA_KERNELS; do
303
				_EXTRA_KERNEL_PATH=${CORE_PKG_REAL_PATH}/All/$(get_pkg_name kernel-${_EXTRA_KERNEL}).txz
304
				if [ -f "${_EXTRA_KERNEL_PATH}" ]; then
305
					echo -n ". adding ${_EXTRA_KERNEL_PATH} on image /pkgs folder"
306
					cp ${_EXTRA_KERNEL_PATH} $FINAL_CHROOT_DIR/pkgs
307
				else
308
					echo ">>> ERROR: Requested kernel $(get_pkg_name kernel-${_EXTRA_KERNEL}).txz was not found to be put on image /pkgs folder!"
309
					print_error_pfS
310
				fi
311
			done
312
		fi
313
	fi
314
	echo "Done." | tee -a ${LOGFILE}
315

    
316
	unset KERNEL_NAME
317
}
318

    
319
# This builds FreeBSD (make buildworld)
320
# Imported from FreeSBIE
321
make_world() {
322

    
323
	LOGFILE=${BUILDER_LOGS}/buildworld.${TARGET}
324
	if [ -n "${NO_BUILDWORLD}" ]; then
325
		echo ">>> NO_BUILDWORLD set, skipping build" | tee -a ${LOGFILE}
326
		return
327
	fi
328

    
329
	# Set SRC_CONF variable if it's not already set.
330
	if [ -z "${SRC_CONF}" ]; then
331
		echo ">>> SRC_CONF is unset make sure this is what you want!" | tee -a ${LOGFILE}
332
	else
333
		echo ">>> Setting SRC_CONF to $SRC_CONF" | tee -a ${LOGFILE}
334
	fi
335

    
336
	# Set default parameters
337
	export MAKE_ARGS="${MAKEJ_WORLD} __MAKE_CONF=${MAKE_CONF} SRCCONF=${SRC_CONF} TARGET=${TARGET} TARGET_ARCH=${TARGET_ARCH}"
338

    
339
	echo ">>> LOGFILE set to $LOGFILE." | tee -a ${LOGFILE}
340
	makeargs="${MAKE_ARGS}"
341
	echo ">>> Building world for ${TARGET} architecture... (Starting - $(LC_ALL=C date))" | tee -a ${LOGFILE}
342
	echo ">>> Builder is running the command: env LOCAL_ITOOLS=\"${EXTRA_TOOLS}\" script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR} -DNO_CLEAN ${makeargs} buildworld" | tee -a ${LOGFILE}
343
	(env LOCAL_ITOOLS="${EXTRA_TOOLS}" script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR} -DNO_CLEAN ${makeargs} buildworld || print_error_pfS;) | egrep '^>>>' | tee -a ${LOGFILE}
344
	echo ">>> Building world for ${TARGET} architecture... (Finished - $(LC_ALL=C date))" | tee -a ${LOGFILE}
345

    
346
	LOGFILE=${BUILDER_LOGS}/installworld.${TARGET}
347
	echo ">>> LOGFILE set to $LOGFILE." | tee -a ${LOGFILE}
348
	# Create if cleaned up
349
	makeargs="${MAKE_ARGS} DESTDIR=${STAGE_CHROOT_DIR} WITHOUT_TOOLCHAIN=1"
350
	echo ">>> Installing world for ${TARGET} architecture... (Starting - $(LC_ALL=C date))" | tee -a ${LOGFILE}
351
	echo ">>> Builder is running the command: env LOCAL_ITOOLS=\"${EXTRA_TOOLS}\" script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR} ${makeargs} installworld" | tee -a ${LOGFILE}
352
	(env LOCAL_ITOOLS="${EXTRA_TOOLS}" script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR} ${makeargs} installworld || print_error_pfS;) | egrep '^>>>' | tee -a ${LOGFILE}
353
	echo ">>> Installing world for ${TARGET} architecture... (Finished - $(LC_ALL=C date))" | tee -a ${LOGFILE}
354

    
355
	makeargs="${MAKE_ARGS} DESTDIR=${STAGE_CHROOT_DIR}"
356
	echo ">>> Distribution world for ${TARGET} architecture... (Starting - $(LC_ALL=C date))" | tee -a ${LOGFILE}
357
	echo ">>> Builder is running the command: script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR} ${makeargs} distribution " | tee -a ${LOGFILE}
358
	(script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR} ${makeargs} distribution  || print_error_pfS;) | egrep '^>>>' | tee -a ${LOGFILE}
359
	echo ">>> Distribution world for ${TARGET} architecture... (Finished - $(LC_ALL=C date))" | tee -a ${LOGFILE}
360

    
361
	[ -d "${STAGE_CHROOT_DIR}/usr/local/bin" ] \
362
		|| mkdir -p ${STAGE_CHROOT_DIR}/usr/local/bin
363
	makeargs="${MAKE_ARGS} DESTDIR=${STAGE_CHROOT_DIR}"
364
	echo ">>> Building and installing crypto tools and athstats for ${TARGET} architecture... (Starting - $(LC_ALL=C date))" | tee -a ${LOGFILE}
365
	echo ">>> Builder is running the command: script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR}/tools/tools/crypto ${makeargs} clean all install " | tee -a ${LOGFILE}
366
	(script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR}/tools/tools/crypto ${makeargs} clean all install || print_error_pfS;) | egrep '^>>>' | tee -a ${LOGFILE}
367
	echo ">>> Builder is running the command: script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR}/tools/tools/ath/athstats ${makeargs} clean" | tee -a ${LOGFILE}
368
	(script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR}/tools/tools/ath/athstats ${makeargs} clean || print_error_pfS;) | egrep '^>>>' | tee -a ${LOGFILE}
369
	echo ">>> Builder is running the command: script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR}/tools/tools/ath/athstats ${makeargs} all" | tee -a ${LOGFILE}
370
	(script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR}/tools/tools/ath/athstats ${makeargs} all || print_error_pfS;) | egrep '^>>>' | tee -a ${LOGFILE}
371
	echo ">>> Builder is running the command: script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR}/tools/tools/ath/athstats ${makeargs} install" | tee -a ${LOGFILE}
372
	(script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR}/tools/tools/ath/athstats ${makeargs} install || print_error_pfS;) | egrep '^>>>' | tee -a ${LOGFILE}
373
	echo ">>> Building and installing crypto tools and athstats for ${TARGET} architecture... (Finished - $(LC_ALL=C date))" | tee -a ${LOGFILE}
374

    
375
	unset makeargs
376
}
377

    
378
nanobsd_image_filename() {
379
	local _size="$1"
380
	local _type="$2"
381

    
382
	echo "$NANOBSD_IMG_TEMPLATE" | sed \
383
		-e "s,%%SIZE%%,${_size},g" \
384
		-e "s,%%TYPE%%,${_type},g"
385

    
386
	return 0
387
}
388

    
389
# This routine originated in nanobsd.sh
390
nanobsd_set_flash_details () {
391
	a1=$(echo $1 | tr '[:upper:]' '[:lower:]')
392

    
393
	# Source:
394
	#	SanDisk CompactFlash Memory Card
395
	#	Product Manual
396
	#	Version 10.9
397
	#	Document No. 20-10-00038
398
	#	April 2005
399
	# Table 2-7
400
	# NB: notice math error in SDCFJ-4096-388 line.
401
	#
402
	case "${a1}" in
403
		2048|2048m|2048mb|2g)
404
			NANO_MEDIASIZE=$((1989999616/512))
405
			;;
406
		4096|4096m|4096mb|4g)
407
			NANO_MEDIASIZE=$((3989999616/512))
408
			;;
409
		8192|8192m|8192mb|8g)
410
			NANO_MEDIASIZE=$((7989999616/512))
411
			;;
412
		16384|16384m|16384mb|16g)
413
			NANO_MEDIASIZE=$((15989999616/512))
414
			;;
415
		*)
416
			echo "Unknown Flash capacity"
417
			exit 2
418
			;;
419
	esac
420

    
421
	NANO_HEADS=16
422
	NANO_SECTS=63
423

    
424
	echo ">>> [nanoo] $1"
425
	echo ">>> [nanoo] NANO_MEDIASIZE: $NANO_MEDIASIZE"
426
	echo ">>> [nanoo] NANO_HEADS: $NANO_HEADS"
427
	echo ">>> [nanoo] NANO_SECTS: $NANO_SECTS"
428
	echo ">>> [nanoo] NANO_BOOT0CFG: $NANO_BOOT0CFG"
429
}
430

    
431
# This routine originated in nanobsd.sh
432
create_nanobsd_diskimage () {
433
	if [ -z "${1}" ]; then
434
		echo ">>> ERROR: Type of image has not been specified"
435
		print_error_pfS
436
	fi
437
	if [ -z "${2}" ]; then
438
		echo ">>> ERROR: Size of image has not been specified"
439
		print_error_pfS
440
	fi
441

    
442
	if [ "${1}" = "nanobsd" ]; then
443
		# It's serial
444
		export NANO_BOOTLOADER="boot/boot0sio"
445
	elif [ "${1}" = "nanobsd-vga" ]; then
446
		# It's vga
447
		export NANO_BOOTLOADER="boot/boot0"
448
	else
449
		echo ">>> ERROR: Type of image to create unknown"
450
		print_error_pfS
451
	fi
452

    
453
	if [ -z "${2}" ]; then
454
		echo ">>> ERROR: Media size(s) not specified."
455
		print_error_pfS
456
	fi
457

    
458
	if [ -z "${2}" ]; then
459
		echo ">>> ERROR: FLASH_SIZE is not set."
460
		print_error_pfS
461
	fi
462

    
463
	LOGFILE=${BUILDER_LOGS}/${1}.${TARGET}
464
	# Prepare folder to be put in image
465
	customize_stagearea_for_image "${1}"
466
	install_default_kernel ${DEFAULT_KERNEL} "no"
467

    
468
	echo ">>> Fixing up NanoBSD Specific items..." | tee -a ${LOGFILE}
469

    
470
	echo "nanobsd" > $FINAL_CHROOT_DIR/etc/platform
471

    
472
	local BOOTCONF=${FINAL_CHROOT_DIR}/boot.config
473
	local LOADERCONF=${FINAL_CHROOT_DIR}/boot/loader.conf
474

    
475
	if [ "${1}" = "nanobsd" ]; then
476
		# Tell loader to use serial console early.
477
		echo "-S115200 -h" >> ${BOOTCONF}
478

    
479
		# Remove old console options if present.
480
		[ -f "${LOADERCONF}" ] \
481
			&& sed -i "" -Ee "/(console|boot_multicons|boot_serial|hint.uart)/d" ${LOADERCONF}
482
		# Activate serial console+video console in loader.conf
483
		echo 'loader_color="NO"' >> ${LOADERCONF}
484
		echo 'beastie_disable="YES"' >> ${LOADERCONF}
485
		echo 'boot_serial="YES"' >> ${LOADERCONF}
486
		echo 'console="comconsole"' >> ${LOADERCONF}
487
		echo 'comconsole_speed="115200"' >> ${LOADERCONF}
488
	fi
489
	echo 'autoboot_delay="5"' >> ${LOADERCONF}
490

    
491
	# Old systems will run (pre|post)_upgrade_command from /tmp
492
	if [ -f ${FINAL_CHROOT_DIR}${PRODUCT_SHARE_DIR}/pre_upgrade_command ]; then
493
		cp -p \
494
			${FINAL_CHROOT_DIR}${PRODUCT_SHARE_DIR}/pre_upgrade_command \
495
			${FINAL_CHROOT_DIR}/tmp
496
	fi
497
	if [ -f ${FINAL_CHROOT_DIR}${PRODUCT_SHARE_DIR}/post_upgrade_command ]; then
498
		cp -p \
499
			${FINAL_CHROOT_DIR}${PRODUCT_SHARE_DIR}/post_upgrade_command \
500
			${FINAL_CHROOT_DIR}/tmp
501
	fi
502

    
503
	mkdir -p ${IMAGES_FINAL_DIR}/nanobsd
504

    
505
	for _NANO_MEDIASIZE in ${2}; do
506
		if [ -z "${_NANO_MEDIASIZE}" ]; then
507
			continue;
508
		fi
509

    
510
		echo ">>> building NanoBSD(${1}) disk image with size ${_NANO_MEDIASIZE} for platform (${TARGET})..." | tee -a ${LOGFILE}
511
		echo "" > $BUILDER_LOGS/nanobsd_cmds.sh
512

    
513
		IMG="${IMAGES_FINAL_DIR}/nanobsd/$(nanobsd_image_filename ${_NANO_MEDIASIZE} ${1})"
514

    
515
		nanobsd_set_flash_details ${_NANO_MEDIASIZE}
516

    
517
		# These are defined in FlashDevice and on builder_default.sh
518
		echo $NANO_MEDIASIZE \
519
			$NANO_IMAGES \
520
			$NANO_SECTS \
521
			$NANO_HEADS \
522
			$NANO_CODESIZE \
523
			$NANO_CONFSIZE \
524
			$NANO_DATASIZE |
525
awk '
526
{
527
	printf "# %s\n", $0
528

    
529
	# size of cylinder in sectors
530
	cs = $3 * $4
531

    
532
	# number of full cylinders on media
533
	cyl = int ($1 / cs)
534

    
535
	# output fdisk geometry spec, truncate cyls to 1023
536
	if (cyl <= 1023)
537
		print "g c" cyl " h" $4 " s" $3
538
	else
539
		print "g c" 1023 " h" $4 " s" $3
540

    
541
	if ($7 > 0) {
542
		# size of data partition in full cylinders
543
		dsl = int (($7 + cs - 1) / cs)
544
	} else {
545
		dsl = 0;
546
	}
547

    
548
	# size of config partition in full cylinders
549
	csl = int (($6 + cs - 1) / cs)
550

    
551
	if ($5 == 0) {
552
		# size of image partition(s) in full cylinders
553
		isl = int ((cyl - dsl - csl) / $2)
554
	} else {
555
		isl = int (($5 + cs - 1) / cs)
556
	}
557

    
558
	# First image partition start at second track
559
	print "p 1 165 " $3, isl * cs - $3
560
	c = isl * cs;
561

    
562
	# Second image partition (if any) also starts offset one
563
	# track to keep them identical.
564
	if ($2 > 1) {
565
		print "p 2 165 " $3 + c, isl * cs - $3
566
		c += isl * cs;
567
	}
568

    
569
	# Config partition starts at cylinder boundary.
570
	print "p 3 165 " c, csl * cs
571
	c += csl * cs
572

    
573
	# Data partition (if any) starts at cylinder boundary.
574
	if ($7 > 0) {
575
		print "p 4 165 " c, dsl * cs
576
	} else if ($7 < 0 && $1 > c) {
577
		print "p 4 165 " c, $1 - c
578
	} else if ($1 < c) {
579
		print "Disk space overcommitted by", \
580
		    c - $1, "sectors" > "/dev/stderr"
581
		exit 2
582
	}
583

    
584
	# Force slice 1 to be marked active. This is necessary
585
	# for booting the image from a USB device to work.
586
	print "a 1"
587
}
588
	' > ${SCRATCHDIR}/_.fdisk
589

    
590
		MNT=${SCRATCHDIR}/_.mnt
591
		mkdir -p ${MNT}
592

    
593
		dd if=/dev/zero of=${IMG} bs=${NANO_SECTS}b \
594
			count=0 seek=$((${NANO_MEDIASIZE}/${NANO_SECTS})) 2>&1 >> ${LOGFILE}
595

    
596
		MD=$(mdconfig -a -t vnode -f ${IMG} -x ${NANO_SECTS} -y ${NANO_HEADS})
597
		trap "mdconfig -d -u ${MD}; return" 1 2 15 EXIT
598

    
599
		fdisk -i -f ${SCRATCHDIR}/_.fdisk ${MD} 2>&1 >> ${LOGFILE}
600
		fdisk ${MD} 2>&1 >> ${LOGFILE}
601

    
602
		boot0cfg -t 100 -B -b ${FINAL_CHROOT_DIR}/${NANO_BOOTLOADER} ${NANO_BOOT0CFG} ${MD} 2>&1 >> ${LOGFILE}
603

    
604
		# Create first image
605
		bsdlabel -m i386 -w -B -b ${FINAL_CHROOT_DIR}/boot/boot ${MD}s1 2>&1 >> ${LOGFILE}
606
		bsdlabel -m i386 ${MD}s1 2>&1 >> ${LOGFILE}
607
		local _label=$(lc ${PRODUCT_NAME})
608
		newfs -L ${_label}0 ${NANO_NEWFS} /dev/${MD}s1a 2>&1 >> ${LOGFILE}
609
		mount /dev/ufs/${_label}0 ${MNT}
610
		if [ $? -ne 0 ]; then
611
			echo ">>> ERROR: Something wrong happened during mount of first slice image creation. STOPPING!" | tee -a ${LOGFILE}
612
			print_error_pfS
613
		fi
614
		# Consider the unmounting as well
615
		trap "umount /dev/ufs/${_label}0; mdconfig -d -u ${MD}; return" 1 2 15 EXIT
616

    
617
		clone_directory_contents ${FINAL_CHROOT_DIR} ${MNT}
618

    
619
		# Set NanoBSD image size
620
		echo "${_NANO_MEDIASIZE}" > ${MNT}/etc/nanosize.txt
621

    
622
		echo "/dev/ufs/${_label}0 / ufs ro,sync,noatime 1 1" > ${MNT}/etc/fstab
623
		if [ $NANO_CONFSIZE -gt 0 ] ; then
624
			echo "/dev/ufs/cf /cf ufs ro,sync,noatime 1 1" >> ${MNT}/etc/fstab
625
		fi
626

    
627
		umount ${MNT}
628
		# Restore the original trap
629
		trap "mdconfig -d -u ${MD}; return" 1 2 15 EXIT
630

    
631
		# Setting NANO_IMAGES to 1 and NANO_INIT_IMG2 will tell
632
		# NanoBSD to only create one partition.  We default to 2
633
		# partitions in case anything happens to the first the
634
		# operator can boot from the 2nd and should be OK.
635

    
636
		# Before just going to use dd for duplicate think!
637
		# The images are created as sparse so lets take advantage
638
		# of that by just exec some commands.
639
		if [ $NANO_IMAGES -gt 1 -a $NANO_INIT_IMG2 -gt 0 ] ; then
640
			# Duplicate to second image (if present)
641
			echo ">>> Creating NanoBSD second slice by duplicating first slice." | tee -a ${LOGFILE}
642
			# Create second image
643
			dd if=/dev/${MD}s1 of=/dev/${MD}s2 conv=sparse bs=64k 2>&1 >> ${LOGFILE}
644
			tunefs -L ${_label}1 /dev/${MD}s2a 2>&1 >> ${LOGFILE}
645
			mount /dev/ufs/${_label}1 ${MNT}
646
			if [ $? -ne 0 ]; then
647
				echo ">>> ERROR: Something wrong happened during mount of second slice image creation. STOPPING!" | tee -a ${LOGFILE}
648
				print_error_pfS
649
			fi
650
			# Consider the unmounting as well
651
			trap "umount /dev/ufs/${_label}1; mdconfig -d -u ${MD}; return" 1 2 15 EXIT
652

    
653
			echo "/dev/ufs/${_label}1 / ufs ro,sync,noatime 1 1" > ${MNT}/etc/fstab
654
			if [ $NANO_CONFSIZE -gt 0 ] ; then
655
				echo "/dev/ufs/cf /cf ufs ro,sync,noatime 1 1" >> ${MNT}/etc/fstab
656
			fi
657

    
658
			umount ${MNT}
659
			# Restore the trap back
660
			trap "mdconfig -d -u ${MD}; return" 1 2 15 EXIT
661
		fi
662

    
663
		# Create Data slice, if any.
664
		# Note the changing of the variable to NANO_CONFSIZE
665
		# from NANO_DATASIZE.  We also added glabel support
666
		# and populate the Product configuration from the /cf
667
		# directory located in FINAL_CHROOT_DIR
668
		if [ $NANO_CONFSIZE -gt 0 ] ; then
669
			echo ">>> Creating /cf area to hold config.xml"
670
			newfs -L cf ${NANO_NEWFS} /dev/${MD}s3 2>&1 >> ${LOGFILE}
671
			# Mount data partition and copy contents of /cf
672
			# Can be used later to create custom default config.xml while building
673
			mount /dev/ufs/cf ${MNT}
674
			if [ $? -ne 0 ]; then
675
				echo ">>> ERROR: Something wrong happened during mount of cf slice image creation. STOPPING!" | tee -a ${LOGFILE}
676
				print_error_pfS
677
			fi
678
			# Consider the unmounting as well
679
			trap "umount /dev/ufs/cf; mdconfig -d -u ${MD}; return" 1 2 15 EXIT
680

    
681
			clone_directory_contents ${FINAL_CHROOT_DIR}/cf ${MNT}
682

    
683
			umount ${MNT}
684
			# Restore the trap back
685
			trap "mdconfig -d -u ${MD}; return" 1 2 15 EXIT
686
		else
687
			">>> [nanoo] NANO_CONFSIZE is not set. Not adding a /conf partition.. You sure about this??" | tee -a ${LOGFILE}
688
		fi
689

    
690
		mdconfig -d -u $MD
691
		# Restore default action
692
		trap "-" 1 2 15 EXIT
693

    
694
		# Check each image and ensure that they are over
695
		# 3 megabytes.  If either image is under 20 megabytes
696
		# in size then error out.
697
		IMGSIZE=$(stat -f "%z" ${IMG})
698
		CHECKSIZE="20040710"
699
		if [ "$IMGSIZE" -lt "$CHECKSIZE" ]; then
700
			echo ">>> ERROR: Something went wrong when building NanoBSD.  The image size is under 20 megabytes!" | tee -a ${LOGFILE}
701
			print_error_pfS
702
		fi
703

    
704
		# Wrap up the show, Johnny
705
		echo ">>> NanoBSD Image completed for size: $_NANO_MEDIASIZE." | tee -a ${LOGFILE}
706

    
707
		gzip -qf $IMG &
708
		_bg_pids="${_bg_pids}${_bg_pids:+ }$!"
709
	done
710

    
711
	unset IMG
712
	unset IMGSIZE
713
}
714

    
715
# This routine creates a ova image that contains
716
# a ovf and vmdk file. These files can be imported
717
# right into vmware or virtual box.
718
# (and many other emulation platforms)
719
# http://www.vmware.com/pdf/ovf_whitepaper_specification.pdf
720
create_ova_image() {
721
	# XXX create a .ovf php creator that you can pass:
722
	#     1. populatedSize
723
	#     2. license
724
	#     3. product name
725
	#     4. version
726
	#     5. number of network interface cards
727
	#     6. allocationUnits
728
	#     7. capacity
729
	#     8. capacityAllocationUnits
730

    
731
	LOGFILE=${BUILDER_LOGS}/ova.${TARGET}.log
732

    
733
	[ -d "${OVA_TMP}" ] \
734
		&& rm -rf ${OVA_TMP}
735

    
736
	mkdir -p $(dirname ${OVAPATH})
737

    
738
	local _mntdir=${OVA_TMP}/mnt
739
	mkdir -p ${_mntdir}
740

    
741
	if [ -z "${OVA_SWAP_PART_SIZE_IN_GB}" -o "${OVA_SWAP_PART_SIZE_IN_GB}" = "0" ]; then
742
		# first partition size (freebsd-ufs)
743
		local OVA_FIRST_PART_SIZE_IN_GB=${VMDK_DISK_CAPACITY_IN_GB}
744
		# Calculate real first partition size, removing 128 blocks (65536 bytes) beginning/loader
745
		local OVA_FIRST_PART_SIZE=$((${OVA_FIRST_PART_SIZE_IN_GB}*1024*1024*1024-65536))
746
		# Unset swap partition size variable
747
		unset OVA_SWAP_PART_SIZE
748
		# Parameter used by mkimg
749
		unset OVA_SWAP_PART_PARAM
750
	else
751
		# first partition size (freebsd-ufs)
752
		local OVA_FIRST_PART_SIZE_IN_GB=$((VMDK_DISK_CAPACITY_IN_GB-OVA_SWAP_PART_SIZE_IN_GB))
753
		# Use first partition size in g
754
		local OVA_FIRST_PART_SIZE="${OVA_FIRST_PART_SIZE_IN_GB}g"
755
		# Calculate real swap size, removing 128 blocks (65536 bytes) beginning/loader
756
		local OVA_SWAP_PART_SIZE=$((${OVA_SWAP_PART_SIZE_IN_GB}*1024*1024*1024-65536))
757
		# Parameter used by mkimg
758
		local OVA_SWAP_PART_PARAM="-p freebsd-swap/swap0::${OVA_SWAP_PART_SIZE}"
759
	fi
760

    
761
	# Prepare folder to be put in image
762
	customize_stagearea_for_image "ova"
763
	install_default_kernel ${DEFAULT_KERNEL} "no"
764

    
765
	# Fill fstab
766
	echo ">>> Installing platform specific items..." | tee -a ${LOGFILE}
767
	echo "/dev/gpt/${PRODUCT_NAME}	/	ufs		rw	1	1" > ${FINAL_CHROOT_DIR}/etc/fstab
768
	if [ -n "${OVA_SWAP_PART_SIZE}" ]; then
769
		echo "/dev/gpt/swap0	none	swap	sw	0	0" >> ${FINAL_CHROOT_DIR}/etc/fstab
770
	fi
771

    
772
	# Create / partition
773
	echo -n ">>> Creating / partition... " | tee -a ${LOGFILE}
774
	truncate -s ${OVA_FIRST_PART_SIZE} ${OVA_TMP}/${OVFUFS}
775
	local _md=$(mdconfig -a -f ${OVA_TMP}/${OVAUFS})
776
	trap "mdconfig -d -u ${_md}; return" 1 2 15 EXIT
777

    
778
	newfs -L ${PRODUCT_NAME} -j /dev/${_md} 2>&1 >>${LOGFILE}
779

    
780
	if ! mount /dev/${_md} ${_mntdir} 2>&1 >>${LOGFILE}; then
781
		echo "Failed!" | tee -a ${LOGFILE}
782
		echo ">>> ERROR: Error mounting temporary vmdk image. STOPPING!" | tee -a ${LOGFILE}
783
		print_error_pfS
784
	fi
785
	trap "umount ${_mntdir}; mdconfig -d -u ${_md}; return" 1 2 15 EXIT
786

    
787
	echo "Done!" | tee -a ${LOGFILE}
788

    
789
	clone_directory_contents ${FINAL_CHROOT_DIR} ${_mntdir}
790

    
791
	sync
792
	umount ${_mntdir} 2>&1 >>${LOGFILE}
793
	mdconfig -d -u ${_md}
794
	trap "-" 1 2 15 EXIT
795

    
796
	# Create raw disk
797
	echo -n ">>> Creating raw disk... " | tee -a ${LOGFILE}
798
	mkimg \
799
		-s gpt \
800
		-f raw \
801
		-b ${FINAL_CHROOT_DIR}/boot/pmbr \
802
		-p freebsd-boot:=${FINAL_CHROOT_DIR}/boot/gptboot \
803
		-p freebsd-ufs/${PRODUCT_NAME}:=${OVA_TMP}/${OVFUFS} \
804
		${OVA_SWAP_PART_PARAM} \
805
		-o ${OVA_TMP}/${OVFRAW} 2>&1 >> ${LOGFILE}
806

    
807
	if [ $? -ne 0 -o ! -f ${OVA_TMP}/${OVFRAW} ]; then
808
		if [ -f ${OVA_TMP}/${OVFUFS} ]; then
809
			rm -f ${OVA_TMP}/${OVFUFS}
810
		fi
811
		if [ -f ${OVA_TMP}/${OVFRAW} ]; then
812
			rm -f ${OVA_TMP}/${OVFRAW}
813
		fi
814
		echo "Failed!" | tee -a ${LOGFILE}
815
		echo ">>> ERROR: Error creating temporary vmdk image. STOPPING!" | tee -a ${LOGFILE}
816
		print_error_pfS
817
	fi
818
	echo "Done!" | tee -a ${LOGFILE}
819

    
820
	# We don't need it anymore
821
	rm -f ${OVA_TMP}/${OVFUFS} >/dev/null 2>&1
822

    
823
	# Convert raw to vmdk
824
	echo -n ">>> Creating vmdk disk... " | tee -a ${LOGFILE}
825
	vmdktool -z9 -v ${OVA_TMP}/${OVFVMDK} ${OVA_TMP}/${OVFRAW}
826

    
827
	if [ $? -ne 0 -o ! -f ${OVA_TMP}/${OVFVMDK} ]; then
828
		if [ -f ${OVA_TMP}/${OVFRAW} ]; then
829
			rm -f ${OVA_TMP}/${OVFRAW}
830
		fi
831
		if [ -f ${OVA_TMP}/${OVFVMDK} ]; then
832
			rm -f ${OVA_TMP}/${OVFVMDK}
833
		fi
834
		echo "Failed!" | tee -a ${LOGFILE}
835
		echo ">>> ERROR: Error creating vmdk image. STOPPING!" | tee -a ${LOGFILE}
836
		print_error_pfS
837
	fi
838
	echo "Done!" | tee -a ${LOGFILE}
839

    
840
	rm -f ${OVA_TMP}/i${OVFRAW}
841

    
842
	ova_setup_ovf_template
843

    
844
	echo -n ">>> Writing final ova image... " | tee -a ${LOGFILE}
845
	# Create OVA file for vmware
846
	gtar -C ${OVA_TMP} -cpf ${OVAPATH} ${PRODUCT_NAME}.ovf ${OVFVMDK}
847
	echo "Done!" | tee -a ${LOGFILE}
848
	rm -f ${OVA_TMP}/${OVFVMDK} >/dev/null 2>&1
849

    
850
	echo ">>> OVA created: $(LC_ALL=C date)" | tee -a ${LOGFILE}
851
}
852

    
853
# called from create_ova_image
854
ova_setup_ovf_template() {
855
	if [ ! -f ${OVFTEMPLATE} ]; then
856
		echo ">>> ERROR: OVF template file (${OVFTEMPLATE}) not found."
857
		print_error_pfS
858
	fi
859

    
860
	#  OperatingSystemSection (${PRODUCT_NAME}.ovf)
861
	#  42   FreeBSD 32-Bit
862
	#  78   FreeBSD 64-Bit
863
	if [ "${TARGET}" = "amd64" ]; then
864
		local _os_id="78"
865
		local _os_type="freebsd64Guest"
866
		local _os_descr="FreeBSD 64-Bit"
867
	else
868
		echo ">>> ERROR: Platform not supported for OVA (${TARGET})"
869
		print_error_pfS
870
	fi
871

    
872
	local POPULATED_SIZE=$(du -d0 -k $FINAL_CHROOT_DIR | cut -f1)
873
	local POPULATED_SIZE_IN_BYTES=$((${POPULATED_SIZE}*1024))
874
	local VMDK_FILE_SIZE=$(stat -f "%z" ${OVA_TMP}/${OVFVMDK})
875

    
876
	sed \
877
		-e "s,%%VMDK_FILE_SIZE%%,${VMDK_FILE_SIZE},g" \
878
		-e "s,%%VMDK_DISK_CAPACITY_IN_GB%%,${VMDK_DISK_CAPACITY_IN_GB},g" \
879
		-e "s,%%POPULATED_SIZE_IN_BYTES%%,${POPULATED_SIZE_IN_BYTES},g" \
880
		-e "s,%%OS_ID%%,${_os_id},g" \
881
		-e "s,%%OS_TYPE%%,${_os_type},g" \
882
		-e "s,%%OS_DESCR%%,${_os_descr},g" \
883
		-e "s,%%PRODUCT_NAME%%,${PRODUCT_NAME},g" \
884
		-e "s,%%PRODUCT_NAME_SUFFIX%%,${PRODUCT_NAME_SUFFIX},g" \
885
		-e "s,%%PRODUCT_VERSION%%,${PRODUCT_VERSION},g" \
886
		-e "s,%%PRODUCT_URL%%,${PRODUCT_URL},g" \
887
		-e "s#%%VENDOR_NAME%%#${VENDOR_NAME}#g" \
888
		-e "s#%%OVF_INFO%%#${OVF_INFO}#g" \
889
		-e "/^%%PRODUCT_LICENSE%%/r ${BUILDER_ROOT}/license.txt" \
890
		-e "/^%%PRODUCT_LICENSE%%/d" \
891
		${OVFTEMPLATE} > ${OVA_TMP}/${PRODUCT_NAME}.ovf
892
}
893

    
894
# Cleans up previous builds
895
clean_builder() {
896
	# Clean out directories
897
	echo ">>> Cleaning up previous build environment...Please wait!"
898

    
899
	staginareas_clean_each_run
900

    
901
	if [ -d "${STAGE_CHROOT_DIR}" ]; then
902
		BASENAME=$(basename ${STAGE_CHROOT_DIR})
903
		echo -n ">>> Cleaning ${STAGE_CHROOT_DIR} ..."
904
		chflags -R noschg ${STAGE_CHROOT_DIR} 2>&1 >/dev/null
905
		rm -rf ${STAGE_CHROOT_DIR}/* 2>/dev/null
906
		echo "Done."
907
	fi
908

    
909
	if [ -z "${NO_CLEAN_FREEBSD_OBJ}" -a -d "${FREEBSD_SRC_DIR}" ]; then
910
		OBJTREE=$(env TARGET=${TARGET} TARGET_ARCH=${TARGET_ARCH} make -C ${FREEBSD_SRC_DIR} -V OBJTREE)
911
		if [ -d "${OBJTREE}" ]; then
912
			echo -n ">>> Cleaning FreeBSD objects dir staging..."
913
			echo -n "."
914
			chflags -R noschg ${OBJTREE} 2>&1 >/dev/null
915
			echo -n "."
916
			rm -rf ${OBJTREE}/*
917
			echo "Done!"
918
		fi
919
		if [ -d "${KERNEL_BUILD_PATH}" ]; then
920
			echo -n ">>> Cleaning previously built kernel stage area..."
921
			rm -rf $KERNEL_BUILD_PATH/*
922
			echo "Done!"
923
		fi
924
	fi
925
	mkdir -p $KERNEL_BUILD_PATH
926

    
927
	echo -n ">>> Cleaning previously built images..."
928
	rm -rf $IMAGES_FINAL_DIR/*
929
	echo "Done!"
930

    
931
	if [ -z "${NO_CLEAN_FREEBSD_SRC}" ]; then
932
		if [ -d "$FREEBSD_SRC_DIR" ]; then
933
			echo -n ">>> Ensuring $FREEBSD_SRC_DIR is clean..."
934
			rm -rf ${FREEBSD_SRC_DIR}
935
			echo "Done!"
936
		fi
937
	fi
938

    
939
	echo -n ">>> Cleaning previous builder logs..."
940
	if [ -d "$BUILDER_LOGS" ]; then
941
		rm -rf ${BUILDER_LOGS}
942
	fi
943
	mkdir -p ${BUILDER_LOGS}
944

    
945
	echo "Done!"
946

    
947
	echo ">>> Cleaning of builder environment has finished."
948
}
949

    
950
clone_directory_contents() {
951
	if [ ! -e "$2" ]; then
952
		mkdir -p "$2"
953
	fi
954
	if [ ! -d "$1" -o ! -d "$2" ]; then
955
		if [ -z "${LOGFILE}" ]; then
956
			echo ">>> ERROR: Argument $1 supplied is not a directory!"
957
		else
958
			echo ">>> ERROR: Argument $1 supplied is not a directory!" | tee -a ${LOGFILE}
959
		fi
960
		print_error_pfS
961
	fi
962
	echo -n ">>> Using TAR to clone $1 to $2 ..."
963
	tar -C ${1} -c -f - . | tar -C ${2} -x -p -f -
964
	echo "Done!"
965
}
966

    
967
clone_to_staging_area() {
968
	# Clone everything to the final staging area
969
	echo -n ">>> Cloning everything to ${STAGE_CHROOT_DIR} staging area..."
970
	LOGFILE=${BUILDER_LOGS}/cloning.${TARGET}.log
971

    
972
	tar -C ${PRODUCT_SRC} -c -f - . | \
973
		tar -C ${STAGE_CHROOT_DIR} -x -p -f -
974

    
975
	if [ "${PRODUCT_NAME}" != "pfSense" ]; then
976
		mv ${STAGE_CHROOT_DIR}/usr/local/sbin/pfSense-upgrade \
977
			${STAGE_CHROOT_DIR}/usr/local/sbin/${PRODUCT_NAME}-upgrade
978
	fi
979

    
980
	mkdir -p ${STAGE_CHROOT_DIR}/etc/mtree
981
	mtree -Pcp ${STAGE_CHROOT_DIR}/var > ${STAGE_CHROOT_DIR}/etc/mtree/var.dist
982
	mtree -Pcp ${STAGE_CHROOT_DIR}/etc > ${STAGE_CHROOT_DIR}/etc/mtree/etc.dist
983
	if [ -d ${STAGE_CHROOT_DIR}/usr/local/etc ]; then
984
		mtree -Pcp ${STAGE_CHROOT_DIR}/usr/local/etc > ${STAGE_CHROOT_DIR}/etc/mtree/localetc.dist
985
	fi
986

    
987
	## Add buildtime and lastcommit information
988
	# This is used for detecting updates.
989
	echo "$BUILTDATESTRING" > $STAGE_CHROOT_DIR/etc/version.buildtime
990
	# Record last commit info if it is available.
991
	if [ -f $SCRATCHDIR/build_commit_info.txt ]; then
992
		cp $SCRATCHDIR/build_commit_info.txt $STAGE_CHROOT_DIR/etc/version.lastcommit
993
	fi
994

    
995
	local _exclude_files="${CORE_PKG_TMP}/base_exclude_files"
996
	sed \
997
		-e "s,%%PRODUCT_NAME%%,${PRODUCT_NAME},g" \
998
		-e "s,%%VERSION%%,${_version},g" \
999
		${BUILDER_TOOLS}/templates/core_pkg/base/exclude_files \
1000
		> ${_exclude_files}
1001

    
1002
	mkdir -p ${STAGE_CHROOT_DIR}${PRODUCT_SHARE_DIR} >/dev/null 2>&1
1003

    
1004
	# Include a sample pkg stable conf to base
1005
	setup_pkg_repo \
1006
		${PKG_REPO_DEFAULT} \
1007
		${STAGE_CHROOT_DIR}${PRODUCT_SHARE_DIR}/${PRODUCT_NAME}-repo.conf \
1008
		${TARGET} \
1009
		${TARGET_ARCH}
1010

    
1011
	mtree \
1012
		-c \
1013
		-k uid,gid,mode,size,flags,sha256digest \
1014
		-p ${STAGE_CHROOT_DIR} \
1015
		-X ${_exclude_files} \
1016
		> ${STAGE_CHROOT_DIR}${PRODUCT_SHARE_DIR}/base.mtree
1017
	tar \
1018
		-C ${STAGE_CHROOT_DIR} \
1019
		-cJf ${STAGE_CHROOT_DIR}${PRODUCT_SHARE_DIR}/base.txz \
1020
		-X ${_exclude_files} \
1021
		.
1022

    
1023
	local _share_repos_path="${SCRATCHDIR}/repo-tmp/${PRODUCT_SHARE_DIR}/pkg/repos"
1024
	rm -rf ${SCRATCHDIR}/repo-tmp >/dev/null 2>&1
1025
	mkdir -p ${_share_repos_path} >/dev/null 2>&1
1026

    
1027
	setup_pkg_repo \
1028
		${PKG_REPO_DEFAULT} \
1029
		${_share_repos_path}/${PRODUCT_NAME}-repo.conf \
1030
		${TARGET} \
1031
		${TARGET_ARCH}
1032

    
1033
	cp -f ${PKG_REPO_DEFAULT%%.conf}.descr ${_share_repos_path}
1034

    
1035
	# Add additional repos
1036
	for _template in ${PKG_REPO_BASE}/${PRODUCT_NAME}-repo-*.conf; do
1037
		_template_filename=$(basename ${_template})
1038
		setup_pkg_repo \
1039
			${_template} \
1040
			${_share_repos_path}/${_template_filename} \
1041
			${TARGET} \
1042
			${TARGET_ARCH}
1043
		cp -f ${_template%%.conf}.descr ${_share_repos_path}
1044
	done
1045

    
1046
	core_pkg_create repo "" ${CORE_PKG_VERSION} ${SCRATCHDIR}/repo-tmp
1047

    
1048
	core_pkg_create rc "" ${CORE_PKG_VERSION} ${STAGE_CHROOT_DIR}
1049
	core_pkg_create base "" ${CORE_PKG_VERSION} ${STAGE_CHROOT_DIR}
1050
	core_pkg_create base-nanobsd "" ${CORE_PKG_VERSION} ${STAGE_CHROOT_DIR}
1051
	core_pkg_create default-config "" ${CORE_PKG_VERSION} ${STAGE_CHROOT_DIR}
1052

    
1053
	local DEFAULTCONF=${STAGE_CHROOT_DIR}/conf.default/config.xml
1054

    
1055
	# Save current WAN and LAN if value
1056
	local _old_wan_if=$(xml sel -t -v "${XML_ROOTOBJ}/interfaces/wan/if" ${DEFAULTCONF})
1057
	local _old_lan_if=$(xml sel -t -v "${XML_ROOTOBJ}/interfaces/lan/if" ${DEFAULTCONF})
1058

    
1059
	# Change default interface names to match vmware driver
1060
	xml ed -P -L -u "${XML_ROOTOBJ}/interfaces/wan/if" -v "vmx0" ${DEFAULTCONF}
1061
	xml ed -P -L -u "${XML_ROOTOBJ}/interfaces/lan/if" -v "vmx1" ${DEFAULTCONF}
1062
	core_pkg_create default-config "vmware" ${CORE_PKG_VERSION} ${STAGE_CHROOT_DIR}
1063

    
1064
	# Restore default values to be used by serial package
1065
	xml ed -P -L -u "${XML_ROOTOBJ}/interfaces/wan/if" -v "${_old_wan_if}" ${DEFAULTCONF}
1066
	xml ed -P -L -u "${XML_ROOTOBJ}/interfaces/lan/if" -v "${_old_lan_if}" ${DEFAULTCONF}
1067

    
1068
	# Activate serial console in config.xml
1069
	xml ed -L -P -d "${XML_ROOTOBJ}/system/enableserial" ${DEFAULTCONF}
1070
	xml ed -P -s "${XML_ROOTOBJ}/system" -t elem -n "enableserial" \
1071
		${DEFAULTCONF} > ${DEFAULTCONF}.tmp
1072
	xml fo -t ${DEFAULTCONF}.tmp > ${DEFAULTCONF}
1073
	rm -f ${DEFAULTCONF}.tmp
1074

    
1075
	echo force > ${STAGE_CHROOT_DIR}/cf/conf/enableserial_force
1076

    
1077
	core_pkg_create default-config-serial "" ${CORE_PKG_VERSION} ${STAGE_CHROOT_DIR}
1078

    
1079
	rm -f ${STAGE_CHROOT_DIR}/cf/conf/enableserial_force
1080
	rm -f ${STAGE_CHROOT_DIR}/cf/conf/config.xml
1081

    
1082
	# Make sure pkg is present
1083
	pkg_bootstrap ${STAGE_CHROOT_DIR}
1084

    
1085
	echo "Done!"
1086
}
1087

    
1088
create_final_staging_area() {
1089
	if [ -z "${FINAL_CHROOT_DIR}" ]; then
1090
		echo ">>> ERROR: FINAL_CHROOT_DIR is not set, cannot continue!" | tee -a ${LOGFILE}
1091
		print_error_pfS
1092
	fi
1093

    
1094
	if [ -d "${FINAL_CHROOT_DIR}" ]; then
1095
		echo -n ">>> Previous ${FINAL_CHROOT_DIR} detected cleaning up..." | tee -a ${LOGFILE}
1096
		chflags -R noschg ${FINAL_CHROOT_DIR} 2>&1 1>/dev/null
1097
		rm -rf ${FINAL_CHROOT_DIR}/* 2>&1 1>/dev/null
1098
		echo "Done." | tee -a ${LOGFILE}
1099
	fi
1100

    
1101
	echo ">>> Preparing Final image staging area: $(LC_ALL=C date)" 2>&1 | tee -a ${LOGFILE}
1102
	echo ">>> Cloning ${STAGE_CHROOT_DIR} to ${FINAL_CHROOT_DIR}" 2>&1 | tee -a ${LOGFILE}
1103
	clone_directory_contents ${STAGE_CHROOT_DIR} ${FINAL_CHROOT_DIR}
1104

    
1105
	if [ ! -f $FINAL_CHROOT_DIR/sbin/init ]; then
1106
		echo ">>> ERROR: Something went wrong during cloning -- Please verify!" 2>&1 | tee -a ${LOGFILE}
1107
		print_error_pfS
1108
	fi
1109
}
1110

    
1111
customize_stagearea_for_image() {
1112
	local _image_type="$1"
1113
	local _default_config="" # filled with $2 below
1114
	local _image_variant="$3"
1115

    
1116
	if [ -n "$2" ]; then
1117
		_default_config="$2"
1118
	elif [ "${_image_type}" = "nanobsd" -o \
1119
	     "${_image_type}" = "memstickserial" -o \
1120
	     "${_image_type}" = "memstickadi" ]; then
1121
		_default_config="default-config-serial"
1122
	elif [ "${_image_type}" = "ova" ]; then
1123
		_default_config="default-config-vmware"
1124
	else
1125
		_default_config="default-config"
1126
	fi
1127

    
1128
	# Prepare final stage area
1129
	create_final_staging_area
1130

    
1131
	pkg_chroot_add ${FINAL_CHROOT_DIR} rc
1132
	pkg_chroot_add ${FINAL_CHROOT_DIR} repo
1133

    
1134
	if [ "${_image_type}" = "nanobsd" -o \
1135
	     "${_image_type}" = "nanobsd-vga" ]; then
1136

    
1137
		mkdir -p ${FINAL_CHROOT_DIR}/root/var/db \
1138
			 ${FINAL_CHROOT_DIR}/root/var/cache \
1139
			 ${FINAL_CHROOT_DIR}/var/db/pkg \
1140
			 ${FINAL_CHROOT_DIR}/var/cache/pkg
1141
		mv -f ${FINAL_CHROOT_DIR}/var/db/pkg ${FINAL_CHROOT_DIR}/root/var/db
1142
		mv -f ${FINAL_CHROOT_DIR}/var/cache/pkg ${FINAL_CHROOT_DIR}/root/var/cache
1143
		ln -sf ../../root/var/db/pkg ${FINAL_CHROOT_DIR}/var/db/pkg
1144
		ln -sf ../../root/var/cache/pkg ${FINAL_CHROOT_DIR}/var/cache/pkg
1145

    
1146
		pkg_chroot_add ${FINAL_CHROOT_DIR} base-nanobsd
1147
	else
1148
		pkg_chroot_add ${FINAL_CHROOT_DIR} base
1149
	fi
1150

    
1151
	if [ "${_image_type}" = "iso" -o \
1152
	     "${_image_type}" = "memstick" -o \
1153
	     "${_image_type}" = "memstickserial" -o \
1154
	     "${_image_type}" = "memstickadi" ]; then
1155
		install_bsdinstaller
1156
		mkdir -p ${FINAL_CHROOT_DIR}/pkgs
1157
		cp ${CORE_PKG_REAL_PATH}/All/*default-config*.txz ${FINAL_CHROOT_DIR}/pkgs
1158
	fi
1159

    
1160
	pkg_chroot_add ${FINAL_CHROOT_DIR} ${_default_config}
1161

    
1162
	# XXX: Workaround to avoid pkg to complain regarding release
1163
	#      repo on first boot since packages are installed from
1164
	#      staging server during build phase
1165
	if [ -n "${USE_PKG_REPO_STAGING}" ]; then
1166
		_read_cmd="select value from repodata where key='packagesite'"
1167
		if [ -n "${_IS_RELEASE}" ]; then
1168
			local _tgt_server="${PKG_REPO_SERVER_RELEASE}"
1169
		else
1170
			local _tgt_server="${PKG_REPO_SERVER_DEVEL}"
1171
		fi
1172
		for _db in ${FINAL_CHROOT_DIR}/var/db/pkg/repo-*sqlite; do
1173
			_cur=$(/usr/local/bin/sqlite3 ${_db} "${_read_cmd}")
1174
			_new=$(echo "${_cur}" | sed -e "s,^${PKG_REPO_SERVER_STAGING},${_tgt_server},")
1175
			/usr/local/bin/sqlite3 ${_db} "update repodata set value='${_new}' where key='packagesite'"
1176
		done
1177
	fi
1178

    
1179
	if [ -n "$_image_variant" -a \
1180
	    -d ${BUILDER_TOOLS}/templates/custom_logos/${_image_variant} ]; then
1181
		mkdir -p ${FINAL_CHROOT_DIR}/usr/local/share/${PRODUCT_NAME}/custom_logos
1182
		cp -f \
1183
			${BUILDER_TOOLS}/templates/custom_logos/${_image_variant}/*.png \
1184
			${FINAL_CHROOT_DIR}/usr/local/share/${PRODUCT_NAME}/custom_logos
1185
	fi
1186
}
1187

    
1188
create_distribution_tarball() {
1189
	mkdir -p ${FINAL_CHROOT_DIR}/install
1190

    
1191
	tar -C ${FINAL_CHROOT_DIR} --exclude ./install --exclude ./pkgs -cJf ${FINAL_CHROOT_DIR}/install/${PRODUCT_NAME}.txz .
1192
}
1193

    
1194
create_iso_image() {
1195
	LOGFILE=${BUILDER_LOGS}/isoimage.${TARGET}
1196
	echo ">>> Building bootable ISO image for ${TARGET}" | tee -a ${LOGFILE}
1197
	if [ -z "${DEFAULT_KERNEL}" ]; then
1198
		echo ">>> ERROR: Could not identify DEFAULT_KERNEL to install on image!" | tee -a ${LOGFILE}
1199
		print_error_pfS
1200
	fi
1201

    
1202
	mkdir -p $(dirname ${ISOPATH})
1203

    
1204
	customize_stagearea_for_image "iso"
1205
	install_default_kernel ${DEFAULT_KERNEL}
1206

    
1207
	echo cdrom > $FINAL_CHROOT_DIR/etc/platform
1208

    
1209
	FSLABEL=$(echo ${PRODUCT_NAME} | tr '[:lower:]' '[:upper:]')
1210
	echo "/dev/iso9660/${FSLABEL} / cd9660 ro 0 0" > ${FINAL_CHROOT_DIR}/etc/fstab
1211

    
1212
	# This check is for supporting create memstick/ova images
1213
	echo -n ">>> Running command: script -aq $LOGFILE makefs -t cd9660 -o bootimage=\"i386;${FINAL_CHROOT_DIR}/boot/cdboot \"-o no-emul-boot -o rockridge " | tee -a ${LOGFILE}
1214
	echo "-o label=${FSLABEL} -o publisher=\"${PRODUCT_NAME} project.\" $ISOPATH ${FINAL_CHROOT_DIR}" | tee -a ${LOGFILE}
1215

    
1216
	create_distribution_tarball
1217

    
1218
	# Remove /rescue from iso since cd9660 cannot deal with hardlinks
1219
	rm -rf ${FINAL_CHROOT_DIR}/rescue
1220

    
1221
	makefs -t cd9660 -o bootimage="i386;${FINAL_CHROOT_DIR}/boot/cdboot" -o no-emul-boot -o rockridge \
1222
		-o label=${FSLABEL} -o publisher="${PRODUCT_NAME} project." $ISOPATH ${FINAL_CHROOT_DIR} 2>&1 >> ${LOGFILE}
1223
	if [ $? -ne 0 -o ! -f $ISOPATH ]; then
1224
		if [ -f ${ISOPATH} ]; then
1225
			rm -f $ISOPATH
1226
		fi
1227
		echo ">>> ERROR: Something wrong happened during ISO image creation. STOPPING!" | tee -a ${LOGFILE}
1228
		print_error_pfS
1229
	fi
1230
	gzip -qf $ISOPATH &
1231
	_bg_pids="${_bg_pids}${_bg_pids:+ }$!"
1232

    
1233
	echo ">>> ISO created: $(LC_ALL=C date)" | tee -a ${LOGFILE}
1234
}
1235

    
1236
create_memstick_image() {
1237
	local _variant="$1"
1238

    
1239
	LOGFILE=${BUILDER_LOGS}/memstick.${TARGET}
1240
	if [ "${MEMSTICKPATH}" = "" ]; then
1241
		echo ">>> MEMSTICKPATH is empty skipping generation of memstick image!" | tee -a ${LOGFILE}
1242
		return
1243
	fi
1244

    
1245
	mkdir -p $(dirname ${MEMSTICKPATH})
1246

    
1247
	local _image_path=${MEMSTICKPATH}
1248
	if [ -n "${_variant}" ]; then
1249
		_image_path=$(echo "$_image_path" | \
1250
			sed "s/-memstick-/-memstick-${_variant}-/")
1251
		VARIANTIMAGES="${VARIANTIMAGES}${VARIANTIMAGES:+ }${_image_path}"
1252
	fi
1253

    
1254
	customize_stagearea_for_image "memstick" "" $_variant
1255
	install_default_kernel ${DEFAULT_KERNEL}
1256

    
1257
	echo cdrom > $FINAL_CHROOT_DIR/etc/platform
1258

    
1259
	echo ">>> Creating memstick to ${_image_path}." 2>&1 | tee -a ${LOGFILE}
1260
	echo "/dev/ufs/${PRODUCT_NAME} / ufs ro 0 0" > ${FINAL_CHROOT_DIR}/etc/fstab
1261
	echo "kern.cam.boot_delay=10000" >> ${FINAL_CHROOT_DIR}/boot/loader.conf.local
1262

    
1263
	create_distribution_tarball
1264

    
1265
	makefs -B little -o label=${PRODUCT_NAME},version=2 ${_image_path} ${FINAL_CHROOT_DIR}
1266
	if [ $? -ne 0 ]; then
1267
		if [ -f ${_image_path} ]; then
1268
			rm -f $_image_path
1269
		fi
1270
		echo ">>> ERROR: Something wrong happened during MEMSTICK image creation. STOPPING!" | tee -a ${LOGFILE}
1271
		print_error_pfS
1272
	fi
1273
	MD=$(mdconfig -a -t vnode -f $_image_path)
1274
	# Just in case
1275
	trap "mdconfig -d -u ${MD}" 1 2 15 EXIT
1276
	gpart create -s BSD ${MD} 2>&1 >> ${LOGFILE}
1277
	gpart bootcode -b ${FINAL_CHROOT_DIR}/boot/boot ${MD} 2>&1 >> ${LOGFILE}
1278
	gpart add -t freebsd-ufs ${MD} 2>&1 >> ${LOGFILE}
1279
	trap "-" 1 2 15 EXIT
1280
	mdconfig -d -u ${MD} 2>&1 | tee -a ${LOGFILE}
1281
	gzip -qf $_image_path &
1282
	_bg_pids="${_bg_pids}${_bg_pids:+ }$!"
1283

    
1284
	echo ">>> MEMSTICK created: $(LC_ALL=C date)" | tee -a ${LOGFILE}
1285
}
1286

    
1287
create_memstick_serial_image() {
1288
	LOGFILE=${BUILDER_LOGS}/memstickserial.${TARGET}
1289
	if [ "${MEMSTICKSERIALPATH}" = "" ]; then
1290
		echo ">>> MEMSTICKSERIALPATH is empty skipping generation of memstick image!" | tee -a ${LOGFILE}
1291
		return
1292
	fi
1293

    
1294
	mkdir -p $(dirname ${MEMSTICKSERIALPATH})
1295

    
1296
	customize_stagearea_for_image "memstickserial"
1297
	install_default_kernel ${DEFAULT_KERNEL}
1298

    
1299
	echo cdrom > $FINAL_CHROOT_DIR/etc/platform
1300

    
1301
	echo "/dev/ufs/${PRODUCT_NAME} / ufs ro 0 0" > ${FINAL_CHROOT_DIR}/etc/fstab
1302
	echo "kern.cam.boot_delay=10000" >> ${FINAL_CHROOT_DIR}/boot/loader.conf.local
1303

    
1304
	echo ">>> Creating serial memstick to ${MEMSTICKSERIALPATH}." 2>&1 | tee -a ${LOGFILE}
1305

    
1306
	BOOTCONF=${FINAL_CHROOT_DIR}/boot.config
1307
	LOADERCONF=${FINAL_CHROOT_DIR}/boot/loader.conf
1308

    
1309
	echo ">>> Activating serial console..." 2>&1 | tee -a ${LOGFILE}
1310
	# Activate serial console in boot.config
1311
	if [ -f ${BOOTCONF} ]; then
1312
		sed -i "" '/-D$/d' ${BOOTCONF}
1313
	fi
1314
	echo "-S115200 -D" >> ${BOOTCONF}
1315

    
1316
	# Remove old console options if present.
1317
	[ -f "${LOADERCONF}" ] \
1318
		&& sed -i "" -Ee "/(console|boot_multicons|boot_serial)/d" ${LOADERCONF}
1319
	# Activate serial console+video console in loader.conf
1320
	echo 'boot_multicons="YES"' >>  ${LOADERCONF}
1321
	echo 'boot_serial="YES"' >> ${LOADERCONF}
1322
	echo 'console="comconsole,vidconsole"' >> ${LOADERCONF}
1323
	echo 'comconsole_speed="115200"' >> ${LOADERCONF}
1324

    
1325
	create_distribution_tarball
1326

    
1327
	makefs -B little -o label=${PRODUCT_NAME},version=2 ${MEMSTICKSERIALPATH} ${FINAL_CHROOT_DIR}
1328
	if [ $? -ne 0 ]; then
1329
		if [ -f ${MEMSTICKSERIALPATH} ]; then
1330
			rm -f $MEMSTICKSERIALPATH
1331
		fi
1332
		echo ">>> ERROR: Something wrong happened during MEMSTICKSERIAL image creation. STOPPING!" | tee -a ${LOGFILE}
1333
		print_error_pfS
1334
	fi
1335
	MD=$(mdconfig -a -t vnode -f $MEMSTICKSERIALPATH)
1336
	# Just in case
1337
	trap "mdconfig -d -u ${MD}" 1 2 15 EXIT
1338
	gpart create -s BSD ${MD} 2>&1 >> ${LOGFILE}
1339
	gpart bootcode -b ${FINAL_CHROOT_DIR}/boot/boot ${MD} 2>&1 >> ${LOGFILE}
1340
	gpart add -t freebsd-ufs ${MD} 2>&1 >> ${LOGFILE}
1341
	trap "-" 1 2 15 EXIT
1342
	mdconfig -d -u ${MD} 2>&1 >> ${LOGFILE}
1343
	gzip -qf $MEMSTICKSERIALPATH &
1344
	_bg_pids="${_bg_pids}${_bg_pids:+ }$!"
1345

    
1346
	echo ">>> MEMSTICKSERIAL created: $(LC_ALL=C date)" | tee -a ${LOGFILE}
1347
}
1348

    
1349
create_memstick_adi_image() {
1350
	LOGFILE=${BUILDER_LOGS}/memstickadi.${TARGET}
1351
	if [ "${MEMSTICKADIPATH}" = "" ]; then
1352
		echo ">>> MEMSTICKADIPATH is empty skipping generation of memstick image!" | tee -a ${LOGFILE}
1353
		return
1354
	fi
1355

    
1356
	mkdir -p $(dirname ${MEMSTICKADIPATH})
1357

    
1358
	customize_stagearea_for_image "memstickadi"
1359
	install_default_kernel ${DEFAULT_KERNEL}
1360

    
1361
	echo cdrom > $FINAL_CHROOT_DIR/etc/platform
1362

    
1363
	echo "/dev/ufs/${PRODUCT_NAME} / ufs ro 0 0" > ${FINAL_CHROOT_DIR}/etc/fstab
1364
	echo "kern.cam.boot_delay=10000" >> ${FINAL_CHROOT_DIR}/boot/loader.conf.local
1365

    
1366
	echo ">>> Creating serial memstick to ${MEMSTICKADIPATH}." 2>&1 | tee -a ${LOGFILE}
1367

    
1368
	BOOTCONF=${FINAL_CHROOT_DIR}/boot.config
1369
	LOADERCONF=${FINAL_CHROOT_DIR}/boot/loader.conf
1370

    
1371
	echo ">>> Activating serial console..." 2>&1 | tee -a ${LOGFILE}
1372
	# Activate serial console in boot.config
1373
	if [ -f ${BOOTCONF} ]; then
1374
		sed -i "" '/-[Dh]$/d' ${BOOTCONF}
1375
	fi
1376
	echo "-S115200 -h" >> ${BOOTCONF}
1377

    
1378
	# Remove old console options if present.
1379
	[ -f "${LOADERCONF}" ] \
1380
		&& sed -i "" -Ee "/(console|boot_multicons|boot_serial|hint.uart)/d" ${LOADERCONF}
1381
	# Activate serial console+video console in loader.conf
1382
	echo 'boot_serial="YES"' >> ${LOADERCONF}
1383
	echo 'console="comconsole"' >> ${LOADERCONF}
1384
	echo 'comconsole_speed="115200"' >> ${LOADERCONF}
1385
	echo 'comconsole_port="0x2F8"' >> ${LOADERCONF}
1386
	echo 'hint.uart.0.flags="0x00"' >> ${LOADERCONF}
1387
	echo 'hint.uart.1.flags="0x10"' >> ${LOADERCONF}
1388

    
1389
	create_distribution_tarball
1390

    
1391
	makefs -B little -o label=${PRODUCT_NAME},version=2 ${MEMSTICKADIPATH} ${FINAL_CHROOT_DIR}
1392
	if [ $? -ne 0 ]; then
1393
		if [ -f ${MEMSTICKADIPATH} ]; then
1394
			rm -f $MEMSTICKADIPATH
1395
		fi
1396
		echo ">>> ERROR: Something wrong happened during MEMSTICKADI image creation. STOPPING!" | tee -a ${LOGFILE}
1397
		print_error_pfS
1398
	fi
1399
	MD=$(mdconfig -a -t vnode -f $MEMSTICKADIPATH)
1400
	# Just in case
1401
	trap "mdconfig -d -u ${MD}" 1 2 15 EXIT
1402
	gpart create -s BSD ${MD} 2>&1 >> ${LOGFILE}
1403
	gpart bootcode -b ${FINAL_CHROOT_DIR}/boot/boot ${MD} 2>&1 >> ${LOGFILE}
1404
	gpart add -t freebsd-ufs ${MD} 2>&1 >> ${LOGFILE}
1405
	trap "-" 1 2 15 EXIT
1406
	mdconfig -d -u ${MD} 2>&1 >> ${LOGFILE}
1407
	gzip -qf $MEMSTICKADIPATH &
1408
	_bg_pids="${_bg_pids}${_bg_pids:+ }$!"
1409

    
1410
	echo ">>> MEMSTICKADI created: $(LC_ALL=C date)" | tee -a ${LOGFILE}
1411
}
1412

    
1413
# Create pkg conf on desired place with desired arch/branch
1414
setup_pkg_repo() {
1415
	if [ -z "${4}" ]; then
1416
		return
1417
	fi
1418

    
1419
	local _template="${1}"
1420
	local _target="${2}"
1421
	local _arch="${3}"
1422
	local _target_arch="${4}"
1423
	local _staging="${5}"
1424

    
1425
	if [ -z "${_template}" -o ! -f "${_template}" ]; then
1426
		echo ">>> ERROR: It was not possible to find pkg conf template ${_template}"
1427
		print_error_pfS
1428
	fi
1429

    
1430
	if [ -n "${_staging}" -a -n "${USE_PKG_REPO_STAGING}" ]; then
1431
		local _pkg_repo_server_devel=${PKG_REPO_SERVER_STAGING}
1432
		local _pkg_repo_branch_devel=${PKG_REPO_BRANCH_STAGING}
1433
		local _pkg_repo_server_release=${PKG_REPO_SERVER_STAGING}
1434
		local _pkg_repo_branch_release=${PKG_REPO_BRANCH_STAGING}
1435
	else
1436
		local _pkg_repo_server_devel=${PKG_REPO_SERVER_DEVEL}
1437
		local _pkg_repo_branch_devel=${PKG_REPO_BRANCH_DEVEL}
1438
		local _pkg_repo_server_release=${PKG_REPO_SERVER_RELEASE}
1439
		local _pkg_repo_branch_release=${PKG_REPO_BRANCH_RELEASE}
1440
	fi
1441

    
1442
	mkdir -p $(dirname ${_target}) >/dev/null 2>&1
1443

    
1444
	sed \
1445
		-e "s/%%ARCH%%/${_target_arch}/" \
1446
		-e "s/%%PKG_REPO_BRANCH_DEVEL%%/${_pkg_repo_branch_devel}/g" \
1447
		-e "s/%%PKG_REPO_BRANCH_RELEASE%%/${_pkg_repo_branch_release}/g" \
1448
		-e "s,%%PKG_REPO_SERVER_DEVEL%%,${_pkg_repo_server_devel},g" \
1449
		-e "s,%%PKG_REPO_SERVER_RELEASE%%,${_pkg_repo_server_release},g" \
1450
		-e "s,%%POUDRIERE_PORTS_NAME%%,${POUDRIERE_PORTS_NAME},g" \
1451
		-e "s/%%PRODUCT_NAME%%/${PRODUCT_NAME}/g" \
1452
		${_template} \
1453
		> ${_target}
1454
}
1455

    
1456
# This routine ensures any ports / binaries that the builder
1457
# system needs are on disk and ready for execution.
1458
builder_setup() {
1459
	# If Product-builder is already installed, just leave
1460
	if pkg info -e -q ${PRODUCT_NAME}-builder; then
1461
		return
1462
	fi
1463

    
1464
	if [ ! -f ${PKG_REPO_PATH} ]; then
1465
		[ -d $(dirname ${PKG_REPO_PATH}) ] \
1466
			|| mkdir -p $(dirname ${PKG_REPO_PATH})
1467

    
1468
		update_freebsd_sources
1469

    
1470
		local _arch=$(uname -m)
1471
		setup_pkg_repo \
1472
			${PKG_REPO_DEFAULT} \
1473
			${PKG_REPO_PATH} \
1474
			${_arch} \
1475
			${_arch} \
1476
			"staging"
1477

    
1478
		# Use fingerprint keys from repo
1479
		sed -i '' -e "/fingerprints:/ s,\"/,\"${BUILDER_ROOT}/src/," \
1480
			${PKG_REPO_PATH}
1481
	fi
1482

    
1483
	pkg install ${PRODUCT_NAME}-builder
1484
}
1485

    
1486
# Updates FreeBSD sources
1487
update_freebsd_sources() {
1488
	if [ "${1}" = "full" ]; then
1489
		local _full=1
1490
		local _clone_params=""
1491
	else
1492
		local _full=0
1493
		local _clone_params="--depth 1 --single-branch"
1494
	fi
1495

    
1496
	if [ ! -d "${FREEBSD_SRC_DIR}" ]; then
1497
		mkdir -p ${FREEBSD_SRC_DIR}
1498
	fi
1499

    
1500
	if [ -n "${NO_BUILDWORLD}" -a -n "${NO_BUILDKERNEL}" ]; then
1501
		echo ">>> NO_BUILDWORLD and NO_BUILDKERNEL set, skipping update of freebsd sources" | tee -a ${LOGFILE}
1502
		return
1503
	fi
1504

    
1505
	echo -n ">>> Obtaining FreeBSD sources ${FREEBSD_BRANCH}..."
1506
	local _FREEBSD_BRANCH=${FREEBSD_BRANCH:-"devel"}
1507
	local _CLONE=1
1508

    
1509
	if [ -d "${FREEBSD_SRC_DIR}/.git" ]; then
1510
		CUR_BRANCH=$(cd ${FREEBSD_SRC_DIR} && git branch | grep '^\*' | cut -d' ' -f2)
1511
		if [ ${_full} -eq 0 -a "${CUR_BRANCH}" = "${_FREEBSD_BRANCH}" ]; then
1512
			_CLONE=0
1513
			( cd ${FREEBSD_SRC_DIR} && git clean -fd; git fetch origin; git reset --hard origin/${_FREEBSD_BRANCH} ) 2>&1 | grep -C3 -i -E 'error|fatal'
1514
		else
1515
			rm -rf ${FREEBSD_SRC_DIR}
1516
		fi
1517
	fi
1518

    
1519
	if [ ${_CLONE} -eq 1 ]; then
1520
		( git clone --branch ${_FREEBSD_BRANCH} ${_clone_params} ${FREEBSD_REPO_BASE} ${FREEBSD_SRC_DIR} ) 2>&1 | grep -C3 -i -E 'error|fatal'
1521
	fi
1522

    
1523
	if [ ! -d "${FREEBSD_SRC_DIR}/.git" ]; then
1524
		echo ">>> ERROR: It was not possible to clone FreeBSD src repo"
1525
		print_error_pfS
1526
	fi
1527

    
1528
	if [ -n "${GIT_FREEBSD_COSHA1}" ]; then
1529
		( cd ${FREEBSD_SRC_DIR} && git checkout ${GIT_FREEBSD_COSHA1} ) 2>&1 | grep -C3 -i -E 'error|fatal'
1530
	fi
1531
	echo "Done!"
1532
}
1533

    
1534
pkg_chroot() {
1535
	local _root="${1}"
1536
	shift
1537

    
1538
	if [ $# -eq 0 ]; then
1539
		return -1
1540
	fi
1541

    
1542
	if [ -z "${_root}" -o "${_root}" = "/" -o ! -d "${_root}" ]; then
1543
		return -1
1544
	fi
1545

    
1546
	mkdir -p \
1547
		${SCRATCHDIR}/pkg_cache \
1548
		${_root}/var/cache/pkg \
1549
		${_root}/dev
1550

    
1551
	/sbin/mount -t nullfs ${SCRATCHDIR}/pkg_cache ${_root}/var/cache/pkg
1552
	/sbin/mount -t devfs devfs ${_root}/dev
1553
	cp -f /etc/resolv.conf ${_root}/etc/resolv.conf
1554
	touch ${BUILDER_LOGS}/install_pkg_install_ports.txt
1555
	script -aq ${BUILDER_LOGS}/install_pkg_install_ports.txt pkg -c ${_root} $@ >/dev/null 2>&1
1556
	local result=$?
1557
	rm -f ${_root}/etc/resolv.conf
1558
	/sbin/umount -f ${_root}/dev
1559
	/sbin/umount -f ${_root}/var/cache/pkg
1560

    
1561
	return $result
1562
}
1563

    
1564

    
1565
pkg_chroot_add() {
1566
	if [ -z "${1}" -o -z "${2}" ]; then
1567
		return 1
1568
	fi
1569

    
1570
	local _target="${1}"
1571
	local _pkg="$(get_pkg_name ${2}).txz"
1572

    
1573
	if [ ! -d "${_target}" ]; then
1574
		echo ">>> ERROR: Target dir ${_target} not found"
1575
		print_error_pfS
1576
	fi
1577

    
1578
	if [ ! -f ${CORE_PKG_REAL_PATH}/All/${_pkg} ]; then
1579
		echo ">>> ERROR: Package ${_pkg} not found"
1580
		print_error_pfS
1581
	fi
1582

    
1583
	cp ${CORE_PKG_REAL_PATH}/All/${_pkg} ${_target}
1584
	pkg_chroot ${_target} add /${_pkg}
1585
	rm -f ${_target}/${_pkg}
1586
}
1587

    
1588
pkg_bootstrap() {
1589
	local _root=${1:-"${STAGE_CHROOT_DIR}"}
1590

    
1591
	setup_pkg_repo \
1592
		${PKG_REPO_DEFAULT} \
1593
		${_root}${PKG_REPO_PATH} \
1594
		${TARGET} \
1595
		${TARGET_ARCH} \
1596
		"staging"
1597

    
1598
	pkg_chroot ${_root} bootstrap -f
1599
}
1600

    
1601
# This routine assists with installing various
1602
# freebsd ports files into the pfsense-fs staging
1603
# area.
1604
install_pkg_install_ports() {
1605
	local MAIN_PKG="${1}"
1606

    
1607
	if [ -z "${MAIN_PKG}" ]; then
1608
		MAIN_PKG=${PRODUCT_NAME}
1609
	fi
1610

    
1611
	echo ">>> Installing pkg repository in chroot (${STAGE_CHROOT_DIR})..."
1612

    
1613
	[ -d ${STAGE_CHROOT_DIR}/var/cache/pkg ] || \
1614
		mkdir -p ${STAGE_CHROOT_DIR}/var/cache/pkg
1615

    
1616
	[ -d ${SCRATCHDIR}/pkg_cache ] || \
1617
		mkdir -p ${SCRATCHDIR}/pkg_cache
1618

    
1619
	echo -n ">>> Installing built ports (packages) in chroot (${STAGE_CHROOT_DIR})... "
1620
	# First mark all packages as automatically installed
1621
	pkg_chroot ${STAGE_CHROOT_DIR} set -A 1 -a
1622
	# Install all necessary packages
1623
	if ! pkg_chroot ${STAGE_CHROOT_DIR} install ${MAIN_PKG} ${custom_package_list}; then
1624
		echo "Failed!"
1625
		print_error_pfS
1626
	fi
1627
	# Make sure required packages are set as non-automatic
1628
	pkg_chroot ${STAGE_CHROOT_DIR} set -A 0 pkg ${MAIN_PKG} ${custom_package_list}
1629
	# Remove unnecessary packages
1630
	pkg_chroot ${STAGE_CHROOT_DIR} autoremove
1631
	echo "Done!"
1632
}
1633

    
1634
install_bsdinstaller() {
1635
	local _params=""
1636

    
1637
	# Use staging repo on RELEASE
1638
	if [ -n "${_IS_RELEASE}" ]; then
1639
		mkdir -p ${FINAL_CHROOT_DIR}/tmp/pkg-repo
1640
		cp -f ${STAGE_CHROOT_DIR}${PKG_REPO_PATH} \
1641
			${FINAL_CHROOT_DIR}/tmp/pkg-repo
1642
		_params="--repo-conf-dir /tmp/pkg-repo "
1643
	fi
1644

    
1645
	echo ">>> Installing BSDInstaller in chroot (${FINAL_CHROOT_DIR})... (starting)"
1646
	pkg_chroot ${FINAL_CHROOT_DIR} ${_params}install -f bsdinstaller
1647
	sed -i '' -e "s,%%PRODUCT_NAME%%,${PRODUCT_NAME}," \
1648
		  -e "s,%%PRODUCT_VERSION%%,${PRODUCT_VERSION}," \
1649
		  -e "s,%%ARCH%%,${TARGET}," \
1650
		  ${FINAL_CHROOT_DIR}/usr/local/share/dfuibe_lua/conf/pfSense.lua \
1651
		  ${FINAL_CHROOT_DIR}/usr/local/share/dfuibe_lua/conf/pfSense_rescue.lua
1652
	if [ -n "${_IS_RELEASE}" ]; then
1653
		rm -rf ${FINAL_CHROOT_DIR}/tmp/pkg-repo
1654
	fi
1655
	echo ">>> Installing BSDInstaller in chroot (${FINAL_CHROOT_DIR})... (finished)"
1656
}
1657

    
1658
staginareas_clean_each_run() {
1659
	echo -n ">>> Cleaning build directories: "
1660
	if [ -d "${FINAL_CHROOT_DIR}" ]; then
1661
		BASENAME=$(basename ${FINAL_CHROOT_DIR})
1662
		echo -n "$BASENAME "
1663
		chflags -R noschg ${FINAL_CHROOT_DIR} 2>&1 >/dev/null
1664
		rm -rf ${FINAL_CHROOT_DIR}/* 2>/dev/null
1665
	fi
1666
	echo "Done!"
1667
}
1668

    
1669
# Imported from FreeSBIE
1670
buildkernel() {
1671
	if [ -n "${NO_BUILDKERNEL}" ]; then
1672
		echo ">>> NO_BUILDKERNEL set, skipping build" | tee -a ${LOGFILE}
1673
		return
1674
	fi
1675

    
1676
	if [ -z "${KERNCONF}" ]; then
1677
		echo ">>> ERROR: No kernel configuration defined probably this is not what you want! STOPPING!" | tee -a ${LOGFILE}
1678
		print_error_pfS
1679
	fi
1680

    
1681
	if [ -n "${KERNELCONF}" ]; then
1682
		export KERNCONFDIR=$(dirname ${KERNELCONF})
1683
		export KERNCONF=$(basename ${KERNELCONF})
1684
	fi
1685

    
1686
	SRCCONFBASENAME=$(basename ${SRC_CONF})
1687
	echo ">>> KERNCONFDIR: ${KERNCONFDIR}"
1688
	echo ">>> ARCH:        ${TARGET}"
1689
	echo ">>> SRC_CONF:    ${SRCCONFBASENAME}"
1690

    
1691
	makeargs="${MAKEJ_KERNEL} SRCCONF=${SRC_CONF} __MAKE_CONF=${MAKE_CONF} TARGET_ARCH=${TARGET_ARCH} TARGET=${TARGET}"
1692
	echo ">>> Builder is running the command: script -aq $LOGFILE make -DNO_KERNELCLEAN $makeargs buildkernel KERNCONF=${KERNCONF}" | tee -a $LOGFILE
1693
	(script -q $LOGFILE make -C ${FREEBSD_SRC_DIR} -DNO_KERNELCLEAN $makeargs buildkernel KERNCONF=${KERNCONF} || print_error_pfS;) | egrep '^>>>'
1694
}
1695

    
1696
# Imported from FreeSBIE
1697
installkernel() {
1698
	if [ -z "${KERNCONF}" ]; then
1699
		echo ">>> ERROR: No kernel configuration defined probably this is not what you want! STOPPING!" | tee -a ${LOGFILE}
1700
		print_error_pfS
1701
	fi
1702

    
1703
	if [ -n "${KERNELCONF}" ]; then
1704
		export KERNCONFDIR=$(dirname ${KERNELCONF})
1705
		export KERNCONF=$(basename ${KERNELCONF})
1706
	fi
1707

    
1708
	mkdir -p ${STAGE_CHROOT_DIR}/boot
1709
	makeargs="${MAKEJ_KERNEL} SRCCONF=${SRC_CONF} __MAKE_CONF=${MAKE_CONF} TARGET_ARCH=${TARGET_ARCH} TARGET=${TARGET} DESTDIR=${KERNEL_DESTDIR}"
1710
	echo ">>> Builder is running the command: script -aq $LOGFILE make ${makeargs} installkernel KERNCONF=${KERNCONF}"  | tee -a $LOGFILE
1711
	(script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR} ${makeargs} installkernel KERNCONF=${KERNCONF} || print_error_pfS;) | egrep '^>>>'
1712
	gzip -f9 $KERNEL_DESTDIR/boot/kernel/kernel
1713
}
1714

    
1715
# Launch is ran first to setup a few variables that we need
1716
# Imported from FreeSBIE
1717
launch() {
1718
	if [ "$(id -u)" != "0" ]; then
1719
		echo "Sorry, this must be done as root."
1720
	fi
1721

    
1722
	echo ">>> Operation $0 has started at $(date)"
1723
}
1724

    
1725
finish() {
1726
	echo ">>> Operation $0 has ended at $(date)"
1727
}
1728

    
1729
pkg_repo_rsync() {
1730
	local _repo_path_param="${1}"
1731
	local _ignore_final_rsync="${2}"
1732

    
1733
	if [ -z "${_repo_path_param}" -o ! -d "${_repo_path_param}" ]; then
1734
		return
1735
	fi
1736

    
1737
	if [ -n "${SKIP_FINAL_RSYNC}" ]; then
1738
		_ignore_final_rsync="1"
1739
	fi
1740

    
1741
	# Sanitize path
1742
	_repo_path=$(realpath ${_repo_path_param})
1743

    
1744
	local _repo_dir=$(dirname ${_repo_path})
1745
	local _repo_base=$(basename ${_repo_path})
1746

    
1747
	# Add ./ it's an rsync trick to make it chdir to directory before sending it
1748
	_repo_path="${_repo_dir}/./${_repo_base}"
1749

    
1750
	if [ -z "${LOGFILE}" ]; then
1751
		local _logfile="/dev/null"
1752
	else
1753
		local _logfile="${LOGFILE}"
1754
	fi
1755

    
1756
	if [ -n "${PKG_REPO_SIGNING_COMMAND}" ]; then
1757

    
1758
		# Detect poudriere directory structure
1759
		if [ -L "${_repo_path}/.latest" ]; then
1760
			local _real_repo_path=$(readlink -f ${_repo_path}/.latest)
1761
		else
1762
			local _real_repo_path=${_repo_path}
1763
		fi
1764

    
1765
		echo -n ">>> Signing repository... " | tee -a ${_logfile}
1766
		############ ATTENTION ##############
1767
		#
1768
		# For some reason pkg-repo fail without / in the end of directory name
1769
		# so removing it will break command
1770
		#
1771
		# https://github.com/freebsd/pkg/issues/1364
1772
		#
1773
		if script -aq ${_logfile} pkg repo ${_real_repo_path}/ \
1774
		    signing_command: ${PKG_REPO_SIGNING_COMMAND} >/dev/null 2>&1; then
1775
			echo "Done!" | tee -a ${_logfile}
1776
		else
1777
			echo "Failed!" | tee -a ${_logfile}
1778
			echo ">>> ERROR: An error occurred trying to sign repo"
1779
			print_error_pfS
1780
		fi
1781

    
1782
		local _pkgfile="${_repo_path}/Latest/pkg.txz"
1783
		if [ -e ${_pkgfile} ]; then
1784
			echo -n ">>> Signing Latest/pkg.txz for bootstraping... " | tee -a ${_logfile}
1785

    
1786
			if sha256 -q ${_pkgfile} | ${PKG_REPO_SIGNING_COMMAND} \
1787
			    > ${_pkgfile}.sig 2>/dev/null; then
1788
				echo "Done!" | tee -a ${_logfile}
1789
			else
1790
				echo "Failed!" | tee -a ${_logfile}
1791
				echo ">>> ERROR: An error occurred trying to sign Latest/pkg.txz"
1792
				print_error_pfS
1793
			fi
1794
		fi
1795
	fi
1796

    
1797
	if [ -n "${DO_NOT_UPLOAD}" ]; then
1798
		return
1799
	fi
1800

    
1801
	# Make sure destination directory exist
1802
	ssh -p ${PKG_RSYNC_SSH_PORT} \
1803
		${PKG_RSYNC_USERNAME}@${PKG_RSYNC_HOSTNAME} \
1804
		"mkdir -p ${PKG_RSYNC_DESTDIR}"
1805

    
1806
	echo -n ">>> Sending updated repository to ${PKG_RSYNC_HOSTNAME}... " | tee -a ${_logfile}
1807
	if script -aq ${_logfile} rsync -Have "ssh -p ${PKG_RSYNC_SSH_PORT}" \
1808
		--timeout=60 --delete-delay ${_repo_path} \
1809
		${PKG_RSYNC_USERNAME}@${PKG_RSYNC_HOSTNAME}:${PKG_RSYNC_DESTDIR} >/dev/null 2>&1
1810
	then
1811
		echo "Done!" | tee -a ${_logfile}
1812
	else
1813
		echo "Failed!" | tee -a ${_logfile}
1814
		echo ">>> ERROR: An error occurred sending repo to remote hostname"
1815
		print_error_pfS
1816
	fi
1817

    
1818
	if [ -z "${USE_PKG_REPO_STAGING}" -o -n "${_ignore_final_rsync}" ]; then
1819
		return
1820
	fi
1821

    
1822
	if [ -n "${_IS_RELEASE}" -o "${_repo_path_param}" = "${CORE_PKG_PATH}" ]; then
1823
		# Send .real* directories first to prevent having a broken repo while transfer happens
1824
		local _cmd="rsync -Have \"ssh -p ${PKG_FINAL_RSYNC_SSH_PORT}\" \
1825
			--timeout=60 ${PKG_RSYNC_DESTDIR}/./${_repo_base%%-core}* \
1826
			--include=\"/*\" --include=\"*/.real*\" --include=\"*/.real*/*\" \
1827
			--exclude=\"*\" \
1828
			${PKG_FINAL_RSYNC_USERNAME}@${PKG_FINAL_RSYNC_HOSTNAME}:${PKG_FINAL_RSYNC_DESTDIR}"
1829

    
1830
		echo -n ">>> Sending updated packages to ${PKG_FINAL_RSYNC_HOSTNAME}... " | tee -a ${_logfile}
1831
		if script -aq ${_logfile} ssh -p ${PKG_RSYNC_SSH_PORT} \
1832
			${PKG_RSYNC_USERNAME}@${PKG_RSYNC_HOSTNAME} ${_cmd} >/dev/null 2>&1; then
1833
			echo "Done!" | tee -a ${_logfile}
1834
		else
1835
			echo "Failed!" | tee -a ${_logfile}
1836
			echo ">>> ERROR: An error occurred sending repo to final hostname"
1837
			print_error_pfS
1838
		fi
1839

    
1840
		_cmd="rsync -Have \"ssh -p ${PKG_FINAL_RSYNC_SSH_PORT}\" \
1841
			--timeout=60 --delete-delay ${PKG_RSYNC_DESTDIR}/./${_repo_base%%-core}* \
1842
			${PKG_FINAL_RSYNC_USERNAME}@${PKG_FINAL_RSYNC_HOSTNAME}:${PKG_FINAL_RSYNC_DESTDIR}"
1843

    
1844
		echo -n ">>> Sending updated repositories metadata to ${PKG_FINAL_RSYNC_HOSTNAME}... " | tee -a ${_logfile}
1845
		if script -aq ${_logfile} ssh -p ${PKG_RSYNC_SSH_PORT} \
1846
			${PKG_RSYNC_USERNAME}@${PKG_RSYNC_HOSTNAME} ${_cmd} >/dev/null 2>&1; then
1847
			echo "Done!" | tee -a ${_logfile}
1848
		else
1849
			echo "Failed!" | tee -a ${_logfile}
1850
			echo ">>> ERROR: An error occurred sending repo to final hostname"
1851
			print_error_pfS
1852
		fi
1853
	fi
1854
}
1855

    
1856
poudriere_possible_archs() {
1857
	local _arch=$(uname -m)
1858
	local _archs=""
1859

    
1860
	# If host is amd64, we'll create both repos, and if possible armv6
1861
	if [ "${_arch}" = "amd64" ]; then
1862
		_archs="amd64.amd64"
1863

    
1864
		if [ -f /usr/local/bin/qemu-arm-static ]; then
1865
			# Make sure binmiscctl is ok
1866
			/usr/local/etc/rc.d/qemu_user_static forcestart >/dev/null 2>&1
1867

    
1868
			if binmiscctl lookup armv6 >/dev/null 2>&1; then
1869
				_archs="${_archs} arm.armv6"
1870
			fi
1871
		fi
1872
	fi
1873

    
1874
	if [ -n "${ARCH_LIST}" ]; then
1875
		local _found=0
1876
		for _desired_arch in ${ARCH_LIST}; do
1877
			_found=0
1878
			for _possible_arch in ${_archs}; do
1879
				if [ "${_desired_arch}" = "${_possible_arch}" ]; then
1880
					_found=1
1881
					break
1882
				fi
1883
			done
1884
			if [ ${_found} -eq 0 ]; then
1885
				echo ">>> ERROR: Impossible to build for arch: ${_desired_arch}"
1886
				print_error_pfS
1887
			fi
1888
		done
1889
		_archs="${ARCH_LIST}"
1890
	fi
1891

    
1892
	echo ${_archs}
1893
}
1894

    
1895
poudriere_jail_name() {
1896
	local _jail_arch="${1}"
1897

    
1898
	if [ -z "${_jail_arch}" ]; then
1899
		return 1
1900
	fi
1901

    
1902
	# Remove arch
1903
	echo "${PRODUCT_NAME}_${POUDRIERE_BRANCH}_${_jail_arch##*.}"
1904
}
1905

    
1906
poudriere_rename_ports() {
1907
	if [ "${PRODUCT_NAME}" = "pfSense" ]; then
1908
		return;
1909
	fi
1910

    
1911
	LOGFILE=${BUILDER_LOGS}/poudriere.log
1912

    
1913
	local _ports_dir="/usr/local/poudriere/ports/${POUDRIERE_PORTS_NAME}"
1914

    
1915
	echo -n ">>> Renaming product ports on ${POUDRIERE_PORTS_NAME}... " | tee -a ${LOGFILE}
1916
	for d in $(find ${_ports_dir} -depth 2 -type d -name '*pfSense*'); do
1917
		local _pdir=$(dirname ${d})
1918
		local _pname=$(echo $(basename ${d}) | sed "s,pfSense,${PRODUCT_NAME},")
1919
		local _plist=""
1920

    
1921
		if [ -e ${_pdir}/${_pname} ]; then
1922
			rm -rf ${_pdir}/${_pname}
1923
		fi
1924

    
1925
		cp -r ${d} ${_pdir}/${_pname}
1926

    
1927
		if [ -f ${_pdir}/${_pname}/pkg-plist ]; then
1928
			_plist=${_pdir}/${_pname}/pkg-plist
1929
		fi
1930

    
1931
		sed -i '' -e "s,pfSense,${PRODUCT_NAME},g" \
1932
			  -e "s,https://www.pfsense.org,${PRODUCT_URL},g" \
1933
			  -e "/^MAINTAINER=/ s,^.*$,MAINTAINER=	${PRODUCT_EMAIL}," \
1934
			${_pdir}/${_pname}/Makefile \
1935
			${_pdir}/${_pname}/pkg-descr ${_plist}
1936

    
1937
		# PHP module is special
1938
		if echo "${_pname}" | grep -q "^php[0-9]*-${PRODUCT_NAME}-module"; then
1939
			local _product_capital=$(echo ${PRODUCT_NAME} | tr '[a-z]' '[A-Z]')
1940
			sed -i '' -e "s,PHP_PFSENSE,PHP_${_product_capital},g" \
1941
				  -e "s,PFSENSE_SHARED_LIBADD,${_product_capital}_SHARED_LIBADD,g" \
1942
				  -e "s,pfSense,${PRODUCT_NAME},g" \
1943
				  -e "s,${PRODUCT_NAME}\.c,pfSense.c,g" \
1944
				${_pdir}/${_pname}/files/config.m4
1945

    
1946
			sed -i '' -e "s,COMPILE_DL_PFSENSE,COMPILE_DL_${_product_capital}," \
1947
				  -e "s,pfSense_module_entry,${PRODUCT_NAME}_module_entry,g" \
1948
				  -e "/ZEND_GET_MODULE/ s,pfSense,${PRODUCT_NAME}," \
1949
				  -e "/PHP_PFSENSE_WORLD_EXTNAME/ s,pfSense,${PRODUCT_NAME}," \
1950
				${_pdir}/${_pname}/files/pfSense.c \
1951
				${_pdir}/${_pname}/files/php_pfSense.h
1952
		fi
1953

    
1954
		if [ -d ${_pdir}/${_pname}/files ]; then
1955
			for fd in $(find ${_pdir}/${_pname}/files -type d -name '*pfSense*'); do
1956
				local _fddir=$(dirname ${fd})
1957
				local _fdname=$(echo $(basename ${fd}) | sed "s,pfSense,${PRODUCT_NAME},")
1958

    
1959
				mv ${fd} ${_fddir}/${_fdname}
1960
			done
1961
		fi
1962
	done
1963
	echo "Done!" | tee -a ${LOGFILE}
1964
}
1965

    
1966
poudriere_create_ports_tree() {
1967
	LOGFILE=${BUILDER_LOGS}/poudriere.log
1968

    
1969
	if ! poudriere ports -l | grep -q -E "^${POUDRIERE_PORTS_NAME}[[:blank:]]"; then
1970
		local _branch=""
1971
		if [ -z "${POUDRIERE_PORTS_GIT_URL}" ]; then
1972
			echo ">>> ERROR: POUDRIERE_PORTS_GIT_URL is not defined"
1973
			print_error_pfS
1974
		fi
1975
		if [ -n "${POUDRIERE_PORTS_GIT_BRANCH}" ]; then
1976
			_branch="-B ${POUDRIERE_PORTS_GIT_BRANCH}"
1977
		fi
1978
		echo -n ">>> Creating poudriere ports tree, it may take some time... " | tee -a ${LOGFILE}
1979
		if ! script -aq ${LOGFILE} poudriere ports -c -p "${POUDRIERE_PORTS_NAME}" -m git -U ${POUDRIERE_PORTS_GIT_URL} ${_branch} >/dev/null 2>&1; then
1980
			echo "" | tee -a ${LOGFILE}
1981
			echo ">>> ERROR: Error creating poudriere ports tree, aborting..." | tee -a ${LOGFILE}
1982
			print_error_pfS
1983
		fi
1984
		echo "Done!" | tee -a ${LOGFILE}
1985
		poudriere_rename_ports
1986
	fi
1987
}
1988

    
1989
poudriere_init() {
1990
	local _error=0
1991
	local _archs=$(poudriere_possible_archs)
1992

    
1993
	LOGFILE=${BUILDER_LOGS}/poudriere.log
1994

    
1995
	# Sanity checks
1996
	if [ -z "${ZFS_TANK}" ]; then
1997
		echo ">>> ERROR: \$ZFS_TANK is empty" | tee -a ${LOGFILE}
1998
		error=1
1999
	fi
2000

    
2001
	if [ -z "${ZFS_ROOT}" ]; then
2002
		echo ">>> ERROR: \$ZFS_ROOT is empty" | tee -a ${LOGFILE}
2003
		error=1
2004
	fi
2005

    
2006
	if [ -z "${POUDRIERE_PORTS_NAME}" ]; then
2007
		echo ">>> ERROR: \$POUDRIERE_PORTS_NAME is empty" | tee -a ${LOGFILE}
2008
		error=1
2009
	fi
2010

    
2011
	if [ ${_error} -eq 1 ]; then
2012
		print_error_pfS
2013
	fi
2014

    
2015
	# Check if zpool exists
2016
	if ! zpool list ${ZFS_TANK} >/dev/null 2>&1; then
2017
		echo ">>> ERROR: ZFS tank ${ZFS_TANK} not found, please create it and try again..." | tee -a ${LOGFILE}
2018
		print_error_pfS
2019
	fi
2020

    
2021
	# Check if zfs rootfs exists
2022
	if ! zfs list ${ZFS_TANK}${ZFS_ROOT} >/dev/null 2>&1; then
2023
		echo -n ">>> Creating ZFS filesystem ${ZFS_TANK}${ZFS_ROOT}... "
2024
		if zfs create -o atime=off -o mountpoint=/usr/local${ZFS_ROOT} \
2025
		    ${ZFS_TANK}${ZFS_ROOT} >/dev/null 2>&1; then
2026
			echo "Done!"
2027
		else
2028
			echo "Failed!"
2029
			print_error_pfS
2030
		fi
2031
	fi
2032

    
2033
	# Make sure poudriere is installed
2034
	if ! pkg info --quiet poudriere-devel; then
2035
		echo ">>> Installing poudriere-devel..." | tee -a ${LOGFILE}
2036
		if ! pkg install poudriere-devel >/dev/null 2>&1; then
2037
			echo ">>> ERROR: poudriere-devel was not installed, aborting..." | tee -a ${LOGFILE}
2038
			print_error_pfS
2039
		fi
2040
	fi
2041

    
2042
	# Create poudriere.conf
2043
	if [ -z "${POUDRIERE_PORTS_GIT_URL}" ]; then
2044
		echo ">>> ERROR: POUDRIERE_PORTS_GIT_URL is not defined"
2045
		print_error_pfS
2046
	fi
2047
	echo ">>> Creating poudriere.conf" | tee -a ${LOGFILE}
2048
	cat <<EOF >/usr/local/etc/poudriere.conf
2049
ZPOOL=${ZFS_TANK}
2050
ZROOTFS=${ZFS_ROOT}
2051
RESOLV_CONF=/etc/resolv.conf
2052
BASEFS=/usr/local/poudriere
2053
USE_PORTLINT=no
2054
USE_TMPFS=yes
2055
NOLINUX=yes
2056
DISTFILES_CACHE=/usr/ports/distfiles
2057
CHECK_CHANGED_OPTIONS=yes
2058
CHECK_CHANGED_DEPS=yes
2059
ATOMIC_PACKAGE_REPOSITORY=yes
2060
COMMIT_PACKAGES_ON_FAILURE=no
2061
KEEP_OLD_PACKAGES=yes
2062
KEEP_OLD_PACKAGES_COUNT=5
2063
EOF
2064

    
2065
	# Create specific items conf
2066
	[ ! -d /usr/local/etc/poudriere.d ] \
2067
		&& mkdir -p /usr/local/etc/poudriere.d
2068

    
2069
	# Create DISTFILES_CACHE if it doesn't exist
2070
	if [ ! -d /usr/ports/distfiles ]; then
2071
		mkdir -p /usr/ports/distfiles
2072
	fi
2073

    
2074
	# Remove old jails
2075
	for jail_arch in ${_archs}; do
2076
		jail_name=$(poudriere_jail_name ${jail_arch})
2077

    
2078
		if poudriere jail -i -j "${jail_name}" >/dev/null 2>&1; then
2079
			echo ">>> Poudriere jail ${jail_name} already exists, deleting it..." | tee -a ${LOGFILE}
2080
			poudriere jail -d -j "${jail_name}" >/dev/null 2>&1
2081
		fi
2082
	done
2083

    
2084
	# Remove old ports tree
2085
	if poudriere ports -l | grep -q -E "^${POUDRIERE_PORTS_NAME}[[:blank:]]"; then
2086
		echo ">>> Poudriere ports tree ${POUDRIERE_PORTS_NAME} already exists, deleting it..." | tee -a ${LOGFILE}
2087
		poudriere ports -d -p "${POUDRIERE_PORTS_NAME}"
2088
	fi
2089

    
2090
	local native_xtools=""
2091
	# Now we are ready to create jails
2092
	for jail_arch in ${_archs}; do
2093
		jail_name=$(poudriere_jail_name ${jail_arch})
2094

    
2095
		if [ "${jail_arch}" = "arm.armv6" ]; then
2096
			native_xtools="-x"
2097
		else
2098
			native_xtools=""
2099
		fi
2100

    
2101
		echo -n ">>> Creating jail ${jail_name}, it may take some time... " | tee -a ${LOGFILE}
2102
		# XXX: Change -m to git when it's available in poudriere
2103
		if ! script -aq ${LOGFILE} poudriere jail -c -j "${jail_name}" -v ${FREEBSD_BRANCH} \
2104
				-a ${jail_arch} -m git -U ${FREEBSD_REPO_BASE_POUDRIERE} ${native_xtools} >/dev/null 2>&1; then
2105
			echo "" | tee -a ${LOGFILE}
2106
			echo ">>> ERROR: Error creating jail ${jail_name}, aborting..." | tee -a ${LOGFILE}
2107
			print_error_pfS
2108
		fi
2109
		echo "Done!" | tee -a ${LOGFILE}
2110
	done
2111

    
2112
	poudriere_create_ports_tree
2113

    
2114
	echo ">>> Poudriere is now configured!" | tee -a ${LOGFILE}
2115
}
2116

    
2117
poudriere_update_jails() {
2118
	local _archs=$(poudriere_possible_archs)
2119

    
2120
	LOGFILE=${BUILDER_LOGS}/poudriere.log
2121

    
2122
	local native_xtools=""
2123
	for jail_arch in ${_archs}; do
2124
		jail_name=$(poudriere_jail_name ${jail_arch})
2125

    
2126
		local _create_or_update="-u"
2127
		local _create_or_update_text="Updating"
2128
		if ! poudriere jail -i -j "${jail_name}" >/dev/null 2>&1; then
2129
			echo ">>> Poudriere jail ${jail_name} not found, creating..." | tee -a ${LOGFILE}
2130
			_create_or_update="-c -v ${FREEBSD_BRANCH} -a ${jail_arch} -m git -U ${FREEBSD_REPO_BASE_POUDRIERE}"
2131
			_create_or_update_text="Creating"
2132
		fi
2133

    
2134
		if [ "${jail_arch}" = "arm.armv6" ]; then
2135
			native_xtools="-x"
2136
		else
2137
			native_xtools=""
2138
		fi
2139

    
2140
		echo -n ">>> ${_create_or_update_text} jail ${jail_name}, it may take some time... " | tee -a ${LOGFILE}
2141
		if ! script -aq ${LOGFILE} poudriere jail ${_create_or_update} -j "${jail_name}" ${native_xtools} >/dev/null 2>&1; then
2142
			echo "" | tee -a ${LOGFILE}
2143
			echo ">>> ERROR: Error ${_create_or_update_text} jail ${jail_name}, aborting..." | tee -a ${LOGFILE}
2144
			print_error_pfS
2145
		fi
2146
		echo "Done!" | tee -a ${LOGFILE}
2147
	done
2148
}
2149

    
2150
poudriere_update_ports() {
2151
	LOGFILE=${BUILDER_LOGS}/poudriere.log
2152

    
2153
	# Create ports tree if necessary
2154
	if ! poudriere ports -l | grep -q -E "^${POUDRIERE_PORTS_NAME}[[:blank:]]"; then
2155
		poudriere_create_ports_tree
2156
	else
2157
		echo -n ">>> Resetting local changes on ports tree ${POUDRIERE_PORTS_NAME}... " | tee -a ${LOGFILE}
2158
		script -aq ${LOGFILE} git -C "/usr/local/poudriere/ports/${POUDRIERE_PORTS_NAME}" reset --hard >/dev/null 2>&1
2159
		script -aq ${LOGFILE} git -C "/usr/local/poudriere/ports/${POUDRIERE_PORTS_NAME}" clean -fd >/dev/null 2>&1
2160
		echo "Done!" | tee -a ${LOGFILE}
2161
		echo -n ">>> Updating ports tree ${POUDRIERE_PORTS_NAME}... " | tee -a ${LOGFILE}
2162
		script -aq ${LOGFILE} poudriere ports -u -p "${POUDRIERE_PORTS_NAME}" >/dev/null 2>&1
2163
		echo "Done!" | tee -a ${LOGFILE}
2164
		poudriere_rename_ports
2165
	fi
2166
}
2167

    
2168
poudriere_bulk() {
2169
	local _archs=$(poudriere_possible_archs)
2170

    
2171
	LOGFILE=${BUILDER_LOGS}/poudriere.log
2172

    
2173
	if [ -z "${DO_NOT_UPLOAD}" -a -z "${PKG_RSYNC_HOSTNAME}" ]; then
2174
		echo ">>> ERROR: PKG_RSYNC_HOSTNAME is not set"
2175
		print_error_pfS
2176
	fi
2177

    
2178
	rm -f ${LOGFILE}
2179

    
2180
	poudriere_create_ports_tree
2181

    
2182
	[ -d /usr/local/etc/poudriere.d ] || \
2183
		mkdir -p /usr/local/etc/poudriere.d
2184

    
2185
	if [ -f "${BUILDER_TOOLS}/conf/pfPorts/make.conf" ]; then
2186
		cp -f "${BUILDER_TOOLS}/conf/pfPorts/make.conf" /usr/local/etc/poudriere.d/${POUDRIERE_PORTS_NAME}-make.conf
2187
	fi
2188

    
2189
	# Change version of pfSense meta ports for snapshots
2190
	if [ -z "${_IS_RELEASE}" ]; then
2191
		local _meta_pkg_version="$(echo "${PRODUCT_VERSION}" | sed 's,DEVELOPMENT,ALPHA,')-${DATESTRING}"
2192
		sed -i '' \
2193
			-e "/^DISTVERSION/ s,^.*,DISTVERSION=	${_meta_pkg_version}," \
2194
			-e "/^PORTREVISION=/d" \
2195
			/usr/local/poudriere/ports/${POUDRIERE_PORTS_NAME}/security/${PRODUCT_NAME}/Makefile
2196
	fi
2197

    
2198
	for jail_arch in ${_archs}; do
2199
		jail_name=$(poudriere_jail_name ${jail_arch})
2200

    
2201
		if ! poudriere jail -i -j "${jail_name}" >/dev/null 2>&1; then
2202
			echo ">>> Poudriere jail ${jail_name} not found, skipping..." | tee -a ${LOGFILE}
2203
			continue
2204
		fi
2205

    
2206
		if [ -f "${POUDRIERE_BULK}.${jail_arch}" ]; then
2207
			_ref_bulk="${POUDRIERE_BULK}.${jail_arch}"
2208
		else
2209
			_ref_bulk="${POUDRIERE_BULK}"
2210
		fi
2211

    
2212
		_bulk=${SCRATCHDIR}/poudriere_bulk.${POUDRIERE_BRANCH}
2213
		sed -e "s,%%PRODUCT_NAME%%,${PRODUCT_NAME},g" ${_ref_bulk} > ${_bulk}
2214

    
2215
		if ! poudriere bulk -f ${_bulk} -j ${jail_name} -p ${POUDRIERE_PORTS_NAME}; then
2216
			echo ">>> ERROR: Something went wrong..."
2217
			print_error_pfS
2218
		fi
2219

    
2220
		echo ">>> Cleaning up old packages from repo..."
2221
		if ! poudriere pkgclean -f ${_bulk} -j ${jail_name} -p ${POUDRIERE_PORTS_NAME} -y; then
2222
			echo ">>> ERROR: Something went wrong..."
2223
			print_error_pfS
2224
		fi
2225

    
2226
		pkg_repo_rsync "/usr/local/poudriere/data/packages/${jail_name}-${POUDRIERE_PORTS_NAME}"
2227
	done
2228
}
2229

    
2230
# This routine is called to write out to stdout
2231
# a string. The string is appended to $SNAPSHOTSLOGFILE
2232
# and we scp the log file to the builder host if
2233
# needed for the real time logging functions.
2234
snapshots_update_status() {
2235
	if [ -z "$1" ]; then
2236
		return
2237
	fi
2238
	if [ -z "${SNAPSHOTS}" -a -z "${POUDRIERE_SNAPSHOTS}" ]; then
2239
		return
2240
	fi
2241
	echo "$*"
2242
	echo "`date` -|- $*" >> $SNAPSHOTSLOGFILE
2243
	if [ -z "${DO_NOT_UPLOAD}" -a -n "${SNAPSHOTS_RSYNCIP}" ]; then
2244
		LU=$(cat $SNAPSHOTSLASTUPDATE 2>/dev/null)
2245
		CT=$(date "+%H%M%S")
2246
		# Only update every minute
2247
		if [ "$LU" != "$CT" ]; then
2248
			ssh ${SNAPSHOTS_RSYNCUSER}@${SNAPSHOTS_RSYNCIP} \
2249
				"mkdir -p ${SNAPSHOTS_RSYNCLOGS}"
2250
			scp -q $SNAPSHOTSLOGFILE \
2251
				${SNAPSHOTS_RSYNCUSER}@${SNAPSHOTS_RSYNCIP}:${SNAPSHOTS_RSYNCLOGS}/build.log
2252
			date "+%H%M%S" > $SNAPSHOTSLASTUPDATE
2253
		fi
2254
	fi
2255
}
2256

    
2257
# Copy the current log file to $filename.old on
2258
# the snapshot www server (real time logs)
2259
snapshots_rotate_logfile() {
2260
	if [ -z "${DO_NOT_UPLOAD}" -a -n "${SNAPSHOTS_RSYNCIP}" ]; then
2261
		scp -q $SNAPSHOTSLOGFILE \
2262
			${SNAPSHOTS_RSYNCUSER}@${SNAPSHOTS_RSYNCIP}:${SNAPSHOTS_RSYNCLOGS}/build.log.old
2263
	fi
2264

    
2265
	# Cleanup log file
2266
	rm -f $SNAPSHOTSLOGFILE;    touch $SNAPSHOTSLOGFILE
2267
	rm -f $SNAPSHOTSLASTUPDATE; touch $SNAPSHOTSLASTUPDATE
2268

    
2269
}
2270

    
2271
create_sha256() {
2272
	local _file="${1}"
2273

    
2274
	if [ ! -f "${_file}" ]; then
2275
		return 1
2276
	fi
2277

    
2278
	( \
2279
		cd $(dirname ${_file}) && \
2280
		sha256 $(basename ${_file}) > $(basename ${_file}).sha256 \
2281
	)
2282
}
2283

    
2284
snapshots_create_latest_symlink() {
2285
	local _image="${1}"
2286

    
2287
	if [ -z "${_image}" ]; then
2288
		return
2289
	fi
2290

    
2291
	if [ -z "${TIMESTAMP_SUFFIX}" ]; then
2292
		return
2293
	fi
2294

    
2295
	if [ ! -f "${_image}" ]; then
2296
		return
2297
	fi
2298

    
2299
	local _symlink=$(echo ${_image} | sed "s,${TIMESTAMP_SUFFIX},-latest,")
2300
	ln -sf $(basename ${_image}) ${_symlink}
2301
	ln -sf $(basename ${_image}).sha256 ${_symlink}.sha256
2302
}
2303

    
2304
snapshots_create_sha256() {
2305
	local _img=""
2306

    
2307
	for _img in ${ISOPATH} ${MEMSTICKPATH} ${MEMSTICKSERIALPATH} ${MEMSTICKADIPATH} ${OVAPATH} ${VARIANTIMAGES}; do
2308
		if [ -f "${_img}.gz" ]; then
2309
			_img="${_img}.gz"
2310
		fi
2311
		if [ ! -f "${_img}" ]; then
2312
			continue
2313
		fi
2314
		create_sha256 ${_img}
2315
		snapshots_create_latest_symlink ${_img}
2316
	done
2317

    
2318
	for NANOTYPE in nanobsd nanobsd-vga; do
2319
		for FILESIZE in ${FLASH_SIZE}; do
2320
			FILENAMEFULL="$(nanobsd_image_filename ${FILESIZE} ${NANOTYPE}).gz"
2321

    
2322
			if [ -f $IMAGES_FINAL_DIR/nanobsd/$FILENAMEFULL ]; then
2323
				create_sha256 $IMAGES_FINAL_DIR/nanobsd/$FILENAMEFULL
2324
			fi
2325
		done
2326
	done
2327
}
2328

    
2329
snapshots_scp_files() {
2330
	if [ -z "${RSYNC_COPY_ARGUMENTS}" ]; then
2331
		RSYNC_COPY_ARGUMENTS="-ave ssh --timeout=60 --bwlimit=${RSYNCKBYTELIMIT}" #--bwlimit=50
2332
	fi
2333

    
2334
	snapshots_update_status ">>> Copying core pkg repo to ${PKG_RSYNC_HOSTNAME}"
2335
	pkg_repo_rsync "${CORE_PKG_PATH}"
2336
	snapshots_update_status ">>> Finished copying core pkg repo"
2337

    
2338
	snapshots_update_status ">>> Copying files to ${RSYNCIP}"
2339

    
2340
	# Ensure directory(s) are available
2341
	ssh ${RSYNCUSER}@${RSYNCIP} "mkdir -p ${RSYNCPATH}/installer"
2342
	ssh ${RSYNCUSER}@${RSYNCIP} "mkdir -p ${RSYNCPATH}/nanobsd"
2343
	if [ -d $IMAGES_FINAL_DIR/virtualization ]; then
2344
		ssh ${RSYNCUSER}@${RSYNCIP} "mkdir -p ${RSYNCPATH}/virtualization"
2345
	fi
2346
	# ensure permissions are correct for r+w
2347
	ssh ${RSYNCUSER}@${RSYNCIP} "chmod -R ug+rw ${RSYNCPATH}/."
2348
	rsync $RSYNC_COPY_ARGUMENTS $IMAGES_FINAL_DIR/installer/* \
2349
		${RSYNCUSER}@${RSYNCIP}:${RSYNCPATH}/installer/
2350
	rsync $RSYNC_COPY_ARGUMENTS $IMAGES_FINAL_DIR/nanobsd/* \
2351
		${RSYNCUSER}@${RSYNCIP}:${RSYNCPATH}/nanobsd/
2352
	if [ -d $IMAGES_FINAL_DIR/virtualization ]; then
2353
		rsync $RSYNC_COPY_ARGUMENTS $IMAGES_FINAL_DIR/virtualization/* \
2354
			${RSYNCUSER}@${RSYNCIP}:${RSYNCPATH}/virtualization/
2355
	fi
2356

    
2357
	snapshots_update_status ">>> Finished copying files."
2358
}
(2-2/3)