1#!/bin/sh
2#
3# Copyright (c) 2005 Poul-Henning Kamp.
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions
8# are met:
9# 1. Redistributions of source code must retain the above copyright
10#    notice, this list of conditions and the following disclaimer.
11# 2. Redistributions in binary form must reproduce the above copyright
12#    notice, this list of conditions and the following disclaimer in the
13#    documentation and/or other materials provided with the distribution.
14#
15# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25# SUCH DAMAGE.
26#
27# $FreeBSD$
28#
29
30set -e
31
32#######################################################################
33#
34# Setup default values for all controlling variables.
35# These values can be overridden from the config file(s)
36#
37#######################################################################
38
39# Name of this NanoBSD build.  (Used to construct workdir names)
40NANO_NAME=full
41
42# Source tree directory
43NANO_SRC=/usr/src
44
45# Where nanobsd additional files live under the source tree
46NANO_TOOLS=tools/tools/nanobsd
47
48# Where cust_pkg() finds packages to install
49NANO_PACKAGE_DIR=${NANO_SRC}/${NANO_TOOLS}/Pkg
50NANO_PACKAGE_LIST="*"
51
52# Object tree directory
53# default is subdir of /usr/obj
54#NANO_OBJ=""
55
56# The directory to put the final images
57# default is ${NANO_OBJ}
58#NANO_DISKIMGDIR=""
59
60# Parallel Make
61NANO_PMAKE="make -j 3"
62
63# The default name for any image we create.
64NANO_IMGNAME="_.disk.full"
65
66# Options to put in make.conf during buildworld only
67CONF_BUILD=' '
68
69# Options to put in make.conf during installworld only
70CONF_INSTALL=' '
71
72# Options to put in make.conf during both build- & installworld.
73CONF_WORLD=' '
74
75# Kernel config file to use
76NANO_KERNEL=GENERIC
77
78# Kernel modules to install. If empty, no modules are installed.
79# Use "default" to install all built modules.
80NANO_MODULES=
81
82# Customize commands.
83NANO_CUSTOMIZE=""
84
85# Late customize commands.
86NANO_LATE_CUSTOMIZE=""
87
88# Newfs paramters to use
89NANO_NEWFS="-b 4096 -f 512 -i 8192 -O1 -U"
90
91# The drive name of the media at runtime
92NANO_DRIVE=ad0
93
94# Target media size in 512 bytes sectors
95NANO_MEDIASIZE=1500000
96
97# Number of code images on media (1 or 2)
98NANO_IMAGES=2
99
100# 0 -> Leave second image all zeroes so it compresses better.
101# 1 -> Initialize second image with a copy of the first
102NANO_INIT_IMG2=1
103
104# Size of code file system in 512 bytes sectors
105# If zero, size will be as large as possible.
106NANO_CODESIZE=0
107
108# Size of configuration file system in 512 bytes sectors
109# Cannot be zero.
110NANO_CONFSIZE=2048
111
112# Size of data file system in 512 bytes sectors
113# If zero: no partition configured.
114# If negative: max size possible
115NANO_DATASIZE=0
116
117# Size of the /etc ramdisk in 512 bytes sectors
118NANO_RAM_ETCSIZE=10240
119
120# Size of the /tmp+/var ramdisk in 512 bytes sectors
121NANO_RAM_TMPVARSIZE=10240
122
123# Media geometry, only relevant if bios doesn't understand LBA.
124NANO_SECTS=63
125NANO_HEADS=16
126
127# boot0 flags/options and configuration
128NANO_BOOT0CFG="-o packet -s 1 -m 3"
129NANO_BOOTLOADER="boot/boot0sio"
130
131# boot2 flags/options
132# default force serial console
133NANO_BOOT2CFG="-h"
134
135# Backing type of md(4) device
136# Can be "file" or "swap"
137NANO_MD_BACKING="file"
138
139# Progress Print level
140PPLEVEL=3
141
142# Set NANO_LABEL to non-blank to form the basis for using /dev/ufs/label
143# in preference to /dev/${NANO_DRIVE}
144# Root partition will be ${NANO_LABEL}s{1,2}
145# /cfg partition will be ${NANO_LABEL}s3
146# /data partition will be ${NANO_LABEL}s4
147NANO_LABEL=""
148
149#######################################################################
150# Architecture to build.  Corresponds to TARGET_ARCH in a buildworld.
151# Unfortunately, there's no way to set TARGET at this time, and it
152# conflates the two, so architectures where TARGET != TARGET_ARCH do
153# not work.  This defaults to the arch of the current machine.
154
155NANO_ARCH=`uname -p`
156
157# Directory to populate /cfg from
158NANO_CFGDIR=""
159
160# Directory to populate /data from
161NANO_DATADIR=""
162
163#######################################################################
164#
165# The functions which do the real work.
166# Can be overridden from the config file(s)
167#
168#######################################################################
169
170clean_build ( ) (
171	pprint 2 "Clean and create object directory (${MAKEOBJDIRPREFIX})"
172
173	if ! rm -rf ${MAKEOBJDIRPREFIX} > /dev/null 2>&1 ; then
174		chflags -R noschg ${MAKEOBJDIRPREFIX}
175		rm -r ${MAKEOBJDIRPREFIX}
176	fi
177	mkdir -p ${MAKEOBJDIRPREFIX}
178	printenv > ${MAKEOBJDIRPREFIX}/_.env
179)
180
181make_conf_build ( ) (
182	pprint 2 "Construct build make.conf ($NANO_MAKE_CONF_BUILD)"
183
184	echo "${CONF_WORLD}" > ${NANO_MAKE_CONF_BUILD}
185	echo "${CONF_BUILD}" >> ${NANO_MAKE_CONF_BUILD}
186	echo "SRCCONF=/dev/null" >> ${NANO_MAKE_CONF_BUILD}
187)
188
189build_world ( ) (
190	pprint 2 "run buildworld"
191	pprint 3 "log: ${MAKEOBJDIRPREFIX}/_.bw"
192
193	cd ${NANO_SRC}
194	env TARGET_ARCH=${NANO_ARCH} ${NANO_PMAKE} \
195		__MAKE_CONF=${NANO_MAKE_CONF_BUILD} buildworld \
196		> ${MAKEOBJDIRPREFIX}/_.bw 2>&1
197)
198
199build_kernel ( ) (
200	pprint 2 "build kernel ($NANO_KERNEL)"
201	pprint 3 "log: ${MAKEOBJDIRPREFIX}/_.bk"
202
203	(
204	if [ -f ${NANO_KERNEL} ] ; then
205		kernconfdir_arg="KERNCONFDIR='$(realpath $(dirname ${NANO_KERNEL}))'"
206		kernconf=$(basename ${NANO_KERNEL})
207	else
208		kernconf=${NANO_KERNEL}
209	fi
210
211	cd ${NANO_SRC};
212	# unset these just in case to avoid compiler complaints
213	# when cross-building
214	unset TARGET_CPUTYPE
215	unset TARGET_BIG_ENDIAN
216	# Note: We intentionally build all modules, not only the ones in
217	# NANO_MODULES so the built world can be reused by multiple images.
218	eval "TARGET_ARCH=${NANO_ARCH} ${NANO_PMAKE} buildkernel \
219		__MAKE_CONF='${NANO_MAKE_CONF_BUILD}' \
220		${kernconfdir_arg} KERNCONF=${kernconf}"
221	) > ${MAKEOBJDIRPREFIX}/_.bk 2>&1
222)
223
224clean_world ( ) (
225	if [ "${NANO_OBJ}" != "${MAKEOBJDIRPREFIX}" ]; then
226		pprint 2 "Clean and create object directory (${NANO_OBJ})"
227		if ! rm -rf ${NANO_OBJ} > /dev/null 2>&1 ; then
228			chflags -R noschg ${NANO_OBJ}
229			rm -r ${NANO_OBJ}
230		fi
231		mkdir -p ${NANO_OBJ} ${NANO_WORLDDIR}
232		printenv > ${NANO_OBJ}/_.env
233	else
234		pprint 2 "Clean and create world directory (${NANO_WORLDDIR})"
235		if ! rm -rf ${NANO_WORLDDIR}/ > /dev/null 2>&1 ; then
236			chflags -R noschg ${NANO_WORLDDIR}
237			rm -rf ${NANO_WORLDDIR}
238		fi
239		mkdir -p ${NANO_WORLDDIR}
240	fi
241)
242
243make_conf_install ( ) (
244	pprint 2 "Construct install make.conf ($NANO_MAKE_CONF_INSTALL)"
245
246	echo "${CONF_WORLD}" > ${NANO_MAKE_CONF_INSTALL}
247	echo "${CONF_INSTALL}" >> ${NANO_MAKE_CONF_INSTALL}
248	echo "SRCCONF=/dev/null" >> ${NANO_MAKE_CONF_INSTALL}
249)
250
251install_world ( ) (
252	pprint 2 "installworld"
253	pprint 3 "log: ${NANO_OBJ}/_.iw"
254
255	cd ${NANO_SRC}
256	env TARGET_ARCH=${NANO_ARCH} \
257	${NANO_PMAKE} __MAKE_CONF=${NANO_MAKE_CONF_INSTALL} installworld \
258		DESTDIR=${NANO_WORLDDIR} \
259		> ${NANO_OBJ}/_.iw 2>&1
260	chflags -R noschg ${NANO_WORLDDIR}
261)
262
263install_etc ( ) (
264
265	pprint 2 "install /etc"
266	pprint 3 "log: ${NANO_OBJ}/_.etc"
267
268	cd ${NANO_SRC}
269	env TARGET_ARCH=${NANO_ARCH} \
270	${NANO_PMAKE} __MAKE_CONF=${NANO_MAKE_CONF_INSTALL} distribution \
271		DESTDIR=${NANO_WORLDDIR} \
272		> ${NANO_OBJ}/_.etc 2>&1
273	# make.conf doesn't get created by default, but some ports need it
274	# so they can spam it.
275	cp /dev/null ${NANO_WORLDDIR}/etc/make.conf
276)
277
278install_kernel ( ) (
279	pprint 2 "install kernel ($NANO_KERNEL)"
280	pprint 3 "log: ${NANO_OBJ}/_.ik"
281
282	(
283	if [ -f ${NANO_KERNEL} ] ; then
284		kernconfdir_arg="KERNCONFDIR='$(realpath $(dirname ${NANO_KERNEL}))'"
285		kernconf=$(basename ${NANO_KERNEL})
286	else
287		kernconf=${NANO_KERNEL}
288	fi
289
290	# Install all built modules if NANO_MODULES=default,
291	# else install only listed modules (none if NANO_MODULES is empty).
292	if [ "${NANO_MODULES}" != "default" ]; then
293		modules_override_arg="MODULES_OVERRIDE='${NANO_MODULES}'"
294	fi
295
296	cd ${NANO_SRC}
297	eval "TARGET_ARCH=${NANO_ARCH} ${NANO_MAKE} installkernel \
298		DESTDIR='${NANO_WORLDDIR}' \
299		__MAKE_CONF='${NANO_MAKE_CONF_INSTALL}' \
300		${kernconfdir_arg} KERNCONF=${kernconf} \
301		${modules_override_arg}"
302	) > ${NANO_OBJ}/_.ik 2>&1
303)
304
305run_customize() (
306
307	pprint 2 "run customize scripts"
308	for c in $NANO_CUSTOMIZE
309	do
310		pprint 2 "customize \"$c\""
311		pprint 3 "log: ${NANO_OBJ}/_.cust.$c"
312		pprint 4 "`type $c`"
313		( set -x ; $c ) > ${NANO_OBJ}/_.cust.$c 2>&1
314	done
315)
316
317run_late_customize() (
318
319	pprint 2 "run late customize scripts"
320	for c in $NANO_LATE_CUSTOMIZE
321	do
322		pprint 2 "late customize \"$c\""
323		pprint 3 "log: ${NANO_OBJ}/_.late_cust.$c"
324		pprint 4 "`type $c`"
325		( set -x ; $c ) > ${NANO_OBJ}/_.late_cust.$c 2>&1
326	done
327)
328
329setup_nanobsd ( ) (
330	pprint 2 "configure nanobsd setup"
331	pprint 3 "log: ${NANO_OBJ}/_.dl"
332
333	(
334	cd ${NANO_WORLDDIR}
335
336	# Move /usr/local/etc to /etc/local so that the /cfg stuff
337	# can stomp on it.  Otherwise packages like ipsec-tools which
338	# have hardcoded paths under ${prefix}/etc are not tweakable.
339	if [ -d usr/local/etc ] ; then
340		(
341		mkdir -p etc/local
342		cd usr/local/etc
343		find . -print | cpio -dumpl ../../../etc/local
344		cd ..
345		rm -rf etc
346		ln -s ../../etc/local etc
347		)
348	fi
349
350	for d in var etc
351	do
352		# link /$d under /conf
353		# we use hard links so we have them both places.
354		# the files in /$d will be hidden by the mount.
355		# XXX: configure /$d ramdisk size
356		mkdir -p conf/base/$d conf/default/$d
357		find $d -print | cpio -dumpl conf/base/
358	done
359
360	echo "$NANO_RAM_ETCSIZE" > conf/base/etc/md_size
361	echo "$NANO_RAM_TMPVARSIZE" > conf/base/var/md_size
362
363	# pick up config files from the special partition
364	echo "mount -o ro /dev/${NANO_DRIVE}s3" > conf/default/etc/remount
365
366	# Put /tmp on the /var ramdisk (could be symlink already)
367	rmdir tmp || true
368	rm tmp || true
369	ln -s var/tmp tmp
370
371	) > ${NANO_OBJ}/_.dl 2>&1
372)
373
374setup_nanobsd_etc ( ) (
375	pprint 2 "configure nanobsd /etc"
376
377	(
378	cd ${NANO_WORLDDIR}
379
380	# create diskless marker file
381	touch etc/diskless
382
383	# Make root filesystem R/O by default
384	echo "root_rw_mount=NO" >> etc/defaults/rc.conf
385
386	# save config file for scripts
387	echo "NANO_DRIVE=${NANO_DRIVE}" > etc/nanobsd.conf
388
389	echo "/dev/${NANO_DRIVE}s1a / ufs ro 1 1" > etc/fstab
390	echo "/dev/${NANO_DRIVE}s3 /cfg ufs rw,noauto 2 2" >> etc/fstab
391	mkdir -p cfg
392	)
393)
394
395prune_usr() (
396
397	# Remove all empty directories in /usr 
398	find ${NANO_WORLDDIR}/usr -type d -depth -print |
399		while read d
400		do
401			rmdir $d > /dev/null 2>&1 || true 
402		done
403)
404
405newfs_part ( ) (
406	local dev mnt lbl
407	dev=$1
408	mnt=$2
409	lbl=$3
410	echo newfs ${NANO_NEWFS} ${NANO_LABEL:+-L${NANO_LABEL}${lbl}} ${dev}
411	newfs ${NANO_NEWFS} ${NANO_LABEL:+-L${NANO_LABEL}${lbl}} ${dev}
412	mount -o async ${dev} ${mnt}
413)
414
415populate_slice ( ) (
416	local dev dir mnt lbl
417	dev=$1
418	dir=$2
419	mnt=$3
420	lbl=$4
421	test -z $2 && dir=${NANO_WORLDDIR}/var/empty
422	test -d $dir || dir=${NANO_WORLDDIR}/var/empty
423	echo "Creating ${dev} with ${dir} (mounting on ${mnt})"
424	newfs_part $dev $mnt $lbl
425	cd ${dir}
426	find . -print | grep -Ev '/(CVS|\.svn)' | cpio -dumpv ${mnt}
427	df -i ${mnt}
428	umount ${mnt}
429)
430
431populate_cfg_slice ( ) (
432	populate_slice "$1" "$2" "$3" "$4"
433)
434
435populate_data_slice ( ) (
436	populate_slice "$1" "$2" "$3" "$4"
437)
438
439create_i386_diskimage ( ) (
440	pprint 2 "build diskimage"
441	pprint 3 "log: ${NANO_OBJ}/_.di"
442
443	(
444	echo $NANO_MEDIASIZE $NANO_IMAGES \
445		$NANO_SECTS $NANO_HEADS \
446		$NANO_CODESIZE $NANO_CONFSIZE $NANO_DATASIZE |
447	awk '
448	{
449		printf "# %s\n", $0
450
451		# size of cylinder in sectors
452		cs = $3 * $4
453
454		# number of full cylinders on media
455		cyl = int ($1 / cs)
456
457		# output fdisk geometry spec, truncate cyls to 1023
458		if (cyl <= 1023)
459			print "g c" cyl " h" $4 " s" $3
460		else
461			print "g c" 1023 " h" $4 " s" $3
462
463		if ($7 > 0) { 
464			# size of data partition in full cylinders
465			dsl = int (($7 + cs - 1) / cs)
466		} else {
467			dsl = 0;
468		}
469
470		# size of config partition in full cylinders
471		csl = int (($6 + cs - 1) / cs)
472
473		if ($5 == 0) {
474			# size of image partition(s) in full cylinders
475			isl = int ((cyl - dsl - csl) / $2)
476		} else {
477			isl = int (($5 + cs - 1) / cs)
478		}
479
480		# First image partition start at second track
481		print "p 1 165 " $3, isl * cs - $3
482		c = isl * cs;
483
484		# Second image partition (if any) also starts offset one 
485		# track to keep them identical.
486		if ($2 > 1) {
487			print "p 2 165 " $3 + c, isl * cs - $3
488			c += isl * cs;
489		}
490
491		# Config partition starts at cylinder boundary.
492		print "p 3 165 " c, csl * cs
493		c += csl * cs
494
495		# Data partition (if any) starts at cylinder boundary.
496		if ($7 > 0) {
497			print "p 4 165 " c, dsl * cs
498		} else if ($7 < 0 && $1 > c) {
499			print "p 4 165 " c, $1 - c
500		} else if ($1 < c) {
501			print "Disk space overcommitted by", \
502			    c - $1, "sectors" > "/dev/stderr"
503			exit 2
504		}
505
506		# Force slice 1 to be marked active. This is necessary
507		# for booting the image from a USB device to work.
508		print "a 1"
509	}
510	' > ${NANO_OBJ}/_.fdisk
511
512	IMG=${NANO_DISKIMGDIR}/${NANO_IMGNAME}
513	MNT=${NANO_OBJ}/_.mnt
514	mkdir -p ${MNT}
515
516	if [ "${NANO_MD_BACKING}" = "swap" ] ; then
517		MD=`mdconfig -a -t swap -s ${NANO_MEDIASIZE} -x ${NANO_SECTS} \
518			-y ${NANO_HEADS}`
519	else
520		echo "Creating md backing file..."
521		rm -f ${IMG}
522		dd if=/dev/zero of=${IMG} seek=${NANO_MEDIASIZE} count=0
523		MD=`mdconfig -a -t vnode -f ${IMG} -x ${NANO_SECTS} \
524			-y ${NANO_HEADS}`
525	fi
526
527	trap "echo 'Running exit trap code' ; df -i ${MNT} ; umount ${MNT} || true ; mdconfig -d -u $MD" 1 2 15 EXIT
528
529	fdisk -i -f ${NANO_OBJ}/_.fdisk ${MD}
530	fdisk ${MD}
531	# XXX: params
532	# XXX: pick up cached boot* files, they may not be in image anymore.
533	boot0cfg -B -b ${NANO_WORLDDIR}/${NANO_BOOTLOADER} ${NANO_BOOT0CFG} ${MD}
534	bsdlabel -w -B -b ${NANO_WORLDDIR}/boot/boot ${MD}s1
535	bsdlabel ${MD}s1
536
537	# Create first image
538	populate_slice /dev/${MD}s1a ${NANO_WORLDDIR} ${MNT} "s1a"
539	mount /dev/${MD}s1a ${MNT}
540	echo "Generating mtree..."
541	( cd ${MNT} && mtree -c ) > ${NANO_OBJ}/_.mtree
542	( cd ${MNT} && du -k ) > ${NANO_OBJ}/_.du
543	umount ${MNT}
544
545	if [ $NANO_IMAGES -gt 1 -a $NANO_INIT_IMG2 -gt 0 ] ; then
546		# Duplicate to second image (if present)
547		echo "Duplicating to second image..."
548		dd if=/dev/${MD}s1 of=/dev/${MD}s2 bs=64k
549		mount /dev/${MD}s2a ${MNT}
550		for f in ${MNT}/etc/fstab ${MNT}/conf/base/etc/fstab
551		do
552			sed -i "" "s=${NANO_DRIVE}s1=${NANO_DRIVE}s2=g" $f
553		done
554		umount ${MNT}
555		# Override the label from the first partition so we
556		# don't confuse glabel with duplicates.
557		if [ ! -z ${NANO_LABEL} ]; then
558			tunefs -L ${NANO_LABEL}"s2a" /dev/${MD}s2a
559		fi
560	fi
561	
562	# Create Config slice
563	populate_cfg_slice /dev/${MD}s3 "${NANO_CFGDIR}" ${MNT} "s3"
564
565	# Create Data slice, if any.
566	if [ $NANO_DATASIZE -ne 0 ] ; then
567		populate_data_slice /dev/${MD}s4 "${NANO_DATADIR}" ${MNT} "s4"
568	fi
569
570	if [ "${NANO_MD_BACKING}" = "swap" ] ; then
571		echo "Writing out ${NANO_IMGNAME}..."
572		dd if=/dev/${MD} of=${IMG} bs=64k
573	fi
574
575	if ${do_copyout_partition} ; then
576		echo "Writing out _.disk.image..."
577		dd if=/dev/${MD}s1 of=${NANO_DISKIMGDIR}/_.disk.image bs=64k
578	fi
579	mdconfig -d -u $MD
580
581	trap - 1 2 15 EXIT
582
583	) > ${NANO_OBJ}/_.di 2>&1
584)
585
586# i386 and amd64 are identical for disk images
587create_amd64_diskimage ( ) (
588	create_i386_diskimage
589)
590
591last_orders () (
592	# Redefine this function with any last orders you may have
593	# after the build completed, for instance to copy the finished
594	# image to a more convenient place:
595	# cp ${NANO_DISKIMGDIR}/_.disk.image /home/ftp/pub/nanobsd.disk
596)
597
598#######################################################################
599#
600# Optional convenience functions.
601#
602#######################################################################
603
604#######################################################################
605# Common Flash device geometries
606#
607
608FlashDevice () {
609	if [ -d ${NANO_TOOLS} ] ; then
610		. ${NANO_TOOLS}/FlashDevice.sub
611	else
612		. ${NANO_SRC}/${NANO_TOOLS}/FlashDevice.sub
613	fi
614	sub_FlashDevice $1 $2
615}
616
617#######################################################################
618# USB device geometries
619#
620# Usage:
621#	UsbDevice Generic 1000	# a generic flash key sold as having 1GB
622#
623# This function will set NANO_MEDIASIZE, NANO_HEADS and NANO_SECTS for you.
624#
625# Note that the capacity of a flash key is usually advertised in MB or
626# GB, *not* MiB/GiB. As such, the precise number of cylinders available
627# for C/H/S geometry may vary depending on the actual flash geometry.
628#
629# The following generic device layouts are understood:
630#  generic           An alias for generic-hdd.
631#  generic-hdd       255H 63S/T xxxxC with no MBR restrictions.
632#  generic-fdd       64H 32S/T xxxxC with no MBR restrictions.
633#
634# The generic-hdd device is preferred for flash devices larger than 1GB.
635#
636
637UsbDevice () {
638	a1=`echo $1 | tr '[:upper:]' '[:lower:]'`
639	case $a1 in
640	generic-fdd)
641		NANO_HEADS=64
642		NANO_SECTS=32
643		NANO_MEDIASIZE=$(( $2 * 1000 * 1000 / 512 ))
644		;;
645	generic|generic-hdd)
646		NANO_HEADS=255
647		NANO_SECTS=63
648		NANO_MEDIASIZE=$(( $2 * 1000 * 1000 / 512 ))
649		;;
650	*)
651		echo "Unknown USB flash device"
652		exit 2
653		;;
654	esac
655}
656
657#######################################################################
658# Setup serial console
659
660cust_comconsole () (
661	# Enable getty on console
662	sed -i "" -e /tty[du]0/s/off/on/ ${NANO_WORLDDIR}/etc/ttys
663
664	# Disable getty on syscons devices
665	sed -i "" -e '/^ttyv[0-8]/s/	on/	off/' ${NANO_WORLDDIR}/etc/ttys
666
667	# Tell loader to use serial console early.
668	echo "${NANO_BOOT2CFG}" > ${NANO_WORLDDIR}/boot.config
669)
670
671#######################################################################
672# Allow root login via ssh
673
674cust_allow_ssh_root () (
675	sed -i "" -e '/PermitRootLogin/s/.*/PermitRootLogin yes/' \
676	    ${NANO_WORLDDIR}/etc/ssh/sshd_config
677)
678
679#######################################################################
680# Install the stuff under ./Files
681
682cust_install_files () (
683	cd ${NANO_TOOLS}/Files
684	find . -print | grep -Ev '/(CVS|\.svn)' | cpio -Ldumpv ${NANO_WORLDDIR}
685)
686
687#######################################################################
688# Install packages from ${NANO_PACKAGE_DIR}
689
690cust_pkg () (
691
692	# If the package directory doesn't exist, we're done.
693	if [ ! -d ${NANO_PACKAGE_DIR} ]; then
694		echo "DONE 0 packages"
695		return 0
696	fi
697
698	# Copy packages into chroot
699	mkdir -p ${NANO_WORLDDIR}/Pkg
700	(
701		cd ${NANO_PACKAGE_DIR}
702		find ${NANO_PACKAGE_LIST} -print |
703		    cpio -Ldumpv ${NANO_WORLDDIR}/Pkg
704	)
705
706	# Count & report how many we have to install
707	todo=`ls ${NANO_WORLDDIR}/Pkg | wc -l`
708	echo "=== TODO: $todo"
709	ls ${NANO_WORLDDIR}/Pkg
710	echo "==="
711	while true
712	do
713		# Record how many we have now
714		have=`ls ${NANO_WORLDDIR}/var/db/pkg | wc -l`
715
716		# Attempt to install more packages
717		# ...but no more than 200 at a time due to pkg_add's internal
718		# limitations.
719		chroot ${NANO_WORLDDIR} sh -c \
720			'ls Pkg/*tbz | xargs -n 200 pkg_add -F' || true
721
722		# See what that got us
723		now=`ls ${NANO_WORLDDIR}/var/db/pkg | wc -l`
724		echo "=== NOW $now"
725		ls ${NANO_WORLDDIR}/var/db/pkg
726		echo "==="
727
728
729		if [ $now -eq $todo ] ; then
730			echo "DONE $now packages"
731			break
732		elif [ $now -eq $have ] ; then
733			echo "FAILED: Nothing happened on this pass"
734			exit 2
735		fi
736	done
737	rm -rf ${NANO_WORLDDIR}/Pkg
738)
739
740#######################################################################
741# Convenience function:
742# 	Register all args as customize function.
743
744customize_cmd () {
745	NANO_CUSTOMIZE="$NANO_CUSTOMIZE $*"
746}
747
748#######################################################################
749# Convenience function:
750# 	Register all args as late customize function to run just before
751#	image creation.
752
753late_customize_cmd () {
754	NANO_LATE_CUSTOMIZE="$NANO_LATE_CUSTOMIZE $*"
755}
756
757#######################################################################
758#
759# All set up to go...
760#
761#######################################################################
762
763# Progress Print
764#	Print $2 at level $1.
765pprint() {
766    if [ "$1" -le $PPLEVEL ]; then
767	runtime=$(( `date +%s` - $NANO_STARTTIME ))
768	printf "%s %.${1}s %s\n" "`date -u -r $runtime +%H:%M:%S`" "#####" "$2" 1>&3
769    fi
770}
771
772usage () {
773	(
774	echo "Usage: $0 [-bfiknqvw] [-c config_file]"
775	echo "	-b	suppress builds (both kernel and world)"
776	echo "	-f	suppress code slice extraction"
777	echo "	-i	suppress disk image build"
778	echo "	-k	suppress buildkernel"
779	echo "	-n	add -DNO_CLEAN to buildworld, buildkernel, etc"
780	echo "	-q	make output more quiet"
781	echo "	-v	make output more verbose"
782	echo "	-w	suppress buildworld"
783	echo "	-c	specify config file"
784	) 1>&2
785	exit 2
786}
787
788#######################################################################
789# Parse arguments
790
791do_clean=true
792do_kernel=true
793do_world=true
794do_image=true
795do_copyout_partition=true
796
797set +e
798args=`getopt bc:fhiknqvw $*`
799if [ $? -ne 0 ] ; then
800	usage
801	exit 2
802fi
803set -e
804
805set -- $args
806for i
807do
808	case "$i" 
809	in
810	-b)
811		do_world=false
812		do_kernel=false
813		shift
814		;;
815	-k)
816		do_kernel=false
817		shift
818		;;
819	-c)
820		# Make config file path available to the config file
821		# itself so that it can access additional files relative
822		# to its own location.
823		NANO_CONFIG=$2
824		. "$2"
825		shift
826		shift
827		;;
828	-f)
829		do_copyout_partition=false
830		shift
831		;;
832	-h)
833		usage
834		;;
835	-i)
836		do_image=false
837		shift
838		;;
839	-n)
840		do_clean=false
841		shift
842		;;
843	-q)
844		PPLEVEL=$(($PPLEVEL - 1))
845		shift
846		;;
847	-v)
848		PPLEVEL=$(($PPLEVEL + 1))
849		shift
850		;;
851	-w)
852		do_world=false
853		shift
854		;;
855	--)
856		shift
857		break
858	esac
859done
860
861if [ $# -gt 0 ] ; then
862	echo "$0: Extraneous arguments supplied"
863	usage
864fi
865
866#######################################################################
867# Setup and Export Internal variables
868#
869test -n "${NANO_OBJ}" || NANO_OBJ=/usr/obj/nanobsd.${NANO_NAME}/
870test -n "${MAKEOBJDIRPREFIX}" || MAKEOBJDIRPREFIX=${NANO_OBJ}
871test -n "${NANO_DISKIMGDIR}" || NANO_DISKIMGDIR=${NANO_OBJ}
872
873NANO_WORLDDIR=${NANO_OBJ}/_.w
874NANO_MAKE_CONF_BUILD=${MAKEOBJDIRPREFIX}/make.conf.build
875NANO_MAKE_CONF_INSTALL=${NANO_OBJ}/make.conf.install
876
877if [ -d ${NANO_TOOLS} ] ; then
878	true
879elif [ -d ${NANO_SRC}/${NANO_TOOLS} ] ; then
880	NANO_TOOLS=${NANO_SRC}/${NANO_TOOLS}
881else
882	echo "NANO_TOOLS directory does not exist" 1>&2
883	exit 1
884fi
885
886if $do_clean ; then
887	true
888else
889	NANO_PMAKE="${NANO_PMAKE} -DNO_CLEAN"
890fi
891
892# Override user's NANO_DRIVE if they specified a NANO_LABEL
893if [ ! -z "${NANO_LABEL}" ]; then
894	NANO_DRIVE=ufs/${NANO_LABEL}
895fi
896
897export MAKEOBJDIRPREFIX
898
899export NANO_ARCH
900export NANO_CODESIZE
901export NANO_CONFSIZE
902export NANO_CUSTOMIZE
903export NANO_DATASIZE
904export NANO_DRIVE
905export NANO_HEADS
906export NANO_IMAGES
907export NANO_IMGNAME
908export NANO_MAKE_CONF_BUILD
909export NANO_MAKE_CONF_INSTALL
910export NANO_MEDIASIZE
911export NANO_NAME
912export NANO_NEWFS
913export NANO_OBJ
914export NANO_PMAKE
915export NANO_SECTS
916export NANO_SRC
917export NANO_TOOLS
918export NANO_WORLDDIR
919export NANO_BOOT0CFG
920export NANO_BOOTLOADER
921export NANO_LABEL
922
923#######################################################################
924# And then it is as simple as that...
925
926# File descriptor 3 is used for logging output, see pprint
927exec 3>&1
928
929NANO_STARTTIME=`date +%s`
930pprint 1 "NanoBSD image ${NANO_NAME} build starting"
931
932if $do_world ; then
933	if $do_clean ; then
934		clean_build
935	else
936		pprint 2 "Using existing build tree (as instructed)"
937	fi
938	make_conf_build
939	build_world
940else
941	pprint 2 "Skipping buildworld (as instructed)"
942fi
943
944if $do_kernel ; then
945	if ! $do_world ; then
946		make_conf_build
947	fi
948	build_kernel
949else
950	pprint 2 "Skipping buildkernel (as instructed)"
951fi
952
953clean_world
954make_conf_install
955install_world
956install_etc
957setup_nanobsd_etc
958install_kernel
959
960run_customize
961setup_nanobsd
962prune_usr
963run_late_customize
964if $do_image ; then
965	create_${NANO_ARCH}_diskimage
966else
967	pprint 2 "Skipping image build (as instructed)"
968fi
969last_orders
970
971pprint 1 "NanoBSD image ${NANO_NAME} completed"
972