Project

General

Profile

Download (67 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 [ "$MAKEOBJDIRPREFIXFINAL" != "" ]; then
47
	mkdir -p $MAKEOBJDIRPREFIXFINAL
48
else
49
	echo "MAKEOBJDIRPREFIXFINAL 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
	if [ -d "${GIT_REPO_DIR}/${GIT_REPO_BRANCH_OR_TAG}/.git" ]; then
59
		CURRENT_COMMIT=$(cd ${GIT_REPO_DIR}/${GIT_REPO_BRANCH_OR_TAG} && git log -1 --format='%H')
60
		CURRENT_AUTHOR=$(cd ${GIT_REPO_DIR}/${GIT_REPO_BRANCH_OR_TAG} && git log -1 --format='%an')
61
		echo ">>> Last known commit $CURRENT_AUTHOR - $CURRENT_COMMIT"
62
		echo "$CURRENT_COMMIT" > $SCRATCHDIR/build_commit_info.txt
63
	else
64
		echo ">>> WARNING: git repo is not cloned! Previous commit functions disabled."
65
	fi
66
}
67

    
68
# Create core pkg (base, kernel)
69
core_pkg_create() {
70
	local _template="${1}"
71
	local _flavor="${2}"
72
	local _version="${3}"
73
	local _root="${4}"
74

    
75
	[ -d "${CORE_PKG_TMP}" ] \
76
		&& rm -rf ${CORE_PKG_TMP}
77

    
78
	local _templates_path=${BUILDER_SCRIPTS}/templates/core_pkg/${_template}
79
	local _template_metadir=${_templates_path}/metadir
80
	local _metadir=${CORE_PKG_TMP}/${_template}_metadir
81

    
82
	if [ ! -d ${_template_metadir} ]; then
83
		echo "ERROR: Template dir not found for pkg ${_template}"
84
		exit
85
	fi
86

    
87
	mkdir -p ${CORE_PKG_TMP}
88

    
89
	cp -r ${_template_metadir} ${_metadir}
90

    
91
	local _manifest=${_metadir}/+MANIFEST
92
	local _plist=${CORE_PKG_TMP}/${_template}_plist
93
	local _exclude_plist=${CORE_PKG_TMP}/${_template}_exclude_plist
94

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

    
101
	if [ -f "${_templates_path}/exclude_plist" ]; then
102
		cp ${_templates_path}/exclude_plist ${_exclude_plist}
103
	else
104
		touch ${_exclude_plist}
105
	fi
106

    
107
	sed \
108
		-i '' \
109
		-e "s,%%PRODUCT_NAME%%,${PRODUCT_NAME},g" \
110
		-e "s,%%PRODUCT_URL%%,${PRODUCT_URL},g" \
111
		-e "s,%%FLAVOR%%,${_flavor},g" \
112
		-e "s,%%VERSION%%,${_version},g" \
113
		${_metadir}/* \
114
		${_plist} \
115
		${exclude_plist}
116

    
117
	if [ -f "${_exclude_plist}" ]; then
118
		sort -u ${_exclude_plist} > ${_plist}.exclude
119
		mv ${_plist} ${_plist}.tmp
120
		comm -23 ${_plist}.tmp ${_plist}.exclude > ${_plist}
121
		rm -f ${_plist}.tmp ${plist}.exclude
122
	fi
123

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
254
		export SRC_CONF=${SRC_CONF}
255
		buildkernel
256

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

    
260
		ensure_kernel_exists $KERNEL_DESTDIR
261

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

    
265
		rm -rf $KERNEL_DESTDIR 2>&1 1>/dev/null
266

    
267
		echo ".Done" | tee -a ${LOGFILE}
268
	done
269
}
270

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

    
277
	export KERNEL_NAME="${1}"
278

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

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

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

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

    
312
	unset KERNEL_NAME
313
}
314

    
315
# Items that need to be fixed up that are
316
# specific to nanobsd builds
317
cust_fixup_nanobsd() {
318
	local _NANO_WITH_VGA="${1}"
319

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

    
322
	echo "nanobsd" > $FINAL_CHROOT_DIR/etc/platform
323

    
324
	local BOOTCONF=${FINAL_CHROOT_DIR}/boot.config
325
	local LOADERCONF=${FINAL_CHROOT_DIR}/boot/loader.conf
326

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

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

    
347
# Creates a full update file
348
create_Full_update_tarball() {
349
	mkdir -p $UPDATESDIR
350

    
351
	customize_stagearea_for_image "fullupdate"
352
	install_default_kernel ${DEFAULT_KERNEL}
353

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

    
368
	echo ">>> Creating ${UPDATES_TARBALL_FILENAME} ..." | tee -a ${LOGFILE}
369
	tar --exclude=./dev -czPf ${UPDATES_TARBALL_FILENAME} -C ${FINAL_CHROOT_DIR} .
370
}
371

    
372
# Outputs various set variables aka env
373
print_flags() {
374

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

    
408
# This updates the product sources
409
update_product_repository() {
410
	if [ ! -d "${GIT_REPO_DIR}" ]; then
411
		echo ">>> Creating ${GIT_REPO_DIR}"
412
		mkdir -p ${GIT_REPO_DIR}
413
	fi
414

    
415
	echo ">>> Using GIT to checkout ${GIT_REPO_BRANCH_OR_TAG}"
416

    
417
	# There is already a cloned repo, test if branch is correct
418
	if [ -d "${GIT_REPO_DIR}/${GIT_REPO_BRANCH_OR_TAG}/.git" ]; then
419
		if ! (cd ${GIT_REPO_DIR}/${GIT_REPO_BRANCH_OR_TAG} && git rev-parse --verify ${GIT_REPO_BRANCH_OR_TAG} >/dev/null 2>&1); then
420
			echo -n ">>> ${PRODUCT_NAME} git repo is at wrong branch, removing it... "
421
			rm -rf ${GIT_REPO_DIR}/${GIT_REPO_BRANCH_OR_TAG}
422
			echo "Done!"
423
		fi
424
	fi
425

    
426
	if [ ! -d "${GIT_REPO_DIR}/${GIT_REPO_BRANCH_OR_TAG}/.git" ]; then
427
		echo -n ">>> Cloning ${GIT_REPO_URL} (${GIT_REPO_BRANCH_OR_TAG})... "
428
		(git clone --depth 1 --single-branch --branch ${GIT_REPO_BRANCH_OR_TAG} ${GIT_REPO_URL} ${GIT_REPO_DIR}/${GIT_REPO_BRANCH_OR_TAG}) 2>&1 | \
429
			egrep -B3 -A3 -wi -E '(error)|fatal'
430
		if [ ! -d "${GIT_REPO_DIR}/${GIT_REPO_BRANCH_OR_TAG}/conf.default" ]; then
431
			echo "Failed!"
432
			echo
433
			echo "!!!! An error occurred while checking out ${PRODUCT_NAME}"
434
			echo "     Could not locate ${GIT_REPO_DIR}/${GIT_REPO_BRANCH_OR_TAG}/conf.default"
435
			echo
436
			print_error_pfS
437
		fi
438
		echo "Done!"
439
	else
440
		# It is necessary for the case when a tag has moved
441
		local TAG=$(cd ${GIT_REPO_DIR}/${GIT_REPO_BRANCH_OR_TAG} && git tag)
442
		if [ "${TAG}" = "${GIT_REPO_BRANCH_OR_TAG}" ]; then
443
			RESET_TARGET="${GIT_REPO_BRANCH_OR_TAG}"
444
		else
445
			RESET_TARGET="origin/${GIT_REPO_BRANCH_OR_TAG}"
446
		fi
447

    
448
		# Fetch an update of the repository
449
		if ! (cd ${GIT_REPO_DIR}/${GIT_REPO_BRANCH_OR_TAG} && \
450
			git fetch origin; \
451
			git reset --hard ${RESET_TARGET}; \
452
			git clean -fxd ) >/dev/null 2>&1
453
		then
454
			echo ">>> ERROR: Something went wrong while checking out GIT."
455
			print_error_pfS
456
		fi
457
	fi
458
}
459

    
460
# This builds FreeBSD (make buildworld)
461
# Imported from FreeSBIE
462
make_world() {
463

    
464
	LOGFILE=${BUILDER_LOGS}/buildworld.${TARGET}
465
	if [ -n "${NO_BUILDWORLD:-}" ]; then
466
		echo ">>> NO_BUILDWORLD set, skipping build" | tee -a ${LOGFILE}
467
		return
468
	fi
469

    
470
	# Set SRC_CONF variable if it's not already set.
471
	if [ -z "${SRC_CONF:-}" ]; then
472
		echo ">>> SRC_CONF is unset make sure this is what you want!" | tee -a ${LOGFILE}
473
	else
474
		echo ">>> Setting SRC_CONF to $SRC_CONF" | tee -a ${LOGFILE}
475
	fi
476

    
477
	# Set default parameters
478
	export MAKE_ARGS="${MAKEJ_WORLD:-} __MAKE_CONF=${MAKE_CONF} SRCCONF=${SRC_CONF} TARGET=${TARGET} TARGET_ARCH=${TARGET_ARCH}"
479

    
480
	echo ">>> LOGFILE set to $LOGFILE." | tee -a ${LOGFILE}
481
	makeargs="${MAKE_ARGS}"
482
	echo ">>> Building world for ${TARGET} architecture... (Starting - $(LC_ALL=C date))" | tee -a ${LOGFILE}
483
	echo ">>> Builder is running the command: env LOCAL_ITOOLS=\"${EXTRA_TOOLS}\" script -aq $LOGFILE make -C ${SRCDIR} -DNO_CLEAN ${makeargs:-} buildworld" | tee -a ${LOGFILE}
484
	(env LOCAL_ITOOLS="${EXTRA_TOOLS}" script -aq $LOGFILE make -C ${SRCDIR} -DNO_CLEAN ${makeargs:-} buildworld || print_error_pfS;) | egrep '^>>>' | tee -a ${LOGFILE}
485
	echo ">>> Building world for ${TARGET} architecture... (Finished - $(LC_ALL=C date))" | tee -a ${LOGFILE}
486

    
487
	LOGFILE=${BUILDER_LOGS}/installworld.${TARGET}
488
	echo ">>> LOGFILE set to $LOGFILE." | tee -a ${LOGFILE}
489
	# Create if cleaned up
490
	mkdir -p ${STAGE_CHROOT_DIR}
491
	makeargs="${MAKE_ARGS} DESTDIR=${STAGE_CHROOT_DIR} WITHOUT_TOOLCHAIN=1"
492
	echo ">>> Installing world for ${TARGET} architecture... (Starting - $(LC_ALL=C date))" | tee -a ${LOGFILE}
493
	echo ">>> Builder is running the command: env LOCAL_ITOOLS=\"${EXTRA_TOOLS}\" script -aq $LOGFILE make -C ${SRCDIR} ${makeargs:-} installworld" | tee -a ${LOGFILE}
494
	(env LOCAL_ITOOLS="${EXTRA_TOOLS}" script -aq $LOGFILE make -C ${SRCDIR} ${makeargs:-} installworld || print_error_pfS;) | egrep '^>>>' | tee -a ${LOGFILE}
495
	echo ">>> Installing world for ${TARGET} architecture... (Finished - $(LC_ALL=C date))" | tee -a ${LOGFILE}
496

    
497
	makeargs="${MAKE_ARGS} DESTDIR=${STAGE_CHROOT_DIR}"
498
	echo ">>> Distribution world for ${TARGET} architecture... (Starting - $(LC_ALL=C date))" | tee -a ${LOGFILE}
499
	echo ">>> Builder is running the command: script -aq $LOGFILE make -C ${SRCDIR} ${makeargs:-} distribution " | tee -a ${LOGFILE}
500
	(script -aq $LOGFILE make -C ${SRCDIR} ${makeargs:-} distribution  || print_error_pfS;) | egrep '^>>>' | tee -a ${LOGFILE}
501
	echo ">>> Distribution world for ${TARGET} architecture... (Finished - $(LC_ALL=C date))" | tee -a ${LOGFILE}
502

    
503
	[ -d "${STAGE_CHROOT_DIR}/usr/local/bin" ] \
504
		|| mkdir -p ${STAGE_CHROOT_DIR}/usr/local/bin
505
	makeargs="${MAKE_ARGS} DESTDIR=${STAGE_CHROOT_DIR}"
506
	echo ">>> Building and installing crypto tools and athstats for ${TARGET} architecture... (Starting - $(LC_ALL=C date))" | tee -a ${LOGFILE}
507
	echo ">>> Builder is running the command: script -aq $LOGFILE make -C ${SRCDIR}/tools/tools/crypto ${makeargs:-} clean all install " | tee -a ${LOGFILE}
508
	(script -aq $LOGFILE make -C ${SRCDIR}/tools/tools/crypto ${makeargs:-} clean all install || print_error_pfS;) | egrep '^>>>' | tee -a ${LOGFILE}
509
	echo ">>> Builder is running the command: script -aq $LOGFILE make -C ${SRCDIR}/tools/tools/ath/athstats ${makeargs:-} clean" | tee -a ${LOGFILE}
510
	(script -aq $LOGFILE make -C ${SRCDIR}/tools/tools/ath/athstats ${makeargs:-} clean || print_error_pfS;) | egrep '^>>>' | tee -a ${LOGFILE}
511
	echo ">>> Builder is running the command: script -aq $LOGFILE make -C ${SRCDIR}/tools/tools/ath/athstats ${makeargs:-} all" | tee -a ${LOGFILE}
512
	(script -aq $LOGFILE make -C ${SRCDIR}/tools/tools/ath/athstats ${makeargs:-} all || print_error_pfS;) | egrep '^>>>' | tee -a ${LOGFILE}
513
	echo ">>> Builder is running the command: script -aq $LOGFILE make -C ${SRCDIR}/tools/tools/ath/athstats ${makeargs:-} install" | tee -a ${LOGFILE}
514
	(script -aq $LOGFILE make -C ${SRCDIR}/tools/tools/ath/athstats ${makeargs:-} install || print_error_pfS;) | egrep '^>>>' | tee -a ${LOGFILE}
515
	echo ">>> Building and installing crypto tools and athstats for ${TARGET} architecture... (Finished - $(LC_ALL=C date))" | tee -a ${LOGFILE}
516

    
517
	unset makeargs
518
}
519

    
520
# This routine originated in nanobsd.sh
521
nanobsd_set_flash_details () {
522
	a1=$(echo $1 | tr '[:upper:]' '[:lower:]')
523

    
524
	# Source:
525
	#	SanDisk CompactFlash Memory Card
526
	#	Product Manual
527
	#	Version 10.9
528
	#	Document No. 20-10-00038
529
	#	April 2005
530
	# Table 2-7
531
	# NB: notice math error in SDCFJ-4096-388 line.
532
	#
533
	case "${a1}" in
534
		1024|1024m|1024mb|1g)
535
			NANO_MEDIASIZE=$((997129216/512))
536
			;;
537
		2048|2048m|2048mb|2g)
538
			NANO_MEDIASIZE=$((1989999616/512))
539
			;;
540
		4096|4096m|4096mb|4g)
541
			NANO_MEDIASIZE=$((3989999616/512))
542
			;;
543
		8192|8192m|8192mb|8g)
544
			NANO_MEDIASIZE=$((7989999616/512))
545
			;;
546
		16384|16384m|16384mb|16g)
547
			NANO_MEDIASIZE=$((15989999616/512))
548
			;;
549
		*)
550
			echo "Unknown Flash capacity"
551
			exit 2
552
			;;
553
	esac
554

    
555
	NANO_HEADS=16
556
	NANO_SECTS=63
557

    
558
	echo ">>> [nanoo] $1"
559
	echo ">>> [nanoo] NANO_MEDIASIZE: $NANO_MEDIASIZE"
560
	echo ">>> [nanoo] NANO_HEADS: $NANO_HEADS"
561
	echo ">>> [nanoo] NANO_SECTS: $NANO_SECTS"
562
	echo ">>> [nanoo] NANO_BOOT0CFG: $NANO_BOOT0CFG"
563
}
564

    
565
# This routine originated in nanobsd.sh
566
create_nanobsd_diskimage () {
567
	if [ -z "${1}" ]; then
568
		echo ">>> ERROR: Type of image has not been specified"
569
		print_error_pfS
570
	fi
571
	if [ -z "${2}" ]; then
572
		echo ">>> ERROR: Size of image has not been specified"
573
		print_error_pfS
574
	fi
575

    
576
	if [ "${1}" = "nanobsd" ]; then
577
		# It's serial
578
		export NANO_BOOTLOADER="boot/boot0sio"
579
	elif [ "${1}" = "nanobsd-vga" ]; then
580
		# It's vga
581
		export NANO_BOOTLOADER="boot/boot0"
582
	else
583
		echo ">>> ERROR: Type of image to create unknown"
584
		print_error_pfS
585
	fi
586

    
587
	if [ -z "${2}" ]; then
588
		echo ">>> ERROR: Media size(s) not specified."
589
		print_error_pfS
590
	fi
591

    
592
	if [ -z "${2}" ]; then
593
		echo ">>> ERROR: FLASH_SIZE is not set."
594
		print_error_pfS
595
	fi
596

    
597
	LOGFILE=${BUILDER_LOGS}/${1}.${TARGET}
598
	# Prepare folder to be put in image
599
	customize_stagearea_for_image "${1}"
600
	install_default_kernel ${DEFAULT_KERNEL} "no"
601

    
602
	# Must be run after customize_stagearea_for_image
603
	cust_fixup_nanobsd ${1}
604

    
605
	for _NANO_MEDIASIZE in ${2}; do
606
		if [ -z "${_NANO_MEDIASIZE}" ]; then
607
			continue;
608
		fi
609

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

    
613
		IMG="${MAKEOBJDIRPREFIXFINAL}/${PRODUCT_NAME}-${PRODUCT_VERSION}-${_NANO_MEDIASIZE}-${TARGET}-${1}-${DATESTRING}.img"
614
		IMGUPDATE="${MAKEOBJDIRPREFIXFINAL}/${PRODUCT_NAME}-${PRODUCT_VERSION}-${_NANO_MEDIASIZE}-${TARGET}-${1}-upgrade-${DATESTRING}.img"
615

    
616
		nanobsd_set_flash_details ${_NANO_MEDIASIZE}
617

    
618
		# These are defined in FlashDevice and on builder_default.sh
619
		echo $NANO_MEDIASIZE \
620
			$NANO_IMAGES \
621
			$NANO_SECTS \
622
			$NANO_HEADS \
623
			$NANO_CODESIZE \
624
			$NANO_CONFSIZE \
625
			$NANO_DATASIZE |
626
awk '
627
{
628
	printf "# %s\n", $0
629

    
630
	# size of cylinder in sectors
631
	cs = $3 * $4
632

    
633
	# number of full cylinders on media
634
	cyl = int ($1 / cs)
635

    
636
	# output fdisk geometry spec, truncate cyls to 1023
637
	if (cyl <= 1023)
638
		print "g c" cyl " h" $4 " s" $3
639
	else
640
		print "g c" 1023 " h" $4 " s" $3
641

    
642
	if ($7 > 0) {
643
		# size of data partition in full cylinders
644
		dsl = int (($7 + cs - 1) / cs)
645
	} else {
646
		dsl = 0;
647
	}
648

    
649
	# size of config partition in full cylinders
650
	csl = int (($6 + cs - 1) / cs)
651

    
652
	if ($5 == 0) {
653
		# size of image partition(s) in full cylinders
654
		isl = int ((cyl - dsl - csl) / $2)
655
	} else {
656
		isl = int (($5 + cs - 1) / cs)
657
	}
658

    
659
	# First image partition start at second track
660
	print "p 1 165 " $3, isl * cs - $3
661
	c = isl * cs;
662

    
663
	# Second image partition (if any) also starts offset one
664
	# track to keep them identical.
665
	if ($2 > 1) {
666
		print "p 2 165 " $3 + c, isl * cs - $3
667
		c += isl * cs;
668
	}
669

    
670
	# Config partition starts at cylinder boundary.
671
	print "p 3 165 " c, csl * cs
672
	c += csl * cs
673

    
674
	# Data partition (if any) starts at cylinder boundary.
675
	if ($7 > 0) {
676
		print "p 4 165 " c, dsl * cs
677
	} else if ($7 < 0 && $1 > c) {
678
		print "p 4 165 " c, $1 - c
679
	} else if ($1 < c) {
680
		print "Disk space overcommitted by", \
681
		    c - $1, "sectors" > "/dev/stderr"
682
		exit 2
683
	}
684

    
685
	# Force slice 1 to be marked active. This is necessary
686
	# for booting the image from a USB device to work.
687
	print "a 1"
688
}
689
	' > ${MAKEOBJDIRPREFIXFINAL}/_.fdisk
690

    
691
		MNT=${MAKEOBJDIRPREFIXFINAL}/_.mnt
692
		mkdir -p ${MNT}
693

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

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

    
700
		fdisk -i -f ${MAKEOBJDIRPREFIXFINAL}/_.fdisk ${MD} 2>&1 >> ${LOGFILE}
701
		fdisk ${MD} 2>&1 >> ${LOGFILE}
702

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

    
705
		# Create first image
706
		bsdlabel -m i386 -w -B -b ${FINAL_CHROOT_DIR}/boot/boot ${MD}s1 2>&1 >> ${LOGFILE}
707
		bsdlabel -m i386 ${MD}s1 2>&1 >> ${LOGFILE}
708
		local _label=$(lc ${PRODUCT_NAME})
709
		newfs -L ${_label}0 ${NANO_NEWFS} /dev/${MD}s1a 2>&1 >> ${LOGFILE}
710
		mount /dev/ufs/${_label}0 ${MNT}
711
		if [ $? -ne 0 ]; then
712
			echo ">>> ERROR: Something wrong happened during mount of first slice image creation. STOPPING!" | tee -a ${LOGFILE}
713
			print_error_pfS
714
		fi
715
		# Consider the unmounting as well
716
		trap "umount /dev/ufs/${_label}0; mdconfig -d -u ${MD}; return" 1 2 15 EXIT
717

    
718
		clone_directory_contents ${FINAL_CHROOT_DIR} ${MNT}
719

    
720
		# Set NanoBSD image size
721
		echo "${_NANO_MEDIASIZE}" > ${MNT}/etc/nanosize.txt
722
		rm -f $MNT/cf/conf/* 2>/dev/null
723

    
724
		echo "/dev/ufs/${_label}0 / ufs ro,sync,noatime 1 1" > ${MNT}/etc/fstab
725
		if [ $NANO_CONFSIZE -gt 0 ] ; then
726
			echo "/dev/ufs/cf /cf ufs ro,sync,noatime 1 1" >> ${MNT}/etc/fstab
727
		fi
728

    
729
		umount ${MNT}
730
		sync
731
		# Restore the original trap
732
		trap "mdconfig -d -u ${MD}; return" 1 2 15 EXIT
733

    
734
		# Setting NANO_IMAGES to 1 and NANO_INIT_IMG2 will tell
735
		# NanoBSD to only create one partition.  We default to 2
736
		# partitions in case anything happens to the first the
737
		# operator can boot from the 2nd and should be OK.
738

    
739
		# Before just going to use dd for duplicate think!
740
		# The images are created as sparse so lets take advantage
741
		# of that by just exec some commands.
742
		if [ $NANO_IMAGES -gt 1 -a $NANO_INIT_IMG2 -gt 0 ] ; then
743
			# Duplicate to second image (if present)
744
			echo ">>> Creating NanoBSD second slice by duplicating first slice." | tee -a ${LOGFILE}
745
			# Create second image
746
			dd if=/dev/${MD}s1 of=/dev/${MD}s2 conv=sparse bs=64k 2>&1 >> ${LOGFILE}
747
			tunefs -L ${_label}1 /dev/${MD}s2a 2>&1 >> ${LOGFILE}
748
			mount /dev/ufs/${_label}1 ${MNT}
749
			if [ $? -ne 0 ]; then
750
				echo ">>> ERROR: Something wrong happened during mount of second slice image creation. STOPPING!" | tee -a ${LOGFILE}
751
				print_error_pfS
752
			fi
753
			# Consider the unmounting as well
754
			trap "umount /dev/ufs/${_label}1; mdconfig -d -u ${MD}; return" 1 2 15 EXIT
755

    
756
			echo "/dev/ufs/${_label}1 / ufs ro,sync,noatime 1 1" > ${MNT}/etc/fstab
757
			if [ $NANO_CONFSIZE -gt 0 ] ; then
758
				echo "/dev/ufs/cf /cf ufs ro,sync,noatime 1 1" >> ${MNT}/etc/fstab
759
			fi
760

    
761
			umount ${MNT}
762
			# Restore the trap back
763
			trap "mdconfig -d -u ${MD}; return" 1 2 15 EXIT
764
		fi
765

    
766
		# Create Data slice, if any.
767
		# Note the changing of the variable to NANO_CONFSIZE
768
		# from NANO_DATASIZE.  We also added glabel support
769
		# and populate the Product configuration from the /cf
770
		# directory located in FINAL_CHROOT_DIR
771
		if [ $NANO_CONFSIZE -gt 0 ] ; then
772
			echo ">>> Creating /cf area to hold config.xml"
773
			newfs -L cf ${NANO_NEWFS} /dev/${MD}s3 2>&1 >> ${LOGFILE}
774
			# Mount data partition and copy contents of /cf
775
			# Can be used later to create custom default config.xml while building
776
			mount /dev/ufs/cf ${MNT}
777
			if [ $? -ne 0 ]; then
778
				echo ">>> ERROR: Something wrong happened during mount of cf slice image creation. STOPPING!" | tee -a ${LOGFILE}
779
				print_error_pfS
780
			fi
781
			# Consider the unmounting as well
782
			trap "umount /dev/ufs/cf; mdconfig -d -u ${MD}; return" 1 2 15 EXIT
783

    
784
			clone_directory_contents ${FINAL_CHROOT_DIR}/cf ${MNT}
785

    
786
			umount ${MNT}
787
			# Restore the trap back
788
			trap "mdconfig -d -u ${MD}; return" 1 2 15 EXIT
789
		else
790
			">>> [nanoo] NANO_CONFSIZE is not set. Not adding a /conf partition.. You sure about this??" | tee -a ${LOGFILE}
791
		fi
792

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

    
796
		mdconfig -d -u $MD
797
		# Restore default action
798
		trap "-" 1 2 15 EXIT
799

    
800
		# Check each image and ensure that they are over
801
		# 3 megabytes.  If either image is under 20 megabytes
802
		# in size then error out.
803
		IMGSIZE=$(stat -f "%z" ${IMG})
804
		IMGUPDATESIZE=$(stat -f "%z" ${IMGUPDATE})
805
		CHECKSIZE="20040710"
806
		if [ "$IMGSIZE" -lt "$CHECKSIZE" ]; then
807
			echo ">>> ERROR: Something went wrong when building NanoBSD.  The image size is under 20 megabytes!" | tee -a ${LOGFILE}
808
			print_error_pfS
809
		fi
810
		if [ "$IMGUPDATESIZE" -lt "$CHECKSIZE" ]; then
811
			echo ">>> ERROR: Something went wrong when building NanoBSD upgrade image.  The image size is under 20 megabytes!" | tee -a ${LOGFILE}
812
			print_error_pfS
813
		fi
814

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

    
818
		gzip -f $IMG &
819
		gzip -f $IMGUPDATE &
820
	done
821

    
822
	unset IMG
823
	unset IMGUPDATE
824
	unset IMGUPDATESIZE
825
	unset IMGSIZE
826

    
827
	ls -lah $MAKEOBJDIRPREFIXFINAL
828
}
829

    
830
# This routine creates a ova image that contains
831
# a ovf and vmdk file. These files can be imported
832
# right into vmware or virtual box.
833
# (and many other emulation platforms)
834
# http://www.vmware.com/pdf/ovf_whitepaper_specification.pdf
835
create_ova_image() {
836
	# XXX create a .ovf php creator that you can pass:
837
	#     1. populatedSize
838
	#     2. license
839
	#     3. product name
840
	#     4. version
841
	#     5. number of network interface cards
842
	#     6. allocationUnits
843
	#     7. capacity
844
	#     8. capacityAllocationUnits
845

    
846
	LOGFILE=${BUILDER_LOGS}/ova.${TARGET}.log
847

    
848
	# Prepare folder to be put in image
849
	customize_stagearea_for_image "ova"
850
	install_default_kernel ${DEFAULT_KERNEL} "no"
851

    
852
	ova_prereq_check
853
	ova_remove_old_tmp_files
854
	ova_setup_ovf_file
855
	ova_create_raw_backed_file
856
	/bin/echo -n ">>> Creating mdconfig image ${OVFPATH}/${OVFVMDK}.raw... " | tee -a ${LOGFILE}
857
	MD=$(mdconfig -a -t vnode -f ${OVFPATH}/${OVFVMDK}.raw)
858
	# Just in case
859
	trap "mdconfig -d -u ${MD}" 1 2 15 EXIT
860

    
861
	# comment out if using pc-sysinstall
862
	ova_partition_gpart $MD
863
	ova_mount_mnt $MD
864
	ova_cpdup_files
865
	ova_setup_platform_specific # after cpdup
866
	ova_calculate_mnt_size
867
	ova_umount_mnt $MD
868
	# Restore default action
869
	trap "-" 1 2 15 EXIT
870
	ova_umount_mdconfig $MD
871
	# We use vbox because it compresses the vmdk on export
872
	ova_create_vbox_image
873
	# We repack the file with a more universal xml file that
874
	# works in both virtual box and esx server
875
	ova_repack_vbox_image
876
}
877

    
878
ova_repack_vbox_image() {
879
	BUILDPLATFORM=$(uname -p)
880
	POPULATEDSIZE=$(du -d0 -m $FINAL_CHROOT_DIR | awk '{ print \$1 }')
881
	POPULATEDSIZEBYTES=$(echo "${POPULATEDSIZE}*1024^2" | bc)
882
	REFERENCESSIZE=$(stat -f "%z" ${OVFPATH}/${OVFVMDK})
883
	echo ">>> Setting REFERENCESSIZE to ${REFERENCESSIZE}..." | tee -a ${LOGFILE}
884
	file_search_replace REFERENCESSIZE ${REFERENCESSIZE} ${OVFPATH}/${PRODUCT_NAME}.ovf
885
	echo ">>> Setting POPULATEDSIZEBYTES to ${POPULATEDSIZEBYTES}..." | tee -a ${LOGFILE}
886
	#  OperatingSystemSection (${PRODUCT_NAME}.ovf)
887
	#  42   FreeBSD 32-Bit
888
	#  78   FreeBSD 64-Bit
889
	if [ "$BUILDPLATFORM" = "i386" ]; then
890
		file_search_replace '"101"' '"42"' ${OVFPATH}/${PRODUCT_NAME}.ovf
891
		file_search_replace 'FreeBSD XX-Bit' 'FreeBSD' ${OVFPATH}/${PRODUCT_NAME}.ovf
892
	fi
893
	if [ "$BUILDPLATFORM" = "amd64" ]; then
894
		file_search_replace '"101"' '"78"' ${OVFPATH}/${PRODUCT_NAME}.ovf
895
		file_search_replace 'FreeBSD XX-Bit' 'FreeBSD 64-Bit' ${OVFPATH}/${PRODUCT_NAME}.ovf
896
	fi
897
	file_search_replace DISKSECTIONPOPULATEDSIZE $POPULATEDSIZEBYTES ${OVFPATH}/${PRODUCT_NAME}.ovf
898
	# 10737254400 = 10240MB = virtual box vmdk file size XXX grab this value from vbox creation
899
	# 10737418240 = 10GB
900
	echo ">>> Setting DISKSECTIONALLOCATIONUNITS to 10737254400..." | tee -a ${LOGFILE}
901
	file_search_replace DISKSECTIONALLOCATIONUNITS $OVA_DISKSECTIONALLOCATIONUNITS ${OVFPATH}/${PRODUCT_NAME}.ovf
902
	echo ">>> Setting DISKSECTIONCAPACITY to 10737418240..." | tee -a ${LOGFILE}
903
	file_search_replace DISKSECTIONCAPACITY $OVADISKSIZE ${OVFPATH}/${PRODUCT_NAME}.ovf
904
	echo ">>> Repacking OVA with universal OVF file..." | tee -a ${LOGFILE}
905
	mv ${OVFPATH}/${OVFVMDK} ${OVFPATH}/${PRODUCT_NAME}-disk1.vmdk
906
	gtar -C ${OVFPATH} -cpf ${PRODUCT_NAME}.ova ${PRODUCT_NAME}.ovf ${PRODUCT_NAME}-disk1.vmdk
907
	rm $OVFPATH/${PRODUCT_NAME}-disk1.vmdk
908
	ls -lah ${OVFPATH}/${PRODUCT_NAME}*ov*
909
}
910

    
911
# called from create_ova_image
912
ova_umount_mnt() {
913
	# Unmount /dev/mdX
914
	umount /mnt
915
	sync ; sync
916
}
917

    
918
# called from create_ova_image
919
ova_umount_mdconfig() {
920
	MD=$1
921
	# Show gpart info
922
	gpart show $MD
923
	echo ">>> Unmounting ${MD}..." | tee -a ${LOGFILE}
924
	mdconfig -d -u $MD
925
	sync ; sync
926
}
927

    
928
# called from create_ova_image
929
ova_mount_mnt() {
930
	MD=$1
931
	echo ">>> Mounting image to /mnt..." | tee -a ${LOGFILE}
932
	mount -o rw /dev/${MD}p2 /mnt/
933
}
934

    
935
# called from create_ova_image
936
ova_setup_ovf_file() {
937
	if [ -f ${OVFFILE} ]; then
938
		cp ${OVFFILE} ${OVFPATH}/${PRODUCT_NAME}.ovf
939
	fi
940

    
941
	if [ ! -f ${OVFPATH}/${PRODUCT_NAME}.ovf ]; then
942
		cp ${BUILDER_SCRIPTS}/conf/ovf/${PRODUCT_NAME}.ovf ${OVFPATH}/${PRODUCT_NAME}.ovf
943
		file_search_replace PRODUCT_VERSION $PRODUCT_VERSION ${OVFPATH}/${PRODUCT_NAME}.ovf
944
		file_search_replace PRODUCT_URL $PRODUCT_URL ${OVFPATH}/${PRODUCT_NAME}.ovf
945
	fi
946
}
947

    
948
# called from create_ova_image
949
ova_prereq_check() {
950
	if [ ! -f /usr/local/bin/vmdktool ]; then
951
		echo ">>> ERROR: vmdktool is not present please check port sysutils/vmdktool installation" | tee -a ${LOGFILE}
952
		print_error_pfS
953
	fi
954
	sysctl kern.geom.debugflags=16
955
}
956

    
957
# called from create_ova_image
958
ova_calculate_mnt_size() {
959
	/bin/echo -n ">>> Calculating size of /mnt..." | tee -a ${LOFGILE}
960
	INSTALLSIZE=$(du -s /mnt/ | awk '{ print $1 }')
961
	INSTALLSIZEH=$(du -d0 -h /mnt/ | awk '{ print $1 }')
962
	echo $INSTALLSIZEH
963
}
964

    
965
# called from create_ova_image
966
ova_create_raw_backed_file() {
967
	DISKSIZE=$OVADISKSIZE
968
	BLOCKSIZE=$OVABLOCKSIZE
969
	COUNT=$((${DISKSIZE}/${BLOCKSIZE}))
970
	DISKFILE=${OVFPATH}/${OVFVMDK}.raw
971
	echo ">>> Creating raw backing file ${DISKFILE} (Disk Size: ${DISKSIZE}, Block Size: ${BLOCKSIZE}, Count: ${COUNT})..." | tee -a ${LOGFILE}
972
	dd if=/dev/zero of=$DISKFILE bs=$BLOCKSIZE count=0 seek=$COUNT
973
}
974

    
975
# called from create_ova_image
976
ova_remove_old_tmp_files() {
977
	rm ${OVFPATH}/*.ovf.final 2>/dev/null
978
	rm ${OVFPATH}/*.ova 2>/dev/null
979
}
980

    
981
# called from create_ova_image
982
ova_create_vbox_image() {
983
	# VirtualBox
984
	echo ">>> Creating image using vmdktool..." | tee -a ${LOGFILE}
985
	rm ${OVFPATH}/${OVFVMDK} 2>/dev/null
986
	vmdktool -v ${OVFPATH}/${OVFVMDK} ${OVFPATH}/${OVFVMDK}.raw
987
	rm -rf ${OVFPATH}/${OVFVMDK}.raw
988
	echo ">>> ${OVFPATH}/${OVFVMDK} created." | tee -a ${LOGFILE}
989
}
990

    
991
# called from create_ova_image
992
ova_cpdup_files() {
993
	echo ">>> Populating vmdk staging area..."
994
	cpdup -o ${FINAL_CHROOT_DIR}/COPYRIGHT /mnt/COPYRIGHT
995
	cpdup -o ${FINAL_CHROOT_DIR}/boot /mnt/boot
996
	cpdup -o ${FINAL_CHROOT_DIR}/bin /mnt/bin
997
	cpdup -o ${FINAL_CHROOT_DIR}/cf/conf /mnt/cf/conf
998
	cpdup -o ${FINAL_CHROOT_DIR}/conf.default /mnt/conf.default
999
	cpdup -o ${FINAL_CHROOT_DIR}/dev /mnt/dev
1000
	cpdup -o ${FINAL_CHROOT_DIR}/etc /mnt/etc
1001
	cpdup -o ${FINAL_CHROOT_DIR}/home /mnt/home
1002
	cpdup -o ${FINAL_CHROOT_DIR}/pkgs /mnt/pkgs
1003
	cpdup -o ${FINAL_CHROOT_DIR}/libexec /mnt/libexec
1004
	cpdup -o ${FINAL_CHROOT_DIR}/lib /mnt/lib
1005
	cpdup -o ${FINAL_CHROOT_DIR}/root /mnt/root
1006
	cpdup -o ${FINAL_CHROOT_DIR}/sbin /mnt/sbin
1007
	cpdup -o ${FINAL_CHROOT_DIR}/usr /mnt/usr
1008
	cpdup -o ${FINAL_CHROOT_DIR}/var /mnt/var
1009
	sync ; sync ; sync ; sync
1010
}
1011

    
1012
ova_setup_platform_specific() {
1013
	echo ">>> Installing platform specific items..." | tee -a ${LOGFILE}
1014
	echo "/dev/label/${PRODUCT_NAME}	/	ufs		rw	0	0" > /mnt/etc/fstab
1015
	echo "/dev/label/swap0	none	swap	sw	0	0" >> /mnt/etc/fstab
1016
	echo ${PRODUCT_NAME} > /mnt/etc/platform
1017
	rmdir /mnt/conf
1018
	mkdir -p /mnt/cf
1019
	mkdir -p /mnt/cf/conf
1020
	cp /mnt/conf.default/config.xml /mnt/cf/conf/
1021
	chroot /mnt /bin/ln -s /cf/conf /conf
1022
	mkdir -p /mnt/tmp
1023
}
1024

    
1025
# called from create_ova_image
1026
ova_partition_gpart() {
1027
	# XXX: Switch to mkimg tool!!
1028
	MD=$1
1029
	echo ">>> Creating GPT..." | tee -a ${LOGFILE}
1030
	gpart create -s gpt $MD
1031
	echo ">>> Embedding GPT bootstrap into protective MBR..." | tee -a ${LOGFILE}
1032
	gpart bootcode -b /boot/pmbr $MD
1033
	echo ">>> Creating GPT boot partition..." | tee -a ${LOGFILE}
1034
	gpart add -b 34 -s 128 -t freebsd-boot $MD
1035
	gpart bootcode -p /boot/gptboot -i 1 $MD
1036
	echo ">>> Setting up disk slices: ${MD}p2 (Size: ${OVA_FIRST_PART_SIZE})..." | tee -a ${LOGFILE}
1037
	gpart add -s $OVA_FIRST_PART_SIZE -t freebsd-ufs -i 2 $MD
1038
	echo ">>> Setting up disk slices: ${MD}p3 (swap) (Size: ${OVA_SWAP_PART_SIZE})..." | tee -a ${LOGFILE}
1039
	gpart add -s $OVA_SWAP_PART_SIZE -t freebsd-swap -i 3 $MD
1040
	echo ">>> Running newfs..." | tee -a ${LOGFILE}
1041
	newfs -U /dev/${MD}p2
1042
	sync ; sync ; sync ; sync
1043
	echo ">>> Labeling partitions: ${MD}p2..."  | tee -a ${LOGFILE}
1044
	glabel label ${PRODUCT_NAME} ${MD}p2
1045
	sync ; sync
1046
	echo ">>> Labeling partitions: ${MD}p3..." | tee -a ${LOGFILE}
1047
	glabel label swap0 ${MD}p3
1048
	sync ; sync
1049
}
1050

    
1051
# called from create_ova_image
1052
# This routine will replace a string in a file
1053
file_search_replace() {
1054
	local SEARCH="$1"
1055
	local REPLACE="$2"
1056
	local FILENAME="$3"
1057

    
1058
	if [ -f "${FILENAME}" ]; then
1059
		sed -i '' -e "s/${SEARCH}/${REPLACE}/g" ${FILENAME}
1060
	fi
1061
}
1062

    
1063
# Cleans up previous builds
1064
clean_obj_dir() {
1065
	# Clean out directories
1066
	echo ">>> Cleaning up previous build environment...Please wait!"
1067

    
1068
	staginareas_clean_each_run
1069

    
1070
	if [ -d "${STAGE_CHROOT_DIR}" ]; then
1071
		BASENAME=$(basename ${STAGE_CHROOT_DIR})
1072
		echo -n ">>> Cleaning ${STAGE_CHROOT_DIR} ..."
1073
		chflags -R noschg ${STAGE_CHROOT_DIR} 2>&1 >/dev/null
1074
		rm -rf ${STAGE_CHROOT_DIR} 2>/dev/null
1075
		echo "Done."
1076
	fi
1077
	mkdir -p ${STAGE_CHROOT_DIR}
1078

    
1079
	if [ -z "${NO_CLEANFREEBSDOBJDIR}" -a -d "${SRCDIR}" ]; then
1080
		OBJTREE=$(env TARGET=${TARGET} TARGET_ARCH=${TARGET_ARCH} make -C ${SRCDIR} -V OBJTREE)
1081
		if [ -d "${OBJTREE}" ]; then
1082
			echo -n ">>> Cleaning FreeBSD objects dir staging..."
1083
			echo -n "."
1084
			chflags -R noschg ${OBJTREE} 2>&1 >/dev/null
1085
			echo -n "."
1086
			rm -rf ${OBJTREE}/*
1087
			echo "Done!"
1088
		fi
1089
		if [ -n "${KERNEL_DESTDIR}" -a -d "${KERNEL_BUILD_PATH}" ]; then
1090
			echo -n ">>> Cleaning previously built kernel stage area..."
1091
			rm -rf $KERNEL_BUILD_PATH/*
1092
			echo "Done!"
1093
		fi
1094
	fi
1095
	mkdir -p $KERNEL_BUILD_PATH
1096

    
1097
	echo -n ">>> Cleaning previously built images..."
1098
	rm -rf $MAKEOBJDIRPREFIXFINAL/*
1099
	echo "Done!"
1100

    
1101
	if [ -z "${NO_CLEANREPOS}" ]; then
1102
		if [ -d "${GIT_REPO_DIR}/${GIT_REPO_BRANCH_OR_TAG}" ]; then
1103
			echo -n ">>> Cleaning ${PRODUCT_NAME} repo checkout..."
1104
			echo -n "."
1105
			rm -rf "${GIT_REPO_DIR}/${GIT_REPO_BRANCH_OR_TAG}"
1106
			echo "Done!"
1107
		fi
1108

    
1109
		if [ -d "$SRCDIR" ]; then
1110
			echo -n ">>> Ensuring $SRCDIR is clean..."
1111
			rm -rf ${SRCDIR}
1112
			echo "Done!"
1113
		fi
1114
	fi
1115

    
1116
	echo -n ">>> Cleaning previous builder logs..."
1117
	if [ -d "$BUILDER_LOGS" ]; then
1118
		rm -rf ${BUILDER_LOGS}
1119
	fi
1120
	mkdir -p ${BUILDER_LOGS}
1121

    
1122
	echo "Done!"
1123

    
1124
	echo ">>> Cleaning of builder environment has finished."
1125
}
1126

    
1127
# This routine ensures that the $SRCDIR has sources
1128
# and is ready for action / building.
1129
ensure_source_directories_present() {
1130
	update_freebsd_sources
1131

    
1132
	update_product_repository
1133
}
1134

    
1135
clone_directory_contents() {
1136
	if [ ! -d "$1" -o ! -d "$2" ]; then
1137
		if [ -z "${LOGFILE}" ]; then
1138
			echo ">>> ERROR: Argument $1 supplied is not a directory!"
1139
		else
1140
			echo ">>> ERROR: Argument $1 supplied is not a directory!" | tee -a ${LOGFILE}
1141
		fi
1142
		print_error_pfS
1143
	fi
1144
	echo -n ">>> Using TAR to clone $1 to $2 ..."
1145
	tar -C ${1} -c -f - . | tar -C ${2} -x -p -f -
1146
	echo "Done!"
1147
}
1148

    
1149
clone_to_staging_area() {
1150
	# Clone everything to the final staging area
1151
	echo -n ">>> Cloning everything to ${STAGE_CHROOT_DIR} staging area..."
1152
	LOGFILE=${BUILDER_LOGS}/cloning.${TARGET}.log
1153

    
1154
	if [ ! -d ${GIT_REPO_DIR}/${GIT_REPO_BRANCH_OR_TAG} ]; then
1155
		echo "ERROR!"
1156
		echo ">>> ERROR: ${PRODUCT_NAME} repository does not seem to be there please fix...STOPPING!" | tee -a ${LOGFILE}
1157
		print_error_pfS
1158
	fi
1159

    
1160
	tar --exclude=\.git -C ${GIT_REPO_DIR}/${GIT_REPO_BRANCH_OR_TAG} -c -f - . | \
1161
		tar -C ${STAGE_CHROOT_DIR} -x -p -f -
1162

    
1163
	if [ -f ${STAGE_CHROOT_DIR}/etc/master.passwd ]; then
1164
		chroot ${STAGE_CHROOT_DIR} cap_mkdb /etc/master.passwd
1165
		chroot ${STAGE_CHROOT_DIR} pwd_mkdb /etc/master.passwd
1166
	fi
1167
	mkdir -p ${STAGE_CHROOT_DIR}/etc/mtree
1168
	mtree -Pcp ${STAGE_CHROOT_DIR}/var > ${STAGE_CHROOT_DIR}/etc/mtree/var.dist
1169
	mtree -Pcp ${STAGE_CHROOT_DIR}/etc > ${STAGE_CHROOT_DIR}/etc/mtree/etc.dist
1170
	if [ -d ${STAGE_CHROOT_DIR}/usr/local/etc ]; then
1171
		mtree -Pcp ${STAGE_CHROOT_DIR}/usr/local/etc > ${STAGE_CHROOT_DIR}/etc/mtree/localetc.dist
1172
	fi
1173

    
1174
	## Add buildtime and lastcommit information
1175
	# This is used for detecting updates.
1176
	echo "$BUILTDATESTRING" > $STAGE_CHROOT_DIR/etc/version.buildtime
1177
	# Record last commit info if it is available.
1178
	if [ -f $SCRATCHDIR/build_commit_info.txt ]; then
1179
		cp $SCRATCHDIR/build_commit_info.txt $STAGE_CHROOT_DIR/etc/version.lastcommit
1180
	fi
1181

    
1182
	local _exclude_files="${CORE_PKG_TMP}/base_exclude_files"
1183
	sed \
1184
		-e "s,%%PRODUCT_NAME%%,${PRODUCT_NAME},g" \
1185
		-e "s,%%FLAVOR%%,${_flavor},g" \
1186
		-e "s,%%VERSION%%,${_version},g" \
1187
		${BUILDER_SCRIPTS}/templates/core_pkg/base/exclude_files \
1188
		> ${_exclude_files}
1189

    
1190
	mkdir -p ${STAGE_CHROOT_DIR}/usr/local/share/${PRODUCT_NAME} >/dev/null 2>&1
1191
	mtree \
1192
		-c \
1193
		-k uid,gid,mode,size,flags,sha256digest \
1194
		-p ${STAGE_CHROOT_DIR} \
1195
		-X ${_exclude_files} \
1196
		> ${STAGE_CHROOT_DIR}/usr/local/share/${PRODUCT_NAME}/base.mtree
1197
	tar \
1198
		-C ${STAGE_CHROOT_DIR} \
1199
		-cJf ${STAGE_CHROOT_DIR}/usr/local/share/${PRODUCT_NAME}/base.txz \
1200
		-X ${_exclude_files} \
1201
		.
1202

    
1203
	core_pkg_create base "" ${CORE_PKG_VERSION} ${STAGE_CHROOT_DIR}
1204
	core_pkg_create default-config "" ${CORE_PKG_VERSION} ${STAGE_CHROOT_DIR}
1205

    
1206
	local DEFAULTCONF=${STAGE_CHROOT_DIR}/conf.default/config.xml
1207
	# Activate serial console in config.xml
1208
	# If it was there before, clear the setting to be sure we don't add it twice.
1209
	sed -i "" -e "/		<enableserial\/>/d" ${DEFAULTCONF}
1210
	# Enable serial in the config
1211
	sed -i "" -e "s/	<\/system>/		<enableserial\/>\\$(echo -e \\\n)	<\/system>/" ${DEFAULTCONF}
1212

    
1213
	echo force > ${STAGE_CHROOT_DIR}/cf/conf/enableserial_force
1214

    
1215
	core_pkg_create default-config-serial "" ${CORE_PKG_VERSION} ${STAGE_CHROOT_DIR}
1216

    
1217
	rm -f ${STAGE_CHROOT_DIR}/cf/conf/enableserial_force
1218
	rm -f ${STAGE_CHROOT_DIR}/cf/conf/config.xml
1219

    
1220
	# Make sure pkg is present
1221
	pkg_bootstrap ${STAGE_CHROOT_DIR}
1222

    
1223
	pkg_chroot_add ${STAGE_CHROOT_DIR} base
1224

    
1225
	echo "Done!"
1226
}
1227

    
1228
create_final_staging_area() {
1229
	if [ -z "${FINAL_CHROOT_DIR}" ]; then
1230
		echo ">>> ERROR: FINAL_CHROOT_DIR is not set, cannot continue!" | tee -a ${LOGFILE}
1231
		print_error_pfS
1232
	fi
1233

    
1234
	if [ -d "${FINAL_CHROOT_DIR}" ]; then
1235
		echo -n ">>> Previous ${FINAL_CHROOT_DIR} detected cleaning up..." | tee -a ${LOGFILE}
1236
		chflags -R noschg ${FINAL_CHROOT_DIR} 2>&1 1>/dev/null
1237
		rm -rf ${FINAL_CHROOT_DIR}/* 2>&1 1>/dev/null
1238
		echo "Done." | tee -a ${LOGFILE}
1239
	fi
1240
	mkdir -p ${FINAL_CHROOT_DIR}
1241

    
1242
	echo ">>> Preparing Final image staging area: $(LC_ALL=C date)" 2>&1 | tee -a ${LOGFILE}
1243
	echo ">>> Cloning ${STAGE_CHROOT_DIR} to ${FINAL_CHROOT_DIR}" 2>&1 | tee -a ${LOGFILE}
1244
	clone_directory_contents ${STAGE_CHROOT_DIR} ${FINAL_CHROOT_DIR}
1245

    
1246
	if [ ! -f $FINAL_CHROOT_DIR/sbin/init ]; then
1247
		echo ">>> ERROR: Something went wrong during cloning -- Please verify!" 2>&1 | tee -a ${LOGFILE}
1248
		print_error_pfS
1249
	fi
1250
}
1251

    
1252
customize_stagearea_for_image() {
1253
	# Prepare final stage area
1254
	create_final_staging_area
1255

    
1256
	if [ "${1}" = "iso" -o \
1257
	     "${1}" = "memstick" -o \
1258
	     "${1}" = "memstickserial" -o \
1259
	     "${1}" = "memstickadi" ]; then
1260
		install_bsdinstaller
1261
		mkdir -p ${FINAL_CHROOT_DIR}/pkgs
1262
		cp ${CORE_PKG_PATH}/*default-config*.txz ${FINAL_CHROOT_DIR}/pkgs
1263
	fi
1264

    
1265
	if [ "${1}" = "nanobsd" -o \
1266
	     "${1}" = "memstickserial" -o \
1267
	     "${1}" = "memstickadi" ]; then
1268
		pkg_chroot_add ${FINAL_CHROOT_DIR} default-config-serial
1269
	else
1270
		pkg_chroot_add ${FINAL_CHROOT_DIR} default-config
1271
	fi
1272
}
1273

    
1274
create_distribution_tarball() {
1275
	mkdir -p ${FINAL_CHROOT_DIR}/install
1276

    
1277
	tar -C ${FINAL_CHROOT_DIR} --exclude ./install --exclude ./pkgs -cJf ${FINAL_CHROOT_DIR}/install/${PRODUCT_NAME}.txz .
1278
}
1279

    
1280
create_iso_image() {
1281
	LOGFILE=${BUILDER_LOGS}/isoimage.${TARGET}
1282
	echo ">>> Building bootable ISO image for ${TARGET}" | tee -a ${LOGFILE}
1283
	if [ -z "${DEFAULT_KERNEL}" ]; then
1284
		echo ">>> ERROR: Could not identify DEFAULT_KERNEL to install on image!" | tee -a ${LOGFILE}
1285
		print_error_pfS
1286
	fi
1287

    
1288
	customize_stagearea_for_image "iso"
1289
	install_default_kernel ${DEFAULT_KERNEL}
1290

    
1291
	echo cdrom > $FINAL_CHROOT_DIR/etc/platform
1292

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

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

    
1300
	create_distribution_tarball
1301

    
1302
	# Remove /rescue from iso since cd9660 cannot deal with hardlinks
1303
	rm -rf ${FINAL_CHROOT_DIR}/rescue
1304

    
1305
	makefs -t cd9660 -o bootimage="i386;${FINAL_CHROOT_DIR}/boot/cdboot" -o no-emul-boot -o rockridge \
1306
		-o label=${FSLABEL} -o publisher="${PRODUCT_NAME} project." $ISOPATH ${FINAL_CHROOT_DIR} 2>&1 >> ${LOGFILE}
1307
	if [ $? -ne 0 -o ! -f $ISOPATH ]; then
1308
		if [ -f ${ISOPATH} ]; then
1309
			rm -f $ISOPATH
1310
		fi
1311
		echo ">>> ERROR: Something wrong happened during ISO image creation. STOPPING!" | tee -a ${LOGFILE}
1312
		print_error_pfS
1313
	fi
1314
	gzip -qf $ISOPATH &
1315

    
1316
	echo ">>> ISO created: $(LC_ALL=C date)" | tee -a ${LOGFILE}
1317
}
1318

    
1319
create_memstick_image() {
1320

    
1321
	LOGFILE=${BUILDER_LOGS}/memstick.${TARGET}
1322
	if [ "${MEMSTICKPATH}" = "" ]; then
1323
		echo ">>> MEMSTICKPATH is empty skipping generation of memstick image!" | tee -a ${LOGFILE}
1324
		return
1325
	fi
1326

    
1327
	if [ ! -d ${FINAL_CHROOT_DIR}/boot ]; then
1328
		customize_stagearea_for_image "memstick"
1329
		install_default_kernel ${DEFAULT_KERNEL}
1330
	fi
1331

    
1332
	echo cdrom > $FINAL_CHROOT_DIR/etc/platform
1333

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

    
1338
	create_distribution_tarball
1339

    
1340
	makefs -B little -o label=${PRODUCT_NAME} ${MEMSTICKPATH} ${FINAL_CHROOT_DIR}
1341
	if [ $? -ne 0 ]; then
1342
		if [ -f ${MEMSTICKPATH} ]; then
1343
			rm -f $MEMSTICKPATH
1344
		fi
1345
		echo ">>> ERROR: Something wrong happened during MEMSTICK image creation. STOPPING!" | tee -a ${LOGFILE}
1346
		print_error_pfS
1347
	fi
1348
	MD=$(mdconfig -a -t vnode -f $MEMSTICKPATH)
1349
	# Just in case
1350
	trap "mdconfig -d -u ${MD}" 1 2 15 EXIT
1351
	gpart create -s BSD ${MD} 2>&1 >> ${LOGFILE}|
1352
	gpart bootcode -b ${FINAL_CHROOT_DIR}/boot/boot ${MD} 2>&1 >> ${LOGFILE}
1353
	gpart add -t freebsd-ufs ${MD} 2>&1 >> ${LOGFILE}
1354
	trap "-" 1 2 15 EXIT
1355
	mdconfig -d -u ${MD} 2>&1 | tee -a ${LOGFILE}
1356
	gzip -qf $MEMSTICKPATH &
1357

    
1358
	echo ">>> MEMSTICK created: $(LC_ALL=C date)" | tee -a ${LOGFILE}
1359
}
1360

    
1361
create_memstick_serial_image() {
1362
	LOGFILE=${BUILDER_LOGS}/memstickserial.${TARGET}
1363
	if [ "${MEMSTICKSERIALPATH}" = "" ]; then
1364
		echo ">>> MEMSTICKSERIALPATH is empty skipping generation of memstick image!" | tee -a ${LOGFILE}
1365
		return
1366
	fi
1367

    
1368
	if [ ! -d ${FINAL_CHROOT_DIR}/boot ]; then
1369
		customize_stagearea_for_image "memstickserial"
1370
		install_default_kernel ${DEFAULT_KERNEL}
1371
	fi
1372

    
1373
	echo cdrom > $FINAL_CHROOT_DIR/etc/platform
1374

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

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

    
1380
	BOOTCONF=${FINAL_CHROOT_DIR}/boot.config
1381
	LOADERCONF=${FINAL_CHROOT_DIR}/boot/loader.conf
1382

    
1383
	echo ">>>   Activating serial console..." 2>&1 | tee -a ${LOGFILE}
1384
	# Activate serial console in boot.config
1385
	if [ -f ${BOOTCONF} ]; then
1386
		sed -i "" '/-D$/d' ${BOOTCONF}
1387
	fi
1388
	echo "-S115200 -D" >> ${BOOTCONF}
1389

    
1390
	# Remove old console options if present.
1391
	[ -f "${LOADERCONF}" ] \
1392
		&& sed -i "" -Ee "/(console|boot_multicons|boot_serial)/d" ${LOADERCONF}
1393
	# Activate serial console+video console in loader.conf
1394
	echo 'boot_multicons="YES"' >>  ${LOADERCONF}
1395
	echo 'boot_serial="YES"' >> ${LOADERCONF}
1396
	echo 'console="comconsole,vidconsole"' >> ${LOADERCONF}
1397
	echo 'comconsole_speed="115200"' >> ${LOADERCONF}
1398

    
1399
	create_distribution_tarball
1400

    
1401
	makefs -B little -o label=${PRODUCT_NAME} ${MEMSTICKSERIALPATH} ${FINAL_CHROOT_DIR}
1402
	if [ $? -ne 0 ]; then
1403
		if [ -f ${MEMSTICKSERIALPATH} ]; then
1404
			rm -f $MEMSTICKSERIALPATH
1405
		fi
1406
		echo ">>> ERROR: Something wrong happened during MEMSTICKSERIAL image creation. STOPPING!" | tee -a ${LOGFILE}
1407
		print_error_pfS
1408
	fi
1409
	MD=$(mdconfig -a -t vnode -f $MEMSTICKSERIALPATH)
1410
	# Just in case
1411
	trap "mdconfig -d -u ${MD}" 1 2 15 EXIT
1412
	gpart create -s BSD ${MD} 2>&1 >> ${LOGFILE}
1413
	gpart bootcode -b ${FINAL_CHROOT_DIR}/boot/boot ${MD} 2>&1 >> ${LOGFILE}
1414
	gpart add -t freebsd-ufs ${MD} 2>&1 >> ${LOGFILE}
1415
	trap "-" 1 2 15 EXIT
1416
	mdconfig -d -u ${MD} 2>&1 >> ${LOGFILE}
1417
	gzip -qf $MEMSTICKSERIALPATH &
1418

    
1419
	echo ">>> MEMSTICKSERIAL created: $(LC_ALL=C date)" | tee -a ${LOGFILE}
1420
}
1421

    
1422
create_memstick_adi_image() {
1423
	LOGFILE=${BUILDER_LOGS}/memstickadi${TARGET}
1424
	if [ "${MEMSTICKADIPATH}" = "" ]; then
1425
		echo ">>> MEMSTICKADIPATH is empty skipping generation of memstick image!" | tee -a ${LOGFILE}
1426
		return
1427
	fi
1428

    
1429
	if [ ! -d ${FINAL_CHROOT_DIR}/boot ]; then
1430
		customize_stagearea_for_image "memstickadi"
1431
		install_default_kernel ${DEFAULT_KERNEL}
1432
	fi
1433

    
1434
	echo cdrom > $FINAL_CHROOT_DIR/etc/platform
1435

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

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

    
1441
	BOOTCONF=${FINAL_CHROOT_DIR}/boot.config
1442
	LOADERCONF=${FINAL_CHROOT_DIR}/boot/loader.conf
1443

    
1444
	echo ">>>   Activating serial console..." 2>&1 | tee -a ${LOGFILE}
1445
	# Activate serial console in boot.config
1446
	if [ -f ${BOOTCONF} ]; then
1447
		sed -i "" '/-[Dh]$/d' ${BOOTCONF}
1448
	fi
1449
	echo "-S115200 -h" >> ${BOOTCONF}
1450

    
1451
	# Remove old console options if present.
1452
	[ -f "${LOADERCONF}" ] \
1453
		&& sed -i "" -Ee "/(console|boot_multicons|boot_serial|hint.uart)/d" ${LOADERCONF}
1454
	# Activate serial console+video console in loader.conf
1455
	echo 'boot_serial="YES"' >> ${LOADERCONF}
1456
	echo 'console="comconsole"' >> ${LOADERCONF}
1457
	echo 'comconsole_speed="115200"' >> ${LOADERCONF}
1458
	echo 'comconsole_port="0x2F8"' >> ${LOADERCONF}
1459
	echo 'hint.uart.0.flags="0x00"' >> ${LOADERCONF}
1460
	echo 'hint.uart.1.flags="0x10"' >> ${LOADERCONF}
1461

    
1462
	create_distribution_tarball
1463

    
1464
	makefs -B little -o label=${PRODUCT_NAME} ${MEMSTICKADIPATH} ${FINAL_CHROOT_DIR}
1465
	if [ $? -ne 0 ]; then
1466
		if [ -f ${MEMSTICKADIPATH} ]; then
1467
			rm -f $MEMSTICKADIPATH
1468
		fi
1469
		echo ">>> ERROR: Something wrong happened during MEMSTICKADI image creation. STOPPING!" | tee -a ${LOGFILE}
1470
		print_error_pfS
1471
	fi
1472
	MD=$(mdconfig -a -t vnode -f $MEMSTICKADIPATH)
1473
	# Just in case
1474
	trap "mdconfig -d -u ${MD}" 1 2 15 EXIT
1475
	gpart create -s BSD ${MD} 2>&1 >> ${LOGFILE}
1476
	gpart bootcode -b ${FINAL_CHROOT_DIR}/boot/boot ${MD} 2>&1 >> ${LOGFILE}
1477
	gpart add -t freebsd-ufs ${MD} 2>&1 >> ${LOGFILE}
1478
	trap "-" 1 2 15 EXIT
1479
	mdconfig -d -u ${MD} 2>&1 >> ${LOGFILE}
1480
	gzip -qf $MEMSTICKADIPATH &
1481

    
1482
	echo ">>> MEMSTICKADI created: $(LC_ALL=C date)" | tee -a ${LOGFILE}
1483
}
1484

    
1485
# Create pkg conf on desired place with desired arch/branch
1486
setup_pkg_repo() {
1487
	if [ -z "${4}" ]; then
1488
		return
1489
	fi
1490

    
1491
	local _target="${1}"
1492
	local _arch="${2}"
1493
	local _target_arch="${3}"
1494
	local _branch="${4}"
1495

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

    
1498
	sed \
1499
		-e "s/%%ARCH%%/${_arch}_${_target_arch}/" \
1500
		-e "s/%%GIT_REPO_BRANCH_OR_TAG%%/${_branch}/g" \
1501
		-e "s,%%PKG_REPO_SERVER%%,${PKG_REPO_SERVER},g" \
1502
		-e "s/%%PRODUCT_NAME%%/${PRODUCT_NAME}/g" \
1503
		${SRCDIR}/release/pkg_repos/${PRODUCT_NAME}.conf.template \
1504
		> ${_target}
1505
}
1506

    
1507
# This routine ensures any ports / binaries that the builder
1508
# system needs are on disk and ready for execution.
1509
builder_setup() {
1510
	# If Product-builder is already installed, just leave
1511
	if pkg info -e -q ${PRODUCT_NAME}-builder; then
1512
		return
1513
	fi
1514

    
1515
	if [ ! -f /usr/local/etc/pkg/repos/${PRODUCT_NAME}.conf ]; then
1516
		[ -d /usr/local/etc/pkg/repos ] \
1517
			|| mkdir -p /usr/local/etc/pkg/repos
1518

    
1519
		local _arch=$(uname -m)
1520
		setup_pkg_repo /usr/local/etc/pkg/repos/${PRODUCT_NAME}.conf ${_arch} ${_arch} ${PKG_REPO_CONF_BRANCH}
1521
	fi
1522

    
1523
	pkg install ${PRODUCT_NAME}-builder
1524
}
1525

    
1526
# Updates FreeBSD sources
1527
update_freebsd_sources() {
1528
	if [ "${1}" = "full" ]; then
1529
		local _full=1
1530
		local _clone_params=""
1531
	else
1532
		local _full=0
1533
		local _clone_params="--depth 1 --single-branch"
1534
	fi
1535

    
1536
	if [ ! -d "${SRCDIR}" ]; then
1537
		mkdir -p ${SRCDIR}
1538
	fi
1539

    
1540
	if [ -n "${NO_BUILDWORLD:-}" -a -n "${NO_BUILDKERNEL:-}" ]; then
1541
		echo ">>> NO_BUILDWORLD and NO_BUILDKERNEL set, skipping update of freebsd sources" | tee -a ${LOGFILE}
1542
		return
1543
	fi
1544

    
1545
	echo -n ">>> Obtaining FreeBSD sources ${FREEBSD_BRANCH}..."
1546
	local _FREEBSD_BRANCH=${FREEBSD_BRANCH:-"devel"}
1547
	local _CLONE=1
1548

    
1549
	if [ -d "${SRCDIR}/.git" ]; then
1550
		CUR_BRANCH=$(cd ${SRCDIR} && git branch | grep '^\*' | cut -d' ' -f2)
1551
		if [ ${_full} -eq 0 -a "${CUR_BRANCH}" = "${_FREEBSD_BRANCH}" ]; then
1552
			_CLONE=0
1553
			( cd ${SRCDIR} && git clean -fxd; git fetch origin; git reset --hard origin/${_FREEBSD_BRANCH} ) 2>&1 | grep -C3 -i -E 'error|fatal'
1554
		else
1555
			rm -rf ${SRCDIR}
1556
		fi
1557
	fi
1558

    
1559
	if [ ${_CLONE} -eq 1 ]; then
1560
		( git clone --branch ${_FREEBSD_BRANCH} ${_clone_params} ${FREEBSD_REPO_BASE} ${SRCDIR} ) 2>&1 | grep -C3 -i -E 'error|fatal'
1561
	fi
1562

    
1563
	if [ ! -d "${SRCDIR}/.git" ]; then
1564
		echo ">>> ERROR: It was not possible to clone FreeBSD src repo"
1565
		print_error_pfS
1566
	fi
1567

    
1568
	if [ -n "${GIT_FREEBSD_COSHA1}" ]; then
1569
		( cd ${SRCDIR} && git checkout ${GIT_FREEBSD_COSHA1} ) 2>&1 | grep -C3 -i -E 'error|fatal'
1570
	fi
1571
	echo "Done!"
1572
}
1573

    
1574
pkg_chroot() {
1575
	local _root="${1}"
1576
	shift
1577

    
1578
	if [ $# -eq 0 ]; then
1579
		return -1
1580
	fi
1581

    
1582
	if [ -z "${_root}" -o "${_root}" = "/" -o ! -d "${_root}" ]; then
1583
		return -1
1584
	fi
1585

    
1586
	mkdir -p \
1587
		${SCRATCHDIR}/pkg_cache \
1588
		${_root}/var/cache/pkg \
1589
		${_root}/dev
1590

    
1591
	/sbin/mount -t nullfs ${SCRATCHDIR}/pkg_cache ${_root}/var/cache/pkg
1592
	/sbin/mount -t devfs devfs ${_root}/dev
1593
	cp -f /etc/resolv.conf ${_root}/etc/resolv.conf
1594
	touch ${BUILDER_LOGS}/install_pkg_install_ports.txt
1595
	script -aq ${BUILDER_LOGS}/install_pkg_install_ports.txt pkg -c ${_root} $@ >/dev/null 2>&1
1596
	rm -f ${_root}/etc/resolv.conf
1597
	/sbin/umount -f ${_root}/dev
1598
	/sbin/umount -f ${_root}/var/cache/pkg
1599
}
1600

    
1601

    
1602
pkg_chroot_add() {
1603
	if [ -z "${1}" -o -z "${2}" ]; then
1604
		return 1
1605
	fi
1606

    
1607
	local _target="${1}"
1608
	local _pkg="$(get_pkg_name ${2}).txz"
1609

    
1610
	if [ ! -d "${_target}" ]; then
1611
		echo ">>> ERROR: Target dir ${_target} not found"
1612
		print_error_pfS
1613
	fi
1614

    
1615
	if [ ! -f ${CORE_PKG_PATH}/${_pkg} ]; then
1616
		echo ">>> ERROR: Package ${_pkg} not found"
1617
		print_error_pfS
1618
	fi
1619

    
1620
	cp ${CORE_PKG_PATH}/${_pkg} ${_target}
1621
	pkg_chroot ${_target} add /${_pkg}
1622
	rm -f ${_target}/${_pkg}
1623
}
1624

    
1625
pkg_bootstrap() {
1626
	local _root=${1:-"${STAGE_CHROOT_DIR}"}
1627

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

    
1630
	pkg_chroot ${_root} bootstrap -f
1631
}
1632

    
1633
# This routine assists with installing various
1634
# freebsd ports files into the pfsenese-fs staging
1635
# area.
1636
install_pkg_install_ports() {
1637
	local MAIN_PKG="${1}"
1638

    
1639
	if [ -z "${MAIN_PKG}" ]; then
1640
		MAIN_PKG=${PRODUCT_NAME}
1641
	fi
1642

    
1643
	echo ">>> Installing pkg repository in chroot (${STAGE_CHROOT_DIR})..."
1644

    
1645
	[ -d ${STAGE_CHROOT_DIR}/var/cache/pkg ] || \
1646
		mkdir -p ${STAGE_CHROOT_DIR}/var/cache/pkg
1647

    
1648
	[ -d ${SCRATCHDIR}/pkg_cache ] || \
1649
		mkdir -p ${SCRATCHDIR}/pkg_cache
1650

    
1651
	echo ">>> Installing built ports (packages) in chroot (${STAGE_CHROOT_DIR})... (starting)"
1652
	pkg_chroot ${STAGE_CHROOT_DIR} install ${MAIN_PKG} ${custom_package_list}
1653
	pkg_chroot ${STAGE_CHROOT_DIR} autoremove
1654
	echo ">>> Installing built ports (packages) in chroot (${STAGE_CHROOT_DIR})... (finshied)"
1655
}
1656

    
1657
install_bsdinstaller() {
1658
	echo ">>> Installing BSDInstaller in chroot (${FINAL_CHROOT_DIR})... (starting)"
1659
	pkg_chroot ${FINAL_CHROOT_DIR} install -f bsdinstaller ${MAIN_PKG} ${custom_package_list}
1660
	echo ">>> Installing BSDInstaller in chroot (${FINAL_CHROOT_DIR})... (finished)"
1661
}
1662

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

    
1674
# Imported from FreeSBIE
1675
buildkernel() {
1676
	if [ -n "${NO_BUILDKERNEL:-}" ]; then
1677
		echo ">>> NO_BUILDKERNEL set, skipping build" | tee -a ${LOGFILE}
1678
		return
1679
	fi
1680

    
1681
	if [ -z "${KERNCONF:-}" ]; then
1682
		echo ">>> ERROR: No kernel configuration defined probably this is not what you want! STOPPING!" | tee -a ${LOGFILE}
1683
		print_error_pfS
1684
	fi
1685

    
1686
	if [ -n "${KERNELCONF:-}" ]; then
1687
		export KERNCONFDIR=$(dirname ${KERNELCONF})
1688
		export KERNCONF=$(basename ${KERNELCONF})
1689
	fi
1690

    
1691
	SRCCONFBASENAME=$(basename ${SRC_CONF})
1692
	echo ">>> KERNCONFDIR: ${KERNCONFDIR}"
1693
	echo ">>> ARCH:        ${TARGET}"
1694
	echo ">>> SRC_CONF:    ${SRCCONFBASENAME}"
1695

    
1696
	makeargs="${MAKEJ_KERNEL:-} SRCCONF=${SRC_CONF} __MAKE_CONF=${MAKE_CONF} TARGET_ARCH=${TARGET_ARCH} TARGET=${TARGET}"
1697
	echo ">>> Builder is running the command: script -aq $LOGFILE make -DNO_KERNELCLEAN $makeargs buildkernel KERNCONF=${KERNCONF}" | tee -a $LOGFILE
1698
	(script -q $LOGFILE make -C ${SRCDIR} -DNO_KERNELCLEAN $makeargs buildkernel KERNCONF=${KERNCONF} || print_error_pfS;) | egrep '^>>>'
1699
}
1700

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

    
1708
	if [ -n "${KERNELCONF:-}" ]; then
1709
		export KERNCONFDIR=$(dirname ${KERNELCONF})
1710
		export KERNCONF=$(basename ${KERNELCONF})
1711
	fi
1712

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

    
1720
# Launch is ran first to setup a few variables that we need
1721
# Imported from FreeSBIE
1722
launch() {
1723

    
1724
	if [ ! -f $SCRATCHDIR/${PRODUCT_NAME}_builder_set_time ]; then
1725
		echo ">>> Updating system clock..."
1726
		ntpdate 0.freebsd.pool.ntp.org
1727
		touch $SCRATCHDIR/${PRODUCT_NAME}_builder_set_time
1728
	fi
1729

    
1730
	if [ "$(id -u)" != "0" ]; then
1731
		echo "Sorry, this must be done as root."
1732
	fi
1733

    
1734
	echo ">>> Operation $0 has started at $(date)"
1735
}
1736

    
1737
finish() {
1738
	echo ">>> Operation $0 has ended at $(date)"
1739
}
1740

    
1741
poudriere_create_patch() {
1742
	local _jail_patch="${SCRATCHDIR}/poudriere_jail.${GIT_REPO_BRANCH_OR_TAG}.patch"
1743

    
1744
	if [ -z "${FREEBSD_PARENT_BRANCH}" ]; then
1745
		echo ">>> ERROR: FREEBSD_PARENT_BRANCH is not set"
1746
	fi
1747

    
1748
	LOGFILE=${BUILDER_LOGS}/poudriere.log
1749

    
1750
	# Get FreeBSD source and apply patches
1751
	update_freebsd_sources full
1752

    
1753
	[ -f "${_jail_patch}" ] && \
1754
		rm -f "${_jail_patch}"
1755

    
1756
	# Create a big patch with all our changes to use on jail
1757
	( \
1758
		cd ${SRCDIR} && \
1759
		git diff $(git merge-base origin/${FREEBSD_PARENT_BRANCH} ${FREEBSD_BRANCH}) > ${_jail_patch}
1760
	) >/dev/null 2>&1
1761

    
1762
	# Check if patch was created
1763
	if [ ! -s "${_jail_patch}" ]; then
1764
		echo ">>> ERROR: Patch does not exist or is empty, aborting..." | tee -a ${LOGFILE}
1765
		print_error_pfS
1766
	fi
1767
}
1768

    
1769
poudriere_possible_archs() {
1770
	local _arch=$(uname -m)
1771
	local _archs="i386.i386"
1772

    
1773
	# IF host is amd64, we'll create both repos, and if possible armv6
1774
	if [ "${_arch}" = "amd64" ]; then
1775
		_archs="amd64.amd64 ${_archs}"
1776

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

    
1781
			if binmiscctl lookup armv6 >/dev/null 2>&1; then
1782
				_archs="${_archs} arm.armv6"
1783
			fi
1784
		fi
1785
	fi
1786

    
1787
	echo ${_archs}
1788
}
1789

    
1790
poudriere_jail_name() {
1791
	local _jail_arch="${1}"
1792

    
1793
	if [ -z "${_jail_arch}" ]; then
1794
		return 1
1795
	fi
1796

    
1797
	# Poudriere doesn't like periods in jail names
1798
	_jail_arch=$(echo "${_jail_arch}" | tr '.' '_')
1799

    
1800
	echo "${PRODUCT_NAME}_${GIT_REPO_BRANCH_OR_TAG}_${_jail_arch}"
1801
}
1802

    
1803
poudriere_create_ports_tree() {
1804
	LOGFILE=${BUILDER_LOGS}/poudriere.log
1805

    
1806
	if ! poudriere ports -l | grep -q -E "^${POUDRIERE_PORTS_NAME}[[:blank:]]"; then
1807
		local _branch=""
1808
		if [ -z "${POUDRIERE_PORTS_GIT_URL}" ]; then
1809
			echo ">>> ERROR: POUDRIERE_PORTS_GIT_URL is not defined"
1810
			print_error_pfS
1811
		fi
1812
		if [ -n "${POUDRIERE_PORTS_GIT_BRANCH}" ]; then
1813
			_branch="-B ${POUDRIERE_PORTS_GIT_BRANCH}"
1814
		fi
1815
		echo -n ">>> Creating poudriere ports tree, it may take some time... " | tee -a ${LOGFILE}
1816
		if ! script -aq ${LOGFILE} poudriere ports -c -p "${POUDRIERE_PORTS_NAME}" -m git ${_branch} >/dev/null 2>&1; then
1817
			echo "" | tee -a ${LOGFILE}
1818
			echo ">>> ERROR: Error creating poudriere ports tree, aborting..." | tee -a ${LOGFILE}
1819
			print_error_pfS
1820
		fi
1821
		echo "Done!" | tee -a ${LOGFILE}
1822
	fi
1823
}
1824

    
1825
poudriere_init() {
1826
	local _error=0
1827
	local _archs=$(poudriere_possible_archs)
1828
	local _jail_patch="${SCRATCHDIR}/poudriere_jail.${GIT_REPO_BRANCH_OR_TAG}.patch"
1829

    
1830
	LOGFILE=${BUILDER_LOGS}/poudriere.log
1831

    
1832
	# Sanity checks
1833
	if [ -z "${ZFS_TANK}" ]; then
1834
		echo ">>> ERROR: \$ZFS_TANK is empty" | tee -a ${LOGFILE}
1835
		error=1
1836
	fi
1837

    
1838
	if [ -z "${ZFS_ROOT}" ]; then
1839
		echo ">>> ERROR: \$ZFS_ROOT is empty" | tee -a ${LOGFILE}
1840
		error=1
1841
	fi
1842

    
1843
	if [ -z "${POUDRIERE_PORTS_NAME}" ]; then
1844
		echo ">>> ERROR: \$POUDRIERE_PORTS_NAME is empty" | tee -a ${LOGFILE}
1845
		error=1
1846
	fi
1847

    
1848
	if [ ${_error} -eq 1 ]; then
1849
		print_error_pfS
1850
	fi
1851

    
1852
	# Check if zpool exists
1853
	if ! zpool list ${ZFS_TANK} >/dev/null 2>&1; then
1854
		echo ">>> ERROR: ZFS tank ${ZFS_TANK} not found, please create it and try again..." | tee -a ${LOGFILE}
1855
		print_error_pfS
1856
	fi
1857

    
1858
	# Check if zfs rootfs exists
1859
	if ! zfs list ${ZFS_TANK}${ZFS_ROOT} >/dev/null 2>&1; then
1860
		echo ">>> ERROR: ZFS filesystem ${ZFS_TANK}${ZFS_ROOT} not found, please create it and try again..." | tee -a ${LOGFILE}
1861
		print_error_pfS
1862
	fi
1863

    
1864
	# Make sure poudriere is installed
1865
	if ! pkg info --quiet poudriere; then
1866
		echo ">>> Installing poudriere..." | tee -a ${LOGFILE}
1867
		if ! pkg install poudriere >/dev/null 2>&1; then
1868
			echo ">>> ERROR: poudriere was not installed, aborting..." | tee -a ${LOGFILE}
1869
			print_error_pfS
1870
		fi
1871
	fi
1872

    
1873
	# Create poudriere.conf
1874
	if [ -z "${POUDRIERE_PORTS_GIT_URL}" ]; then
1875
		echo ">>> ERROR: POUDRIERE_PORTS_GIT_URL is not defined"
1876
		print_error_pfS
1877
	fi
1878
	echo ">>> Creating poudriere.conf" | tee -a ${LOGFILE}
1879
	cat <<EOF >/usr/local/etc/poudriere.conf
1880
ZPOOL=${ZFS_TANK}
1881
ZROOTFS=${ZFS_ROOT}
1882
RESOLV_CONF=/etc/resolv.conf
1883
BASEFS=/usr/local/poudriere
1884
USE_PORTLINT=no
1885
USE_TMPFS=yes
1886
NOLINUX=yes
1887
DISTFILES_CACHE=/usr/ports/distfiles
1888
CHECK_CHANGED_OPTIONS=yes
1889
CHECK_CHANGED_DEPS=yes
1890
ATOMIC_PACKAGE_REPOSITORY=yes
1891
COMMIT_PACKAGES_ON_FAILURE=no
1892
GIT_URL="${POUDRIERE_PORTS_GIT_URL}"
1893
EOF
1894

    
1895
	# Remove old jails
1896
	for jail_arch in ${_archs}; do
1897
		jail_name=$(poudriere_jail_name ${jail_arch})
1898

    
1899
		if poudriere jail -i -j "${jail_name}" >/dev/null 2>&1; then
1900
			echo ">>> Poudriere jail ${jail_name} already exists, deleting it..." | tee -a ${LOGFILE}
1901
			poudriere jail -d -j "${jail_name}" >/dev/null 2>&1
1902
		fi
1903
	done
1904

    
1905
	# Remove old ports tree
1906
	if poudriere ports -l | grep -q -E "^${POUDRIERE_PORTS_NAME}[[:blank:]]"; then
1907
		echo ">>> Poudriere ports tree ${POUDRIERE_PORTS_NAME} already exists, deleting it..." | tee -a ${LOGFILE}
1908
		poudriere ports -d -p "${POUDRIERE_PORTS_NAME}"
1909
	fi
1910

    
1911
	poudriere_create_patch
1912

    
1913
	local native_xtools=""
1914
	# Now we are ready to create jails
1915
	for jail_arch in ${_archs}; do
1916
		jail_name=$(poudriere_jail_name ${jail_arch})
1917

    
1918
		if [ "${jail_arch}" = "arm.armv6" ]; then
1919
			native_xtools="-x"
1920
		else
1921
			native_xtools=""
1922
		fi
1923

    
1924
		echo -n ">>> Creating jail ${jail_name}, it may take some time... " | tee -a ${LOGFILE}
1925
		# XXX: Change -m to git when it's available in poudriere
1926
		if ! script -aq ${LOGFILE} poudriere jail -c -j "${jail_name}" -v ${FREEBSD_PARENT_BRANCH} \
1927
				-a ${jail_arch} -m svn -P ${_jail_patch} ${native_xtools} >/dev/null 2>&1; then
1928
			echo "" | tee -a ${LOGFILE}
1929
			echo ">>> ERROR: Error creating jail ${jail_name}, aborting..." | tee -a ${LOGFILE}
1930
			print_error_pfS
1931
		fi
1932
		echo "Done!" | tee -a ${LOGFILE}
1933
	done
1934

    
1935
	poudriere_create_ports_tree
1936

    
1937
	echo ">>> Poudriere is now configured!" | tee -a ${LOGFILE}
1938
}
1939

    
1940
poudriere_update_jails() {
1941
	local _archs=$(poudriere_possible_archs)
1942
	local _jail_patch="${SCRATCHDIR}/poudriere_jail.${GIT_REPO_BRANCH_OR_TAG}.patch"
1943

    
1944
	LOGFILE=${BUILDER_LOGS}/poudriere.log
1945

    
1946
	poudriere_create_patch
1947

    
1948
	local native_xtools=""
1949
	for jail_arch in ${_archs}; do
1950
		local _run=0
1951
		if [ -n "${ARCH_LIST}" ]; then
1952
			for _arch in ${ARCH_LIST}; do
1953
				if [ "${jail_arch##*.}" = "${_arch}" ]; then
1954
					_run=1
1955
				fi
1956
			done
1957
		else
1958
			_run=1
1959
		fi
1960

    
1961
		[ ${_run} -eq 0 ] \
1962
			&& continue
1963

    
1964
		jail_name=$(poudriere_jail_name ${jail_arch})
1965

    
1966
		if ! poudriere jail -i -j "${jail_name}" >/dev/null 2>&1; then
1967
			echo ">>> Poudriere jail ${jail_name} not found, skipping..." | tee -a ${LOGFILE}
1968
			continue
1969
		fi
1970

    
1971
		if [ "${jail_arch}" = "arm.armv6" ]; then
1972
			native_xtools="-x"
1973
		else
1974
			native_xtools=""
1975
		fi
1976

    
1977
		echo -n ">>> Updating jail ${jail_name}, it may take some time... " | tee -a ${LOGFILE}
1978
		if ! script -aq ${LOGFILE} poudriere jail -u -j "${jail_name}" -P ${_jail_patch} ${native_xtools} >/dev/null 2>&1; then
1979
			echo "" | tee -a ${LOGFILE}
1980
			echo ">>> ERROR: Error updating jail ${jail_name}, aborting..." | tee -a ${LOGFILE}
1981
			print_error_pfS
1982
		fi
1983
		echo "Done!" | tee -a ${LOGFILE}
1984
	done
1985
}
1986

    
1987
poudriere_update_ports() {
1988
	LOGFILE=${BUILDER_LOGS}/poudriere.log
1989

    
1990
	# Create ports tree if necessary
1991
	if ! poudriere ports -l | grep -q -E "^${POUDRIERE_PORTS_NAME}[[:blank:]]"; then
1992
		poudriere_create_ports_tree
1993
	else
1994
		echo -n ">>> Updating ports tree ${POUDRIERE_PORTS_NAME}... " | tee -a ${LOGFILE}
1995
		script -aq ${LOGFILE} poudriere ports -u -p "${POUDRIERE_PORTS_NAME}" >/dev/null 2>&1
1996
		echo "Done!" | tee -a ${LOGFILE}
1997
	fi
1998
}
1999

    
2000
poudriere_bulk() {
2001
	local _archs=$(poudriere_possible_archs)
2002

    
2003
	LOGFILE=${BUILDER_LOGS}/poudriere.log
2004

    
2005
	poudriere_create_ports_tree
2006

    
2007
	local CUR_BRANCH=$(cd ${BUILDER_TOOLS} && git branch | grep '^\*' | cut -d' ' -f2)
2008

    
2009
	[ -d /usr/local/etc/poudriere.d ] || \
2010
		mkdir -p /usr/local/etc/poudriere.d
2011

    
2012
	if [ "${CUR_BRANCH}" != "${GIT_REPO_BRANCH_OR_TAG}" ] && git show "${GIT_REPO_BRANCH_OR_TAG}:builder_scripts/conf/pfPorts/make.conf" >/dev/null 2>&1; then
2013
		git show "origin/${GIT_REPO_BRANCH_OR_TAG}:builder_scripts/conf/pfPorts/make.conf" > /usr/local/etc/poudriere.d/${POUDRIERE_PORTS_NAME}-make.conf
2014
	elif [ -f "${BUILDER_SCRIPTS}/conf/pfPorts/make.conf" ]; then
2015
		cp -f "${BUILDER_SCRIPTS}/conf/pfPorts/make.conf" /usr/local/etc/poudriere.d/${POUDRIERE_PORTS_NAME}-make.conf
2016
	fi
2017

    
2018
	for jail_arch in ${_archs}; do
2019
		jail_name=$(poudriere_jail_name ${jail_arch})
2020

    
2021
		if ! poudriere jail -i -j "${jail_name}" >/dev/null 2>&1; then
2022
			echo ">>> Poudriere jail ${jail_name} not found, skipping..." | tee -a ${LOGFILE}
2023
			continue
2024
		fi
2025

    
2026
		if [ -f "${POUDRIERE_BULK}.${jail_arch}" ]; then
2027
			_ref_bulk="${POUDRIERE_BULK}.${jail_arch}"
2028
		else
2029
			_ref_bulk="${POUDRIERE_BULK}"
2030
		fi
2031

    
2032
		_bulk=${SCRATCHDIR}/poudriere_bulk.${GIT_REPO_BRANCH_OR_TAG}
2033
		sed -e "s,%%PRODUCT_NAME%%,${PRODUCT_NAME},g" ${_ref_bulk} > ${_bulk}
2034

    
2035
		if ! poudriere bulk -f ${_bulk} -j ${jail_name} -p ${POUDRIERE_PORTS_NAME}; then
2036
			echo ">>> ERROR: Something went wrong..."
2037
			print_error_pfS
2038
		fi
2039

    
2040
		echo ">>> Cleaning up old packages from repo..."
2041
		if ! poudriere pkgclean -f ${_bulk} -j ${jail_name} -p ${POUDRIERE_PORTS_NAME} -y; then
2042
			echo ">>> ERROR: Something went wrong..."
2043
			print_error_pfS
2044
		fi
2045

    
2046
		# ./ is intentional, it's a rsync trick to make it chdir to directory before send it
2047
		REPO_PATH="/usr/local/poudriere/data/packages/./${jail_name}-${POUDRIERE_PORTS_NAME}"
2048
		if [ -z "${DO_NOT_UPLOAD}" -a -d "${REPO_PATH}" ]; then
2049
			echo -n ">>> Sending updated repository to ${PKG_RSYNC_HOSTNAME}... " | tee -a ${LOGFILE}
2050
			if script -aq ${LOGFILE} rsync -ave "ssh -p ${PKG_RSYNC_SSH_PORT}" \
2051
				--timeout=60 --delete-delay ${REPO_PATH} \
2052
				${PKG_RSYNC_USERNAME}@${PKG_RSYNC_HOSTNAME}:${PKG_RSYNC_DESTDIR} >/dev/null 2>&1
2053
			then
2054
				echo "Done!" | tee -a ${LOGFILE}
2055
			else
2056
				echo "Failed!" | tee -a ${LOGFILE}
2057
				echo ">>> ERROR: An error occurred sending repo to remote hostname"
2058
				print_error_pfS
2059
			fi
2060
		fi
2061
	done
2062
}
(2-2/4)