Project

General

Profile

Download (86.8 KB) Statistics
| Branch: | Tag: | Revision:
1
#!/bin/sh
2
#
3
# builder_common.sh
4
#
5
# part of pfSense (https://www.pfsense.org)
6
# Copyright (c) 2004-2016 Rubicon Communications, LLC (Netgate)
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 are met:
21
#
22
# 1. Redistributions of source code must retain the above copyright notice,
23
#    this list of conditions and the following disclaimer.
24
#
25
# 2. Redistributions in binary form must reproduce the above copyright
26
#    notice, this list of conditions and the following disclaimer in
27
#    the documentation and/or other materials provided with the
28
#    distribution.
29
#
30
# 3. All advertising materials mentioning features or use of this software
31
#    must display the following acknowledgment:
32
#    "This product includes software developed by the pfSense Project
33
#    for use in the pfSense® software distribution. (http://www.pfsense.org/).
34
#
35
# 4. The names "pfSense" and "pfSense Project" must not be used to
36
#    endorse or promote products derived from this software without
37
#    prior written permission. For written permission, please contact
38
#    coreteam@pfsense.org.
39
#
40
# 5. Products derived from this software may not be called "pfSense"
41
#    nor may "pfSense" appear in their names without prior written
42
#    permission of the Electric Sheep Fencing, LLC.
43
#
44
# 6. Redistributions of any form whatsoever must retain the following
45
#    acknowledgment:
46
#
47
# "This product includes software developed by the pfSense Project
48
# for use in the pfSense software distribution (http://www.pfsense.org/).
49
#
50
# THIS SOFTWARE IS PROVIDED BY THE pfSense PROJECT ``AS IS'' AND ANY
51
# EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
53
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE pfSense PROJECT OR
54
# ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
55
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
56
# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
57
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
58
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
59
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
60
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
61
# OF THE POSSIBILITY OF SUCH DAMAGE.
62

    
63
if [ -n "${IMAGES_FINAL_DIR}" -a "${IMAGES_FINAL_DIR}" != "/" ]; then
64
	mkdir -p ${IMAGES_FINAL_DIR}
65
else
66
	echo "IMAGES_FINAL_DIR is not defined"
67
	print_error_pfS
68
fi
69

    
70
lc() {
71
	echo "${1}" | tr '[[:upper:]]' '[[:lower:]]'
72
}
73

    
74
git_last_commit() {
75
	export CURRENT_COMMIT=$(git -C ${BUILDER_ROOT} log -1 --format='%H')
76
	export CURRENT_AUTHOR=$(git -C ${BUILDER_ROOT} log -1 --format='%an')
77
	echo ">>> Last known commit $CURRENT_AUTHOR - $CURRENT_COMMIT"
78
	echo "$CURRENT_COMMIT" > $SCRATCHDIR/build_commit_info.txt
79
}
80

    
81
# Create core pkg repository
82
core_pkg_create_repo() {
83
	if [ ! -d "${CORE_PKG_REAL_PATH}/All" ]; then
84
		return
85
	fi
86

    
87
	############ ATTENTION ##############
88
	#
89
	# For some reason pkg-repo fail without / in the end of directory name
90
	# so removing it will break command
91
	#
92
	# https://github.com/freebsd/pkg/issues/1364
93
	#
94
	echo -n ">>> Creating core packages repository... "
95
	if pkg repo -q "${CORE_PKG_REAL_PATH}/"; then
96
		echo "Done!"
97
	else
98
		echo "Failed!"
99
		print_error_pfS
100
	fi
101

    
102
	# Use the same directory structure as poudriere does to avoid
103
	# breaking snapshot repositories during rsync
104
	ln -sf $(basename ${CORE_PKG_REAL_PATH}) ${CORE_PKG_PATH}/.latest
105
	ln -sf .latest/All ${CORE_PKG_ALL_PATH}
106
	ln -sf .latest/digests.txz ${CORE_PKG_PATH}/digests.txz
107
	ln -sf .latest/meta.txz ${CORE_PKG_PATH}/meta.txz
108
	ln -sf .latest/packagesite.txz ${CORE_PKG_PATH}/packagesite.txz
109
}
110

    
111
# Create core pkg (base, kernel)
112
core_pkg_create() {
113
	local _template="${1}"
114
	local _flavor="${2}"
115
	local _version="${3}"
116
	local _root="${4}"
117
	local _filter="${5}"
118

    
119
	[ -d "${CORE_PKG_TMP}" ] \
120
		&& rm -rf ${CORE_PKG_TMP}
121

    
122
	local _templates_path=${BUILDER_TOOLS}/templates/core_pkg/${_template}
123
	local _template_metadir=${_templates_path}/metadir
124
	local _metadir=${CORE_PKG_TMP}/${_template}_metadir
125

    
126
	if [ ! -d ${_template_metadir} ]; then
127
		echo "ERROR: Template dir not found for pkg ${_template}"
128
		exit
129
	fi
130

    
131
	mkdir -p ${CORE_PKG_TMP}
132

    
133
	cp -r ${_template_metadir} ${_metadir}
134

    
135
	local _manifest=${_metadir}/+MANIFEST
136
	local _plist=${CORE_PKG_TMP}/${_template}_plist
137
	local _exclude_plist=${CORE_PKG_TMP}/${_template}_exclude_plist
138

    
139
	if [ -f "${_templates_path}/pkg-plist" ]; then
140
		cp ${_templates_path}/pkg-plist ${_plist}
141
	else
142
		if [ -n "${_filter}" ]; then
143
			_filter="-name ${_filter}"
144
		fi
145
		(cd ${_root} && find . ${_filter} -type f -or -type l | sed 's,^.,,' | sort -u) > ${_plist}
146
	fi
147

    
148
	if [ -f "${_templates_path}/exclude_plist" ]; then
149
		cp ${_templates_path}/exclude_plist ${_exclude_plist}
150
	else
151
		touch ${_exclude_plist}
152
	fi
153

    
154
	sed \
155
		-i '' \
156
		-e "s,%%PRODUCT_NAME%%,${PRODUCT_NAME},g" \
157
		-e "s,%%PRODUCT_URL%%,${PRODUCT_URL},g" \
158
		-e "s,%%FLAVOR%%,${_flavor:+-}${_flavor},g" \
159
		-e "s,%%FLAVOR_DESC%%,${_flavor:+ (${_flavor})},g" \
160
		-e "s,%%VERSION%%,${_version},g" \
161
		${_metadir}/* \
162
		${_plist} \
163
		${exclude_plist}
164

    
165
	if [ -f "${_exclude_plist}" ]; then
166
		sort -u ${_exclude_plist} > ${_plist}.exclude
167
		mv ${_plist} ${_plist}.tmp
168
		comm -23 ${_plist}.tmp ${_plist}.exclude > ${_plist}
169
		rm -f ${_plist}.tmp ${plist}.exclude
170
	fi
171

    
172
	# Add license information
173
	local _portname=$(sed '/^name: /!d; s,^[^"]*",,; s,",,' ${_metadir}/+MANIFEST)
174
	local _licenses_dir="/usr/local/share/licenses/${_portname}-${_version}"
175
	mkdir -p ${_root}${_licenses_dir}
176
	cp ${BUILDER_ROOT}/license.txt ${_root}${_licenses_dir}/ESF
177
	echo "This package has a single license: ESF (Electric Sheep Fencing License)." \
178
		> ${_root}${_licenses_dir}/LICENSE
179
	cat <<EOF >${_root}${_licenses_dir}/catalog.mk
180
_LICENSE=ESF
181
_LICENSE_NAME=Electric Sheep Fencing License
182
_LICENSE_PERMS=dist-mirror dist-sell pkg-mirror pkg-sell auto-accept
183
_LICENSE_GROUPS=
184
_LICENSE_DISTFILES=
185
EOF
186
	cat <<EOF >>${_plist}
187
${_licenses_dir}/catalog.mk
188
${_licenses_dir}/LICENSE
189
${_licenses_dir}/ESF
190
EOF
191

    
192
	mkdir -p ${CORE_PKG_REAL_PATH}/All
193
	if ! pkg create -o ${CORE_PKG_REAL_PATH}/All -p ${_plist} -r ${_root} -m ${_metadir}; then
194
		echo ">>> ERROR: Error building package ${_template} ${_flavor}"
195
		print_error_pfS
196
	fi
197

    
198
	# Cleanup _licenses_dir
199
	rm -rf ${_root}${_licenses_dir}
200
}
201

    
202
# This routine will output that something went wrong
203
print_error_pfS() {
204
	echo
205
	echo "####################################"
206
	echo "Something went wrong, check errors!" >&2
207
	echo "####################################"
208
	echo
209
	echo "NOTE: a lot of times you can run './build.sh --clean-builder' to resolve."
210
	echo
211
	if [ "$1" != "" ]; then
212
		echo $1
213
	fi
214
	[ -n "${LOGFILE}" -a -f "${LOGFILE}" ] && \
215
		echo "Log saved on ${LOGFILE}" && \
216
		tail -n20 ${LOGFILE} >&2
217
	echo
218
	kill $$
219
	exit 1
220
}
221

    
222
prestage_on_ram_setup() {
223
	# Do not use memory disks for release build
224
	if [ -n "${_IS_RELEASE}" -o -n "${_IS_RC}" ]; then
225
		return
226
	fi
227

    
228
	[ -d "${STAGE_CHROOT_DIR}" ] \
229
		|| mkdir -p ${STAGE_CHROOT_DIR}
230
	[ -d "${FINAL_CHROOT_DIR}" ] \
231
		|| mkdir -p ${FINAL_CHROOT_DIR}
232

    
233
	_AVAIL_MEM=$(($(sysctl -n hw.usermem) / 1024 / 1024))
234
	if [ $_AVAIL_MEM -lt 2000 ]; then
235
		echo ">>> Builder has less than 2GiB RAM skipping memory disks"
236
		return
237
	else
238
		echo "######################################################################################"
239
		echo
240
		echo ">>> Builder has more than 2GiB RAM enabling memory disks"
241
		echo ">>> WARNING: Remember to remove these memory disks by running $0 --disable-memorydisks"
242
		echo
243
		echo "######################################################################################"
244
	fi
245

    
246
	if df /dev/ufs/prestagebacking >/dev/null 2>&1; then
247
		echo ">>> Detected preexisting memory disk enabled for ${STAGE_CHROOT_DIR}."
248
	else
249
		mdconfig -a -t swap -u 10001 -s ${MEMORYDISK_SIZE}
250
		newfs -L prestagebacking -U /dev/md10001
251
		mount /dev/ufs/prestagebacking ${STAGE_CHROOT_DIR}
252
	fi
253

    
254
	if df /dev/ufs/finalstagebacking >/dev/null 2>&1; then
255
		echo ">>> Detected preexisting memory disk enabled for ${FINAL_CHROOT_DIR}."
256
	else
257
		mdconfig -a -t swap -u 10002 -s ${MEMORYDISK_SIZE}
258
		newfs -L finalstagebacking -U /dev/md10002
259
		mount /dev/ufs/finalstagebacking ${FINAL_CHROOT_DIR}
260
	fi
261
}
262

    
263
prestage_on_ram_cleanup() {
264
	if [ -c /dev/md10001 ]; then
265
		if [ -d ${STAGE_CHROOT_DIR} ]; then
266
			umount ${STAGE_CHROOT_DIR}
267
		fi
268
		mdconfig -d -u 10001
269
	fi
270
	if [ -c /dev/md10002 ]; then
271
		if [ -d ${FINAL_CHROOT_DIR} ]; then
272
			umount ${FINAL_CHROOT_DIR}
273
		fi
274
		mdconfig -d -u 10002
275
	fi
276
}
277

    
278
# This routine will verify that the kernel has been
279
# installed OK to the staging area.
280
ensure_kernel_exists() {
281
	if [ ! -f "$1/boot/kernel/kernel.gz" ]; then
282
		echo ">>> ERROR: Could not locate $1/boot/kernel.gz"
283
		print_error_pfS
284
	fi
285
	KERNEL_SIZE=$(stat -f "%z" $1/boot/kernel/kernel.gz)
286
	if [ "$KERNEL_SIZE" -lt 3500 ]; then
287
		echo ">>> ERROR: Kernel $1/boot/kernel.gz appears to be smaller than it should be: $KERNEL_SIZE"
288
		print_error_pfS
289
	fi
290
}
291

    
292
get_pkg_name() {
293
	echo "${PRODUCT_NAME}-${1}-${CORE_PKG_VERSION}"
294
}
295

    
296
# This routine builds all related kernels
297
build_all_kernels() {
298
	# Set KERNEL_BUILD_PATH if it has not been set
299
	if [ -z "${KERNEL_BUILD_PATH}" ]; then
300
		KERNEL_BUILD_PATH=$SCRATCHDIR/kernels
301
		echo ">>> KERNEL_BUILD_PATH has not been set. Setting to ${KERNEL_BUILD_PATH}!"
302
	fi
303

    
304
	[ -d "${KERNEL_BUILD_PATH}" ] \
305
		&& rm -rf ${KERNEL_BUILD_PATH}
306

    
307
	# Build embedded kernel
308
	for BUILD_KERNEL in $BUILD_KERNELS; do
309
		unset KERNCONF
310
		unset KERNEL_DESTDIR
311
		unset KERNELCONF
312
		unset KERNEL_NAME
313
		export KERNCONF=$BUILD_KERNEL
314
		export KERNEL_DESTDIR="$KERNEL_BUILD_PATH/$BUILD_KERNEL"
315
		export KERNELCONF="${FREEBSD_SRC_DIR}/sys/${TARGET}/conf/$BUILD_KERNEL"
316
		export KERNEL_NAME=${BUILD_KERNEL}
317

    
318
		LOGFILE="${BUILDER_LOGS}/kernel.${KERNCONF}.${TARGET}.log"
319
		echo ">>> Building $BUILD_KERNEL kernel."  | tee -a ${LOGFILE}
320

    
321
		if [ ! -e "${FREEBSD_SRC_DIR}/sys/${TARGET}/conf/${BUILD_KERNEL}" ]; then
322
			echo ">>> ERROR: Could not find $KERNELCONF"
323
			print_error_pfS
324
		fi
325

    
326
		if [ -n "${NO_BUILDKERNEL}" -a -f "${CORE_PKG_ALL_PATH}/$(get_pkg_name kernel-${KERNEL_NAME}).txz" ]; then
327
			echo ">>> NO_BUILDKERNEL set, skipping build" | tee -a ${LOGFILE}
328
			continue
329
		fi
330

    
331
		export SRC_CONF=${SRC_CONF}
332
		buildkernel
333

    
334
		echo ">>> Staging $BUILD_KERNEL kernel..." | tee -a ${LOGFILE}
335
		installkernel
336

    
337
		ensure_kernel_exists $KERNEL_DESTDIR
338

    
339
		echo -n ">>> Creating pkg of $KERNEL_NAME-debug kernel to staging area... "  | tee -a ${LOGFILE}
340
		core_pkg_create kernel-debug ${KERNEL_NAME} ${CORE_PKG_VERSION} ${KERNEL_DESTDIR} \*.symbols
341
		find ${KERNEL_DESTDIR} -name '*.symbols' -type f -delete
342
		echo " Done" | tee -a ${LOGFILE}
343

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

    
347
		rm -rf $KERNEL_DESTDIR 2>&1 1>/dev/null
348

    
349
		echo " Done" | tee -a ${LOGFILE}
350
	done
351
}
352

    
353
install_default_kernel() {
354
	if [ -z "${1}" ]; then
355
		echo ">>> ERROR: install_default_kernel called without a kernel config name"| tee -a ${LOGFILE}
356
		print_error_pfS
357
	fi
358

    
359
	export KERNEL_NAME="${1}"
360

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

    
363
	# Copy kernel package to chroot, otherwise pkg won't find it to install
364
	if ! pkg_chroot_add ${FINAL_CHROOT_DIR} kernel-${KERNEL_NAME}; then
365
		echo ">>> ERROR: Error installing kernel package $(get_pkg_name kernel-${KERNEL_NAME}).txz" | tee -a ${LOGFILE}
366
		print_error_pfS
367
	fi
368

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

    
372
	if [ ! -f $FINAL_CHROOT_DIR/boot/kernel/kernel.gz ]; then
373
		echo ">>> ERROR: No kernel installed on $FINAL_CHROOT_DIR and the resulting image will be unusable. STOPPING!" | tee -a ${LOGFILE}
374
		print_error_pfS
375
	fi
376
	mkdir -p $FINAL_CHROOT_DIR/pkgs
377
	if [ -z "${2}" -o -n "${INSTALL_EXTRA_KERNELS}" ]; then
378
		cp ${CORE_PKG_ALL_PATH}/$(get_pkg_name kernel-${KERNEL_NAME}).txz $FINAL_CHROOT_DIR/pkgs
379
		if [ -n "${INSTALL_EXTRA_KERNELS}" ]; then
380
			for _EXTRA_KERNEL in $INSTALL_EXTRA_KERNELS; do
381
				_EXTRA_KERNEL_PATH=${CORE_PKG_ALL_PATH}/$(get_pkg_name kernel-${_EXTRA_KERNEL}).txz
382
				if [ -f "${_EXTRA_KERNEL_PATH}" ]; then
383
					echo -n ". adding ${_EXTRA_KERNEL_PATH} on image /pkgs folder"
384
					cp ${_EXTRA_KERNEL_PATH} $FINAL_CHROOT_DIR/pkgs
385
				else
386
					echo ">>> ERROR: Requested kernel $(get_pkg_name kernel-${_EXTRA_KERNEL}).txz was not found to be put on image /pkgs folder!"
387
					print_error_pfS
388
				fi
389
			done
390
		fi
391
	fi
392
	echo "Done." | tee -a ${LOGFILE}
393

    
394
	unset KERNEL_NAME
395
}
396

    
397
# Creates a full update file
398
create_Full_update_tarball() {
399
	local _variant="$1"
400

    
401
	LOGFILE=${BUILDER_LOGS}/full_update.${TARGET}
402
	if [ "${UPDATES_TARBALL_FILENAME}" = "" ]; then
403
		echo ">>> UPDATES_TARBALL_FILENAME is empty skipping generation of full update image!" | tee -a ${LOGFILE}
404
		return
405
	fi
406

    
407
	local _image_path=${UPDATES_TARBALL_FILENAME}
408
	if [ -n "${_variant}" ]; then
409
		_image_path=$(echo "$_image_path" | \
410
			sed "s/-Full-Update-/-Full-Update-${_variant}-/")
411
		VARIANTUPDATES="${VARIANTUPDATES}${VARIANTUPDATES:+ }${_image_path}"
412
	fi
413

    
414
	mkdir -p $UPDATESDIR
415

    
416
	customize_stagearea_for_image "fullupdate" "" $_variant
417
	install_default_kernel ${DEFAULT_KERNEL}
418

    
419
	rm -rf ${FINAL_CHROOT_DIR}/cf
420
	rm -rf ${FINAL_CHROOT_DIR}/conf
421
	rm -f ${FINAL_CHROOT_DIR}/etc/dh-parameters.*
422
	rm -f ${FINAL_CHROOT_DIR}/etc/rc.conf
423
	rm -f ${FINAL_CHROOT_DIR}/etc/pwd.db 2>/dev/null
424
	rm -f ${FINAL_CHROOT_DIR}/etc/group 2>/dev/null
425
	rm -f ${FINAL_CHROOT_DIR}/etc/spwd.db 2>/dev/null
426
	rm -f ${FINAL_CHROOT_DIR}/etc/passwd 2>/dev/null
427
	rm -f ${FINAL_CHROOT_DIR}/etc/master.passwd 2>/dev/null
428
	rm -f ${FINAL_CHROOT_DIR}/etc/fstab 2>/dev/null
429
	rm -f ${FINAL_CHROOT_DIR}/etc/bogons 2>/dev/null
430
	# Remove loader.conf and friends.  Ticket #560
431
	rm ${FINAL_CHROOT_DIR}/boot/loader.conf 2>/dev/null
432
	rm ${FINAL_CHROOT_DIR}/boot/loader.conf.local 2>/dev/null
433

    
434
	# Old systems will run (pre|post)_upgrade_command from /tmp
435
	if [ -f ${FINAL_CHROOT_DIR}${PRODUCT_SHARE_DIR}/pre_upgrade_command ]; then
436
		cp -p \
437
			${FINAL_CHROOT_DIR}${PRODUCT_SHARE_DIR}/pre_upgrade_command \
438
			${FINAL_CHROOT_DIR}/tmp
439
	fi
440
	if [ -f ${FINAL_CHROOT_DIR}${PRODUCT_SHARE_DIR}/post_upgrade_command ]; then
441
		cp -p \
442
			${FINAL_CHROOT_DIR}${PRODUCT_SHARE_DIR}/post_upgrade_command \
443
			${FINAL_CHROOT_DIR}/tmp
444
	fi
445

    
446
	echo ">>> Creating ${_image_path} ..." | tee -a ${LOGFILE}
447
	tar --exclude=./dev -czPf ${_image_path} -C ${FINAL_CHROOT_DIR} .
448

    
449
	echo ">>> Full Update created: $(LC_ALL=C date)" | tee -a ${LOGFILE}
450
}
451

    
452
# Outputs various set variables aka env
453
print_flags() {
454

    
455
	echo
456
	printf "             Product version: %s\n" $PRODUCT_VERSION
457
	printf "                   Stage DIR: %s\n" $STAGE_CHROOT_DIR
458
	printf "                 Updates dir: %s\n" $UPDATESDIR
459
	printf " Image Preparation Stage DIR: %s\n" $FINAL_CHROOT_DIR
460
	printf "                  Source DIR: %s\n" $FREEBSD_SRC_DIR
461
	printf "          FreeBSD repository: %s\n" $FREEBSD_REPO_BASE
462
	printf "          FreeBSD-src branch: %s\n" $FREEBSD_BRANCH
463
	printf "     FreeBSD original branch: %s\n" $FREEBSD_PARENT_BRANCH
464
	printf "               BUILD_KERNELS: %s\n" $BUILD_KERNELS
465
	printf "           Git Branch or Tag: %s\n" $GIT_REPO_BRANCH_OR_TAG
466
	printf "            MODULES_OVERRIDE: %s\n" $MODULES_OVERRIDE
467
	printf "    VMDK_DISK_CAPACITY_IN_GB: %s\n" $VMDK_DISK_CAPACITY_IN_GB
468
	printf "                 OVFTEMPLATE: %s\n" $OVFTEMPLATE
469
	printf "                     OVFVMDK: %s\n" $OVFVMDK
470
	printf "                    SRC_CONF: %s\n" $SRC_CONF
471
	printf "                     ISOPATH: %s\n" $ISOPATH
472
	printf "                MEMSTICKPATH: %s\n" $MEMSTICKPATH
473
	printf "    UPDATES_TARBALL_FILENAME: %s\n" $UPDATES_TARBALL_FILENAME
474
if [ -n "$SHOW_ENV" ]; then
475
	for LINE in $(env | egrep -v '(terminal|PASS|NAME|USER|SSH|GROUP|HOST)'); do
476
		echo "SHOW_ENV: $LINE"
477
	done
478
fi
479
	echo
480
}
481

    
482
# This builds FreeBSD (make buildworld)
483
# Imported from FreeSBIE
484
make_world() {
485

    
486
	LOGFILE=${BUILDER_LOGS}/buildworld.${TARGET}
487
	if [ -n "${NO_BUILDWORLD}" ]; then
488
		echo ">>> NO_BUILDWORLD set, skipping build" | tee -a ${LOGFILE}
489
		return
490
	fi
491

    
492
	# Set SRC_CONF variable if it's not already set.
493
	if [ -z "${SRC_CONF}" ]; then
494
		echo ">>> SRC_CONF is unset make sure this is what you want!" | tee -a ${LOGFILE}
495
	else
496
		echo ">>> Setting SRC_CONF to $SRC_CONF" | tee -a ${LOGFILE}
497
	fi
498

    
499
	# Set default parameters
500
	export MAKE_ARGS="${MAKEJ_WORLD} __MAKE_CONF=${MAKE_CONF} SRCCONF=${SRC_CONF} TARGET=${TARGET} TARGET_ARCH=${TARGET_ARCH}"
501

    
502
	echo ">>> LOGFILE set to $LOGFILE." | tee -a ${LOGFILE}
503
	makeargs="${MAKE_ARGS}"
504
	echo ">>> Building world for ${TARGET} architecture... (Starting - $(LC_ALL=C date))" | tee -a ${LOGFILE}
505
	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}
506
	(env LOCAL_ITOOLS="${EXTRA_TOOLS}" script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR} -DNO_CLEAN ${makeargs} buildworld || print_error_pfS;) | egrep '^>>>' | tee -a ${LOGFILE}
507
	echo ">>> Building world for ${TARGET} architecture... (Finished - $(LC_ALL=C date))" | tee -a ${LOGFILE}
508

    
509
	LOGFILE=${BUILDER_LOGS}/installworld.${TARGET}
510
	echo ">>> LOGFILE set to $LOGFILE." | tee -a ${LOGFILE}
511
	# Create if cleaned up
512
	makeargs="${MAKE_ARGS} DESTDIR=${STAGE_CHROOT_DIR} WITHOUT_TOOLCHAIN=1"
513
	echo ">>> Installing world for ${TARGET} architecture... (Starting - $(LC_ALL=C date))" | tee -a ${LOGFILE}
514
	echo ">>> Builder is running the command: env LOCAL_ITOOLS=\"${EXTRA_TOOLS}\" script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR} ${makeargs} installworld" | tee -a ${LOGFILE}
515
	(env LOCAL_ITOOLS="${EXTRA_TOOLS}" script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR} ${makeargs} installworld || print_error_pfS;) | egrep '^>>>' | tee -a ${LOGFILE}
516
	echo ">>> Installing world for ${TARGET} architecture... (Finished - $(LC_ALL=C date))" | tee -a ${LOGFILE}
517

    
518
	makeargs="${MAKE_ARGS} DESTDIR=${STAGE_CHROOT_DIR}"
519
	echo ">>> Distribution world for ${TARGET} architecture... (Starting - $(LC_ALL=C date))" | tee -a ${LOGFILE}
520
	echo ">>> Builder is running the command: script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR} ${makeargs} distribution " | tee -a ${LOGFILE}
521
	(script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR} ${makeargs} distribution  || print_error_pfS;) | egrep '^>>>' | tee -a ${LOGFILE}
522
	echo ">>> Distribution world for ${TARGET} architecture... (Finished - $(LC_ALL=C date))" | tee -a ${LOGFILE}
523

    
524
	[ -d "${STAGE_CHROOT_DIR}/usr/local/bin" ] \
525
		|| mkdir -p ${STAGE_CHROOT_DIR}/usr/local/bin
526
	makeargs="${MAKE_ARGS} DESTDIR=${STAGE_CHROOT_DIR}"
527
	echo ">>> Building and installing crypto tools and athstats for ${TARGET} architecture... (Starting - $(LC_ALL=C date))" | tee -a ${LOGFILE}
528
	echo ">>> Builder is running the command: script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR}/tools/tools/crypto ${makeargs} clean all install " | tee -a ${LOGFILE}
529
	(script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR}/tools/tools/crypto ${makeargs} clean all install || print_error_pfS;) | egrep '^>>>' | tee -a ${LOGFILE}
530
	echo ">>> Builder is running the command: script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR}/tools/tools/ath/athstats ${makeargs} clean" | tee -a ${LOGFILE}
531
	(script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR}/tools/tools/ath/athstats ${makeargs} clean || print_error_pfS;) | egrep '^>>>' | tee -a ${LOGFILE}
532
	echo ">>> Builder is running the command: script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR}/tools/tools/ath/athstats ${makeargs} all" | tee -a ${LOGFILE}
533
	(script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR}/tools/tools/ath/athstats ${makeargs} all || print_error_pfS;) | egrep '^>>>' | tee -a ${LOGFILE}
534
	echo ">>> Builder is running the command: script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR}/tools/tools/ath/athstats ${makeargs} install" | tee -a ${LOGFILE}
535
	(script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR}/tools/tools/ath/athstats ${makeargs} install || print_error_pfS;) | egrep '^>>>' | tee -a ${LOGFILE}
536
	echo ">>> Building and installing crypto tools and athstats for ${TARGET} architecture... (Finished - $(LC_ALL=C date))" | tee -a ${LOGFILE}
537

    
538
	unset makeargs
539
}
540

    
541
nanobsd_image_filename() {
542
	local _size="$1"
543
	local _type="$2"
544
	local _upgrade="$3"
545

    
546
	if [ -z "$_upgrade" ]; then
547
		local _template=${NANOBSD_IMG_TEMPLATE}
548
	else
549
		local _template=${NANOBSD_UPGRADE_TEMPLATE}
550
	fi
551

    
552
	echo "$_template" | sed \
553
		-e "s,%%SIZE%%,${_size},g" \
554
		-e "s,%%TYPE%%,${_type},g"
555

    
556
	return 0
557
}
558

    
559
# This routine originated in nanobsd.sh
560
nanobsd_set_flash_details () {
561
	a1=$(echo $1 | tr '[:upper:]' '[:lower:]')
562

    
563
	# Source:
564
	#	SanDisk CompactFlash Memory Card
565
	#	Product Manual
566
	#	Version 10.9
567
	#	Document No. 20-10-00038
568
	#	April 2005
569
	# Table 2-7
570
	# NB: notice math error in SDCFJ-4096-388 line.
571
	#
572
	case "${a1}" in
573
		2048|2048m|2048mb|2g)
574
			NANO_MEDIASIZE=$((1989999616/512))
575
			;;
576
		4096|4096m|4096mb|4g)
577
			NANO_MEDIASIZE=$((3989999616/512))
578
			;;
579
		8192|8192m|8192mb|8g)
580
			NANO_MEDIASIZE=$((7989999616/512))
581
			;;
582
		16384|16384m|16384mb|16g)
583
			NANO_MEDIASIZE=$((15989999616/512))
584
			;;
585
		*)
586
			echo "Unknown Flash capacity"
587
			exit 2
588
			;;
589
	esac
590

    
591
	NANO_HEADS=16
592
	NANO_SECTS=63
593

    
594
	echo ">>> [nanoo] $1"
595
	echo ">>> [nanoo] NANO_MEDIASIZE: $NANO_MEDIASIZE"
596
	echo ">>> [nanoo] NANO_HEADS: $NANO_HEADS"
597
	echo ">>> [nanoo] NANO_SECTS: $NANO_SECTS"
598
	echo ">>> [nanoo] NANO_BOOT0CFG: $NANO_BOOT0CFG"
599
}
600

    
601
# This routine originated in nanobsd.sh
602
create_nanobsd_diskimage () {
603
	if [ -z "${1}" ]; then
604
		echo ">>> ERROR: Type of image has not been specified"
605
		print_error_pfS
606
	fi
607
	if [ -z "${2}" ]; then
608
		echo ">>> ERROR: Size of image has not been specified"
609
		print_error_pfS
610
	fi
611

    
612
	if [ "${1}" = "nanobsd" ]; then
613
		# It's serial
614
		export NANO_BOOTLOADER="boot/boot0sio"
615
	elif [ "${1}" = "nanobsd-vga" ]; then
616
		# It's vga
617
		export NANO_BOOTLOADER="boot/boot0"
618
	else
619
		echo ">>> ERROR: Type of image to create unknown"
620
		print_error_pfS
621
	fi
622

    
623
	if [ -z "${2}" ]; then
624
		echo ">>> ERROR: Media size(s) not specified."
625
		print_error_pfS
626
	fi
627

    
628
	if [ -z "${2}" ]; then
629
		echo ">>> ERROR: FLASH_SIZE is not set."
630
		print_error_pfS
631
	fi
632

    
633
	LOGFILE=${BUILDER_LOGS}/${1}.${TARGET}
634
	# Prepare folder to be put in image
635
	customize_stagearea_for_image "${1}"
636
	install_default_kernel ${DEFAULT_KERNEL} "no"
637

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

    
640
	echo "nanobsd" > $FINAL_CHROOT_DIR/etc/platform
641

    
642
	local BOOTCONF=${FINAL_CHROOT_DIR}/boot.config
643
	local LOADERCONF=${FINAL_CHROOT_DIR}/boot/loader.conf
644

    
645
	if [ "${1}" = "nanobsd" ]; then
646
		# Tell loader to use serial console early.
647
		echo "-S115200 -h" >> ${BOOTCONF}
648

    
649
		# Remove old console options if present.
650
		[ -f "${LOADERCONF}" ] \
651
			&& sed -i "" -Ee "/(console|boot_multicons|boot_serial|hint.uart)/d" ${LOADERCONF}
652
		# Activate serial console+video console in loader.conf
653
		echo 'loader_color="NO"' >> ${LOADERCONF}
654
		echo 'beastie_disable="YES"' >> ${LOADERCONF}
655
		echo 'boot_serial="YES"' >> ${LOADERCONF}
656
		echo 'console="comconsole"' >> ${LOADERCONF}
657
		echo 'comconsole_speed="115200"' >> ${LOADERCONF}
658
	fi
659
	echo 'autoboot_delay="5"' >> ${LOADERCONF}
660

    
661
	# Old systems will run (pre|post)_upgrade_command from /tmp
662
	if [ -f ${FINAL_CHROOT_DIR}${PRODUCT_SHARE_DIR}/pre_upgrade_command ]; then
663
		cp -p \
664
			${FINAL_CHROOT_DIR}${PRODUCT_SHARE_DIR}/pre_upgrade_command \
665
			${FINAL_CHROOT_DIR}/tmp
666
	fi
667
	if [ -f ${FINAL_CHROOT_DIR}${PRODUCT_SHARE_DIR}/post_upgrade_command ]; then
668
		cp -p \
669
			${FINAL_CHROOT_DIR}${PRODUCT_SHARE_DIR}/post_upgrade_command \
670
			${FINAL_CHROOT_DIR}/tmp
671
	fi
672

    
673
	for _NANO_MEDIASIZE in ${2}; do
674
		if [ -z "${_NANO_MEDIASIZE}" ]; then
675
			continue;
676
		fi
677

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

    
681
		IMG="${IMAGES_FINAL_DIR}/$(nanobsd_image_filename ${_NANO_MEDIASIZE} ${1})"
682
		IMGUPDATE="${IMAGES_FINAL_DIR}/$(nanobsd_image_filename ${_NANO_MEDIASIZE} ${1} 1)"
683

    
684
		nanobsd_set_flash_details ${_NANO_MEDIASIZE}
685

    
686
		# These are defined in FlashDevice and on builder_default.sh
687
		echo $NANO_MEDIASIZE \
688
			$NANO_IMAGES \
689
			$NANO_SECTS \
690
			$NANO_HEADS \
691
			$NANO_CODESIZE \
692
			$NANO_CONFSIZE \
693
			$NANO_DATASIZE |
694
awk '
695
{
696
	printf "# %s\n", $0
697

    
698
	# size of cylinder in sectors
699
	cs = $3 * $4
700

    
701
	# number of full cylinders on media
702
	cyl = int ($1 / cs)
703

    
704
	# output fdisk geometry spec, truncate cyls to 1023
705
	if (cyl <= 1023)
706
		print "g c" cyl " h" $4 " s" $3
707
	else
708
		print "g c" 1023 " h" $4 " s" $3
709

    
710
	if ($7 > 0) {
711
		# size of data partition in full cylinders
712
		dsl = int (($7 + cs - 1) / cs)
713
	} else {
714
		dsl = 0;
715
	}
716

    
717
	# size of config partition in full cylinders
718
	csl = int (($6 + cs - 1) / cs)
719

    
720
	if ($5 == 0) {
721
		# size of image partition(s) in full cylinders
722
		isl = int ((cyl - dsl - csl) / $2)
723
	} else {
724
		isl = int (($5 + cs - 1) / cs)
725
	}
726

    
727
	# First image partition start at second track
728
	print "p 1 165 " $3, isl * cs - $3
729
	c = isl * cs;
730

    
731
	# Second image partition (if any) also starts offset one
732
	# track to keep them identical.
733
	if ($2 > 1) {
734
		print "p 2 165 " $3 + c, isl * cs - $3
735
		c += isl * cs;
736
	}
737

    
738
	# Config partition starts at cylinder boundary.
739
	print "p 3 165 " c, csl * cs
740
	c += csl * cs
741

    
742
	# Data partition (if any) starts at cylinder boundary.
743
	if ($7 > 0) {
744
		print "p 4 165 " c, dsl * cs
745
	} else if ($7 < 0 && $1 > c) {
746
		print "p 4 165 " c, $1 - c
747
	} else if ($1 < c) {
748
		print "Disk space overcommitted by", \
749
		    c - $1, "sectors" > "/dev/stderr"
750
		exit 2
751
	}
752

    
753
	# Force slice 1 to be marked active. This is necessary
754
	# for booting the image from a USB device to work.
755
	print "a 1"
756
}
757
	' > ${IMAGES_FINAL_DIR}/_.fdisk
758

    
759
		MNT=${IMAGES_FINAL_DIR}/_.mnt
760
		mkdir -p ${MNT}
761

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

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

    
768
		fdisk -i -f ${IMAGES_FINAL_DIR}/_.fdisk ${MD} 2>&1 >> ${LOGFILE}
769
		fdisk ${MD} 2>&1 >> ${LOGFILE}
770

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

    
773
		# Create first image
774
		bsdlabel -m i386 -w -B -b ${FINAL_CHROOT_DIR}/boot/boot ${MD}s1 2>&1 >> ${LOGFILE}
775
		bsdlabel -m i386 ${MD}s1 2>&1 >> ${LOGFILE}
776
		local _label=$(lc ${PRODUCT_NAME})
777
		newfs -L ${_label}0 ${NANO_NEWFS} /dev/${MD}s1a 2>&1 >> ${LOGFILE}
778
		mount /dev/ufs/${_label}0 ${MNT}
779
		if [ $? -ne 0 ]; then
780
			echo ">>> ERROR: Something wrong happened during mount of first slice image creation. STOPPING!" | tee -a ${LOGFILE}
781
			print_error_pfS
782
		fi
783
		# Consider the unmounting as well
784
		trap "umount /dev/ufs/${_label}0; mdconfig -d -u ${MD}; return" 1 2 15 EXIT
785

    
786
		clone_directory_contents ${FINAL_CHROOT_DIR} ${MNT}
787

    
788
		# Set NanoBSD image size
789
		echo "${_NANO_MEDIASIZE}" > ${MNT}/etc/nanosize.txt
790

    
791
		echo "/dev/ufs/${_label}0 / ufs ro,sync,noatime 1 1" > ${MNT}/etc/fstab
792
		if [ $NANO_CONFSIZE -gt 0 ] ; then
793
			echo "/dev/ufs/cf /cf ufs ro,sync,noatime 1 1" >> ${MNT}/etc/fstab
794
		fi
795

    
796
		sync; sync; sync
797
		umount ${MNT} || umount -f ${MNT}
798
		# Restore the original trap
799
		trap "mdconfig -d -u ${MD}; return" 1 2 15 EXIT
800

    
801
		# Setting NANO_IMAGES to 1 and NANO_INIT_IMG2 will tell
802
		# NanoBSD to only create one partition.  We default to 2
803
		# partitions in case anything happens to the first the
804
		# operator can boot from the 2nd and should be OK.
805

    
806
		# Before just going to use dd for duplicate think!
807
		# The images are created as sparse so lets take advantage
808
		# of that by just exec some commands.
809
		if [ $NANO_IMAGES -gt 1 -a $NANO_INIT_IMG2 -gt 0 ] ; then
810
			# Duplicate to second image (if present)
811
			echo ">>> Creating NanoBSD second slice by duplicating first slice." | tee -a ${LOGFILE}
812
			# Create second image
813
			dd if=/dev/${MD}s1 of=/dev/${MD}s2 conv=sparse bs=64k 2>&1 >> ${LOGFILE}
814
			tunefs -L ${_label}1 /dev/${MD}s2a 2>&1 >> ${LOGFILE}
815
			mount /dev/ufs/${_label}1 ${MNT}
816
			if [ $? -ne 0 ]; then
817
				echo ">>> ERROR: Something wrong happened during mount of second slice image creation. STOPPING!" | tee -a ${LOGFILE}
818
				print_error_pfS
819
			fi
820
			# Consider the unmounting as well
821
			trap "umount /dev/ufs/${_label}1; mdconfig -d -u ${MD}; return" 1 2 15 EXIT
822

    
823
			echo "/dev/ufs/${_label}1 / ufs ro,sync,noatime 1 1" > ${MNT}/etc/fstab
824
			if [ $NANO_CONFSIZE -gt 0 ] ; then
825
				echo "/dev/ufs/cf /cf ufs ro,sync,noatime 1 1" >> ${MNT}/etc/fstab
826
			fi
827

    
828
			sync; sync; sync
829
			umount ${MNT} || umount -f ${MNT}
830
			# Restore the trap back
831
			trap "mdconfig -d -u ${MD}; return" 1 2 15 EXIT
832
		fi
833

    
834
		# Create Data slice, if any.
835
		# Note the changing of the variable to NANO_CONFSIZE
836
		# from NANO_DATASIZE.  We also added glabel support
837
		# and populate the Product configuration from the /cf
838
		# directory located in FINAL_CHROOT_DIR
839
		if [ $NANO_CONFSIZE -gt 0 ] ; then
840
			echo ">>> Creating /cf area to hold config.xml"
841
			newfs -L cf ${NANO_NEWFS} /dev/${MD}s3 2>&1 >> ${LOGFILE}
842
			# Mount data partition and copy contents of /cf
843
			# Can be used later to create custom default config.xml while building
844
			mount /dev/ufs/cf ${MNT}
845
			if [ $? -ne 0 ]; then
846
				echo ">>> ERROR: Something wrong happened during mount of cf slice image creation. STOPPING!" | tee -a ${LOGFILE}
847
				print_error_pfS
848
			fi
849
			# Consider the unmounting as well
850
			trap "umount /dev/ufs/cf; mdconfig -d -u ${MD}; return" 1 2 15 EXIT
851

    
852
			clone_directory_contents ${FINAL_CHROOT_DIR}/cf ${MNT}
853

    
854
			sync; sync; sync
855
			umount ${MNT} || umount -f ${MNT}
856
			# Restore the trap back
857
			trap "mdconfig -d -u ${MD}; return" 1 2 15 EXIT
858
		else
859
			">>> [nanoo] NANO_CONFSIZE is not set. Not adding a /conf partition.. You sure about this??" | tee -a ${LOGFILE}
860
		fi
861

    
862
		echo ">>> [nanoo] Creating NanoBSD upgrade file from first slice..." | tee -a ${LOGFILE}
863
		dd if=/dev/${MD}s1 of=$IMGUPDATE conv=sparse bs=64k 2>&1 >> ${LOGFILE}
864

    
865
		mdconfig -d -u $MD
866
		# Restore default action
867
		trap "-" 1 2 15 EXIT
868

    
869
		# Check each image and ensure that they are over
870
		# 3 megabytes.  If either image is under 20 megabytes
871
		# in size then error out.
872
		IMGSIZE=$(stat -f "%z" ${IMG})
873
		IMGUPDATESIZE=$(stat -f "%z" ${IMGUPDATE})
874
		CHECKSIZE="20040710"
875
		if [ "$IMGSIZE" -lt "$CHECKSIZE" ]; then
876
			echo ">>> ERROR: Something went wrong when building NanoBSD.  The image size is under 20 megabytes!" | tee -a ${LOGFILE}
877
			print_error_pfS
878
		fi
879
		if [ "$IMGUPDATESIZE" -lt "$CHECKSIZE" ]; then
880
			echo ">>> ERROR: Something went wrong when building NanoBSD upgrade image.  The image size is under 20 megabytes!" | tee -a ${LOGFILE}
881
			print_error_pfS
882
		fi
883

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

    
887
		gzip -qf $IMG &
888
		_bg_pids="${_bg_pids}${_bg_pids:+ }$!"
889
		gzip -qf $IMGUPDATE &
890
		_bg_pids="${_bg_pids}${_bg_pids:+ }$!"
891
	done
892

    
893
	unset IMG
894
	unset IMGUPDATE
895
	unset IMGUPDATESIZE
896
	unset IMGSIZE
897

    
898
	ls -lah $IMAGES_FINAL_DIR
899
}
900

    
901
# This routine creates a ova image that contains
902
# a ovf and vmdk file. These files can be imported
903
# right into vmware or virtual box.
904
# (and many other emulation platforms)
905
# http://www.vmware.com/pdf/ovf_whitepaper_specification.pdf
906
create_ova_image() {
907
	# XXX create a .ovf php creator that you can pass:
908
	#     1. populatedSize
909
	#     2. license
910
	#     3. product name
911
	#     4. version
912
	#     5. number of network interface cards
913
	#     6. allocationUnits
914
	#     7. capacity
915
	#     8. capacityAllocationUnits
916

    
917
	LOGFILE=${BUILDER_LOGS}/ova.${TARGET}.log
918

    
919
	if [ -d "${OVA_TMP}" ]; then
920
		chflags -R noschg ${OVA_TMP}
921
		rm -rf ${OVA_TMP}
922
	fi
923

    
924
	local _mntdir=${OVA_TMP}/mnt
925
	mkdir -p ${_mntdir}
926

    
927
	if [ -z "${OVA_SWAP_PART_SIZE_IN_GB}" -o "${OVA_SWAP_PART_SIZE_IN_GB}" = "0" ]; then
928
		# first partition size (freebsd-ufs)
929
		local OVA_FIRST_PART_SIZE_IN_GB=${VMDK_DISK_CAPACITY_IN_GB}
930
		# Calculate real first partition size, removing 128 blocks (65536 bytes) beginning/loader
931
		local OVA_FIRST_PART_SIZE=$((${OVA_FIRST_PART_SIZE_IN_GB}*1024*1024*1024-65536))
932
		# Unset swap partition size variable
933
		unset OVA_SWAP_PART_SIZE
934
		# Parameter used by mkimg
935
		unset OVA_SWAP_PART_PARAM
936
	else
937
		# first partition size (freebsd-ufs)
938
		local OVA_FIRST_PART_SIZE_IN_GB=$((VMDK_DISK_CAPACITY_IN_GB-OVA_SWAP_PART_SIZE_IN_GB))
939
		# Use first partition size in g
940
		local OVA_FIRST_PART_SIZE="${OVA_FIRST_PART_SIZE_IN_GB}g"
941
		# Calculate real swap size, removing 128 blocks (65536 bytes) beginning/loader
942
		local OVA_SWAP_PART_SIZE=$((${OVA_SWAP_PART_SIZE_IN_GB}*1024*1024*1024-65536))
943
		# Parameter used by mkimg
944
		local OVA_SWAP_PART_PARAM="-p freebsd-swap/swap0::${OVA_SWAP_PART_SIZE}"
945
	fi
946

    
947
	# Prepare folder to be put in image
948
	customize_stagearea_for_image "ova"
949
	install_default_kernel ${DEFAULT_KERNEL} "no"
950

    
951
	# Fill fstab
952
	echo ">>> Installing platform specific items..." | tee -a ${LOGFILE}
953
	echo "/dev/gpt/${PRODUCT_NAME}	/	ufs		rw	1	1" > ${FINAL_CHROOT_DIR}/etc/fstab
954
	if [ -n "${OVA_SWAP_PART_SIZE}" ]; then
955
		echo "/dev/gpt/swap0	none	swap	sw	0	0" >> ${FINAL_CHROOT_DIR}/etc/fstab
956
	fi
957

    
958
	# Create / partition
959
	echo -n ">>> Creating / partition... " | tee -a ${LOGFILE}
960
	truncate -s ${OVA_FIRST_PART_SIZE} ${OVA_TMP}/${OVFUFS}
961
	local _md=$(mdconfig -a -f ${OVA_TMP}/${OVFUFS})
962
	trap "mdconfig -d -u ${_md}; return" 1 2 15 EXIT
963

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

    
966
	if ! mount /dev/${_md} ${_mntdir} 2>&1 >>${LOGFILE}; then
967
		echo "Failed!" | tee -a ${LOGFILE}
968
		echo ">>> ERROR: Error mounting temporary vmdk image. STOPPING!" | tee -a ${LOGFILE}
969
		print_error_pfS
970
	fi
971
	trap "sync; sleep 3; umount ${_mntdir} || umount -f ${_mntdir}; mdconfig -d -u ${_md}; return" 1 2 15 EXIT
972

    
973
	echo "Done!" | tee -a ${LOGFILE}
974

    
975
	clone_directory_contents ${FINAL_CHROOT_DIR} ${_mntdir}
976

    
977
	sync
978
	sleep 3
979
	umount ${_mntdir} || umount -f ${_mntdir} >>${LOGFILE} 2>&1
980
	mdconfig -d -u ${_md}
981
	trap "-" 1 2 15 EXIT
982

    
983
	# Create raw disk
984
	echo -n ">>> Creating raw disk... " | tee -a ${LOGFILE}
985
	mkimg \
986
		-s gpt \
987
		-f raw \
988
		-b ${FINAL_CHROOT_DIR}/boot/pmbr \
989
		-p freebsd-boot:=${FINAL_CHROOT_DIR}/boot/gptboot \
990
		-p freebsd-ufs/${PRODUCT_NAME}:=${OVA_TMP}/${OVFUFS} \
991
		${OVA_SWAP_PART_PARAM} \
992
		-o ${OVA_TMP}/${OVFRAW} 2>&1 >> ${LOGFILE}
993

    
994
	if [ $? -ne 0 -o ! -f ${OVA_TMP}/${OVFRAW} ]; then
995
		if [ -f ${OVA_TMP}/${OVFUFS} ]; then
996
			rm -f ${OVA_TMP}/${OVFUFS}
997
		fi
998
		if [ -f ${OVA_TMP}/${OVFRAW} ]; then
999
			rm -f ${OVA_TMP}/${OVFRAW}
1000
		fi
1001
		echo "Failed!" | tee -a ${LOGFILE}
1002
		echo ">>> ERROR: Error creating temporary vmdk image. STOPPING!" | tee -a ${LOGFILE}
1003
		print_error_pfS
1004
	fi
1005
	echo "Done!" | tee -a ${LOGFILE}
1006

    
1007
	# We don't need it anymore
1008
	rm -f ${OVA_TMP}/${OVFUFS} >/dev/null 2>&1
1009

    
1010
	# Convert raw to vmdk
1011
	echo -n ">>> Creating vmdk disk... " | tee -a ${LOGFILE}
1012
	vmdktool -z9 -v ${OVA_TMP}/${OVFVMDK} ${OVA_TMP}/${OVFRAW}
1013

    
1014
	if [ $? -ne 0 -o ! -f ${OVA_TMP}/${OVFVMDK} ]; then
1015
		if [ -f ${OVA_TMP}/${OVFRAW} ]; then
1016
			rm -f ${OVA_TMP}/${OVFRAW}
1017
		fi
1018
		if [ -f ${OVA_TMP}/${OVFVMDK} ]; then
1019
			rm -f ${OVA_TMP}/${OVFVMDK}
1020
		fi
1021
		echo "Failed!" | tee -a ${LOGFILE}
1022
		echo ">>> ERROR: Error creating vmdk image. STOPPING!" | tee -a ${LOGFILE}
1023
		print_error_pfS
1024
	fi
1025
	echo "Done!" | tee -a ${LOGFILE}
1026

    
1027
	rm -f ${OVA_TMP}/${OVFRAW}
1028

    
1029
	ova_setup_ovf_template
1030

    
1031
	echo -n ">>> Writing final ova image... " | tee -a ${LOGFILE}
1032
	# Create OVA file for vmware
1033
	gtar -C ${OVA_TMP} -cpf ${OVAPATH} ${PRODUCT_NAME}.ovf ${OVFVMDK}
1034
	echo "Done!" | tee -a ${LOGFILE}
1035
	rm -f ${OVA_TMP}/${OVFVMDK} >/dev/null 2>&1
1036

    
1037
	echo ">>> OVA created: $(LC_ALL=C date)" | tee -a ${LOGFILE}
1038
}
1039

    
1040
# called from create_ova_image
1041
ova_setup_ovf_template() {
1042
	if [ ! -f ${OVFTEMPLATE} ]; then
1043
		echo ">>> ERROR: OVF template file (${OVFTEMPLATE}) not found."
1044
		print_error_pfS
1045
	fi
1046

    
1047
	#  OperatingSystemSection (${PRODUCT_NAME}.ovf)
1048
	#  42   FreeBSD 32-Bit
1049
	#  78   FreeBSD 64-Bit
1050
	if [ "${TARGET}" = "amd64" ]; then
1051
		local _os_id="78"
1052
		local _os_type="freebsd64Guest"
1053
		local _os_descr="FreeBSD 64-Bit"
1054
	elif [ "${TARGET}" = "i386" ]; then
1055
		local _os_id="42"
1056
		local _os_type="freebsdGuest"
1057
		local _os_descr="FreeBSD"
1058
	else
1059
		echo ">>> ERROR: Platform not supported for OVA (${TARGET})"
1060
		print_error_pfS
1061
	fi
1062

    
1063
	local POPULATED_SIZE=$(du -d0 -k $FINAL_CHROOT_DIR | cut -f1)
1064
	local POPULATED_SIZE_IN_BYTES=$((${POPULATED_SIZE}*1024))
1065
	local VMDK_FILE_SIZE=$(stat -f "%z" ${OVA_TMP}/${OVFVMDK})
1066

    
1067
	sed \
1068
		-e "s,%%VMDK_FILE_SIZE%%,${VMDK_FILE_SIZE},g" \
1069
		-e "s,%%VMDK_DISK_CAPACITY_IN_GB%%,${VMDK_DISK_CAPACITY_IN_GB},g" \
1070
		-e "s,%%POPULATED_SIZE_IN_BYTES%%,${POPULATED_SIZE_IN_BYTES},g" \
1071
		-e "s,%%OS_ID%%,${_os_id},g" \
1072
		-e "s,%%OS_TYPE%%,${_os_type},g" \
1073
		-e "s,%%OS_DESCR%%,${_os_descr},g" \
1074
		-e "s,%%PRODUCT_NAME%%,${PRODUCT_NAME},g" \
1075
		-e "s,%%PRODUCT_NAME_SUFFIX%%,${PRODUCT_NAME_SUFFIX},g" \
1076
		-e "s,%%PRODUCT_VERSION%%,${PRODUCT_VERSION},g" \
1077
		-e "s,%%PRODUCT_URL%%,${PRODUCT_URL},g" \
1078
		-e "s#%%VENDOR_NAME%%#${VENDOR_NAME}#g" \
1079
		-e "s#%%OVF_INFO%%#${OVF_INFO}#g" \
1080
		-e "/^%%PRODUCT_LICENSE%%/r ${BUILDER_ROOT}/license.txt" \
1081
		-e "/^%%PRODUCT_LICENSE%%/d" \
1082
		${OVFTEMPLATE} > ${OVA_TMP}/${PRODUCT_NAME}.ovf
1083
}
1084

    
1085
# Cleans up previous builds
1086
clean_builder() {
1087
	# Clean out directories
1088
	echo ">>> Cleaning up previous build environment...Please wait!"
1089

    
1090
	staginareas_clean_each_run
1091

    
1092
	if [ -d "${STAGE_CHROOT_DIR}" ]; then
1093
		BASENAME=$(basename ${STAGE_CHROOT_DIR})
1094
		echo -n ">>> Cleaning ${STAGE_CHROOT_DIR} ..."
1095
		chflags -R noschg ${STAGE_CHROOT_DIR} 2>&1 >/dev/null
1096
		rm -rf ${STAGE_CHROOT_DIR}/* 2>/dev/null
1097
		echo "Done."
1098
	fi
1099

    
1100
	if [ -z "${NO_CLEAN_FREEBSD_OBJ}" -a -d "${FREEBSD_SRC_DIR}" ]; then
1101
		OBJTREE=$(env TARGET=${TARGET} TARGET_ARCH=${TARGET_ARCH} make -C ${FREEBSD_SRC_DIR} -V OBJTREE)
1102
		if [ -d "${OBJTREE}" ]; then
1103
			echo -n ">>> Cleaning FreeBSD objects dir staging..."
1104
			echo -n "."
1105
			chflags -R noschg ${OBJTREE} 2>&1 >/dev/null
1106
			echo -n "."
1107
			rm -rf ${OBJTREE}/*
1108
			echo "Done!"
1109
		fi
1110
		if [ -d "${KERNEL_BUILD_PATH}" ]; then
1111
			echo -n ">>> Cleaning previously built kernel stage area..."
1112
			rm -rf $KERNEL_BUILD_PATH/*
1113
			echo "Done!"
1114
		fi
1115
	fi
1116
	mkdir -p $KERNEL_BUILD_PATH
1117

    
1118
	echo -n ">>> Cleaning previously built images..."
1119
	chflags -R noschg ${IMAGES_FINAL_DIR} ${STAGINGAREA}2>&1 1>/dev/null
1120
	rm -rf $IMAGES_FINAL_DIR/*
1121
	rm -rf $STAGINGAREA/*
1122
	echo "Done!"
1123

    
1124
	if [ -z "${NO_CLEAN_FREEBSD_SRC}" ]; then
1125
		if [ -d "$FREEBSD_SRC_DIR" ]; then
1126
			echo -n ">>> Ensuring $FREEBSD_SRC_DIR is clean..."
1127
			rm -rf ${FREEBSD_SRC_DIR}
1128
			echo "Done!"
1129
		fi
1130
	fi
1131

    
1132
	echo -n ">>> Cleaning previous builder logs..."
1133
	if [ -d "$BUILDER_LOGS" ]; then
1134
		rm -rf ${BUILDER_LOGS}
1135
	fi
1136
	mkdir -p ${BUILDER_LOGS}
1137

    
1138
	echo "Done!"
1139

    
1140
	echo ">>> Cleaning of builder environment has finished."
1141
}
1142

    
1143
clone_directory_contents() {
1144
	if [ ! -e "$2" ]; then
1145
		mkdir -p "$2"
1146
	fi
1147
	if [ ! -d "$1" -o ! -d "$2" ]; then
1148
		if [ -z "${LOGFILE}" ]; then
1149
			echo ">>> ERROR: Argument $1 supplied is not a directory!"
1150
		else
1151
			echo ">>> ERROR: Argument $1 supplied is not a directory!" | tee -a ${LOGFILE}
1152
		fi
1153
		print_error_pfS
1154
	fi
1155
	echo -n ">>> Using TAR to clone $1 to $2 ..."
1156
	tar -C ${1} -c -f - . | tar -C ${2} -x -p -f -
1157
	echo "Done!"
1158
}
1159

    
1160
clone_to_staging_area() {
1161
	# Clone everything to the final staging area
1162
	echo -n ">>> Cloning everything to ${STAGE_CHROOT_DIR} staging area..."
1163
	LOGFILE=${BUILDER_LOGS}/cloning.${TARGET}.log
1164

    
1165
	tar -C ${PRODUCT_SRC} -c -f - . | \
1166
		tar -C ${STAGE_CHROOT_DIR} -x -p -f -
1167

    
1168
	if [ "${PRODUCT_NAME}" != "pfSense" ]; then
1169
		mv ${STAGE_CHROOT_DIR}/usr/local/sbin/pfSense-upgrade \
1170
			${STAGE_CHROOT_DIR}/usr/local/sbin/${PRODUCT_NAME}-upgrade
1171
	fi
1172

    
1173
	if [ -f ${STAGE_CHROOT_DIR}/etc/master.passwd ]; then
1174
		chroot ${STAGE_CHROOT_DIR} pwd_mkdb /etc/master.passwd
1175
	fi
1176
	mkdir -p ${STAGE_CHROOT_DIR}/etc/mtree
1177
	mtree -Pcp ${STAGE_CHROOT_DIR}/var > ${STAGE_CHROOT_DIR}/etc/mtree/var.dist
1178
	mtree -Pcp ${STAGE_CHROOT_DIR}/etc > ${STAGE_CHROOT_DIR}/etc/mtree/etc.dist
1179
	if [ -d ${STAGE_CHROOT_DIR}/usr/local/etc ]; then
1180
		mtree -Pcp ${STAGE_CHROOT_DIR}/usr/local/etc > ${STAGE_CHROOT_DIR}/etc/mtree/localetc.dist
1181
	fi
1182

    
1183
	## Add buildtime and lastcommit information
1184
	# This is used for detecting updates.
1185
	echo "$BUILTDATESTRING" > $STAGE_CHROOT_DIR/etc/version.buildtime
1186
	# Record last commit info if it is available.
1187
	if [ -f $SCRATCHDIR/build_commit_info.txt ]; then
1188
		cp $SCRATCHDIR/build_commit_info.txt $STAGE_CHROOT_DIR/etc/version.lastcommit
1189
	fi
1190

    
1191
	local _exclude_files="${CORE_PKG_TMP}/base_exclude_files"
1192
	sed \
1193
		-e "s,%%PRODUCT_NAME%%,${PRODUCT_NAME},g" \
1194
		-e "s,%%VERSION%%,${_version},g" \
1195
		${BUILDER_TOOLS}/templates/core_pkg/base/exclude_files \
1196
		> ${_exclude_files}
1197

    
1198
	mkdir -p ${STAGE_CHROOT_DIR}${PRODUCT_SHARE_DIR} >/dev/null 2>&1
1199

    
1200
	# Include a sample pkg stable conf to base
1201
	setup_pkg_repo \
1202
		${PKG_REPO_DEFAULT} \
1203
		${STAGE_CHROOT_DIR}${PRODUCT_SHARE_DIR}/${PRODUCT_NAME}-repo.conf \
1204
		${TARGET} \
1205
		${TARGET_ARCH}
1206

    
1207
	mtree \
1208
		-c \
1209
		-k uid,gid,mode,size,flags,sha256digest \
1210
		-p ${STAGE_CHROOT_DIR} \
1211
		-X ${_exclude_files} \
1212
		> ${STAGE_CHROOT_DIR}${PRODUCT_SHARE_DIR}/base.mtree
1213
	tar \
1214
		-C ${STAGE_CHROOT_DIR} \
1215
		-cJf ${STAGE_CHROOT_DIR}${PRODUCT_SHARE_DIR}/base.txz \
1216
		-X ${_exclude_files} \
1217
		.
1218

    
1219
	core_pkg_create rc "" ${CORE_PKG_VERSION} ${STAGE_CHROOT_DIR}
1220
	core_pkg_create base "" ${CORE_PKG_VERSION} ${STAGE_CHROOT_DIR}
1221
	core_pkg_create base-nanobsd "" ${CORE_PKG_VERSION} ${STAGE_CHROOT_DIR}
1222
	core_pkg_create default-config "" ${CORE_PKG_VERSION} ${STAGE_CHROOT_DIR}
1223

    
1224
	local DEFAULTCONF=${STAGE_CHROOT_DIR}/conf.default/config.xml
1225

    
1226
	# Save current WAN and LAN if value
1227
	local _old_wan_if=$(xml sel -t -v "${XML_ROOTOBJ}/interfaces/wan/if" ${DEFAULTCONF})
1228
	local _old_lan_if=$(xml sel -t -v "${XML_ROOTOBJ}/interfaces/lan/if" ${DEFAULTCONF})
1229

    
1230
	# Change default interface names to match vmware driver
1231
	xml ed -P -L -u "${XML_ROOTOBJ}/interfaces/wan/if" -v "vmx0" ${DEFAULTCONF}
1232
	xml ed -P -L -u "${XML_ROOTOBJ}/interfaces/lan/if" -v "vmx1" ${DEFAULTCONF}
1233
	core_pkg_create default-config "vmware" ${CORE_PKG_VERSION} ${STAGE_CHROOT_DIR}
1234

    
1235
	# Restore default values to be used by serial package
1236
	xml ed -P -L -u "${XML_ROOTOBJ}/interfaces/wan/if" -v "${_old_wan_if}" ${DEFAULTCONF}
1237
	xml ed -P -L -u "${XML_ROOTOBJ}/interfaces/lan/if" -v "${_old_lan_if}" ${DEFAULTCONF}
1238

    
1239
	# Activate serial console in config.xml
1240
	xml ed -L -P -d "${XML_ROOTOBJ}/system/enableserial" ${DEFAULTCONF}
1241
	xml ed -P -s "${XML_ROOTOBJ}/system" -t elem -n "enableserial" \
1242
		${DEFAULTCONF} > ${DEFAULTCONF}.tmp
1243
	xml fo -t ${DEFAULTCONF}.tmp > ${DEFAULTCONF}
1244
	rm -f ${DEFAULTCONF}.tmp
1245

    
1246
	echo force > ${STAGE_CHROOT_DIR}/cf/conf/enableserial_force
1247

    
1248
	core_pkg_create default-config-serial "" ${CORE_PKG_VERSION} ${STAGE_CHROOT_DIR}
1249

    
1250
	rm -f ${STAGE_CHROOT_DIR}/cf/conf/enableserial_force
1251
	rm -f ${STAGE_CHROOT_DIR}/cf/conf/config.xml
1252

    
1253
	# Make sure pkg is present
1254
	pkg_bootstrap ${STAGE_CHROOT_DIR}
1255

    
1256
	# Make sure correct repo is available on tmp dir
1257
	mkdir -p ${STAGE_CHROOT_DIR}/tmp/pkg-repos
1258
	setup_pkg_repo \
1259
		${PKG_REPO_DEFAULT} \
1260
		${STAGE_CHROOT_DIR}/tmp/pkg-repos/repo.conf \
1261
		${TARGET} \
1262
		${TARGET_ARCH} \
1263
		staging
1264

    
1265
	echo "Done!"
1266
}
1267

    
1268
create_final_staging_area() {
1269
	if [ -z "${FINAL_CHROOT_DIR}" ]; then
1270
		echo ">>> ERROR: FINAL_CHROOT_DIR is not set, cannot continue!" | tee -a ${LOGFILE}
1271
		print_error_pfS
1272
	fi
1273

    
1274
	if [ -d "${FINAL_CHROOT_DIR}" ]; then
1275
		echo -n ">>> Previous ${FINAL_CHROOT_DIR} detected cleaning up..." | tee -a ${LOGFILE}
1276
		chflags -R noschg ${FINAL_CHROOT_DIR} 2>&1 1>/dev/null
1277
		rm -rf ${FINAL_CHROOT_DIR}/* 2>&1 1>/dev/null
1278
		echo "Done." | tee -a ${LOGFILE}
1279
	fi
1280

    
1281
	echo ">>> Preparing Final image staging area: $(LC_ALL=C date)" 2>&1 | tee -a ${LOGFILE}
1282
	echo ">>> Cloning ${STAGE_CHROOT_DIR} to ${FINAL_CHROOT_DIR}" 2>&1 | tee -a ${LOGFILE}
1283
	clone_directory_contents ${STAGE_CHROOT_DIR} ${FINAL_CHROOT_DIR}
1284

    
1285
	if [ ! -f $FINAL_CHROOT_DIR/sbin/init ]; then
1286
		echo ">>> ERROR: Something went wrong during cloning -- Please verify!" 2>&1 | tee -a ${LOGFILE}
1287
		print_error_pfS
1288
	fi
1289
}
1290

    
1291
customize_stagearea_for_image() {
1292
	local _image_type="$1"
1293
	local _default_config="" # filled with $2 below
1294
	local _image_variant="$3"
1295

    
1296
	if [ -n "$2" ]; then
1297
		_default_config="$2"
1298
	elif [ "${_image_type}" = "nanobsd" -o \
1299
	     "${_image_type}" = "memstickserial" -o \
1300
	     "${_image_type}" = "memstickadi" ]; then
1301
		_default_config="default-config-serial"
1302
	elif [ "${_image_type}" = "ova" ]; then
1303
		_default_config="default-config-vmware"
1304
	else
1305
		_default_config="default-config"
1306
	fi
1307

    
1308
	# Prepare final stage area
1309
	create_final_staging_area
1310

    
1311
	pkg_chroot_add ${FINAL_CHROOT_DIR} rc
1312

    
1313
	if [ "${_image_type}" = "nanobsd" -o \
1314
	     "${_image_type}" = "nanobsd-vga" ]; then
1315

    
1316
		mkdir -p ${FINAL_CHROOT_DIR}/root/var/db \
1317
			 ${FINAL_CHROOT_DIR}/root/var/cache \
1318
			 ${FINAL_CHROOT_DIR}/var/db/pkg \
1319
			 ${FINAL_CHROOT_DIR}/var/cache/pkg
1320
		mv -f ${FINAL_CHROOT_DIR}/var/db/pkg ${FINAL_CHROOT_DIR}/root/var/db
1321
		mv -f ${FINAL_CHROOT_DIR}/var/cache/pkg ${FINAL_CHROOT_DIR}/root/var/cache
1322
		ln -sf ../../root/var/db/pkg ${FINAL_CHROOT_DIR}/var/db/pkg
1323
		ln -sf ../../root/var/cache/pkg ${FINAL_CHROOT_DIR}/var/cache/pkg
1324

    
1325
		pkg_chroot_add ${FINAL_CHROOT_DIR} base-nanobsd
1326
	else
1327
		pkg_chroot_add ${FINAL_CHROOT_DIR} base
1328
	fi
1329

    
1330
	if [ "${_image_type}" = "iso" -o \
1331
	     "${_image_type}" = "memstick" -o \
1332
	     "${_image_type}" = "memstickserial" -o \
1333
	     "${_image_type}" = "memstickadi" ]; then
1334
		install_bsdinstaller
1335
		mkdir -p ${FINAL_CHROOT_DIR}/pkgs
1336
		cp ${CORE_PKG_ALL_PATH}/*default-config*.txz ${FINAL_CHROOT_DIR}/pkgs
1337
	fi
1338

    
1339
	pkg_chroot_add ${FINAL_CHROOT_DIR} ${_default_config}
1340

    
1341
	# XXX: Workaround to avoid pkg to complain regarding release
1342
	#      repo on first boot since packages are installed from
1343
	#      staging server during build phase
1344
	if [ -n "${USE_PKG_REPO_STAGING}" ]; then
1345
		_read_cmd="select value from repodata where key='packagesite'"
1346
		if [ -n "${_IS_RELEASE}" ]; then
1347
			local _tgt_server="${PKG_REPO_SERVER_RELEASE}"
1348
		else
1349
			local _tgt_server="${PKG_REPO_SERVER_DEVEL}"
1350
		fi
1351
		for _db in ${FINAL_CHROOT_DIR}/var/db/pkg/repo-*sqlite; do
1352
			_cur=$(/usr/local/bin/sqlite3 ${_db} "${_read_cmd}")
1353
			_new=$(echo "${_cur}" | sed -e "s,^${PKG_REPO_SERVER_STAGING},${_tgt_server},")
1354
			/usr/local/bin/sqlite3 ${_db} "update repodata set value='${_new}' where key='packagesite'"
1355
		done
1356
	fi
1357

    
1358
	if [ -n "$_image_variant" -a \
1359
	    -d ${BUILDER_TOOLS}/templates/custom_logos/${_image_variant} ]; then
1360
		mkdir -p ${FINAL_CHROOT_DIR}/usr/local/share/${PRODUCT_NAME}/custom_logos
1361
		cp -f \
1362
			${BUILDER_TOOLS}/templates/custom_logos/${_image_variant}/*.png \
1363
			${FINAL_CHROOT_DIR}/usr/local/share/${PRODUCT_NAME}/custom_logos
1364
	fi
1365

    
1366
	# Remove temporary repo conf
1367
	rm -rf ${FINAL_CHROOT_DIR}/tmp/pkg-repos
1368
}
1369

    
1370
create_distribution_tarball() {
1371
	mkdir -p ${FINAL_CHROOT_DIR}/distrib
1372

    
1373
	tar -C ${FINAL_CHROOT_DIR} --exclude ./distrib --exclude ./pkgs -cJf ${FINAL_CHROOT_DIR}/distrib/${PRODUCT_NAME}.txz .
1374
}
1375

    
1376
create_iso_image() {
1377
	local _variant="$1"
1378

    
1379
	LOGFILE=${BUILDER_LOGS}/isoimage.${TARGET}
1380
	echo ">>> Building bootable ISO image for ${TARGET}" | tee -a ${LOGFILE}
1381
	if [ -z "${DEFAULT_KERNEL}" ]; then
1382
		echo ">>> ERROR: Could not identify DEFAULT_KERNEL to install on image!" | tee -a ${LOGFILE}
1383
		print_error_pfS
1384
	fi
1385

    
1386
	local _image_path=${ISOPATH}
1387
	if [ -n "${_variant}" ]; then
1388
		_image_path=$(echo "$_image_path" | \
1389
			sed "s/${PRODUCT_NAME_SUFFIX}-/&${_variant}-/")
1390
		VARIANTIMAGES="${VARIANTIMAGES}${VARIANTIMAGES:+ }${_image_path}"
1391
	fi
1392

    
1393
	customize_stagearea_for_image "iso" "" $_variant
1394
	install_default_kernel ${DEFAULT_KERNEL}
1395

    
1396
	echo cdrom > $FINAL_CHROOT_DIR/etc/platform
1397

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

    
1401
	# This check is for supporting create memstick/ova images
1402
	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}
1403
	echo "-o label=${FSLABEL} -o publisher=\"${PRODUCT_NAME} project.\" $_image_path ${FINAL_CHROOT_DIR}" | tee -a ${LOGFILE}
1404

    
1405
	create_distribution_tarball
1406

    
1407
	# Remove /rescue from iso since cd9660 cannot deal with hardlinks
1408
	rm -rf ${FINAL_CHROOT_DIR}/rescue
1409

    
1410
	makefs -t cd9660 -o bootimage="i386;${FINAL_CHROOT_DIR}/boot/cdboot" -o no-emul-boot -o rockridge \
1411
		-o label=${FSLABEL} -o publisher="${PRODUCT_NAME} project." $_image_path ${FINAL_CHROOT_DIR} 2>&1 >> ${LOGFILE}
1412
	if [ $? -ne 0 -o ! -f $_image_path ]; then
1413
		if [ -f ${_image_path} ]; then
1414
			rm -f $_image_path
1415
		fi
1416
		echo ">>> ERROR: Something wrong happened during ISO image creation. STOPPING!" | tee -a ${LOGFILE}
1417
		print_error_pfS
1418
	fi
1419
	gzip -qf $_image_path &
1420
	_bg_pids="${_bg_pids}${_bg_pids:+ }$!"
1421

    
1422
	echo ">>> ISO created: $(LC_ALL=C date)" | tee -a ${LOGFILE}
1423
}
1424

    
1425
create_memstick_image() {
1426
	local _variant="$1"
1427

    
1428
	LOGFILE=${BUILDER_LOGS}/memstick.${TARGET}
1429
	if [ "${MEMSTICKPATH}" = "" ]; then
1430
		echo ">>> MEMSTICKPATH is empty skipping generation of memstick image!" | tee -a ${LOGFILE}
1431
		return
1432
	fi
1433

    
1434
	local _image_path=${MEMSTICKPATH}
1435
	if [ -n "${_variant}" ]; then
1436
		_image_path=$(echo "$_image_path" | \
1437
			sed "s/-memstick-/-memstick-${_variant}-/")
1438
		VARIANTIMAGES="${VARIANTIMAGES}${VARIANTIMAGES:+ }${_image_path}"
1439
	fi
1440

    
1441
	customize_stagearea_for_image "memstick" "" $_variant
1442
	install_default_kernel ${DEFAULT_KERNEL}
1443

    
1444
	echo cdrom > $FINAL_CHROOT_DIR/etc/platform
1445

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

    
1450
	create_distribution_tarball
1451

    
1452
	makefs -B little -o label=${PRODUCT_NAME},version=2 ${_image_path} ${FINAL_CHROOT_DIR}
1453
	if [ $? -ne 0 ]; then
1454
		if [ -f ${_image_path} ]; then
1455
			rm -f $_image_path
1456
		fi
1457
		echo ">>> ERROR: Something wrong happened during MEMSTICK image creation. STOPPING!" | tee -a ${LOGFILE}
1458
		print_error_pfS
1459
	fi
1460
	MD=$(mdconfig -a -t vnode -f $_image_path)
1461
	# Just in case
1462
	trap "mdconfig -d -u ${MD}" 1 2 15 EXIT
1463
	gpart create -s BSD ${MD} 2>&1 >> ${LOGFILE}
1464
	gpart bootcode -b ${FINAL_CHROOT_DIR}/boot/boot ${MD} 2>&1 >> ${LOGFILE}
1465
	gpart add -t freebsd-ufs ${MD} 2>&1 >> ${LOGFILE}
1466
	trap "-" 1 2 15 EXIT
1467
	mdconfig -d -u ${MD} 2>&1 | tee -a ${LOGFILE}
1468
	gzip -qf $_image_path &
1469
	_bg_pids="${_bg_pids}${_bg_pids:+ }$!"
1470

    
1471
	echo ">>> MEMSTICK created: $(LC_ALL=C date)" | tee -a ${LOGFILE}
1472
}
1473

    
1474
create_memstick_serial_image() {
1475
	LOGFILE=${BUILDER_LOGS}/memstickserial.${TARGET}
1476
	if [ "${MEMSTICKSERIALPATH}" = "" ]; then
1477
		echo ">>> MEMSTICKSERIALPATH is empty skipping generation of memstick image!" | tee -a ${LOGFILE}
1478
		return
1479
	fi
1480

    
1481
	customize_stagearea_for_image "memstickserial"
1482
	install_default_kernel ${DEFAULT_KERNEL}
1483

    
1484
	echo cdrom > $FINAL_CHROOT_DIR/etc/platform
1485

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

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

    
1491
	BOOTCONF=${FINAL_CHROOT_DIR}/boot.config
1492
	LOADERCONF=${FINAL_CHROOT_DIR}/boot/loader.conf
1493

    
1494
	echo ">>> Activating serial console..." 2>&1 | tee -a ${LOGFILE}
1495
	# Activate serial console in boot.config
1496
	if [ -f ${BOOTCONF} ]; then
1497
		sed -i "" '/-D$/d' ${BOOTCONF}
1498
	fi
1499
	echo "-S115200 -D" >> ${BOOTCONF}
1500

    
1501
	# Remove old console options if present.
1502
	[ -f "${LOADERCONF}" ] \
1503
		&& sed -i "" -Ee "/(console|boot_multicons|boot_serial)/d" ${LOADERCONF}
1504
	# Activate serial console+video console in loader.conf
1505
	echo 'boot_multicons="YES"' >>  ${LOADERCONF}
1506
	echo 'boot_serial="YES"' >> ${LOADERCONF}
1507
	echo 'console="comconsole,vidconsole"' >> ${LOADERCONF}
1508
	echo 'comconsole_speed="115200"' >> ${LOADERCONF}
1509

    
1510
	create_distribution_tarball
1511

    
1512
	makefs -B little -o label=${PRODUCT_NAME},version=2 ${MEMSTICKSERIALPATH} ${FINAL_CHROOT_DIR}
1513
	if [ $? -ne 0 ]; then
1514
		if [ -f ${MEMSTICKSERIALPATH} ]; then
1515
			rm -f $MEMSTICKSERIALPATH
1516
		fi
1517
		echo ">>> ERROR: Something wrong happened during MEMSTICKSERIAL image creation. STOPPING!" | tee -a ${LOGFILE}
1518
		print_error_pfS
1519
	fi
1520
	MD=$(mdconfig -a -t vnode -f $MEMSTICKSERIALPATH)
1521
	# Just in case
1522
	trap "mdconfig -d -u ${MD}" 1 2 15 EXIT
1523
	gpart create -s BSD ${MD} 2>&1 >> ${LOGFILE}
1524
	gpart bootcode -b ${FINAL_CHROOT_DIR}/boot/boot ${MD} 2>&1 >> ${LOGFILE}
1525
	gpart add -t freebsd-ufs ${MD} 2>&1 >> ${LOGFILE}
1526
	trap "-" 1 2 15 EXIT
1527
	mdconfig -d -u ${MD} 2>&1 >> ${LOGFILE}
1528
	gzip -qf $MEMSTICKSERIALPATH &
1529
	_bg_pids="${_bg_pids}${_bg_pids:+ }$!"
1530

    
1531
	echo ">>> MEMSTICKSERIAL created: $(LC_ALL=C date)" | tee -a ${LOGFILE}
1532
}
1533

    
1534
create_memstick_adi_image() {
1535
	LOGFILE=${BUILDER_LOGS}/memstickadi.${TARGET}
1536
	if [ "${MEMSTICKADIPATH}" = "" ]; then
1537
		echo ">>> MEMSTICKADIPATH is empty skipping generation of memstick image!" | tee -a ${LOGFILE}
1538
		return
1539
	fi
1540

    
1541
	customize_stagearea_for_image "memstickadi"
1542
	install_default_kernel ${DEFAULT_KERNEL}
1543

    
1544
	echo cdrom > $FINAL_CHROOT_DIR/etc/platform
1545

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

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

    
1551
	BOOTCONF=${FINAL_CHROOT_DIR}/boot.config
1552
	LOADERCONF=${FINAL_CHROOT_DIR}/boot/loader.conf
1553

    
1554
	echo ">>> Activating serial console..." 2>&1 | tee -a ${LOGFILE}
1555
	# Activate serial console in boot.config
1556
	if [ -f ${BOOTCONF} ]; then
1557
		sed -i "" '/-[Dh]$/d' ${BOOTCONF}
1558
	fi
1559
	echo "-S115200 -h" >> ${BOOTCONF}
1560

    
1561
	# Remove old console options if present.
1562
	[ -f "${LOADERCONF}" ] \
1563
		&& sed -i "" -Ee "/(console|boot_multicons|boot_serial|hint.uart)/d" ${LOADERCONF}
1564
	# Activate serial console+video console in loader.conf
1565
	echo 'boot_serial="YES"' >> ${LOADERCONF}
1566
	echo 'console="comconsole"' >> ${LOADERCONF}
1567
	echo 'comconsole_speed="115200"' >> ${LOADERCONF}
1568
	echo 'comconsole_port="0x2F8"' >> ${LOADERCONF}
1569
	echo 'hint.uart.0.flags="0x00"' >> ${LOADERCONF}
1570
	echo 'hint.uart.1.flags="0x10"' >> ${LOADERCONF}
1571

    
1572
	create_distribution_tarball
1573

    
1574
	makefs -B little -o label=${PRODUCT_NAME},version=2 ${MEMSTICKADIPATH} ${FINAL_CHROOT_DIR}
1575
	if [ $? -ne 0 ]; then
1576
		if [ -f ${MEMSTICKADIPATH} ]; then
1577
			rm -f $MEMSTICKADIPATH
1578
		fi
1579
		echo ">>> ERROR: Something wrong happened during MEMSTICKADI image creation. STOPPING!" | tee -a ${LOGFILE}
1580
		print_error_pfS
1581
	fi
1582
	MD=$(mdconfig -a -t vnode -f $MEMSTICKADIPATH)
1583
	# Just in case
1584
	trap "mdconfig -d -u ${MD}" 1 2 15 EXIT
1585
	gpart create -s BSD ${MD} 2>&1 >> ${LOGFILE}
1586
	gpart bootcode -b ${FINAL_CHROOT_DIR}/boot/boot ${MD} 2>&1 >> ${LOGFILE}
1587
	gpart add -t freebsd-ufs ${MD} 2>&1 >> ${LOGFILE}
1588
	trap "-" 1 2 15 EXIT
1589
	mdconfig -d -u ${MD} 2>&1 >> ${LOGFILE}
1590
	gzip -qf $MEMSTICKADIPATH &
1591
	_bg_pids="${_bg_pids}${_bg_pids:+ }$!"
1592

    
1593
	echo ">>> MEMSTICKADI created: $(LC_ALL=C date)" | tee -a ${LOGFILE}
1594
}
1595

    
1596
# Create pkg conf on desired place with desired arch/branch
1597
setup_pkg_repo() {
1598
	if [ -z "${4}" ]; then
1599
		return
1600
	fi
1601

    
1602
	local _template="${1}"
1603
	local _target="${2}"
1604
	local _arch="${3}"
1605
	local _target_arch="${4}"
1606
	local _staging="${5}"
1607

    
1608
	if [ -z "${_template}" -o ! -f "${_template}" ]; then
1609
		echo ">>> ERROR: It was not possible to find pkg conf template ${_template}"
1610
		print_error_pfS
1611
	fi
1612

    
1613
	if [ -n "${_staging}" -a -n "${USE_PKG_REPO_STAGING}" ]; then
1614
		local _pkg_repo_server_devel=${PKG_REPO_SERVER_STAGING}
1615
		local _pkg_repo_branch_devel=${PKG_REPO_BRANCH_STAGING}
1616
		local _pkg_repo_server_release=${PKG_REPO_SERVER_STAGING}
1617
		local _pkg_repo_branch_release=${PKG_REPO_BRANCH_STAGING}
1618
	else
1619
		local _pkg_repo_server_devel=${PKG_REPO_SERVER_DEVEL}
1620
		local _pkg_repo_branch_devel=${PKG_REPO_BRANCH_DEVEL}
1621
		local _pkg_repo_server_release=${PKG_REPO_SERVER_RELEASE}
1622
		local _pkg_repo_branch_release=${PKG_REPO_BRANCH_RELEASE}
1623
	fi
1624

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

    
1627
	sed \
1628
		-e "s/%%ARCH%%/${_target_arch}/" \
1629
		-e "s/%%PKG_REPO_BRANCH_DEVEL%%/${_pkg_repo_branch_devel}/g" \
1630
		-e "s/%%PKG_REPO_BRANCH_RELEASE%%/${_pkg_repo_branch_release}/g" \
1631
		-e "s,%%PKG_REPO_SERVER_DEVEL%%,${_pkg_repo_server_devel},g" \
1632
		-e "s,%%PKG_REPO_SERVER_RELEASE%%,${_pkg_repo_server_release},g" \
1633
		-e "s/%%PRODUCT_NAME%%/${PRODUCT_NAME}/g" \
1634
		${_template} \
1635
		> ${_target}
1636
}
1637

    
1638
# This routine ensures any ports / binaries that the builder
1639
# system needs are on disk and ready for execution.
1640
builder_setup() {
1641
	# If Product-builder is already installed, just leave
1642
	if pkg info -e -q ${PRODUCT_NAME}-builder; then
1643
		return
1644
	fi
1645

    
1646
	if [ ! -f ${PKG_REPO_PATH} ]; then
1647
		[ -d $(dirname ${PKG_REPO_PATH}) ] \
1648
			|| mkdir -p $(dirname ${PKG_REPO_PATH})
1649

    
1650
		update_freebsd_sources
1651

    
1652
		local _arch=$(uname -m)
1653
		setup_pkg_repo \
1654
			${PKG_REPO_DEFAULT} \
1655
			${PKG_REPO_PATH} \
1656
			${_arch} \
1657
			${_arch} \
1658
			"staging"
1659

    
1660
		# Use fingerprint keys from repo
1661
		sed -i '' -e "/fingerprints:/ s,\"/,\"${BUILDER_ROOT}/src/," \
1662
			${PKG_REPO_PATH}
1663
	fi
1664

    
1665
	pkg install ${PRODUCT_NAME}-builder
1666
}
1667

    
1668
# Updates FreeBSD sources
1669
update_freebsd_sources() {
1670
	if [ "${1}" = "full" ]; then
1671
		local _full=1
1672
		local _clone_params=""
1673
	else
1674
		local _full=0
1675
		local _clone_params="--depth 1 --single-branch"
1676
	fi
1677

    
1678
	if [ ! -d "${FREEBSD_SRC_DIR}" ]; then
1679
		mkdir -p ${FREEBSD_SRC_DIR}
1680
	fi
1681

    
1682
	if [ -n "${NO_BUILDWORLD}" -a -n "${NO_BUILDKERNEL}" ]; then
1683
		echo ">>> NO_BUILDWORLD and NO_BUILDKERNEL set, skipping update of freebsd sources" | tee -a ${LOGFILE}
1684
		return
1685
	fi
1686

    
1687
	echo -n ">>> Obtaining FreeBSD sources ${FREEBSD_BRANCH}..."
1688
	local _FREEBSD_BRANCH=${FREEBSD_BRANCH:-"devel"}
1689
	local _CLONE=1
1690

    
1691
	if [ -d "${FREEBSD_SRC_DIR}/.git" ]; then
1692
		CUR_BRANCH=$(cd ${FREEBSD_SRC_DIR} && git branch | grep '^\*' | cut -d' ' -f2)
1693
		if [ ${_full} -eq 0 -a "${CUR_BRANCH}" = "${_FREEBSD_BRANCH}" ]; then
1694
			_CLONE=0
1695
			( cd ${FREEBSD_SRC_DIR} && git clean -fd; git fetch origin; git reset --hard origin/${_FREEBSD_BRANCH} ) 2>&1 | grep -C3 -i -E 'error|fatal'
1696
		else
1697
			rm -rf ${FREEBSD_SRC_DIR}
1698
		fi
1699
	fi
1700

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

    
1705
	if [ ! -d "${FREEBSD_SRC_DIR}/.git" ]; then
1706
		echo ">>> ERROR: It was not possible to clone FreeBSD src repo"
1707
		print_error_pfS
1708
	fi
1709

    
1710
	if [ -n "${GIT_FREEBSD_COSHA1}" ]; then
1711
		( cd ${FREEBSD_SRC_DIR} && git checkout ${GIT_FREEBSD_COSHA1} ) 2>&1 | grep -C3 -i -E 'error|fatal'
1712
	fi
1713
	echo "Done!"
1714
}
1715

    
1716
pkg_chroot() {
1717
	local _root="${1}"
1718
	shift
1719

    
1720
	if [ $# -eq 0 ]; then
1721
		return -1
1722
	fi
1723

    
1724
	if [ -z "${_root}" -o "${_root}" = "/" -o ! -d "${_root}" ]; then
1725
		return -1
1726
	fi
1727

    
1728
	mkdir -p \
1729
		${SCRATCHDIR}/pkg_cache \
1730
		${_root}/var/cache/pkg \
1731
		${_root}/dev
1732

    
1733
	/sbin/mount -t nullfs ${SCRATCHDIR}/pkg_cache ${_root}/var/cache/pkg
1734
	/sbin/mount -t devfs devfs ${_root}/dev
1735
	cp -f /etc/resolv.conf ${_root}/etc/resolv.conf
1736
	touch ${BUILDER_LOGS}/install_pkg_install_ports.txt
1737
	local _params=""
1738
	if [ -f "${_root}/tmp/pkg-repos/repo.conf" ]; then
1739
		_params="--repo-conf-dir /tmp/pkg-repos "
1740
	fi
1741
	script -aq ${BUILDER_LOGS}/install_pkg_install_ports.txt \
1742
		pkg -c ${_root} ${_params}$@ >/dev/null 2>&1
1743
	local result=$?
1744
	rm -f ${_root}/etc/resolv.conf
1745
	/sbin/umount -f ${_root}/dev
1746
	/sbin/umount -f ${_root}/var/cache/pkg
1747

    
1748
	return $result
1749
}
1750

    
1751

    
1752
pkg_chroot_add() {
1753
	if [ -z "${1}" -o -z "${2}" ]; then
1754
		return 1
1755
	fi
1756

    
1757
	local _target="${1}"
1758
	local _pkg="$(get_pkg_name ${2}).txz"
1759

    
1760
	if [ ! -d "${_target}" ]; then
1761
		echo ">>> ERROR: Target dir ${_target} not found"
1762
		print_error_pfS
1763
	fi
1764

    
1765
	if [ ! -f ${CORE_PKG_ALL_PATH}/${_pkg} ]; then
1766
		echo ">>> ERROR: Package ${_pkg} not found"
1767
		print_error_pfS
1768
	fi
1769

    
1770
	cp ${CORE_PKG_ALL_PATH}/${_pkg} ${_target}
1771
	pkg_chroot ${_target} add /${_pkg}
1772
	rm -f ${_target}/${_pkg}
1773
}
1774

    
1775
pkg_bootstrap() {
1776
	local _root=${1:-"${STAGE_CHROOT_DIR}"}
1777

    
1778
	setup_pkg_repo \
1779
		${PKG_REPO_DEFAULT} \
1780
		${_root}${PKG_REPO_PATH} \
1781
		${TARGET} \
1782
		${TARGET_ARCH} \
1783
		"staging"
1784

    
1785
	pkg_chroot ${_root} bootstrap -f
1786
}
1787

    
1788
# This routine assists with installing various
1789
# freebsd ports files into the pfsense-fs staging
1790
# area.
1791
install_pkg_install_ports() {
1792
	local MAIN_PKG="${1}"
1793

    
1794
	if [ -z "${MAIN_PKG}" ]; then
1795
		MAIN_PKG=${PRODUCT_NAME}
1796
	fi
1797

    
1798
	echo ">>> Installing pkg repository in chroot (${STAGE_CHROOT_DIR})..."
1799

    
1800
	[ -d ${STAGE_CHROOT_DIR}/var/cache/pkg ] || \
1801
		mkdir -p ${STAGE_CHROOT_DIR}/var/cache/pkg
1802

    
1803
	[ -d ${SCRATCHDIR}/pkg_cache ] || \
1804
		mkdir -p ${SCRATCHDIR}/pkg_cache
1805

    
1806
	echo -n ">>> Installing built ports (packages) in chroot (${STAGE_CHROOT_DIR})... "
1807
	# First mark all packages as automatically installed
1808
	pkg_chroot ${STAGE_CHROOT_DIR} set -A 1 -a
1809
	# Install all necessary packages
1810
	if ! pkg_chroot ${STAGE_CHROOT_DIR} install ${MAIN_PKG} ${custom_package_list}; then
1811
		echo "Failed!"
1812
		print_error_pfS
1813
	fi
1814
	# Make sure required packages are set as non-automatic
1815
	pkg_chroot ${STAGE_CHROOT_DIR} set -A 0 pkg ${MAIN_PKG} ${custom_package_list}
1816
	# Remove unnecessary packages
1817
	pkg_chroot ${STAGE_CHROOT_DIR} autoremove
1818
	echo "Done!"
1819
}
1820

    
1821
install_bsdinstaller() {
1822
	local _params=""
1823

    
1824
	echo ">>> Installing BSDInstaller in chroot (${FINAL_CHROOT_DIR})... (starting)"
1825
	pkg_chroot ${FINAL_CHROOT_DIR} install -f bsdinstaller
1826
	sed -i '' -e "s,%%PRODUCT_NAME%%,${PRODUCT_NAME}," \
1827
		  -e "s,%%PRODUCT_VERSION%%,${PRODUCT_VERSION}," \
1828
		  -e "s,%%ARCH%%,${TARGET}," \
1829
		  ${FINAL_CHROOT_DIR}/usr/local/share/dfuibe_lua/conf/pfSense.lua \
1830
		  ${FINAL_CHROOT_DIR}/usr/local/share/dfuibe_lua/conf/pfSense_rescue.lua
1831
	echo ">>> Installing BSDInstaller in chroot (${FINAL_CHROOT_DIR})... (finished)"
1832
}
1833

    
1834
staginareas_clean_each_run() {
1835
	echo -n ">>> Cleaning build directories: "
1836
	if [ -d "${FINAL_CHROOT_DIR}" ]; then
1837
		BASENAME=$(basename ${FINAL_CHROOT_DIR})
1838
		echo -n "$BASENAME "
1839
		chflags -R noschg ${FINAL_CHROOT_DIR} 2>&1 >/dev/null
1840
		rm -rf ${FINAL_CHROOT_DIR}/* 2>/dev/null
1841
	fi
1842
	echo "Done!"
1843
}
1844

    
1845
# Imported from FreeSBIE
1846
buildkernel() {
1847
	if [ -n "${NO_BUILDKERNEL}" ]; then
1848
		echo ">>> NO_BUILDKERNEL set, skipping build" | tee -a ${LOGFILE}
1849
		return
1850
	fi
1851

    
1852
	if [ -z "${KERNCONF}" ]; then
1853
		echo ">>> ERROR: No kernel configuration defined probably this is not what you want! STOPPING!" | tee -a ${LOGFILE}
1854
		print_error_pfS
1855
	fi
1856

    
1857
	if [ -n "${KERNELCONF}" ]; then
1858
		export KERNCONFDIR=$(dirname ${KERNELCONF})
1859
		export KERNCONF=$(basename ${KERNELCONF})
1860
	fi
1861

    
1862
	SRCCONFBASENAME=$(basename ${SRC_CONF})
1863
	echo ">>> KERNCONFDIR: ${KERNCONFDIR}"
1864
	echo ">>> ARCH:        ${TARGET}"
1865
	echo ">>> SRC_CONF:    ${SRCCONFBASENAME}"
1866

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

    
1872
# Imported from FreeSBIE
1873
installkernel() {
1874
	if [ -z "${KERNCONF}" ]; then
1875
		echo ">>> ERROR: No kernel configuration defined probably this is not what you want! STOPPING!" | tee -a ${LOGFILE}
1876
		print_error_pfS
1877
	fi
1878

    
1879
	if [ -n "${KERNELCONF}" ]; then
1880
		export KERNCONFDIR=$(dirname ${KERNELCONF})
1881
		export KERNCONF=$(basename ${KERNELCONF})
1882
	fi
1883

    
1884
	mkdir -p ${STAGE_CHROOT_DIR}/boot
1885
	makeargs="${MAKEJ_KERNEL} SRCCONF=${SRC_CONF} __MAKE_CONF=${MAKE_CONF} TARGET_ARCH=${TARGET_ARCH} TARGET=${TARGET} DESTDIR=${KERNEL_DESTDIR}"
1886
	echo ">>> Builder is running the command: script -aq $LOGFILE make ${makeargs} installkernel KERNCONF=${KERNCONF}"  | tee -a $LOGFILE
1887
	(script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR} ${makeargs} installkernel KERNCONF=${KERNCONF} || print_error_pfS;) | egrep '^>>>'
1888
	gzip -f9 $KERNEL_DESTDIR/boot/kernel/kernel
1889
}
1890

    
1891
# Launch is ran first to setup a few variables that we need
1892
# Imported from FreeSBIE
1893
launch() {
1894
	if [ "$(id -u)" != "0" ]; then
1895
		echo "Sorry, this must be done as root."
1896
	fi
1897

    
1898
	echo ">>> Operation $0 has started at $(date)"
1899
}
1900

    
1901
finish() {
1902
	echo ">>> Operation $0 has ended at $(date)"
1903
}
1904

    
1905
pkg_repo_rsync() {
1906
	local _repo_path_param="${1}"
1907
	local _ignore_final_rsync="${2}"
1908

    
1909
	if [ -z "${_repo_path_param}" -o ! -d "${_repo_path_param}" ]; then
1910
		return
1911
	fi
1912

    
1913
	if [ -n "${SKIP_FINAL_RSYNC}" ]; then
1914
		_ignore_final_rsync="1"
1915
	fi
1916

    
1917
	# Sanitize path
1918
	_repo_path=$(realpath ${_repo_path_param})
1919

    
1920
	local _repo_dir=$(dirname ${_repo_path})
1921
	local _repo_base=$(basename ${_repo_path})
1922

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

    
1926
	if [ -z "${LOGFILE}" ]; then
1927
		local _logfile="/dev/null"
1928
	else
1929
		local _logfile="${LOGFILE}"
1930
	fi
1931

    
1932
	if [ -n "${PKG_REPO_SIGNING_COMMAND}" -a -z "${DO_NOT_SIGN_PKG_REPO}" ]; then
1933
		# Detect poudriere directory structure
1934
		if [ -L "${_repo_path}/.latest" ]; then
1935
			local _real_repo_path=$(readlink -f ${_repo_path}/.latest)
1936
		else
1937
			local _real_repo_path=${_repo_path}
1938
		fi
1939

    
1940
		echo -n ">>> Signing repository... " | tee -a ${_logfile}
1941
		############ ATTENTION ##############
1942
		#
1943
		# For some reason pkg-repo fail without / in the end of directory name
1944
		# so removing it will break command
1945
		#
1946
		# https://github.com/freebsd/pkg/issues/1364
1947
		#
1948
		if script -aq ${_logfile} pkg repo ${_real_repo_path}/ \
1949
		    signing_command: ${PKG_REPO_SIGNING_COMMAND} >/dev/null 2>&1; then
1950
			echo "Done!" | tee -a ${_logfile}
1951
		else
1952
			echo "Failed!" | tee -a ${_logfile}
1953
			echo ">>> ERROR: An error occurred trying to sign repo"
1954
			print_error_pfS
1955
		fi
1956

    
1957
		local _pkgfile="${_repo_path}/Latest/pkg.txz"
1958
		if [ -e ${_pkgfile} ]; then
1959
			echo -n ">>> Signing Latest/pkg.txz for bootstraping... " | tee -a ${_logfile}
1960

    
1961
			if sha256 -q ${_pkgfile} | ${PKG_REPO_SIGNING_COMMAND} \
1962
			    > ${_pkgfile}.sig 2>/dev/null; then
1963
				echo "Done!" | tee -a ${_logfile}
1964
			else
1965
				echo "Failed!" | tee -a ${_logfile}
1966
				echo ">>> ERROR: An error occurred trying to sign Latest/pkg.txz"
1967
				print_error_pfS
1968
			fi
1969
		fi
1970
	fi
1971

    
1972
	if [ -n "${DO_NOT_UPLOAD}" ]; then
1973
		return
1974
	fi
1975

    
1976
	for _pkg_rsync_hostname in ${PKG_RSYNC_HOSTNAME}; do
1977
		# Make sure destination directory exist
1978
		ssh -p ${PKG_RSYNC_SSH_PORT} \
1979
			${PKG_RSYNC_USERNAME}@${_pkg_rsync_hostname} \
1980
			"mkdir -p ${PKG_RSYNC_DESTDIR}"
1981

    
1982
		echo -n ">>> Sending updated repository to ${_pkg_rsync_hostname}... " | tee -a ${_logfile}
1983
		if script -aq ${_logfile} rsync -Have "ssh -p ${PKG_RSYNC_SSH_PORT}" \
1984
			--timeout=60 --delete-delay ${_repo_path} \
1985
			${PKG_RSYNC_USERNAME}@${_pkg_rsync_hostname}:${PKG_RSYNC_DESTDIR} >/dev/null 2>&1
1986
		then
1987
			echo "Done!" | tee -a ${_logfile}
1988
		else
1989
			echo "Failed!" | tee -a ${_logfile}
1990
			echo ">>> ERROR: An error occurred sending repo to remote hostname"
1991
			print_error_pfS
1992
		fi
1993

    
1994
		if [ -z "${USE_PKG_REPO_STAGING}" -o -n "${_ignore_final_rsync}" ]; then
1995
			return
1996
		fi
1997

    
1998
		if [ -n "${_IS_RELEASE}" -o "${_repo_path_param}" = "${CORE_PKG_PATH}" ]; then
1999
			for _pkg_final_rsync_hostname in ${PKG_FINAL_RSYNC_HOSTNAME}; do
2000
				# Send .real* directories first to prevent having a broken repo while transfer happens
2001
				local _cmd="rsync -Have \"ssh -p ${PKG_FINAL_RSYNC_SSH_PORT}\" \
2002
					--timeout=60 ${PKG_RSYNC_DESTDIR}/./${_repo_base%%-core}* \
2003
					--include=\"/*\" --include=\"*/.real*\" --include=\"*/.real*/***\" \
2004
					--exclude=\"*\" \
2005
					${PKG_FINAL_RSYNC_USERNAME}@${_pkg_final_rsync_hostname}:${PKG_FINAL_RSYNC_DESTDIR}"
2006

    
2007
				echo -n ">>> Sending updated packages to ${_pkg_final_rsync_hostname}... " | tee -a ${_logfile}
2008
				if script -aq ${_logfile} ssh -p ${PKG_RSYNC_SSH_PORT} \
2009
					${PKG_RSYNC_USERNAME}@${_pkg_rsync_hostname} ${_cmd} >/dev/null 2>&1; then
2010
					echo "Done!" | tee -a ${_logfile}
2011
				else
2012
					echo "Failed!" | tee -a ${_logfile}
2013
					echo ">>> ERROR: An error occurred sending repo to final hostname"
2014
					print_error_pfS
2015
				fi
2016

    
2017
				_cmd="rsync -Have \"ssh -p ${PKG_FINAL_RSYNC_SSH_PORT}\" \
2018
					--timeout=60 --delete-delay ${PKG_RSYNC_DESTDIR}/./${_repo_base%%-core}* \
2019
					${PKG_FINAL_RSYNC_USERNAME}@${_pkg_final_rsync_hostname}:${PKG_FINAL_RSYNC_DESTDIR}"
2020

    
2021
				echo -n ">>> Sending updated repositories metadata to ${_pkg_final_rsync_hostname}... " | tee -a ${_logfile}
2022
				if script -aq ${_logfile} ssh -p ${PKG_RSYNC_SSH_PORT} \
2023
					${PKG_RSYNC_USERNAME}@${_pkg_rsync_hostname} ${_cmd} >/dev/null 2>&1; then
2024
					echo "Done!" | tee -a ${_logfile}
2025
				else
2026
					echo "Failed!" | tee -a ${_logfile}
2027
					echo ">>> ERROR: An error occurred sending repo to final hostname"
2028
					print_error_pfS
2029
				fi
2030
			done
2031
		fi
2032
	done
2033
}
2034

    
2035
poudriere_create_patch() {
2036
	local _jail_patch="${SCRATCHDIR}/poudriere_jail.${POUDRIERE_BRANCH}.patch"
2037

    
2038
	if [ -z "${FREEBSD_PARENT_BRANCH}" ]; then
2039
		echo ">>> ERROR: FREEBSD_PARENT_BRANCH is not set"
2040
	fi
2041

    
2042
	LOGFILE=${BUILDER_LOGS}/poudriere.log
2043

    
2044
	# Get FreeBSD source and apply patches
2045
	update_freebsd_sources full
2046

    
2047
	[ -f "${_jail_patch}" ] && \
2048
		rm -f "${_jail_patch}"
2049

    
2050
	# Create a big patch with all our changes to use on jail
2051
	( \
2052
		cd ${FREEBSD_SRC_DIR} && \
2053
		git diff $(git merge-base origin/${FREEBSD_PARENT_BRANCH} ${FREEBSD_BRANCH}) > ${_jail_patch}
2054
	) >/dev/null 2>&1
2055

    
2056
	# Check if patch was created
2057
	if [ ! -s "${_jail_patch}" ]; then
2058
		echo ">>> ERROR: Patch does not exist or is empty, aborting..." | tee -a ${LOGFILE}
2059
		print_error_pfS
2060
	fi
2061
}
2062

    
2063
poudriere_possible_archs() {
2064
	local _arch=$(uname -m)
2065
	local _archs="i386.i386"
2066

    
2067
	# If host is amd64, we'll create both repos, and if possible armv6
2068
	if [ "${_arch}" = "amd64" ]; then
2069
		_archs="amd64.amd64 ${_archs}"
2070

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

    
2075
			if binmiscctl lookup armv6 >/dev/null 2>&1; then
2076
				_archs="${_archs} arm.armv6"
2077
			fi
2078
		fi
2079
	fi
2080

    
2081
	if [ -n "${ARCH_LIST}" ]; then
2082
		local _found=0
2083
		for _desired_arch in ${ARCH_LIST}; do
2084
			_found=0
2085
			for _possible_arch in ${_archs}; do
2086
				if [ "${_desired_arch}" = "${_possible_arch}" ]; then
2087
					_found=1
2088
					break
2089
				fi
2090
			done
2091
			if [ ${_found} -eq 0 ]; then
2092
				echo ">>> ERROR: Impossible to build for arch: ${_desired_arch}"
2093
				print_error_pfS
2094
			fi
2095
		done
2096
		_archs="${ARCH_LIST}"
2097
	fi
2098

    
2099
	echo ${_archs}
2100
}
2101

    
2102
poudriere_jail_name() {
2103
	local _jail_arch="${1}"
2104

    
2105
	if [ -z "${_jail_arch}" ]; then
2106
		return 1
2107
	fi
2108

    
2109
	# Remove arch
2110
	echo "${PRODUCT_NAME}_${POUDRIERE_BRANCH}_${_jail_arch##*.}"
2111
}
2112

    
2113
poudriere_rename_ports() {
2114
	if [ "${PRODUCT_NAME}" = "pfSense" ]; then
2115
		return;
2116
	fi
2117

    
2118
	LOGFILE=${BUILDER_LOGS}/poudriere.log
2119

    
2120
	local _ports_dir="/usr/local/poudriere/ports/${POUDRIERE_PORTS_NAME}"
2121

    
2122
	echo -n ">>> Renaming product ports on ${POUDRIERE_PORTS_NAME}... " | tee -a ${LOGFILE}
2123
	for d in $(find ${_ports_dir} -depth 2 -type d -name '*pfSense*'); do
2124
		local _pdir=$(dirname ${d})
2125
		local _pname=$(echo $(basename ${d}) | sed "s,pfSense,${PRODUCT_NAME},")
2126
		local _plist=""
2127

    
2128
		if [ -e ${_pdir}/${_pname} ]; then
2129
			rm -rf ${_pdir}/${_pname}
2130
		fi
2131

    
2132
		cp -r ${d} ${_pdir}/${_pname}
2133

    
2134
		if [ -f ${_pdir}/${_pname}/pkg-plist ]; then
2135
			_plist=${_pdir}/${_pname}/pkg-plist
2136
		fi
2137

    
2138
		sed -i '' -e "s,pfSense,${PRODUCT_NAME},g" \
2139
			  -e "s,https://www.pfsense.org,${PRODUCT_URL},g" \
2140
			  -e "/^MAINTAINER=/ s,^.*$,MAINTAINER=	${PRODUCT_EMAIL}," \
2141
			${_pdir}/${_pname}/Makefile \
2142
			${_pdir}/${_pname}/pkg-descr ${_plist}
2143

    
2144
		# PHP module is special
2145
		if echo "${_pname}" | grep -q "^php[0-9]*-${PRODUCT_NAME}-module"; then
2146
			local _product_capital=$(echo ${PRODUCT_NAME} | tr '[a-z]' '[A-Z]')
2147
			sed -i '' -e "s,PHP_PFSENSE,PHP_${_product_capital},g" \
2148
				  -e "s,PFSENSE_SHARED_LIBADD,${_product_capital}_SHARED_LIBADD,g" \
2149
				  -e "s,pfSense,${PRODUCT_NAME},g" \
2150
				  -e "s,${PRODUCT_NAME}\.c,pfSense.c,g" \
2151
				${_pdir}/${_pname}/files/config.m4
2152

    
2153
			sed -i '' -e "s,COMPILE_DL_PFSENSE,COMPILE_DL_${_product_capital}," \
2154
				  -e "s,pfSense_module_entry,${PRODUCT_NAME}_module_entry,g" \
2155
				  -e "/ZEND_GET_MODULE/ s,pfSense,${PRODUCT_NAME}," \
2156
				  -e "/PHP_PFSENSE_WORLD_EXTNAME/ s,pfSense,${PRODUCT_NAME}," \
2157
				${_pdir}/${_pname}/files/pfSense.c \
2158
				${_pdir}/${_pname}/files/php_pfSense.h
2159
		fi
2160

    
2161
		if [ -d ${_pdir}/${_pname}/files ]; then
2162
			for fd in $(find ${_pdir}/${_pname}/files -type d -name '*pfSense*'); do
2163
				local _fddir=$(dirname ${fd})
2164
				local _fdname=$(echo $(basename ${fd}) | sed "s,pfSense,${PRODUCT_NAME},")
2165

    
2166
				mv ${fd} ${_fddir}/${_fdname}
2167
			done
2168
		fi
2169
	done
2170
	echo "Done!" | tee -a ${LOGFILE}
2171
}
2172

    
2173
poudriere_create_ports_tree() {
2174
	LOGFILE=${BUILDER_LOGS}/poudriere.log
2175

    
2176
	if ! poudriere ports -l | grep -q -E "^${POUDRIERE_PORTS_NAME}[[:blank:]]"; then
2177
		local _branch=""
2178
		if [ -z "${POUDRIERE_PORTS_GIT_URL}" ]; then
2179
			echo ">>> ERROR: POUDRIERE_PORTS_GIT_URL is not defined"
2180
			print_error_pfS
2181
		fi
2182
		if [ -n "${POUDRIERE_PORTS_GIT_BRANCH}" ]; then
2183
			_branch="-B ${POUDRIERE_PORTS_GIT_BRANCH}"
2184
		fi
2185
		echo -n ">>> Creating poudriere ports tree, it may take some time... " | tee -a ${LOGFILE}
2186
		if ! script -aq ${LOGFILE} poudriere ports -c -p "${POUDRIERE_PORTS_NAME}" -m git ${_branch} >/dev/null 2>&1; then
2187
			echo "" | tee -a ${LOGFILE}
2188
			echo ">>> ERROR: Error creating poudriere ports tree, aborting..." | tee -a ${LOGFILE}
2189
			print_error_pfS
2190
		fi
2191
		echo "Done!" | tee -a ${LOGFILE}
2192
		poudriere_rename_ports
2193
	fi
2194
}
2195

    
2196
poudriere_init() {
2197
	local _error=0
2198
	local _archs=$(poudriere_possible_archs)
2199
	local _jail_patch="${SCRATCHDIR}/poudriere_jail.${POUDRIERE_BRANCH}.patch"
2200

    
2201
	LOGFILE=${BUILDER_LOGS}/poudriere.log
2202

    
2203
	# Sanity checks
2204
	if [ -z "${ZFS_TANK}" ]; then
2205
		echo ">>> ERROR: \$ZFS_TANK is empty" | tee -a ${LOGFILE}
2206
		error=1
2207
	fi
2208

    
2209
	if [ -z "${ZFS_ROOT}" ]; then
2210
		echo ">>> ERROR: \$ZFS_ROOT is empty" | tee -a ${LOGFILE}
2211
		error=1
2212
	fi
2213

    
2214
	if [ -z "${POUDRIERE_PORTS_NAME}" ]; then
2215
		echo ">>> ERROR: \$POUDRIERE_PORTS_NAME is empty" | tee -a ${LOGFILE}
2216
		error=1
2217
	fi
2218

    
2219
	if [ ${_error} -eq 1 ]; then
2220
		print_error_pfS
2221
	fi
2222

    
2223
	# Check if zpool exists
2224
	if ! zpool list ${ZFS_TANK} >/dev/null 2>&1; then
2225
		echo ">>> ERROR: ZFS tank ${ZFS_TANK} not found, please create it and try again..." | tee -a ${LOGFILE}
2226
		print_error_pfS
2227
	fi
2228

    
2229
	# Check if zfs rootfs exists
2230
	if ! zfs list ${ZFS_TANK}${ZFS_ROOT} >/dev/null 2>&1; then
2231
		echo -n ">>> Creating ZFS filesystem ${ZFS_TANK}${ZFS_ROOT}... "
2232
		if zfs create -o atime=off -o mountpoint=/usr/local${ZFS_ROOT} \
2233
		    ${ZFS_TANK}${ZFS_ROOT} >/dev/null 2>&1; then
2234
			echo "Done!"
2235
		else
2236
			echo "Failed!"
2237
			print_error_pfS
2238
		fi
2239
	fi
2240

    
2241
	# Make sure poudriere is installed
2242
	if ! pkg info --quiet poudriere; then
2243
		echo ">>> Installing poudriere..." | tee -a ${LOGFILE}
2244
		if ! pkg install poudriere >/dev/null 2>&1; then
2245
			echo ">>> ERROR: poudriere was not installed, aborting..." | tee -a ${LOGFILE}
2246
			print_error_pfS
2247
		fi
2248
	fi
2249

    
2250
	# Create poudriere.conf
2251
	if [ -z "${POUDRIERE_PORTS_GIT_URL}" ]; then
2252
		echo ">>> ERROR: POUDRIERE_PORTS_GIT_URL is not defined"
2253
		print_error_pfS
2254
	fi
2255
	echo ">>> Creating poudriere.conf" | tee -a ${LOGFILE}
2256
	cat <<EOF >/usr/local/etc/poudriere.conf
2257
ZPOOL=${ZFS_TANK}
2258
ZROOTFS=${ZFS_ROOT}
2259
RESOLV_CONF=/etc/resolv.conf
2260
BASEFS=/usr/local/poudriere
2261
USE_PORTLINT=no
2262
USE_TMPFS=yes
2263
NOLINUX=yes
2264
DISTFILES_CACHE=/usr/ports/distfiles
2265
CHECK_CHANGED_OPTIONS=yes
2266
CHECK_CHANGED_DEPS=yes
2267
ATOMIC_PACKAGE_REPOSITORY=yes
2268
COMMIT_PACKAGES_ON_FAILURE=no
2269
KEEP_OLD_PACKAGES=yes
2270
KEEP_OLD_PACKAGES_COUNT=5
2271
EOF
2272

    
2273
	# Create specific items conf
2274
	[ ! -d /usr/local/etc/poudriere.d ] \
2275
		&& mkdir -p /usr/local/etc/poudriere.d
2276

    
2277
	cat <<EOF >/usr/local/etc/poudriere.d/${POUDRIERE_PORTS_NAME}-poudriere.conf
2278
GIT_URL="${POUDRIERE_PORTS_GIT_URL}"
2279
EOF
2280

    
2281
	# Create DISTFILES_CACHE if it doesn't exist
2282
	if [ ! -d /usr/ports/distfiles ]; then
2283
		mkdir -p /usr/ports/distfiles
2284
	fi
2285

    
2286
	# Remove old jails
2287
	for jail_arch in ${_archs}; do
2288
		jail_name=$(poudriere_jail_name ${jail_arch})
2289

    
2290
		if poudriere jail -i -j "${jail_name}" >/dev/null 2>&1; then
2291
			echo ">>> Poudriere jail ${jail_name} already exists, deleting it..." | tee -a ${LOGFILE}
2292
			poudriere jail -d -j "${jail_name}" >/dev/null 2>&1
2293
		fi
2294
	done
2295

    
2296
	# Remove old ports tree
2297
	if poudriere ports -l | grep -q -E "^${POUDRIERE_PORTS_NAME}[[:blank:]]"; then
2298
		echo ">>> Poudriere ports tree ${POUDRIERE_PORTS_NAME} already exists, deleting it..." | tee -a ${LOGFILE}
2299
		poudriere ports -d -p "${POUDRIERE_PORTS_NAME}"
2300
	fi
2301

    
2302
	poudriere_create_patch
2303

    
2304
	local native_xtools=""
2305
	# Now we are ready to create jails
2306
	for jail_arch in ${_archs}; do
2307
		jail_name=$(poudriere_jail_name ${jail_arch})
2308

    
2309
		if [ "${jail_arch}" = "arm.armv6" ]; then
2310
			native_xtools="-x"
2311
		else
2312
			native_xtools=""
2313
		fi
2314

    
2315
		echo -n ">>> Creating jail ${jail_name}, it may take some time... " | tee -a ${LOGFILE}
2316
		# XXX: Change -m to git when it's available in poudriere
2317
		if ! script -aq ${LOGFILE} poudriere jail -c -j "${jail_name}" -v ${FREEBSD_PARENT_BRANCH} \
2318
				-a ${jail_arch} -m svn -P ${_jail_patch} ${native_xtools} >/dev/null 2>&1; then
2319
			echo "" | tee -a ${LOGFILE}
2320
			echo ">>> ERROR: Error creating jail ${jail_name}, aborting..." | tee -a ${LOGFILE}
2321
			print_error_pfS
2322
		fi
2323
		echo "Done!" | tee -a ${LOGFILE}
2324
	done
2325

    
2326
	poudriere_create_ports_tree
2327

    
2328
	echo ">>> Poudriere is now configured!" | tee -a ${LOGFILE}
2329
}
2330

    
2331
poudriere_update_jails() {
2332
	local _archs=$(poudriere_possible_archs)
2333
	local _jail_patch="${SCRATCHDIR}/poudriere_jail.${POUDRIERE_BRANCH}.patch"
2334

    
2335
	LOGFILE=${BUILDER_LOGS}/poudriere.log
2336

    
2337
	poudriere_create_patch
2338

    
2339
	local native_xtools=""
2340
	for jail_arch in ${_archs}; do
2341
		jail_name=$(poudriere_jail_name ${jail_arch})
2342

    
2343
		local _create_or_update="-u"
2344
		local _create_or_update_text="Updating"
2345
		if ! poudriere jail -i -j "${jail_name}" >/dev/null 2>&1; then
2346
			echo ">>> Poudriere jail ${jail_name} not found, creating..." | tee -a ${LOGFILE}
2347
			_create_or_update="-c -v ${FREEBSD_PARENT_BRANCH} -a ${jail_arch} -m svn"
2348
			_create_or_update_text="Creating"
2349
		fi
2350

    
2351
		if [ "${jail_arch}" = "arm.armv6" ]; then
2352
			native_xtools="-x"
2353
		else
2354
			native_xtools=""
2355
		fi
2356

    
2357
		echo -n ">>> ${_create_or_update_text} jail ${jail_name}, it may take some time... " | tee -a ${LOGFILE}
2358
		if ! script -aq ${LOGFILE} poudriere jail ${_create_or_update} -j "${jail_name}" -P ${_jail_patch} ${native_xtools} >/dev/null 2>&1; then
2359
			echo "" | tee -a ${LOGFILE}
2360
			echo ">>> ERROR: Error ${_create_or_update_text} jail ${jail_name}, aborting..." | tee -a ${LOGFILE}
2361
			print_error_pfS
2362
		fi
2363
		echo "Done!" | tee -a ${LOGFILE}
2364
	done
2365
}
2366

    
2367
poudriere_update_ports() {
2368
	LOGFILE=${BUILDER_LOGS}/poudriere.log
2369

    
2370
	# Create ports tree if necessary
2371
	if ! poudriere ports -l | grep -q -E "^${POUDRIERE_PORTS_NAME}[[:blank:]]"; then
2372
		poudriere_create_ports_tree
2373
	else
2374
		echo -n ">>> Resetting local changes on ports tree ${POUDRIERE_PORTS_NAME}... " | tee -a ${LOGFILE}
2375
		script -aq ${LOGFILE} git -C "/usr/local/poudriere/ports/${POUDRIERE_PORTS_NAME}" reset --hard >/dev/null 2>&1
2376
		script -aq ${LOGFILE} git -C "/usr/local/poudriere/ports/${POUDRIERE_PORTS_NAME}" clean -fd >/dev/null 2>&1
2377
		echo "Done!" | tee -a ${LOGFILE}
2378
		echo -n ">>> Updating ports tree ${POUDRIERE_PORTS_NAME}... " | tee -a ${LOGFILE}
2379
		script -aq ${LOGFILE} poudriere ports -u -p "${POUDRIERE_PORTS_NAME}" >/dev/null 2>&1
2380
		echo "Done!" | tee -a ${LOGFILE}
2381
		poudriere_rename_ports
2382
	fi
2383
}
2384

    
2385
poudriere_bulk() {
2386
	local _archs=$(poudriere_possible_archs)
2387

    
2388
	LOGFILE=${BUILDER_LOGS}/poudriere.log
2389

    
2390
	if [ -z "${DO_NOT_UPLOAD}" -a -z "${PKG_RSYNC_HOSTNAME}" ]; then
2391
		echo ">>> ERROR: PKG_RSYNC_HOSTNAME is not set"
2392
		print_error_pfS
2393
	fi
2394

    
2395
	rm -f ${LOGFILE}
2396

    
2397
	poudriere_create_ports_tree
2398

    
2399
	[ -d /usr/local/etc/poudriere.d ] || \
2400
		mkdir -p /usr/local/etc/poudriere.d
2401

    
2402
	if [ -f "${BUILDER_TOOLS}/conf/pfPorts/make.conf" ]; then
2403
		cp -f "${BUILDER_TOOLS}/conf/pfPorts/make.conf" \
2404
			/usr/local/etc/poudriere.d/${POUDRIERE_PORTS_NAME}-make.conf
2405
	fi
2406

    
2407
	cat <<EOF >>/usr/local/etc/poudriere.d/${POUDRIERE_PORTS_NAME}-make.conf
2408
PKG_REPO_BRANCH_DEVEL=${PKG_REPO_BRANCH_DEVEL}
2409
PKG_REPO_BRANCH_RELEASE=${PKG_REPO_BRANCH_RELEASE}
2410
PKG_REPO_SERVER_DEVEL=${PKG_REPO_SERVER_DEVEL}
2411
PKG_REPO_SERVER_RELEASE=${PKG_REPO_SERVER_RELEASE}
2412
POUDRIERE_PORTS_NAME=${POUDRIERE_PORTS_NAME}
2413
PRODUCT_NAME=${PRODUCT_NAME}
2414
EOF
2415

    
2416
	# Change version of pfSense meta ports for snapshots
2417
	if [ -z "${_IS_RELEASE}" ]; then
2418
		local _meta_pkg_version="$(echo "${PRODUCT_VERSION}" | sed 's,DEVELOPMENT,ALPHA,')-${DATESTRING}"
2419
		sed -i '' \
2420
			-e "/^DISTVERSION/ s,^.*,DISTVERSION=	${_meta_pkg_version}," \
2421
			-e "/^PORTREVISION=/d" \
2422
			/usr/local/poudriere/ports/${POUDRIERE_PORTS_NAME}/security/${PRODUCT_NAME}/Makefile \
2423
			/usr/local/poudriere/ports/${POUDRIERE_PORTS_NAME}/sysutils/${PRODUCT_NAME}-repo/Makefile
2424
	fi
2425

    
2426
	# Copy over pkg repo templates to pfSense-repo
2427
	mkdir -p /usr/local/poudriere/ports/${POUDRIERE_PORTS_NAME}/sysutils/${PRODUCT_NAME}-repo/files
2428
	cp -f ${PKG_REPO_BASE}/* \
2429
		/usr/local/poudriere/ports/${POUDRIERE_PORTS_NAME}/sysutils/${PRODUCT_NAME}-repo/files
2430

    
2431
	for jail_arch in ${_archs}; do
2432
		jail_name=$(poudriere_jail_name ${jail_arch})
2433

    
2434
		if ! poudriere jail -i -j "${jail_name}" >/dev/null 2>&1; then
2435
			echo ">>> Poudriere jail ${jail_name} not found, skipping..." | tee -a ${LOGFILE}
2436
			continue
2437
		fi
2438

    
2439
		if [ -f "${POUDRIERE_BULK}.${jail_arch}" ]; then
2440
			_ref_bulk="${POUDRIERE_BULK}.${jail_arch}"
2441
		else
2442
			_ref_bulk="${POUDRIERE_BULK}"
2443
		fi
2444

    
2445
		_bulk=${SCRATCHDIR}/poudriere_bulk.${POUDRIERE_BRANCH}
2446
		sed -e "s,%%PRODUCT_NAME%%,${PRODUCT_NAME},g" ${_ref_bulk} > ${_bulk}
2447

    
2448
		local _exclude_bulk="${POUDRIERE_BULK}.exclude.${jail_arch}"
2449
		if [ -f "${_exclude_bulk}" ]; then
2450
			mv ${_bulk} ${_bulk}.tmp
2451
			sed -e "s,%%PRODUCT_NAME%%,${PRODUCT_NAME},g" ${_exclude_bulk} > ${_bulk}.exclude
2452
			cat ${_bulk}.tmp ${_bulk}.exclude | sort | uniq -u > ${_bulk}
2453
			rm -f ${_bulk}.tmp ${_bulk}.exclude
2454
		fi
2455

    
2456
		if ! poudriere bulk -f ${_bulk} -j ${jail_name} -p ${POUDRIERE_PORTS_NAME}; then
2457
			echo ">>> ERROR: Something went wrong..."
2458
			print_error_pfS
2459
		fi
2460

    
2461
		echo ">>> Cleaning up old packages from repo..."
2462
		if ! poudriere pkgclean -f ${_bulk} -j ${jail_name} -p ${POUDRIERE_PORTS_NAME} -y; then
2463
			echo ">>> ERROR: Something went wrong..."
2464
			print_error_pfS
2465
		fi
2466

    
2467
		pkg_repo_rsync "/usr/local/poudriere/data/packages/${jail_name}-${POUDRIERE_PORTS_NAME}"
2468
	done
2469
}
2470

    
2471
# This routine is called to write out to stdout
2472
# a string. The string is appended to $SNAPSHOTSLOGFILE
2473
snapshots_update_status() {
2474
	if [ -z "$1" ]; then
2475
		return
2476
	fi
2477
	if [ -z "${SNAPSHOTS}" -a -z "${POUDRIERE_SNAPSHOTS}" ]; then
2478
		return
2479
	fi
2480
	echo "$*"
2481
	echo "`date` -|- $*" >> $SNAPSHOTSLOGFILE
2482
}
2483

    
2484
create_sha256() {
2485
	local _file="${1}"
2486

    
2487
	if [ ! -f "${_file}" ]; then
2488
		return 1
2489
	fi
2490

    
2491
	( \
2492
		cd $(dirname ${_file}) && \
2493
		sha256 $(basename ${_file}) > $(basename ${_file}).sha256 \
2494
	)
2495
}
2496

    
2497
snapshots_create_latest_symlink() {
2498
	local _image="${1}"
2499

    
2500
	if [ -z "${_image}" ]; then
2501
		return
2502
	fi
2503

    
2504
	if [ -z "${TIMESTAMP_SUFFIX}" ]; then
2505
		return
2506
	fi
2507

    
2508
	if [ ! -f "${_image}" ]; then
2509
		return
2510
	fi
2511

    
2512
	local _symlink=$(echo ${_image} | sed "s,${TIMESTAMP_SUFFIX},-latest,")
2513
	ln -sf $(basename ${_image}) ${_symlink}
2514
	ln -sf $(basename ${_image}).sha256 ${_symlink}.sha256
2515
}
2516

    
2517
snapshots_copy_to_staging_nanobsd() {
2518
	for NANOTYPE in nanobsd nanobsd-vga; do
2519
		for FILESIZE in ${1}; do
2520
			FILENAMEFULL="$(nanobsd_image_filename ${FILESIZE} ${NANOTYPE}).gz"
2521
			FILENAMEUPGRADE="$(nanobsd_image_filename ${FILESIZE} ${NANOTYPE} 1).gz"
2522
			mkdir -p $STAGINGAREA/nanobsd
2523
			mkdir -p $STAGINGAREA/nanobsdupdates
2524

    
2525
			cp -l $IMAGES_FINAL_DIR/$FILENAMEFULL $STAGINGAREA/nanobsd/ 2>/dev/null
2526
			cp -l $IMAGES_FINAL_DIR/$FILENAMEUPGRADE $STAGINGAREA/nanobsdupdates 2>/dev/null
2527

    
2528
			if [ -f $STAGINGAREA/nanobsd/$FILENAMEFULL ]; then
2529
				create_sha256 $STAGINGAREA/nanobsd/$FILENAMEFULL
2530
			fi
2531
			if [ -f $STAGINGAREA/nanobsdupdates/$FILENAMEUPGRADE ]; then
2532
				create_sha256 $STAGINGAREA/nanobsdupdates/$FILENAMEUPGRADE
2533
			fi
2534

    
2535
			# Copy NanoBSD auto update:
2536
			if [ -f $STAGINGAREA/nanobsdupdates/$FILENAMEUPGRADE ]; then
2537
				cp -l $STAGINGAREA/nanobsdupdates/$FILENAMEUPGRADE $STAGINGAREA/latest-${NANOTYPE}-$FILESIZE.img.gz 2>/dev/null
2538
				create_sha256 $STAGINGAREA/latest-${NANOTYPE}-$FILESIZE.img.gz
2539
				# NOTE: Updates need a file with output similar to date output
2540
				# Use the file generated at start of snapshots_dobuilds() to be consistent on times
2541
				cp $BUILTDATESTRINGFILE $STAGINGAREA/version-${NANOTYPE}-$FILESIZE
2542
			fi
2543
		done
2544
	done
2545
}
2546

    
2547
snapshots_copy_to_staging_iso_updates() {
2548
	local _img=""
2549

    
2550
	for _img in ${ISOPATH} ${MEMSTICKPATH} ${MEMSTICKSERIALPATH} ${MEMSTICKADIPATH} ${VARIANTIMAGES}; do
2551
		if [ ! -f "${_img}.gz" ]; then
2552
			continue
2553
		fi
2554
		_img="${_img}.gz"
2555
		create_sha256 ${_img}
2556
		cp -l ${_img}* $STAGINGAREA/ 2>/dev/null
2557
		snapshots_create_latest_symlink ${STAGINGAREA}/$(basename ${_img})
2558
	done
2559

    
2560
	for _img in ${UPDATES_TARBALL_FILENAME} ${VARIANTUPDATES}; do
2561
		if [ -f "${_img}" ]; then
2562
			create_sha256 ${_img}
2563
			cp -l ${_img}* $STAGINGAREA/ 2>/dev/null
2564
			snapshots_create_latest_symlink ${STAGINGAREA}/$(basename ${_img})
2565
		fi
2566
	done
2567

    
2568
	if [ -f "${OVAPATH}" ]; then
2569
		mkdir -p ${STAGINGAREA}/virtualization
2570
		create_sha256 ${OVAPATH}
2571
		cp -l ${OVAPATH}* $STAGINGAREA/virtualization 2>/dev/null
2572
		snapshots_create_latest_symlink ${STAGINGAREA}/virtualization/$(basename ${OVAPATH})
2573
	fi
2574

    
2575
	# NOTE: Updates need a file with output similar to date output
2576
	# Use the file generated at start of snapshots_dobuilds() to be consistent on times
2577
	if [ -z "${_IS_RELEASE}" ]; then
2578
		cp $BUILTDATESTRINGFILE $STAGINGAREA/version 2>/dev/null
2579
	fi
2580
}
2581

    
2582
snapshots_scp_files() {
2583
	if [ -z "${RSYNC_COPY_ARGUMENTS}" ]; then
2584
		RSYNC_COPY_ARGUMENTS="-ave ssh --timeout=60"
2585
	fi
2586

    
2587
	snapshots_update_status ">>> Copying core pkg repo to ${PKG_RSYNC_HOSTNAME}"
2588
	pkg_repo_rsync "${CORE_PKG_PATH}"
2589
	snapshots_update_status ">>> Finished copying core pkg repo"
2590

    
2591
	for _rsyncip in ${RSYNCIP}; do
2592
		snapshots_update_status ">>> Copying files to ${_rsyncip}"
2593

    
2594
		# Ensure directory(s) are available
2595
		ssh ${RSYNCUSER}@${_rsyncip} "mkdir -p ${RSYNCPATH}/installer"
2596
		ssh ${RSYNCUSER}@${_rsyncip} "mkdir -p ${RSYNCPATH}/updates"
2597
		ssh ${RSYNCUSER}@${_rsyncip} "mkdir -p ${RSYNCPATH}/nanobsd"
2598
		if [ -d $STAGINGAREA/virtualization ]; then
2599
			ssh ${RSYNCUSER}@${_rsyncip} "mkdir -p ${RSYNCPATH}/virtualization"
2600
		fi
2601
		ssh ${RSYNCUSER}@${_rsyncip} "mkdir -p ${RSYNCPATH}/.updaters"
2602
		# ensure permissions are correct for r+w
2603
		ssh ${RSYNCUSER}@${_rsyncip} "chmod -R ug+rw ${RSYNCPATH}/."
2604
		rsync $RSYNC_COPY_ARGUMENTS $STAGINGAREA/${PRODUCT_NAME}${PRODUCT_NAME_SUFFIX}-*iso* \
2605
			${RSYNCUSER}@${_rsyncip}:${RSYNCPATH}/installer/
2606
		rsync $RSYNC_COPY_ARGUMENTS $STAGINGAREA/${PRODUCT_NAME}${PRODUCT_NAME_SUFFIX}-memstick* \
2607
			${RSYNCUSER}@${_rsyncip}:${RSYNCPATH}/installer/
2608
		rsync $RSYNC_COPY_ARGUMENTS $STAGINGAREA/${PRODUCT_NAME}${PRODUCT_NAME_SUFFIX}-*Update* \
2609
			${RSYNCUSER}@${_rsyncip}:${RSYNCPATH}/updates/
2610
		rsync $RSYNC_COPY_ARGUMENTS $STAGINGAREA/nanobsd/* \
2611
			${RSYNCUSER}@${_rsyncip}:${RSYNCPATH}/nanobsd/
2612
		rsync $RSYNC_COPY_ARGUMENTS $STAGINGAREA/nanobsdupdates/* \
2613
			${RSYNCUSER}@${_rsyncip}:${RSYNCPATH}/updates/
2614
		if [ -d $STAGINGAREA/virtualization ]; then
2615
			rsync $RSYNC_COPY_ARGUMENTS $STAGINGAREA/virtualization/* \
2616
				${RSYNCUSER}@${_rsyncip}:${RSYNCPATH}/virtualization/
2617
		fi
2618

    
2619
		# Rather than copy these twice, use ln to link to the latest one.
2620

    
2621
		ssh ${RSYNCUSER}@${_rsyncip} "rm -f ${RSYNCPATH}/.updaters/latest.tgz"
2622
		ssh ${RSYNCUSER}@${_rsyncip} "rm -f ${RSYNCPATH}/.updaters/latest.tgz.sha256"
2623

    
2624
		LATESTFILENAME=$(basename ${UPDATES_TARBALL_FILENAME})
2625
		ssh ${RSYNCUSER}@${_rsyncip} "ln -s ${RSYNCPATH}/updates/${LATESTFILENAME} \
2626
			${RSYNCPATH}/.updaters/latest.tgz"
2627
		ssh ${RSYNCUSER}@${_rsyncip} "ln -s ${RSYNCPATH}/updates/${LATESTFILENAME}.sha256 \
2628
			${RSYNCPATH}/.updaters/latest.tgz.sha256"
2629

    
2630
		for i in ${FLASH_SIZE}
2631
		do
2632
			ssh ${RSYNCUSER}@${_rsyncip} "rm -f ${RSYNCPATH}/.updaters/latest-nanobsd-${i}.img.gz"
2633
			ssh ${RSYNCUSER}@${_rsyncip} "rm -f ${RSYNCPATH}/.updaters/latest-nanobsd-${i}.img.gz.sha256"
2634
			ssh ${RSYNCUSER}@${_rsyncip} "rm -f ${RSYNCPATH}/.updaters/latest-nanobsd-vga-${i}.img.gz"
2635
			ssh ${RSYNCUSER}@${_rsyncip} "rm -f ${RSYNCPATH}/.updaters/latest-nanobsd-vga-${i}.img.gz.sha256"
2636

    
2637
			FILENAMEUPGRADE="$(nanobsd_image_filename ${i} nanobsd 1).gz"
2638
			ssh ${RSYNCUSER}@${_rsyncip} "ln -s ${RSYNCPATH}/updates/${FILENAMEUPGRADE} \
2639
				${RSYNCPATH}/.updaters/latest-nanobsd-${i}.img.gz"
2640
			ssh ${RSYNCUSER}@${_rsyncip} "ln -s ${RSYNCPATH}/updates/${FILENAMEUPGRADE}.sha256 \
2641
				${RSYNCPATH}/.updaters/latest-nanobsd-${i}.img.gz.sha256"
2642

    
2643
			FILENAMEUPGRADE="$(nanobsd_image_filename ${i} nanobsd-vga 1).gz"
2644
			ssh ${RSYNCUSER}@${_rsyncip} "ln -s ${RSYNCPATH}/updates/${FILENAMEUPGRADE} \
2645
				${RSYNCPATH}/.updaters/latest-nanobsd-vga-${i}.img.gz"
2646
			ssh ${RSYNCUSER}@${_rsyncip} "ln -s ${RSYNCPATH}/updates/${FILENAMEUPGRADE}.sha256 \
2647
				${RSYNCPATH}/.updaters/latest-nanobsd-vga-${i}.img.gz.sha256"
2648
		done
2649

    
2650
		rsync $RSYNC_COPY_ARGUMENTS $STAGINGAREA/version* \
2651
			${RSYNCUSER}@${_rsyncip}:${RSYNCPATH}/.updaters
2652
		snapshots_update_status ">>> Finished copying files."
2653
	done
2654
}
(2-2/3)