Project

General

Profile

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

    
46
if [ -n "${IMAGES_FINAL_DIR}" -a "${IMAGES_FINAL_DIR}" != "/" ]; then
47
	mkdir -p ${IMAGES_FINAL_DIR}
48
else
49
	echo "IMAGES_FINAL_DIR is not defined"
50
	print_error_pfS
51
fi
52

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

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

    
64
# Create core pkg (base, kernel)
65
core_pkg_create() {
66
	local _template="${1}"
67
	local _flavor="${2}"
68
	local _version="${3}"
69
	local _root="${4}"
70

    
71
	[ -d "${CORE_PKG_TMP}" ] \
72
		&& rm -rf ${CORE_PKG_TMP}
73

    
74
	local _templates_path=${BUILDER_TOOLS}/templates/core_pkg/${_template}
75
	local _template_metadir=${_templates_path}/metadir
76
	local _metadir=${CORE_PKG_TMP}/${_template}_metadir
77

    
78
	if [ ! -d ${_template_metadir} ]; then
79
		echo "ERROR: Template dir not found for pkg ${_template}"
80
		exit
81
	fi
82

    
83
	mkdir -p ${CORE_PKG_TMP}
84

    
85
	cp -r ${_template_metadir} ${_metadir}
86

    
87
	local _manifest=${_metadir}/+MANIFEST
88
	local _plist=${CORE_PKG_TMP}/${_template}_plist
89
	local _exclude_plist=${CORE_PKG_TMP}/${_template}_exclude_plist
90

    
91
	if [ -f "${_templates_path}/pkg-plist" ]; then
92
		cp ${_templates_path}/pkg-plist ${_plist}
93
	else
94
		(cd ${_root} && find . -type f -or -type l | sed 's,^.,,' | sort -u) > ${_plist}
95
	fi
96

    
97
	if [ -f "${_templates_path}/exclude_plist" ]; then
98
		cp ${_templates_path}/exclude_plist ${_exclude_plist}
99
	else
100
		touch ${_exclude_plist}
101
	fi
102

    
103
	sed \
104
		-i '' \
105
		-e "s,%%PRODUCT_NAME%%,${PRODUCT_NAME},g" \
106
		-e "s,%%PRODUCT_URL%%,${PRODUCT_URL},g" \
107
		-e "s,%%FLAVOR%%,${_flavor},g" \
108
		-e "s,%%VERSION%%,${_version},g" \
109
		${_metadir}/* \
110
		${_plist} \
111
		${exclude_plist}
112

    
113
	if [ -f "${_exclude_plist}" ]; then
114
		sort -u ${_exclude_plist} > ${_plist}.exclude
115
		mv ${_plist} ${_plist}.tmp
116
		comm -23 ${_plist}.tmp ${_plist}.exclude > ${_plist}
117
		rm -f ${_plist}.tmp ${plist}.exclude
118
	fi
119

    
120
	mkdir -p ${CORE_PKG_PATH}
121
	if ! pkg create -o ${CORE_PKG_PATH} -p ${_plist} -r ${_root} -m ${_metadir}; then
122
		echo ">>> ERROR: Error building package ${_template} ${_flavor}"
123
		print_error_pfS
124
	fi
125
}
126

    
127
# This routine will output that something went wrong
128
print_error_pfS() {
129
	echo
130
	echo "####################################"
131
	echo "Something went wrong, check errors!" >&2
132
	echo "####################################"
133
	echo
134
	echo "NOTE: a lot of times you can run './build.sh --clean-builder' to resolve."
135
	echo
136
	if [ "$1" != "" ]; then
137
		echo $1
138
	fi
139
	[ -n "${LOGFILE:-}" ] && \
140
		echo "Log saved on ${LOGFILE}" && \
141
		tail -n20 ${LOGFILE} >&2
142
	echo
143
	echo "Press enter to continue."
144
	read ans
145
	kill $$
146
	exit 1
147
}
148

    
149
prestage_on_ram_setup() {
150
	_AVAIL_MEM=$(($(sysctl -n hw.usermem) / 1024 / 1024))
151
	if [ $_AVAIL_MEM -lt 2000 ]; then
152
		echo ">>> Builder has less than 2GiB RAM skipping memory disks"
153
		return
154
	else
155
		echo "######################################################################################"
156
		echo
157
		echo ">>> Builder has more than 1.4GiB RAM enabling memory disks"
158
		echo ">>> WARNING: Remember to remove these memory disks by running $0 --disable-memorydisks"
159
		echo
160
		echo "######################################################################################"
161
	fi
162

    
163
	if df /dev/ufs/prestagebacking >/dev/null 2>&1; then
164
		echo ">>> Detected preexisting memory disk enabled for ${STAGE_CHROOT_DIR}."
165
	else
166
		mdconfig -a -t swap -u 10001 -s ${MEMORYDISK_SIZE}
167
		mkdir -p ${STAGE_CHROOT_DIR}
168
		newfs -L prestagebacking -U /dev/md10001
169
		mount /dev/ufs/prestagebacking ${STAGE_CHROOT_DIR}
170
	fi
171

    
172
	if df /dev/ufs/finalstagebacking >/dev/null 2>&1; then
173
		echo ">>> Detected preexisting memory disk enabled for ${FINAL_CHROOT_DIR}."
174
	else
175
		mdconfig -a -t swap -u 10002 -s ${MEMORYDISK_SIZE}
176
		mkdir -p ${FINAL_CHROOT_DIR}
177
		newfs -L finalstagebacking -U /dev/md10002
178
		mount /dev/ufs/finalstagebacking ${FINAL_CHROOT_DIR}
179
	fi
180
}
181

    
182
prestage_on_ram_cleanup() {
183
	if [ -c /dev/md10001 ]; then
184
		if [ -d ${STAGE_CHROOT_DIR} ]; then
185
			umount ${STAGE_CHROOT_DIR}
186
		fi
187
		mdconfig -d -u 10001
188
	fi
189
	if [ -c /dev/md10002 ]; then
190
		if [ -d ${FINAL_CHROOT_DIR} ]; then
191
			umount ${FINAL_CHROOT_DIR}
192
		fi
193
		mdconfig -d -u 10002
194
	fi
195
}
196

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

    
211
get_pkg_name() {
212
	echo "${PRODUCT_NAME}-${1}-${CORE_PKG_VERSION}"
213
}
214

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

    
223
	[ -d "${KERNEL_BUILD_PATH}" ] \
224
		&& rm -rf ${KERNEL_BUILD_PATH}
225

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

    
237
		LOGFILE="${BUILDER_LOGS}/kernel.${KERNCONF}.${TARGET}.log"
238
		echo ">>> Building $BUILD_KERNEL kernel."  | tee -a ${LOGFILE}
239

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

    
245
		if [ -n "${NO_BUILDKERNEL:-}" -a -f "${CORE_PKG_PATH}/$(get_pkg_name kernel-${KERNEL_NAME}).txz" ]; then
246
			echo ">>> NO_BUILDKERNEL set, skipping build" | tee -a ${LOGFILE}
247
			continue
248
		fi
249

    
250
		export SRC_CONF=${SRC_CONF}
251
		buildkernel
252

    
253
		echo ">>> Staging $BUILD_KERNEL kernel..." | tee -a ${LOGFILE}
254
		installkernel
255

    
256
		ensure_kernel_exists $KERNEL_DESTDIR
257

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

    
261
		rm -rf $KERNEL_DESTDIR 2>&1 1>/dev/null
262

    
263
		echo ".Done" | tee -a ${LOGFILE}
264
	done
265
}
266

    
267
install_default_kernel() {
268
	if [ -z "${1}" ]; then
269
		echo ">>> ERROR: install_default_kernel called without a kernel config name"| tee -a ${LOGFILE}
270
		print_error_pfS
271
	fi
272

    
273
	export KERNEL_NAME="${1}"
274

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

    
277
	# Copy kernel package to chroot, otherwise pkg won't find it to install
278
	if ! pkg_chroot_add ${FINAL_CHROOT_DIR} kernel-${KERNEL_NAME}; then
279
		echo ">>> ERROR: Error installing kernel package $(get_pkg_name kernel-${KERNEL_NAME}).txz" | tee -a ${LOGFILE}
280
		print_error_pfS
281
	fi
282

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

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

    
308
	unset KERNEL_NAME
309
}
310

    
311
# Items that need to be fixed up that are
312
# specific to nanobsd builds
313
cust_fixup_nanobsd() {
314
	local _NANO_WITH_VGA="${1}"
315

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

    
318
	echo "nanobsd" > $FINAL_CHROOT_DIR/etc/platform
319

    
320
	local BOOTCONF=${FINAL_CHROOT_DIR}/boot.config
321
	local LOADERCONF=${FINAL_CHROOT_DIR}/boot/loader.conf
322

    
323
	if [ "${_NANO_WITH_VGA}" = "nanobsd" ]; then
324
		# Tell loader to use serial console early.
325
		echo "-S115200 -h" >> ${BOOTCONF}
326
	else
327
		# Empty file to identify nanobsd_vga images
328
		touch ${FINAL_CHROOT_DIR}/etc/nano_use_vga.txt
329
	fi
330

    
331
	# Remove old console options if present.
332
	[ -f "${LOADERCONF}" ] \
333
		&& sed -i "" -Ee "/(console|boot_multicons|boot_serial|hint.uart)/d" ${LOADERCONF}
334
	# Activate serial console+video console in loader.conf
335
	echo 'autoboot_delay="5"' >> ${LOADERCONF}
336
	echo 'loader_color="NO"' >> ${LOADERCONF}
337
	echo 'beastie_disable="YES"' >> ${LOADERCONF}
338
	echo 'boot_serial="YES"' >> ${LOADERCONF}
339
	echo 'console="comconsole"' >> ${LOADERCONF}
340
	echo 'comconsole_speed="115200"' >> ${LOADERCONF}
341
}
342

    
343
# Creates a full update file
344
create_Full_update_tarball() {
345
	mkdir -p $UPDATESDIR
346

    
347
	customize_stagearea_for_image "fullupdate"
348
	install_default_kernel ${DEFAULT_KERNEL}
349

    
350
	rm -rf ${FINAL_CHROOT_DIR}/cf
351
	rm -rf ${FINAL_CHROOT_DIR}/conf
352
	rm -f ${FINAL_CHROOT_DIR}/etc/rc.conf
353
	rm -f ${FINAL_CHROOT_DIR}/etc/pwd.db 2>/dev/null
354
	rm -f ${FINAL_CHROOT_DIR}/etc/group 2>/dev/null
355
	rm -f ${FINAL_CHROOT_DIR}/etc/spwd.db 2>/dev/null
356
	rm -f ${FINAL_CHROOT_DIR}/etc/passwd 2>/dev/null
357
	rm -f ${FINAL_CHROOT_DIR}/etc/master.passwd 2>/dev/null
358
	rm -f ${FINAL_CHROOT_DIR}/etc/fstab 2>/dev/null
359
	rm -f ${FINAL_CHROOT_DIR}/etc/bogons 2>/dev/null
360
	# Remove loader.conf and friends.  Ticket #560
361
	rm ${FINAL_CHROOT_DIR}/boot/loader.conf 2>/dev/null
362
	rm ${FINAL_CHROOT_DIR}/boot/loader.conf.local 2>/dev/null
363

    
364
	echo ">>> Creating ${UPDATES_TARBALL_FILENAME} ..." | tee -a ${LOGFILE}
365
	tar --exclude=./dev -czPf ${UPDATES_TARBALL_FILENAME} -C ${FINAL_CHROOT_DIR} .
366
}
367

    
368
# Outputs various set variables aka env
369
print_flags() {
370

    
371
	echo
372
	printf "             Product version: %s\n" $PRODUCT_VERSION
373
	printf "                   Stage DIR: %s\n" $STAGE_CHROOT_DIR
374
	printf "                 Updates dir: %s\n" $UPDATESDIR
375
	printf " Image Preparation Stage DIR: %s\n" $FINAL_CHROOT_DIR
376
	printf "                  Source DIR: %s\n" $FREEBSD_SRC_DIR
377
	printf "          FreeBSD repository: %s\n" $FREEBSD_REPO_BASE
378
	printf "          FreeBSD-src branch: %s\n" $FREEBSD_BRANCH
379
	printf "     FreeBSD original branch: %s\n" $FREEBSD_PARENT_BRANCH
380
	printf "               BUILD_KERNELS: %s\n" $BUILD_KERNELS
381
	printf "           Git Branch or Tag: %s\n" $GIT_REPO_BRANCH_OR_TAG
382
	printf "            MODULES_OVERRIDE: %s\n" $MODULES_OVERRIDE
383
	printf "                 OVADISKSIZE: %s\n" $OVADISKSIZE
384
	printf "                OVABLOCKSIZE: %s\n" $OVABLOCKSIZE
385
	printf "         OVA_FIRST_PART_SIZE: %s\n" $OVA_FIRST_PART_SIZE
386
	printf "          OVA_SWAP_PART_SIZE: %s\n" $OVA_SWAP_PART_SIZE
387
	printf "                     OVFFILE: %s\n" $OVFFILE
388
	printf "                     OVFVMDK: %s\n" $OVFVMDK
389
	printf "                     OVFCERT: %s\n" $OVFCERT
390
	printf "                    SRC_CONF: %s\n" $SRC_CONF
391
	printf "                     ISOPATH: %s\n" $ISOPATH
392
	printf "                MEMSTICKPATH: %s\n" $MEMSTICKPATH
393
	printf "    UPDATES_TARBALL_FILENAME: %s\n" $UPDATES_TARBALL_FILENAME
394
if [ -n "$SHOW_ENV" ]; then
395
	for LINE in $(env | egrep -v '(terminal|PASS|NAME|USER|SSH|GROUP|HOST)'); do
396
		echo "SHOW_ENV: $LINE"
397
	done
398
fi
399
	echo
400
}
401

    
402
# This builds FreeBSD (make buildworld)
403
# Imported from FreeSBIE
404
make_world() {
405

    
406
	LOGFILE=${BUILDER_LOGS}/buildworld.${TARGET}
407
	if [ -n "${NO_BUILDWORLD:-}" ]; then
408
		echo ">>> NO_BUILDWORLD set, skipping build" | tee -a ${LOGFILE}
409
		return
410
	fi
411

    
412
	# Set SRC_CONF variable if it's not already set.
413
	if [ -z "${SRC_CONF:-}" ]; then
414
		echo ">>> SRC_CONF is unset make sure this is what you want!" | tee -a ${LOGFILE}
415
	else
416
		echo ">>> Setting SRC_CONF to $SRC_CONF" | tee -a ${LOGFILE}
417
	fi
418

    
419
	# Set default parameters
420
	export MAKE_ARGS="${MAKEJ_WORLD:-} __MAKE_CONF=${MAKE_CONF} SRCCONF=${SRC_CONF} TARGET=${TARGET} TARGET_ARCH=${TARGET_ARCH}"
421

    
422
	echo ">>> LOGFILE set to $LOGFILE." | tee -a ${LOGFILE}
423
	makeargs="${MAKE_ARGS}"
424
	echo ">>> Building world for ${TARGET} architecture... (Starting - $(LC_ALL=C date))" | tee -a ${LOGFILE}
425
	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}
426
	(env LOCAL_ITOOLS="${EXTRA_TOOLS}" script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR} -DNO_CLEAN ${makeargs:-} buildworld || print_error_pfS;) | egrep '^>>>' | tee -a ${LOGFILE}
427
	echo ">>> Building world for ${TARGET} architecture... (Finished - $(LC_ALL=C date))" | tee -a ${LOGFILE}
428

    
429
	LOGFILE=${BUILDER_LOGS}/installworld.${TARGET}
430
	echo ">>> LOGFILE set to $LOGFILE." | tee -a ${LOGFILE}
431
	# Create if cleaned up
432
	mkdir -p ${STAGE_CHROOT_DIR}
433
	makeargs="${MAKE_ARGS} DESTDIR=${STAGE_CHROOT_DIR} WITHOUT_TOOLCHAIN=1"
434
	echo ">>> Installing world for ${TARGET} architecture... (Starting - $(LC_ALL=C date))" | tee -a ${LOGFILE}
435
	echo ">>> Builder is running the command: env LOCAL_ITOOLS=\"${EXTRA_TOOLS}\" script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR} ${makeargs:-} installworld" | tee -a ${LOGFILE}
436
	(env LOCAL_ITOOLS="${EXTRA_TOOLS}" script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR} ${makeargs:-} installworld || print_error_pfS;) | egrep '^>>>' | tee -a ${LOGFILE}
437
	echo ">>> Installing world for ${TARGET} architecture... (Finished - $(LC_ALL=C date))" | tee -a ${LOGFILE}
438

    
439
	makeargs="${MAKE_ARGS} DESTDIR=${STAGE_CHROOT_DIR}"
440
	echo ">>> Distribution world for ${TARGET} architecture... (Starting - $(LC_ALL=C date))" | tee -a ${LOGFILE}
441
	echo ">>> Builder is running the command: script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR} ${makeargs:-} distribution " | tee -a ${LOGFILE}
442
	(script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR} ${makeargs:-} distribution  || print_error_pfS;) | egrep '^>>>' | tee -a ${LOGFILE}
443
	echo ">>> Distribution world for ${TARGET} architecture... (Finished - $(LC_ALL=C date))" | tee -a ${LOGFILE}
444

    
445
	[ -d "${STAGE_CHROOT_DIR}/usr/local/bin" ] \
446
		|| mkdir -p ${STAGE_CHROOT_DIR}/usr/local/bin
447
	makeargs="${MAKE_ARGS} DESTDIR=${STAGE_CHROOT_DIR}"
448
	echo ">>> Building and installing crypto tools and athstats for ${TARGET} architecture... (Starting - $(LC_ALL=C date))" | tee -a ${LOGFILE}
449
	echo ">>> Builder is running the command: script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR}/tools/tools/crypto ${makeargs:-} clean all install " | tee -a ${LOGFILE}
450
	(script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR}/tools/tools/crypto ${makeargs:-} clean all install || print_error_pfS;) | egrep '^>>>' | tee -a ${LOGFILE}
451
	echo ">>> Builder is running the command: script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR}/tools/tools/ath/athstats ${makeargs:-} clean" | tee -a ${LOGFILE}
452
	(script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR}/tools/tools/ath/athstats ${makeargs:-} clean || print_error_pfS;) | egrep '^>>>' | tee -a ${LOGFILE}
453
	echo ">>> Builder is running the command: script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR}/tools/tools/ath/athstats ${makeargs:-} all" | tee -a ${LOGFILE}
454
	(script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR}/tools/tools/ath/athstats ${makeargs:-} all || print_error_pfS;) | egrep '^>>>' | tee -a ${LOGFILE}
455
	echo ">>> Builder is running the command: script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR}/tools/tools/ath/athstats ${makeargs:-} install" | tee -a ${LOGFILE}
456
	(script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR}/tools/tools/ath/athstats ${makeargs:-} install || print_error_pfS;) | egrep '^>>>' | tee -a ${LOGFILE}
457
	echo ">>> Building and installing crypto tools and athstats for ${TARGET} architecture... (Finished - $(LC_ALL=C date))" | tee -a ${LOGFILE}
458

    
459
	unset makeargs
460
}
461

    
462
# This routine originated in nanobsd.sh
463
nanobsd_set_flash_details () {
464
	a1=$(echo $1 | tr '[:upper:]' '[:lower:]')
465

    
466
	# Source:
467
	#	SanDisk CompactFlash Memory Card
468
	#	Product Manual
469
	#	Version 10.9
470
	#	Document No. 20-10-00038
471
	#	April 2005
472
	# Table 2-7
473
	# NB: notice math error in SDCFJ-4096-388 line.
474
	#
475
	case "${a1}" in
476
		1024|1024m|1024mb|1g)
477
			NANO_MEDIASIZE=$((997129216/512))
478
			;;
479
		2048|2048m|2048mb|2g)
480
			NANO_MEDIASIZE=$((1989999616/512))
481
			;;
482
		4096|4096m|4096mb|4g)
483
			NANO_MEDIASIZE=$((3989999616/512))
484
			;;
485
		8192|8192m|8192mb|8g)
486
			NANO_MEDIASIZE=$((7989999616/512))
487
			;;
488
		16384|16384m|16384mb|16g)
489
			NANO_MEDIASIZE=$((15989999616/512))
490
			;;
491
		*)
492
			echo "Unknown Flash capacity"
493
			exit 2
494
			;;
495
	esac
496

    
497
	NANO_HEADS=16
498
	NANO_SECTS=63
499

    
500
	echo ">>> [nanoo] $1"
501
	echo ">>> [nanoo] NANO_MEDIASIZE: $NANO_MEDIASIZE"
502
	echo ">>> [nanoo] NANO_HEADS: $NANO_HEADS"
503
	echo ">>> [nanoo] NANO_SECTS: $NANO_SECTS"
504
	echo ">>> [nanoo] NANO_BOOT0CFG: $NANO_BOOT0CFG"
505
}
506

    
507
# This routine originated in nanobsd.sh
508
create_nanobsd_diskimage () {
509
	if [ -z "${1}" ]; then
510
		echo ">>> ERROR: Type of image has not been specified"
511
		print_error_pfS
512
	fi
513
	if [ -z "${2}" ]; then
514
		echo ">>> ERROR: Size of image has not been specified"
515
		print_error_pfS
516
	fi
517

    
518
	if [ "${1}" = "nanobsd" ]; then
519
		# It's serial
520
		export NANO_BOOTLOADER="boot/boot0sio"
521
	elif [ "${1}" = "nanobsd-vga" ]; then
522
		# It's vga
523
		export NANO_BOOTLOADER="boot/boot0"
524
	else
525
		echo ">>> ERROR: Type of image to create unknown"
526
		print_error_pfS
527
	fi
528

    
529
	if [ -z "${2}" ]; then
530
		echo ">>> ERROR: Media size(s) not specified."
531
		print_error_pfS
532
	fi
533

    
534
	if [ -z "${2}" ]; then
535
		echo ">>> ERROR: FLASH_SIZE is not set."
536
		print_error_pfS
537
	fi
538

    
539
	LOGFILE=${BUILDER_LOGS}/${1}.${TARGET}
540
	# Prepare folder to be put in image
541
	customize_stagearea_for_image "${1}"
542
	install_default_kernel ${DEFAULT_KERNEL} "no"
543

    
544
	# Must be run after customize_stagearea_for_image
545
	cust_fixup_nanobsd ${1}
546

    
547
	for _NANO_MEDIASIZE in ${2}; do
548
		if [ -z "${_NANO_MEDIASIZE}" ]; then
549
			continue;
550
		fi
551

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

    
555
		IMG="${IMAGES_FINAL_DIR}/${PRODUCT_NAME}-${PRODUCT_VERSION}-${_NANO_MEDIASIZE}-${TARGET}-${1}-${DATESTRING}.img"
556
		IMGUPDATE="${IMAGES_FINAL_DIR}/${PRODUCT_NAME}-${PRODUCT_VERSION}-${_NANO_MEDIASIZE}-${TARGET}-${1}-upgrade-${DATESTRING}.img"
557

    
558
		nanobsd_set_flash_details ${_NANO_MEDIASIZE}
559

    
560
		# These are defined in FlashDevice and on builder_default.sh
561
		echo $NANO_MEDIASIZE \
562
			$NANO_IMAGES \
563
			$NANO_SECTS \
564
			$NANO_HEADS \
565
			$NANO_CODESIZE \
566
			$NANO_CONFSIZE \
567
			$NANO_DATASIZE |
568
awk '
569
{
570
	printf "# %s\n", $0
571

    
572
	# size of cylinder in sectors
573
	cs = $3 * $4
574

    
575
	# number of full cylinders on media
576
	cyl = int ($1 / cs)
577

    
578
	# output fdisk geometry spec, truncate cyls to 1023
579
	if (cyl <= 1023)
580
		print "g c" cyl " h" $4 " s" $3
581
	else
582
		print "g c" 1023 " h" $4 " s" $3
583

    
584
	if ($7 > 0) {
585
		# size of data partition in full cylinders
586
		dsl = int (($7 + cs - 1) / cs)
587
	} else {
588
		dsl = 0;
589
	}
590

    
591
	# size of config partition in full cylinders
592
	csl = int (($6 + cs - 1) / cs)
593

    
594
	if ($5 == 0) {
595
		# size of image partition(s) in full cylinders
596
		isl = int ((cyl - dsl - csl) / $2)
597
	} else {
598
		isl = int (($5 + cs - 1) / cs)
599
	}
600

    
601
	# First image partition start at second track
602
	print "p 1 165 " $3, isl * cs - $3
603
	c = isl * cs;
604

    
605
	# Second image partition (if any) also starts offset one
606
	# track to keep them identical.
607
	if ($2 > 1) {
608
		print "p 2 165 " $3 + c, isl * cs - $3
609
		c += isl * cs;
610
	}
611

    
612
	# Config partition starts at cylinder boundary.
613
	print "p 3 165 " c, csl * cs
614
	c += csl * cs
615

    
616
	# Data partition (if any) starts at cylinder boundary.
617
	if ($7 > 0) {
618
		print "p 4 165 " c, dsl * cs
619
	} else if ($7 < 0 && $1 > c) {
620
		print "p 4 165 " c, $1 - c
621
	} else if ($1 < c) {
622
		print "Disk space overcommitted by", \
623
		    c - $1, "sectors" > "/dev/stderr"
624
		exit 2
625
	}
626

    
627
	# Force slice 1 to be marked active. This is necessary
628
	# for booting the image from a USB device to work.
629
	print "a 1"
630
}
631
	' > ${IMAGES_FINAL_DIR}/_.fdisk
632

    
633
		MNT=${IMAGES_FINAL_DIR}/_.mnt
634
		mkdir -p ${MNT}
635

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

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

    
642
		fdisk -i -f ${IMAGES_FINAL_DIR}/_.fdisk ${MD} 2>&1 >> ${LOGFILE}
643
		fdisk ${MD} 2>&1 >> ${LOGFILE}
644

    
645
		boot0cfg -B -b ${FINAL_CHROOT_DIR}/${NANO_BOOTLOADER} ${NANO_BOOT0CFG} ${MD} 2>&1 >> ${LOGFILE}
646

    
647
		# Create first image
648
		bsdlabel -m i386 -w -B -b ${FINAL_CHROOT_DIR}/boot/boot ${MD}s1 2>&1 >> ${LOGFILE}
649
		bsdlabel -m i386 ${MD}s1 2>&1 >> ${LOGFILE}
650
		local _label=$(lc ${PRODUCT_NAME})
651
		newfs -L ${_label}0 ${NANO_NEWFS} /dev/${MD}s1a 2>&1 >> ${LOGFILE}
652
		mount /dev/ufs/${_label}0 ${MNT}
653
		if [ $? -ne 0 ]; then
654
			echo ">>> ERROR: Something wrong happened during mount of first slice image creation. STOPPING!" | tee -a ${LOGFILE}
655
			print_error_pfS
656
		fi
657
		# Consider the unmounting as well
658
		trap "umount /dev/ufs/${_label}0; mdconfig -d -u ${MD}; return" 1 2 15 EXIT
659

    
660
		clone_directory_contents ${FINAL_CHROOT_DIR} ${MNT}
661

    
662
		# Set NanoBSD image size
663
		echo "${_NANO_MEDIASIZE}" > ${MNT}/etc/nanosize.txt
664
		rm -f $MNT/cf/conf/* 2>/dev/null
665

    
666
		echo "/dev/ufs/${_label}0 / ufs ro,sync,noatime 1 1" > ${MNT}/etc/fstab
667
		if [ $NANO_CONFSIZE -gt 0 ] ; then
668
			echo "/dev/ufs/cf /cf ufs ro,sync,noatime 1 1" >> ${MNT}/etc/fstab
669
		fi
670

    
671
		umount ${MNT}
672
		sync
673
		# Restore the original trap
674
		trap "mdconfig -d -u ${MD}; return" 1 2 15 EXIT
675

    
676
		# Setting NANO_IMAGES to 1 and NANO_INIT_IMG2 will tell
677
		# NanoBSD to only create one partition.  We default to 2
678
		# partitions in case anything happens to the first the
679
		# operator can boot from the 2nd and should be OK.
680

    
681
		# Before just going to use dd for duplicate think!
682
		# The images are created as sparse so lets take advantage
683
		# of that by just exec some commands.
684
		if [ $NANO_IMAGES -gt 1 -a $NANO_INIT_IMG2 -gt 0 ] ; then
685
			# Duplicate to second image (if present)
686
			echo ">>> Creating NanoBSD second slice by duplicating first slice." | tee -a ${LOGFILE}
687
			# Create second image
688
			dd if=/dev/${MD}s1 of=/dev/${MD}s2 conv=sparse bs=64k 2>&1 >> ${LOGFILE}
689
			tunefs -L ${_label}1 /dev/${MD}s2a 2>&1 >> ${LOGFILE}
690
			mount /dev/ufs/${_label}1 ${MNT}
691
			if [ $? -ne 0 ]; then
692
				echo ">>> ERROR: Something wrong happened during mount of second slice image creation. STOPPING!" | tee -a ${LOGFILE}
693
				print_error_pfS
694
			fi
695
			# Consider the unmounting as well
696
			trap "umount /dev/ufs/${_label}1; mdconfig -d -u ${MD}; return" 1 2 15 EXIT
697

    
698
			echo "/dev/ufs/${_label}1 / ufs ro,sync,noatime 1 1" > ${MNT}/etc/fstab
699
			if [ $NANO_CONFSIZE -gt 0 ] ; then
700
				echo "/dev/ufs/cf /cf ufs ro,sync,noatime 1 1" >> ${MNT}/etc/fstab
701
			fi
702

    
703
			umount ${MNT}
704
			# Restore the trap back
705
			trap "mdconfig -d -u ${MD}; return" 1 2 15 EXIT
706
		fi
707

    
708
		# Create Data slice, if any.
709
		# Note the changing of the variable to NANO_CONFSIZE
710
		# from NANO_DATASIZE.  We also added glabel support
711
		# and populate the Product configuration from the /cf
712
		# directory located in FINAL_CHROOT_DIR
713
		if [ $NANO_CONFSIZE -gt 0 ] ; then
714
			echo ">>> Creating /cf area to hold config.xml"
715
			newfs -L cf ${NANO_NEWFS} /dev/${MD}s3 2>&1 >> ${LOGFILE}
716
			# Mount data partition and copy contents of /cf
717
			# Can be used later to create custom default config.xml while building
718
			mount /dev/ufs/cf ${MNT}
719
			if [ $? -ne 0 ]; then
720
				echo ">>> ERROR: Something wrong happened during mount of cf slice image creation. STOPPING!" | tee -a ${LOGFILE}
721
				print_error_pfS
722
			fi
723
			# Consider the unmounting as well
724
			trap "umount /dev/ufs/cf; mdconfig -d -u ${MD}; return" 1 2 15 EXIT
725

    
726
			clone_directory_contents ${FINAL_CHROOT_DIR}/cf ${MNT}
727

    
728
			umount ${MNT}
729
			# Restore the trap back
730
			trap "mdconfig -d -u ${MD}; return" 1 2 15 EXIT
731
		else
732
			">>> [nanoo] NANO_CONFSIZE is not set. Not adding a /conf partition.. You sure about this??" | tee -a ${LOGFILE}
733
		fi
734

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

    
738
		mdconfig -d -u $MD
739
		# Restore default action
740
		trap "-" 1 2 15 EXIT
741

    
742
		# Check each image and ensure that they are over
743
		# 3 megabytes.  If either image is under 20 megabytes
744
		# in size then error out.
745
		IMGSIZE=$(stat -f "%z" ${IMG})
746
		IMGUPDATESIZE=$(stat -f "%z" ${IMGUPDATE})
747
		CHECKSIZE="20040710"
748
		if [ "$IMGSIZE" -lt "$CHECKSIZE" ]; then
749
			echo ">>> ERROR: Something went wrong when building NanoBSD.  The image size is under 20 megabytes!" | tee -a ${LOGFILE}
750
			print_error_pfS
751
		fi
752
		if [ "$IMGUPDATESIZE" -lt "$CHECKSIZE" ]; then
753
			echo ">>> ERROR: Something went wrong when building NanoBSD upgrade image.  The image size is under 20 megabytes!" | tee -a ${LOGFILE}
754
			print_error_pfS
755
		fi
756

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

    
760
		gzip -f $IMG &
761
		gzip -f $IMGUPDATE &
762
	done
763

    
764
	unset IMG
765
	unset IMGUPDATE
766
	unset IMGUPDATESIZE
767
	unset IMGSIZE
768

    
769
	ls -lah $IMAGES_FINAL_DIR
770
}
771

    
772
# This routine creates a ova image that contains
773
# a ovf and vmdk file. These files can be imported
774
# right into vmware or virtual box.
775
# (and many other emulation platforms)
776
# http://www.vmware.com/pdf/ovf_whitepaper_specification.pdf
777
create_ova_image() {
778
	# XXX create a .ovf php creator that you can pass:
779
	#     1. populatedSize
780
	#     2. license
781
	#     3. product name
782
	#     4. version
783
	#     5. number of network interface cards
784
	#     6. allocationUnits
785
	#     7. capacity
786
	#     8. capacityAllocationUnits
787

    
788
	LOGFILE=${BUILDER_LOGS}/ova.${TARGET}.log
789

    
790
	# Prepare folder to be put in image
791
	customize_stagearea_for_image "ova"
792
	install_default_kernel ${DEFAULT_KERNEL} "no"
793

    
794
	ova_prereq_check
795
	ova_remove_old_tmp_files
796
	ova_setup_ovf_file
797
	ova_create_raw_backed_file
798
	/bin/echo -n ">>> Creating mdconfig image ${OVFPATH}/${OVFVMDK}.raw... " | tee -a ${LOGFILE}
799
	MD=$(mdconfig -a -t vnode -f ${OVFPATH}/${OVFVMDK}.raw)
800
	# Just in case
801
	trap "mdconfig -d -u ${MD}" 1 2 15 EXIT
802

    
803
	# comment out if using pc-sysinstall
804
	ova_partition_gpart $MD
805
	ova_mount_mnt $MD
806
	ova_cpdup_files
807
	ova_setup_platform_specific # after cpdup
808
	ova_calculate_mnt_size
809
	ova_umount_mnt $MD
810
	# Restore default action
811
	trap "-" 1 2 15 EXIT
812
	ova_umount_mdconfig $MD
813
	# We use vbox because it compresses the vmdk on export
814
	ova_create_vbox_image
815
	# We repack the file with a more universal xml file that
816
	# works in both virtual box and esx server
817
	ova_repack_vbox_image
818
}
819

    
820
ova_repack_vbox_image() {
821
	BUILDPLATFORM=$(uname -p)
822
	POPULATEDSIZE=$(du -d0 -m $FINAL_CHROOT_DIR | awk '{ print \$1 }')
823
	POPULATEDSIZEBYTES=$(echo "${POPULATEDSIZE}*1024^2" | bc)
824
	REFERENCESSIZE=$(stat -f "%z" ${OVFPATH}/${OVFVMDK})
825
	echo ">>> Setting REFERENCESSIZE to ${REFERENCESSIZE}..." | tee -a ${LOGFILE}
826
	file_search_replace REFERENCESSIZE ${REFERENCESSIZE} ${OVFPATH}/${PRODUCT_NAME}.ovf
827
	echo ">>> Setting POPULATEDSIZEBYTES to ${POPULATEDSIZEBYTES}..." | tee -a ${LOGFILE}
828
	#  OperatingSystemSection (${PRODUCT_NAME}.ovf)
829
	#  42   FreeBSD 32-Bit
830
	#  78   FreeBSD 64-Bit
831
	if [ "$BUILDPLATFORM" = "i386" ]; then
832
		file_search_replace '"101"' '"42"' ${OVFPATH}/${PRODUCT_NAME}.ovf
833
		file_search_replace 'FreeBSD XX-Bit' 'FreeBSD' ${OVFPATH}/${PRODUCT_NAME}.ovf
834
	fi
835
	if [ "$BUILDPLATFORM" = "amd64" ]; then
836
		file_search_replace '"101"' '"78"' ${OVFPATH}/${PRODUCT_NAME}.ovf
837
		file_search_replace 'FreeBSD XX-Bit' 'FreeBSD 64-Bit' ${OVFPATH}/${PRODUCT_NAME}.ovf
838
	fi
839
	file_search_replace DISKSECTIONPOPULATEDSIZE $POPULATEDSIZEBYTES ${OVFPATH}/${PRODUCT_NAME}.ovf
840
	# 10737254400 = 10240MB = virtual box vmdk file size XXX grab this value from vbox creation
841
	# 10737418240 = 10GB
842
	echo ">>> Setting DISKSECTIONALLOCATIONUNITS to 10737254400..." | tee -a ${LOGFILE}
843
	file_search_replace DISKSECTIONALLOCATIONUNITS $OVA_DISKSECTIONALLOCATIONUNITS ${OVFPATH}/${PRODUCT_NAME}.ovf
844
	echo ">>> Setting DISKSECTIONCAPACITY to 10737418240..." | tee -a ${LOGFILE}
845
	file_search_replace DISKSECTIONCAPACITY $OVADISKSIZE ${OVFPATH}/${PRODUCT_NAME}.ovf
846
	echo ">>> Repacking OVA with universal OVF file..." | tee -a ${LOGFILE}
847
	mv ${OVFPATH}/${OVFVMDK} ${OVFPATH}/${PRODUCT_NAME}-disk1.vmdk
848
	gtar -C ${OVFPATH} -cpf ${PRODUCT_NAME}.ova ${PRODUCT_NAME}.ovf ${PRODUCT_NAME}-disk1.vmdk
849
	rm $OVFPATH/${PRODUCT_NAME}-disk1.vmdk
850
	ls -lah ${OVFPATH}/${PRODUCT_NAME}*ov*
851
}
852

    
853
# called from create_ova_image
854
ova_umount_mnt() {
855
	# Unmount /dev/mdX
856
	umount /mnt
857
	sync ; sync
858
}
859

    
860
# called from create_ova_image
861
ova_umount_mdconfig() {
862
	MD=$1
863
	# Show gpart info
864
	gpart show $MD
865
	echo ">>> Unmounting ${MD}..." | tee -a ${LOGFILE}
866
	mdconfig -d -u $MD
867
	sync ; sync
868
}
869

    
870
# called from create_ova_image
871
ova_mount_mnt() {
872
	MD=$1
873
	echo ">>> Mounting image to /mnt..." | tee -a ${LOGFILE}
874
	mount -o rw /dev/${MD}p2 /mnt/
875
}
876

    
877
# called from create_ova_image
878
ova_setup_ovf_file() {
879
	if [ -f ${OVFFILE} ]; then
880
		cp ${OVFFILE} ${OVFPATH}/${PRODUCT_NAME}.ovf
881
	fi
882

    
883
	if [ ! -f ${OVFPATH}/${PRODUCT_NAME}.ovf ]; then
884
		cp ${BUILDER_TOOLS}/conf/ovf/${PRODUCT_NAME}.ovf ${OVFPATH}/${PRODUCT_NAME}.ovf
885
		file_search_replace PRODUCT_VERSION $PRODUCT_VERSION ${OVFPATH}/${PRODUCT_NAME}.ovf
886
		file_search_replace PRODUCT_URL $PRODUCT_URL ${OVFPATH}/${PRODUCT_NAME}.ovf
887
	fi
888
}
889

    
890
# called from create_ova_image
891
ova_prereq_check() {
892
	if [ ! -f /usr/local/bin/vmdktool ]; then
893
		echo ">>> ERROR: vmdktool is not present please check port sysutils/vmdktool installation" | tee -a ${LOGFILE}
894
		print_error_pfS
895
	fi
896
	sysctl kern.geom.debugflags=16
897
}
898

    
899
# called from create_ova_image
900
ova_calculate_mnt_size() {
901
	/bin/echo -n ">>> Calculating size of /mnt..." | tee -a ${LOFGILE}
902
	INSTALLSIZE=$(du -s /mnt/ | awk '{ print $1 }')
903
	INSTALLSIZEH=$(du -d0 -h /mnt/ | awk '{ print $1 }')
904
	echo $INSTALLSIZEH
905
}
906

    
907
# called from create_ova_image
908
ova_create_raw_backed_file() {
909
	DISKSIZE=$OVADISKSIZE
910
	BLOCKSIZE=$OVABLOCKSIZE
911
	COUNT=$((${DISKSIZE}/${BLOCKSIZE}))
912
	DISKFILE=${OVFPATH}/${OVFVMDK}.raw
913
	echo ">>> Creating raw backing file ${DISKFILE} (Disk Size: ${DISKSIZE}, Block Size: ${BLOCKSIZE}, Count: ${COUNT})..." | tee -a ${LOGFILE}
914
	dd if=/dev/zero of=$DISKFILE bs=$BLOCKSIZE count=0 seek=$COUNT
915
}
916

    
917
# called from create_ova_image
918
ova_remove_old_tmp_files() {
919
	rm ${OVFPATH}/*.ovf.final 2>/dev/null
920
	rm ${OVFPATH}/*.ova 2>/dev/null
921
}
922

    
923
# called from create_ova_image
924
ova_create_vbox_image() {
925
	# VirtualBox
926
	echo ">>> Creating image using vmdktool..." | tee -a ${LOGFILE}
927
	rm ${OVFPATH}/${OVFVMDK} 2>/dev/null
928
	vmdktool -v ${OVFPATH}/${OVFVMDK} ${OVFPATH}/${OVFVMDK}.raw
929
	rm -rf ${OVFPATH}/${OVFVMDK}.raw
930
	echo ">>> ${OVFPATH}/${OVFVMDK} created." | tee -a ${LOGFILE}
931
}
932

    
933
# called from create_ova_image
934
ova_cpdup_files() {
935
	echo ">>> Populating vmdk staging area..."
936
	cpdup -o ${FINAL_CHROOT_DIR}/COPYRIGHT /mnt/COPYRIGHT
937
	cpdup -o ${FINAL_CHROOT_DIR}/boot /mnt/boot
938
	cpdup -o ${FINAL_CHROOT_DIR}/bin /mnt/bin
939
	cpdup -o ${FINAL_CHROOT_DIR}/cf/conf /mnt/cf/conf
940
	cpdup -o ${FINAL_CHROOT_DIR}/conf.default /mnt/conf.default
941
	cpdup -o ${FINAL_CHROOT_DIR}/dev /mnt/dev
942
	cpdup -o ${FINAL_CHROOT_DIR}/etc /mnt/etc
943
	cpdup -o ${FINAL_CHROOT_DIR}/home /mnt/home
944
	cpdup -o ${FINAL_CHROOT_DIR}/pkgs /mnt/pkgs
945
	cpdup -o ${FINAL_CHROOT_DIR}/libexec /mnt/libexec
946
	cpdup -o ${FINAL_CHROOT_DIR}/lib /mnt/lib
947
	cpdup -o ${FINAL_CHROOT_DIR}/root /mnt/root
948
	cpdup -o ${FINAL_CHROOT_DIR}/sbin /mnt/sbin
949
	cpdup -o ${FINAL_CHROOT_DIR}/usr /mnt/usr
950
	cpdup -o ${FINAL_CHROOT_DIR}/var /mnt/var
951
	sync ; sync ; sync ; sync
952
}
953

    
954
ova_setup_platform_specific() {
955
	echo ">>> Installing platform specific items..." | tee -a ${LOGFILE}
956
	echo "/dev/label/${PRODUCT_NAME}	/	ufs		rw	0	0" > /mnt/etc/fstab
957
	echo "/dev/label/swap0	none	swap	sw	0	0" >> /mnt/etc/fstab
958
	echo ${PRODUCT_NAME} > /mnt/etc/platform
959
	rmdir /mnt/conf
960
	mkdir -p /mnt/cf
961
	mkdir -p /mnt/cf/conf
962
	cp /mnt/conf.default/config.xml /mnt/cf/conf/
963
	chroot /mnt /bin/ln -s /cf/conf /conf
964
	mkdir -p /mnt/tmp
965
}
966

    
967
# called from create_ova_image
968
ova_partition_gpart() {
969
	# XXX: Switch to mkimg tool!!
970
	MD=$1
971
	echo ">>> Creating GPT..." | tee -a ${LOGFILE}
972
	gpart create -s gpt $MD
973
	echo ">>> Embedding GPT bootstrap into protective MBR..." | tee -a ${LOGFILE}
974
	gpart bootcode -b /boot/pmbr $MD
975
	echo ">>> Creating GPT boot partition..." | tee -a ${LOGFILE}
976
	gpart add -b 34 -s 128 -t freebsd-boot $MD
977
	gpart bootcode -p /boot/gptboot -i 1 $MD
978
	echo ">>> Setting up disk slices: ${MD}p2 (Size: ${OVA_FIRST_PART_SIZE})..." | tee -a ${LOGFILE}
979
	gpart add -s $OVA_FIRST_PART_SIZE -t freebsd-ufs -i 2 $MD
980
	echo ">>> Setting up disk slices: ${MD}p3 (swap) (Size: ${OVA_SWAP_PART_SIZE})..." | tee -a ${LOGFILE}
981
	gpart add -s $OVA_SWAP_PART_SIZE -t freebsd-swap -i 3 $MD
982
	echo ">>> Running newfs..." | tee -a ${LOGFILE}
983
	newfs -U /dev/${MD}p2
984
	sync ; sync ; sync ; sync
985
	echo ">>> Labeling partitions: ${MD}p2..."  | tee -a ${LOGFILE}
986
	glabel label ${PRODUCT_NAME} ${MD}p2
987
	sync ; sync
988
	echo ">>> Labeling partitions: ${MD}p3..." | tee -a ${LOGFILE}
989
	glabel label swap0 ${MD}p3
990
	sync ; sync
991
}
992

    
993
# called from create_ova_image
994
# This routine will replace a string in a file
995
file_search_replace() {
996
	local SEARCH="$1"
997
	local REPLACE="$2"
998
	local FILENAME="$3"
999

    
1000
	if [ -f "${FILENAME}" ]; then
1001
		sed -i '' -e "s/${SEARCH}/${REPLACE}/g" ${FILENAME}
1002
	fi
1003
}
1004

    
1005
# Cleans up previous builds
1006
clean_obj_dir() {
1007
	# Clean out directories
1008
	echo ">>> Cleaning up previous build environment...Please wait!"
1009

    
1010
	staginareas_clean_each_run
1011

    
1012
	if [ -d "${STAGE_CHROOT_DIR}" ]; then
1013
		BASENAME=$(basename ${STAGE_CHROOT_DIR})
1014
		echo -n ">>> Cleaning ${STAGE_CHROOT_DIR} ..."
1015
		chflags -R noschg ${STAGE_CHROOT_DIR} 2>&1 >/dev/null
1016
		rm -rf ${STAGE_CHROOT_DIR} 2>/dev/null
1017
		echo "Done."
1018
	fi
1019
	mkdir -p ${STAGE_CHROOT_DIR}
1020

    
1021
	if [ -z "${NO_CLEANFREEBSDOBJDIR}" -a -d "${FREEBSD_SRC_DIR}" ]; then
1022
		OBJTREE=$(env TARGET=${TARGET} TARGET_ARCH=${TARGET_ARCH} make -C ${FREEBSD_SRC_DIR} -V OBJTREE)
1023
		if [ -d "${OBJTREE}" ]; then
1024
			echo -n ">>> Cleaning FreeBSD objects dir staging..."
1025
			echo -n "."
1026
			chflags -R noschg ${OBJTREE} 2>&1 >/dev/null
1027
			echo -n "."
1028
			rm -rf ${OBJTREE}/*
1029
			echo "Done!"
1030
		fi
1031
		if [ -n "${KERNEL_DESTDIR}" -a -d "${KERNEL_BUILD_PATH}" ]; then
1032
			echo -n ">>> Cleaning previously built kernel stage area..."
1033
			rm -rf $KERNEL_BUILD_PATH/*
1034
			echo "Done!"
1035
		fi
1036
	fi
1037
	mkdir -p $KERNEL_BUILD_PATH
1038

    
1039
	echo -n ">>> Cleaning previously built images..."
1040
	rm -rf $IMAGES_FINAL_DIR/*
1041
	echo "Done!"
1042

    
1043
	if [ -z "${NO_CLEANREPOS}" ]; then
1044
		if [ -d "$FREEBSD_SRC_DIR" ]; then
1045
			echo -n ">>> Ensuring $FREEBSD_SRC_DIR is clean..."
1046
			rm -rf ${FREEBSD_SRC_DIR}
1047
			echo "Done!"
1048
		fi
1049
	fi
1050

    
1051
	echo -n ">>> Cleaning previous builder logs..."
1052
	if [ -d "$BUILDER_LOGS" ]; then
1053
		rm -rf ${BUILDER_LOGS}
1054
	fi
1055
	mkdir -p ${BUILDER_LOGS}
1056

    
1057
	echo "Done!"
1058

    
1059
	echo ">>> Cleaning of builder environment has finished."
1060
}
1061

    
1062
# This routine ensures that the $FREEBSD_SRC_DIR has sources
1063
# and is ready for action / building.
1064
ensure_source_directories_present() {
1065
	update_freebsd_sources
1066
}
1067

    
1068
clone_directory_contents() {
1069
	if [ ! -d "$1" -o ! -d "$2" ]; then
1070
		if [ -z "${LOGFILE}" ]; then
1071
			echo ">>> ERROR: Argument $1 supplied is not a directory!"
1072
		else
1073
			echo ">>> ERROR: Argument $1 supplied is not a directory!" | tee -a ${LOGFILE}
1074
		fi
1075
		print_error_pfS
1076
	fi
1077
	echo -n ">>> Using TAR to clone $1 to $2 ..."
1078
	tar -C ${1} -c -f - . | tar -C ${2} -x -p -f -
1079
	echo "Done!"
1080
}
1081

    
1082
clone_to_staging_area() {
1083
	# Clone everything to the final staging area
1084
	echo -n ">>> Cloning everything to ${STAGE_CHROOT_DIR} staging area..."
1085
	LOGFILE=${BUILDER_LOGS}/cloning.${TARGET}.log
1086

    
1087
	tar -C ${PRODUCT_SRC} -c -f - . | \
1088
		tar -C ${STAGE_CHROOT_DIR} -x -p -f -
1089

    
1090
	if [ -f ${STAGE_CHROOT_DIR}/etc/master.passwd ]; then
1091
		chroot ${STAGE_CHROOT_DIR} cap_mkdb /etc/master.passwd
1092
		chroot ${STAGE_CHROOT_DIR} pwd_mkdb /etc/master.passwd
1093
	fi
1094
	mkdir -p ${STAGE_CHROOT_DIR}/etc/mtree
1095
	mtree -Pcp ${STAGE_CHROOT_DIR}/var > ${STAGE_CHROOT_DIR}/etc/mtree/var.dist
1096
	mtree -Pcp ${STAGE_CHROOT_DIR}/etc > ${STAGE_CHROOT_DIR}/etc/mtree/etc.dist
1097
	if [ -d ${STAGE_CHROOT_DIR}/usr/local/etc ]; then
1098
		mtree -Pcp ${STAGE_CHROOT_DIR}/usr/local/etc > ${STAGE_CHROOT_DIR}/etc/mtree/localetc.dist
1099
	fi
1100

    
1101
	## Add buildtime and lastcommit information
1102
	# This is used for detecting updates.
1103
	echo "$BUILTDATESTRING" > $STAGE_CHROOT_DIR/etc/version.buildtime
1104
	# Record last commit info if it is available.
1105
	if [ -f $SCRATCHDIR/build_commit_info.txt ]; then
1106
		cp $SCRATCHDIR/build_commit_info.txt $STAGE_CHROOT_DIR/etc/version.lastcommit
1107
	fi
1108

    
1109
	local _exclude_files="${CORE_PKG_TMP}/base_exclude_files"
1110
	sed \
1111
		-e "s,%%PRODUCT_NAME%%,${PRODUCT_NAME},g" \
1112
		-e "s,%%FLAVOR%%,${_flavor},g" \
1113
		-e "s,%%VERSION%%,${_version},g" \
1114
		${BUILDER_TOOLS}/templates/core_pkg/base/exclude_files \
1115
		> ${_exclude_files}
1116

    
1117
	mkdir -p ${STAGE_CHROOT_DIR}/usr/local/share/${PRODUCT_NAME} >/dev/null 2>&1
1118
	mtree \
1119
		-c \
1120
		-k uid,gid,mode,size,flags,sha256digest \
1121
		-p ${STAGE_CHROOT_DIR} \
1122
		-X ${_exclude_files} \
1123
		> ${STAGE_CHROOT_DIR}/usr/local/share/${PRODUCT_NAME}/base.mtree
1124
	tar \
1125
		-C ${STAGE_CHROOT_DIR} \
1126
		-cJf ${STAGE_CHROOT_DIR}/usr/local/share/${PRODUCT_NAME}/base.txz \
1127
		-X ${_exclude_files} \
1128
		.
1129

    
1130
	core_pkg_create base "" ${CORE_PKG_VERSION} ${STAGE_CHROOT_DIR}
1131
	core_pkg_create default-config "" ${CORE_PKG_VERSION} ${STAGE_CHROOT_DIR}
1132

    
1133
	local DEFAULTCONF=${STAGE_CHROOT_DIR}/conf.default/config.xml
1134
	# Activate serial console in config.xml
1135
	# If it was there before, clear the setting to be sure we don't add it twice.
1136
	sed -i "" -e "/		<enableserial\/>/d" ${DEFAULTCONF}
1137
	# Enable serial in the config
1138
	sed -i "" -e "s/	<\/system>/		<enableserial\/>\\$(echo -e \\\n)	<\/system>/" ${DEFAULTCONF}
1139

    
1140
	echo force > ${STAGE_CHROOT_DIR}/cf/conf/enableserial_force
1141

    
1142
	core_pkg_create default-config-serial "" ${CORE_PKG_VERSION} ${STAGE_CHROOT_DIR}
1143

    
1144
	rm -f ${STAGE_CHROOT_DIR}/cf/conf/enableserial_force
1145
	rm -f ${STAGE_CHROOT_DIR}/cf/conf/config.xml
1146

    
1147
	# Make sure pkg is present
1148
	pkg_bootstrap ${STAGE_CHROOT_DIR}
1149

    
1150
	pkg_chroot_add ${STAGE_CHROOT_DIR} base
1151

    
1152
	echo "Done!"
1153
}
1154

    
1155
create_final_staging_area() {
1156
	if [ -z "${FINAL_CHROOT_DIR}" ]; then
1157
		echo ">>> ERROR: FINAL_CHROOT_DIR is not set, cannot continue!" | tee -a ${LOGFILE}
1158
		print_error_pfS
1159
	fi
1160

    
1161
	if [ -d "${FINAL_CHROOT_DIR}" ]; then
1162
		echo -n ">>> Previous ${FINAL_CHROOT_DIR} detected cleaning up..." | tee -a ${LOGFILE}
1163
		chflags -R noschg ${FINAL_CHROOT_DIR} 2>&1 1>/dev/null
1164
		rm -rf ${FINAL_CHROOT_DIR}/* 2>&1 1>/dev/null
1165
		echo "Done." | tee -a ${LOGFILE}
1166
	fi
1167
	mkdir -p ${FINAL_CHROOT_DIR}
1168

    
1169
	echo ">>> Preparing Final image staging area: $(LC_ALL=C date)" 2>&1 | tee -a ${LOGFILE}
1170
	echo ">>> Cloning ${STAGE_CHROOT_DIR} to ${FINAL_CHROOT_DIR}" 2>&1 | tee -a ${LOGFILE}
1171
	clone_directory_contents ${STAGE_CHROOT_DIR} ${FINAL_CHROOT_DIR}
1172

    
1173
	if [ ! -f $FINAL_CHROOT_DIR/sbin/init ]; then
1174
		echo ">>> ERROR: Something went wrong during cloning -- Please verify!" 2>&1 | tee -a ${LOGFILE}
1175
		print_error_pfS
1176
	fi
1177
}
1178

    
1179
customize_stagearea_for_image() {
1180
	# Prepare final stage area
1181
	create_final_staging_area
1182

    
1183
	if [ "${1}" = "iso" -o \
1184
	     "${1}" = "memstick" -o \
1185
	     "${1}" = "memstickserial" -o \
1186
	     "${1}" = "memstickadi" ]; then
1187
		install_bsdinstaller
1188
		mkdir -p ${FINAL_CHROOT_DIR}/pkgs
1189
		cp ${CORE_PKG_PATH}/*default-config*.txz ${FINAL_CHROOT_DIR}/pkgs
1190
	fi
1191

    
1192
	if [ "${1}" = "nanobsd" -o \
1193
	     "${1}" = "memstickserial" -o \
1194
	     "${1}" = "memstickadi" ]; then
1195
		pkg_chroot_add ${FINAL_CHROOT_DIR} default-config-serial
1196
	else
1197
		pkg_chroot_add ${FINAL_CHROOT_DIR} default-config
1198
	fi
1199
}
1200

    
1201
create_distribution_tarball() {
1202
	mkdir -p ${FINAL_CHROOT_DIR}/install
1203

    
1204
	tar -C ${FINAL_CHROOT_DIR} --exclude ./install --exclude ./pkgs -cJf ${FINAL_CHROOT_DIR}/install/${PRODUCT_NAME}.txz .
1205
}
1206

    
1207
create_iso_image() {
1208
	LOGFILE=${BUILDER_LOGS}/isoimage.${TARGET}
1209
	echo ">>> Building bootable ISO image for ${TARGET}" | tee -a ${LOGFILE}
1210
	if [ -z "${DEFAULT_KERNEL}" ]; then
1211
		echo ">>> ERROR: Could not identify DEFAULT_KERNEL to install on image!" | tee -a ${LOGFILE}
1212
		print_error_pfS
1213
	fi
1214

    
1215
	customize_stagearea_for_image "iso"
1216
	install_default_kernel ${DEFAULT_KERNEL}
1217

    
1218
	echo cdrom > $FINAL_CHROOT_DIR/etc/platform
1219

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

    
1223
	# This check is for supporting create memstick/ova images
1224
	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}
1225
	echo "-o label=${FSLABEL} -o publisher=\"${PRODUCT_NAME} project.\" $ISOPATH ${FINAL_CHROOT_DIR}" | tee -a ${LOGFILE}
1226

    
1227
	create_distribution_tarball
1228

    
1229
	# Remove /rescue from iso since cd9660 cannot deal with hardlinks
1230
	rm -rf ${FINAL_CHROOT_DIR}/rescue
1231

    
1232
	makefs -t cd9660 -o bootimage="i386;${FINAL_CHROOT_DIR}/boot/cdboot" -o no-emul-boot -o rockridge \
1233
		-o label=${FSLABEL} -o publisher="${PRODUCT_NAME} project." $ISOPATH ${FINAL_CHROOT_DIR} 2>&1 >> ${LOGFILE}
1234
	if [ $? -ne 0 -o ! -f $ISOPATH ]; then
1235
		if [ -f ${ISOPATH} ]; then
1236
			rm -f $ISOPATH
1237
		fi
1238
		echo ">>> ERROR: Something wrong happened during ISO image creation. STOPPING!" | tee -a ${LOGFILE}
1239
		print_error_pfS
1240
	fi
1241
	gzip -qf $ISOPATH &
1242

    
1243
	echo ">>> ISO created: $(LC_ALL=C date)" | tee -a ${LOGFILE}
1244
}
1245

    
1246
create_memstick_image() {
1247

    
1248
	LOGFILE=${BUILDER_LOGS}/memstick.${TARGET}
1249
	if [ "${MEMSTICKPATH}" = "" ]; then
1250
		echo ">>> MEMSTICKPATH is empty skipping generation of memstick image!" | tee -a ${LOGFILE}
1251
		return
1252
	fi
1253

    
1254
	if [ ! -d ${FINAL_CHROOT_DIR}/boot ]; then
1255
		customize_stagearea_for_image "memstick"
1256
		install_default_kernel ${DEFAULT_KERNEL}
1257
	fi
1258

    
1259
	echo cdrom > $FINAL_CHROOT_DIR/etc/platform
1260

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

    
1265
	create_distribution_tarball
1266

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

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

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

    
1295
	if [ ! -d ${FINAL_CHROOT_DIR}/boot ]; then
1296
		customize_stagearea_for_image "memstickserial"
1297
		install_default_kernel ${DEFAULT_KERNEL}
1298
	fi
1299

    
1300
	echo cdrom > $FINAL_CHROOT_DIR/etc/platform
1301

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

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

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

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

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

    
1326
	create_distribution_tarball
1327

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

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

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

    
1356
	if [ ! -d ${FINAL_CHROOT_DIR}/boot ]; then
1357
		customize_stagearea_for_image "memstickadi"
1358
		install_default_kernel ${DEFAULT_KERNEL}
1359
	fi
1360

    
1361
	echo cdrom > $FINAL_CHROOT_DIR/etc/platform
1362

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

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

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

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

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

    
1389
	create_distribution_tarball
1390

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

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

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

    
1418
	local _target="${1}"
1419
	local _arch="${2}"
1420
	local _target_arch="${3}"
1421
	local _branch="${4}"
1422

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

    
1425
	sed \
1426
		-e "s/%%ARCH%%/${_arch}_${_target_arch}/" \
1427
		-e "s/%%GIT_REPO_BRANCH_OR_TAG%%/${_branch}/g" \
1428
		-e "s,%%PKG_REPO_SERVER%%,${PKG_REPO_SERVER},g" \
1429
		-e "s/%%PRODUCT_NAME%%/${PRODUCT_NAME}/g" \
1430
		${FREEBSD_SRC_DIR}/release/pkg_repos/${PRODUCT_NAME}.conf.template \
1431
		> ${_target}
1432
}
1433

    
1434
# This routine ensures any ports / binaries that the builder
1435
# system needs are on disk and ready for execution.
1436
builder_setup() {
1437
	# If Product-builder is already installed, just leave
1438
	if pkg info -e -q ${PRODUCT_NAME}-builder; then
1439
		return
1440
	fi
1441

    
1442
	if [ ! -f /usr/local/etc/pkg/repos/${PRODUCT_NAME}.conf ]; then
1443
		[ -d /usr/local/etc/pkg/repos ] \
1444
			|| mkdir -p /usr/local/etc/pkg/repos
1445

    
1446
		local _arch=$(uname -m)
1447
		setup_pkg_repo /usr/local/etc/pkg/repos/${PRODUCT_NAME}.conf ${_arch} ${_arch} ${PKG_REPO_CONF_BRANCH}
1448
	fi
1449

    
1450
	pkg install ${PRODUCT_NAME}-builder
1451
}
1452

    
1453
# Updates FreeBSD sources
1454
update_freebsd_sources() {
1455
	if [ "${1}" = "full" ]; then
1456
		local _full=1
1457
		local _clone_params=""
1458
	else
1459
		local _full=0
1460
		local _clone_params="--depth 1 --single-branch"
1461
	fi
1462

    
1463
	if [ ! -d "${FREEBSD_SRC_DIR}" ]; then
1464
		mkdir -p ${FREEBSD_SRC_DIR}
1465
	fi
1466

    
1467
	if [ -n "${NO_BUILDWORLD:-}" -a -n "${NO_BUILDKERNEL:-}" ]; then
1468
		echo ">>> NO_BUILDWORLD and NO_BUILDKERNEL set, skipping update of freebsd sources" | tee -a ${LOGFILE}
1469
		return
1470
	fi
1471

    
1472
	echo -n ">>> Obtaining FreeBSD sources ${FREEBSD_BRANCH}..."
1473
	local _FREEBSD_BRANCH=${FREEBSD_BRANCH:-"devel"}
1474
	local _CLONE=1
1475

    
1476
	if [ -d "${FREEBSD_SRC_DIR}/.git" ]; then
1477
		CUR_BRANCH=$(cd ${FREEBSD_SRC_DIR} && git branch | grep '^\*' | cut -d' ' -f2)
1478
		if [ ${_full} -eq 0 -a "${CUR_BRANCH}" = "${_FREEBSD_BRANCH}" ]; then
1479
			_CLONE=0
1480
			( cd ${FREEBSD_SRC_DIR} && git clean -fxd; git fetch origin; git reset --hard origin/${_FREEBSD_BRANCH} ) 2>&1 | grep -C3 -i -E 'error|fatal'
1481
		else
1482
			rm -rf ${FREEBSD_SRC_DIR}
1483
		fi
1484
	fi
1485

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

    
1490
	if [ ! -d "${FREEBSD_SRC_DIR}/.git" ]; then
1491
		echo ">>> ERROR: It was not possible to clone FreeBSD src repo"
1492
		print_error_pfS
1493
	fi
1494

    
1495
	if [ -n "${GIT_FREEBSD_COSHA1}" ]; then
1496
		( cd ${FREEBSD_SRC_DIR} && git checkout ${GIT_FREEBSD_COSHA1} ) 2>&1 | grep -C3 -i -E 'error|fatal'
1497
	fi
1498
	echo "Done!"
1499
}
1500

    
1501
pkg_chroot() {
1502
	local _root="${1}"
1503
	shift
1504

    
1505
	if [ $# -eq 0 ]; then
1506
		return -1
1507
	fi
1508

    
1509
	if [ -z "${_root}" -o "${_root}" = "/" -o ! -d "${_root}" ]; then
1510
		return -1
1511
	fi
1512

    
1513
	mkdir -p \
1514
		${SCRATCHDIR}/pkg_cache \
1515
		${_root}/var/cache/pkg \
1516
		${_root}/dev
1517

    
1518
	/sbin/mount -t nullfs ${SCRATCHDIR}/pkg_cache ${_root}/var/cache/pkg
1519
	/sbin/mount -t devfs devfs ${_root}/dev
1520
	cp -f /etc/resolv.conf ${_root}/etc/resolv.conf
1521
	touch ${BUILDER_LOGS}/install_pkg_install_ports.txt
1522
	script -aq ${BUILDER_LOGS}/install_pkg_install_ports.txt pkg -c ${_root} $@ >/dev/null 2>&1
1523
	rm -f ${_root}/etc/resolv.conf
1524
	/sbin/umount -f ${_root}/dev
1525
	/sbin/umount -f ${_root}/var/cache/pkg
1526
}
1527

    
1528

    
1529
pkg_chroot_add() {
1530
	if [ -z "${1}" -o -z "${2}" ]; then
1531
		return 1
1532
	fi
1533

    
1534
	local _target="${1}"
1535
	local _pkg="$(get_pkg_name ${2}).txz"
1536

    
1537
	if [ ! -d "${_target}" ]; then
1538
		echo ">>> ERROR: Target dir ${_target} not found"
1539
		print_error_pfS
1540
	fi
1541

    
1542
	if [ ! -f ${CORE_PKG_PATH}/${_pkg} ]; then
1543
		echo ">>> ERROR: Package ${_pkg} not found"
1544
		print_error_pfS
1545
	fi
1546

    
1547
	cp ${CORE_PKG_PATH}/${_pkg} ${_target}
1548
	pkg_chroot ${_target} add /${_pkg}
1549
	rm -f ${_target}/${_pkg}
1550
}
1551

    
1552
pkg_bootstrap() {
1553
	local _root=${1:-"${STAGE_CHROOT_DIR}"}
1554

    
1555
	setup_pkg_repo ${_root}/usr/local/etc/pkg/repos/${PRODUCT_NAME}.conf ${TARGET} ${TARGET_ARCH} ${PKG_REPO_CONF_BRANCH}
1556

    
1557
	pkg_chroot ${_root} bootstrap -f
1558
}
1559

    
1560
# This routine assists with installing various
1561
# freebsd ports files into the pfsenese-fs staging
1562
# area.
1563
install_pkg_install_ports() {
1564
	local MAIN_PKG="${1}"
1565

    
1566
	if [ -z "${MAIN_PKG}" ]; then
1567
		MAIN_PKG=${PRODUCT_NAME}
1568
	fi
1569

    
1570
	echo ">>> Installing pkg repository in chroot (${STAGE_CHROOT_DIR})..."
1571

    
1572
	[ -d ${STAGE_CHROOT_DIR}/var/cache/pkg ] || \
1573
		mkdir -p ${STAGE_CHROOT_DIR}/var/cache/pkg
1574

    
1575
	[ -d ${SCRATCHDIR}/pkg_cache ] || \
1576
		mkdir -p ${SCRATCHDIR}/pkg_cache
1577

    
1578
	echo ">>> Installing built ports (packages) in chroot (${STAGE_CHROOT_DIR})... (starting)"
1579
	pkg_chroot ${STAGE_CHROOT_DIR} install ${MAIN_PKG} ${custom_package_list}
1580
	pkg_chroot ${STAGE_CHROOT_DIR} autoremove
1581
	echo ">>> Installing built ports (packages) in chroot (${STAGE_CHROOT_DIR})... (finshied)"
1582
}
1583

    
1584
install_bsdinstaller() {
1585
	echo ">>> Installing BSDInstaller in chroot (${FINAL_CHROOT_DIR})... (starting)"
1586
	pkg_chroot ${FINAL_CHROOT_DIR} install -f bsdinstaller ${MAIN_PKG} ${custom_package_list}
1587
	echo ">>> Installing BSDInstaller in chroot (${FINAL_CHROOT_DIR})... (finished)"
1588
}
1589

    
1590
staginareas_clean_each_run() {
1591
	echo -n ">>> Cleaning build directories: "
1592
	if [ -d "${FINAL_CHROOT_DIR}" ]; then
1593
		BASENAME=$(basename ${FINAL_CHROOT_DIR})
1594
		echo -n "$BASENAME "
1595
		chflags -R noschg ${FINAL_CHROOT_DIR} 2>&1 >/dev/null
1596
		rm -rf ${FINAL_CHROOT_DIR} 2>/dev/null
1597
	fi
1598
	echo "Done!"
1599
}
1600

    
1601
# Imported from FreeSBIE
1602
buildkernel() {
1603
	if [ -n "${NO_BUILDKERNEL:-}" ]; then
1604
		echo ">>> NO_BUILDKERNEL set, skipping build" | tee -a ${LOGFILE}
1605
		return
1606
	fi
1607

    
1608
	if [ -z "${KERNCONF:-}" ]; then
1609
		echo ">>> ERROR: No kernel configuration defined probably this is not what you want! STOPPING!" | tee -a ${LOGFILE}
1610
		print_error_pfS
1611
	fi
1612

    
1613
	if [ -n "${KERNELCONF:-}" ]; then
1614
		export KERNCONFDIR=$(dirname ${KERNELCONF})
1615
		export KERNCONF=$(basename ${KERNELCONF})
1616
	fi
1617

    
1618
	SRCCONFBASENAME=$(basename ${SRC_CONF})
1619
	echo ">>> KERNCONFDIR: ${KERNCONFDIR}"
1620
	echo ">>> ARCH:        ${TARGET}"
1621
	echo ">>> SRC_CONF:    ${SRCCONFBASENAME}"
1622

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

    
1628
# Imported from FreeSBIE
1629
installkernel() {
1630
	if [ -z "${KERNCONF:-}" ]; then
1631
		echo ">>> ERROR: No kernel configuration defined probably this is not what you want! STOPPING!" | tee -a ${LOGFILE}
1632
		print_error_pfS
1633
	fi
1634

    
1635
	if [ -n "${KERNELCONF:-}" ]; then
1636
		export KERNCONFDIR=$(dirname ${KERNELCONF})
1637
		export KERNCONF=$(basename ${KERNELCONF})
1638
	fi
1639

    
1640
	mkdir -p ${STAGE_CHROOT_DIR}/boot
1641
	makeargs="${MAKEJ_KERNEL:-} SRCCONF=${SRC_CONF} __MAKE_CONF=${MAKE_CONF} TARGET_ARCH=${TARGET_ARCH} TARGET=${TARGET} DESTDIR=${KERNEL_DESTDIR}"
1642
	echo ">>> Builder is running the command: script -aq $LOGFILE make ${makeargs:-} installkernel KERNCONF=${KERNCONF}"  | tee -a $LOGFILE
1643
	(script -aq $LOGFILE make -C ${FREEBSD_SRC_DIR} ${makeargs:-} installkernel KERNCONF=${KERNCONF} || print_error_pfS;) | egrep '^>>>'
1644
	gzip -f9 $KERNEL_DESTDIR/boot/kernel/kernel
1645
}
1646

    
1647
# Launch is ran first to setup a few variables that we need
1648
# Imported from FreeSBIE
1649
launch() {
1650

    
1651
	if [ ! -f $SCRATCHDIR/${PRODUCT_NAME}_builder_set_time ]; then
1652
		echo ">>> Updating system clock..."
1653
		ntpdate 0.freebsd.pool.ntp.org
1654
		touch $SCRATCHDIR/${PRODUCT_NAME}_builder_set_time
1655
	fi
1656

    
1657
	if [ "$(id -u)" != "0" ]; then
1658
		echo "Sorry, this must be done as root."
1659
	fi
1660

    
1661
	echo ">>> Operation $0 has started at $(date)"
1662
}
1663

    
1664
finish() {
1665
	echo ">>> Operation $0 has ended at $(date)"
1666
}
1667

    
1668
poudriere_create_patch() {
1669
	local _jail_patch="${SCRATCHDIR}/poudriere_jail.${GIT_REPO_BRANCH_OR_TAG}.patch"
1670

    
1671
	if [ -z "${FREEBSD_PARENT_BRANCH}" ]; then
1672
		echo ">>> ERROR: FREEBSD_PARENT_BRANCH is not set"
1673
	fi
1674

    
1675
	LOGFILE=${BUILDER_LOGS}/poudriere.log
1676

    
1677
	# Get FreeBSD source and apply patches
1678
	update_freebsd_sources full
1679

    
1680
	[ -f "${_jail_patch}" ] && \
1681
		rm -f "${_jail_patch}"
1682

    
1683
	# Create a big patch with all our changes to use on jail
1684
	( \
1685
		cd ${FREEBSD_SRC_DIR} && \
1686
		git diff $(git merge-base origin/${FREEBSD_PARENT_BRANCH} ${FREEBSD_BRANCH}) > ${_jail_patch}
1687
	) >/dev/null 2>&1
1688

    
1689
	# Check if patch was created
1690
	if [ ! -s "${_jail_patch}" ]; then
1691
		echo ">>> ERROR: Patch does not exist or is empty, aborting..." | tee -a ${LOGFILE}
1692
		print_error_pfS
1693
	fi
1694
}
1695

    
1696
poudriere_possible_archs() {
1697
	local _arch=$(uname -m)
1698
	local _archs="i386.i386"
1699

    
1700
	# IF host is amd64, we'll create both repos, and if possible armv6
1701
	if [ "${_arch}" = "amd64" ]; then
1702
		_archs="amd64.amd64 ${_archs}"
1703

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

    
1708
			if binmiscctl lookup armv6 >/dev/null 2>&1; then
1709
				_archs="${_archs} arm.armv6"
1710
			fi
1711
		fi
1712
	fi
1713

    
1714
	echo ${_archs}
1715
}
1716

    
1717
poudriere_jail_name() {
1718
	local _jail_arch="${1}"
1719

    
1720
	if [ -z "${_jail_arch}" ]; then
1721
		return 1
1722
	fi
1723

    
1724
	# Poudriere doesn't like periods in jail names
1725
	_jail_arch=$(echo "${_jail_arch}" | tr '.' '_')
1726

    
1727
	echo "${PRODUCT_NAME}_${GIT_REPO_BRANCH_OR_TAG}_${_jail_arch}"
1728
}
1729

    
1730
poudriere_create_ports_tree() {
1731
	LOGFILE=${BUILDER_LOGS}/poudriere.log
1732

    
1733
	if ! poudriere ports -l | grep -q -E "^${POUDRIERE_PORTS_NAME}[[:blank:]]"; then
1734
		local _branch=""
1735
		if [ -z "${POUDRIERE_PORTS_GIT_URL}" ]; then
1736
			echo ">>> ERROR: POUDRIERE_PORTS_GIT_URL is not defined"
1737
			print_error_pfS
1738
		fi
1739
		if [ -n "${POUDRIERE_PORTS_GIT_BRANCH}" ]; then
1740
			_branch="-B ${POUDRIERE_PORTS_GIT_BRANCH}"
1741
		fi
1742
		echo -n ">>> Creating poudriere ports tree, it may take some time... " | tee -a ${LOGFILE}
1743
		if ! script -aq ${LOGFILE} poudriere ports -c -p "${POUDRIERE_PORTS_NAME}" -m git ${_branch} >/dev/null 2>&1; then
1744
			echo "" | tee -a ${LOGFILE}
1745
			echo ">>> ERROR: Error creating poudriere ports tree, aborting..." | tee -a ${LOGFILE}
1746
			print_error_pfS
1747
		fi
1748
		echo "Done!" | tee -a ${LOGFILE}
1749
	fi
1750
}
1751

    
1752
poudriere_init() {
1753
	local _error=0
1754
	local _archs=$(poudriere_possible_archs)
1755
	local _jail_patch="${SCRATCHDIR}/poudriere_jail.${GIT_REPO_BRANCH_OR_TAG}.patch"
1756

    
1757
	LOGFILE=${BUILDER_LOGS}/poudriere.log
1758

    
1759
	# Sanity checks
1760
	if [ -z "${ZFS_TANK}" ]; then
1761
		echo ">>> ERROR: \$ZFS_TANK is empty" | tee -a ${LOGFILE}
1762
		error=1
1763
	fi
1764

    
1765
	if [ -z "${ZFS_ROOT}" ]; then
1766
		echo ">>> ERROR: \$ZFS_ROOT is empty" | tee -a ${LOGFILE}
1767
		error=1
1768
	fi
1769

    
1770
	if [ -z "${POUDRIERE_PORTS_NAME}" ]; then
1771
		echo ">>> ERROR: \$POUDRIERE_PORTS_NAME is empty" | tee -a ${LOGFILE}
1772
		error=1
1773
	fi
1774

    
1775
	if [ ${_error} -eq 1 ]; then
1776
		print_error_pfS
1777
	fi
1778

    
1779
	# Check if zpool exists
1780
	if ! zpool list ${ZFS_TANK} >/dev/null 2>&1; then
1781
		echo ">>> ERROR: ZFS tank ${ZFS_TANK} not found, please create it and try again..." | tee -a ${LOGFILE}
1782
		print_error_pfS
1783
	fi
1784

    
1785
	# Check if zfs rootfs exists
1786
	if ! zfs list ${ZFS_TANK}${ZFS_ROOT} >/dev/null 2>&1; then
1787
		echo ">>> ERROR: ZFS filesystem ${ZFS_TANK}${ZFS_ROOT} not found, please create it and try again..." | tee -a ${LOGFILE}
1788
		print_error_pfS
1789
	fi
1790

    
1791
	# Make sure poudriere is installed
1792
	if ! pkg info --quiet poudriere; then
1793
		echo ">>> Installing poudriere..." | tee -a ${LOGFILE}
1794
		if ! pkg install poudriere >/dev/null 2>&1; then
1795
			echo ">>> ERROR: poudriere was not installed, aborting..." | tee -a ${LOGFILE}
1796
			print_error_pfS
1797
		fi
1798
	fi
1799

    
1800
	# Create poudriere.conf
1801
	if [ -z "${POUDRIERE_PORTS_GIT_URL}" ]; then
1802
		echo ">>> ERROR: POUDRIERE_PORTS_GIT_URL is not defined"
1803
		print_error_pfS
1804
	fi
1805
	echo ">>> Creating poudriere.conf" | tee -a ${LOGFILE}
1806
	cat <<EOF >/usr/local/etc/poudriere.conf
1807
ZPOOL=${ZFS_TANK}
1808
ZROOTFS=${ZFS_ROOT}
1809
RESOLV_CONF=/etc/resolv.conf
1810
BASEFS=/usr/local/poudriere
1811
USE_PORTLINT=no
1812
USE_TMPFS=yes
1813
NOLINUX=yes
1814
DISTFILES_CACHE=/usr/ports/distfiles
1815
CHECK_CHANGED_OPTIONS=yes
1816
CHECK_CHANGED_DEPS=yes
1817
ATOMIC_PACKAGE_REPOSITORY=yes
1818
COMMIT_PACKAGES_ON_FAILURE=no
1819
GIT_URL="${POUDRIERE_PORTS_GIT_URL}"
1820
EOF
1821

    
1822
	# Remove old jails
1823
	for jail_arch in ${_archs}; do
1824
		jail_name=$(poudriere_jail_name ${jail_arch})
1825

    
1826
		if poudriere jail -i -j "${jail_name}" >/dev/null 2>&1; then
1827
			echo ">>> Poudriere jail ${jail_name} already exists, deleting it..." | tee -a ${LOGFILE}
1828
			poudriere jail -d -j "${jail_name}" >/dev/null 2>&1
1829
		fi
1830
	done
1831

    
1832
	# Remove old ports tree
1833
	if poudriere ports -l | grep -q -E "^${POUDRIERE_PORTS_NAME}[[:blank:]]"; then
1834
		echo ">>> Poudriere ports tree ${POUDRIERE_PORTS_NAME} already exists, deleting it..." | tee -a ${LOGFILE}
1835
		poudriere ports -d -p "${POUDRIERE_PORTS_NAME}"
1836
	fi
1837

    
1838
	poudriere_create_patch
1839

    
1840
	local native_xtools=""
1841
	# Now we are ready to create jails
1842
	for jail_arch in ${_archs}; do
1843
		jail_name=$(poudriere_jail_name ${jail_arch})
1844

    
1845
		if [ "${jail_arch}" = "arm.armv6" ]; then
1846
			native_xtools="-x"
1847
		else
1848
			native_xtools=""
1849
		fi
1850

    
1851
		echo -n ">>> Creating jail ${jail_name}, it may take some time... " | tee -a ${LOGFILE}
1852
		# XXX: Change -m to git when it's available in poudriere
1853
		if ! script -aq ${LOGFILE} poudriere jail -c -j "${jail_name}" -v ${FREEBSD_PARENT_BRANCH} \
1854
				-a ${jail_arch} -m svn -P ${_jail_patch} ${native_xtools} >/dev/null 2>&1; then
1855
			echo "" | tee -a ${LOGFILE}
1856
			echo ">>> ERROR: Error creating jail ${jail_name}, aborting..." | tee -a ${LOGFILE}
1857
			print_error_pfS
1858
		fi
1859
		echo "Done!" | tee -a ${LOGFILE}
1860
	done
1861

    
1862
	poudriere_create_ports_tree
1863

    
1864
	echo ">>> Poudriere is now configured!" | tee -a ${LOGFILE}
1865
}
1866

    
1867
poudriere_update_jails() {
1868
	local _archs=$(poudriere_possible_archs)
1869
	local _jail_patch="${SCRATCHDIR}/poudriere_jail.${GIT_REPO_BRANCH_OR_TAG}.patch"
1870

    
1871
	LOGFILE=${BUILDER_LOGS}/poudriere.log
1872

    
1873
	poudriere_create_patch
1874

    
1875
	local native_xtools=""
1876
	for jail_arch in ${_archs}; do
1877
		local _run=0
1878
		if [ -n "${ARCH_LIST}" ]; then
1879
			for _arch in ${ARCH_LIST}; do
1880
				if [ "${jail_arch##*.}" = "${_arch}" ]; then
1881
					_run=1
1882
				fi
1883
			done
1884
		else
1885
			_run=1
1886
		fi
1887

    
1888
		[ ${_run} -eq 0 ] \
1889
			&& continue
1890

    
1891
		jail_name=$(poudriere_jail_name ${jail_arch})
1892

    
1893
		if ! poudriere jail -i -j "${jail_name}" >/dev/null 2>&1; then
1894
			echo ">>> Poudriere jail ${jail_name} not found, skipping..." | tee -a ${LOGFILE}
1895
			continue
1896
		fi
1897

    
1898
		if [ "${jail_arch}" = "arm.armv6" ]; then
1899
			native_xtools="-x"
1900
		else
1901
			native_xtools=""
1902
		fi
1903

    
1904
		echo -n ">>> Updating jail ${jail_name}, it may take some time... " | tee -a ${LOGFILE}
1905
		if ! script -aq ${LOGFILE} poudriere jail -u -j "${jail_name}" -P ${_jail_patch} ${native_xtools} >/dev/null 2>&1; then
1906
			echo "" | tee -a ${LOGFILE}
1907
			echo ">>> ERROR: Error updating jail ${jail_name}, aborting..." | tee -a ${LOGFILE}
1908
			print_error_pfS
1909
		fi
1910
		echo "Done!" | tee -a ${LOGFILE}
1911
	done
1912
}
1913

    
1914
poudriere_update_ports() {
1915
	LOGFILE=${BUILDER_LOGS}/poudriere.log
1916

    
1917
	# Create ports tree if necessary
1918
	if ! poudriere ports -l | grep -q -E "^${POUDRIERE_PORTS_NAME}[[:blank:]]"; then
1919
		poudriere_create_ports_tree
1920
	else
1921
		echo -n ">>> Updating ports tree ${POUDRIERE_PORTS_NAME}... " | tee -a ${LOGFILE}
1922
		script -aq ${LOGFILE} poudriere ports -u -p "${POUDRIERE_PORTS_NAME}" >/dev/null 2>&1
1923
		echo "Done!" | tee -a ${LOGFILE}
1924
	fi
1925
}
1926

    
1927
poudriere_bulk() {
1928
	local _archs=$(poudriere_possible_archs)
1929

    
1930
	LOGFILE=${BUILDER_LOGS}/poudriere.log
1931

    
1932
	poudriere_create_ports_tree
1933

    
1934
	[ -d /usr/local/etc/poudriere.d ] || \
1935
		mkdir -p /usr/local/etc/poudriere.d
1936

    
1937
	if [ -f "${BUILDER_TOOLS}/conf/pfPorts/make.conf" ]; then
1938
		cp -f "${BUILDER_TOOLS}/conf/pfPorts/make.conf" /usr/local/etc/poudriere.d/${POUDRIERE_PORTS_NAME}-make.conf
1939
	fi
1940

    
1941
	for jail_arch in ${_archs}; do
1942
		jail_name=$(poudriere_jail_name ${jail_arch})
1943

    
1944
		if ! poudriere jail -i -j "${jail_name}" >/dev/null 2>&1; then
1945
			echo ">>> Poudriere jail ${jail_name} not found, skipping..." | tee -a ${LOGFILE}
1946
			continue
1947
		fi
1948

    
1949
		if [ -f "${POUDRIERE_BULK}.${jail_arch}" ]; then
1950
			_ref_bulk="${POUDRIERE_BULK}.${jail_arch}"
1951
		else
1952
			_ref_bulk="${POUDRIERE_BULK}"
1953
		fi
1954

    
1955
		_bulk=${SCRATCHDIR}/poudriere_bulk.${GIT_REPO_BRANCH_OR_TAG}
1956
		sed -e "s,%%PRODUCT_NAME%%,${PRODUCT_NAME},g" ${_ref_bulk} > ${_bulk}
1957

    
1958
		if ! poudriere bulk -f ${_bulk} -j ${jail_name} -p ${POUDRIERE_PORTS_NAME}; then
1959
			echo ">>> ERROR: Something went wrong..."
1960
			print_error_pfS
1961
		fi
1962

    
1963
		echo ">>> Cleaning up old packages from repo..."
1964
		if ! poudriere pkgclean -f ${_bulk} -j ${jail_name} -p ${POUDRIERE_PORTS_NAME} -y; then
1965
			echo ">>> ERROR: Something went wrong..."
1966
			print_error_pfS
1967
		fi
1968

    
1969
		# ./ is intentional, it's a rsync trick to make it chdir to directory before send it
1970
		REPO_PATH="/usr/local/poudriere/data/packages/./${jail_name}-${POUDRIERE_PORTS_NAME}"
1971
		if [ -z "${DO_NOT_UPLOAD}" -a -d "${REPO_PATH}" ]; then
1972
			echo -n ">>> Sending updated repository to ${PKG_RSYNC_HOSTNAME}... " | tee -a ${LOGFILE}
1973
			if script -aq ${LOGFILE} rsync -ave "ssh -p ${PKG_RSYNC_SSH_PORT}" \
1974
				--timeout=60 --delete-delay ${REPO_PATH} \
1975
				${PKG_RSYNC_USERNAME}@${PKG_RSYNC_HOSTNAME}:${PKG_RSYNC_DESTDIR} >/dev/null 2>&1
1976
			then
1977
				echo "Done!" | tee -a ${LOGFILE}
1978
			else
1979
				echo "Failed!" | tee -a ${LOGFILE}
1980
				echo ">>> ERROR: An error occurred sending repo to remote hostname"
1981
				print_error_pfS
1982
			fi
1983
		fi
1984
	done
1985
}
(2-2/3)