temp version that at least fixes a serious regression in previous revision
[bootcd.git] / build.sh
1 #!/bin/bash
2 #
3 # Builds custom BootCD ISO and USB images in the current
4 # directory. 
5 #
6 # Aaron Klingaman <alk@absarokasoft.com>
7 # Mark Huang <mlhuang@cs.princeton.edu>
8 # Copyright (C) 2004-2007 The Trustees of Princeton University
9 #
10
11 COMMAND=$(basename $0)
12 DIRNAME=$(dirname $0)
13 PATH=/sbin:/bin:/usr/sbin:/usr/bin
14
15 DEBUG_SYSTEMD=""
16 # uncomment this on to get systemd's full log on console (slows things down)
17 #DEBUG_SYSTEMD=true
18
19 # defaults
20 DEFAULT_TYPES="usb iso"
21 # Leave 4 MB of free space
22 GRAPHIC_CONSOLE="graphic"
23 SERIAL_CONSOLE="ttyS0:115200:n:8"
24 CONSOLE_INFO=$GRAPHIC_CONSOLE
25 MKISOFS_OPTS="-R -J -r -f -b isolinux.bin -c boot.cat -no-emul-boot -boot-load-size 4 -boot-info-table"
26 FREE_SPACE=4096
27
28 # command-line settable args
29 NODE_CONFIGURATION_FILE=
30 CUSTOM_DIR=
31 OUTPUT_BASE=
32 DRY_RUN=""
33 OUTPUT_NAME=""
34 TYPES=""
35 KERNEL_ARGS=""
36
37 # various globals
38 BUILDTMP=""
39 FULL_VERSION_STRING=""
40 ISOREF=""
41 ISOFS=""
42 OVERLAY=""
43 IS_SERIAL=""
44 console_dev=""
45 console_baud=""
46 console_spec=""
47 console_serial_line=""
48
49
50 #################### compute all supported types
51 # removing support for serial in the type
52 # this is because kargs.txt goes in the overlay, that is computed only once
53 # so we cannot handle serial and graphic modes within the same invokation of this script
54
55 ALL_TYPES=""
56 for x in iso usb usb_partition; do for c in "" "_cramfs" ; do
57   t="${x}${c}"
58   case $t in
59       usb_partition_cramfs)
60           # unsupported
61           ;;
62       *)
63           ALL_TYPES="$ALL_TYPES $t" ;;
64   esac
65 done; done
66
67 #################### cleanup utilities
68 declare -a _CLEANUPS=()
69 function do_cleanup() {
70     cd / ; for i in "${_CLEANUPS[@]}"; do $i ; done
71 }
72 function push_cleanup() {
73     _CLEANUPS=( "${_CLEANUPS[@]}" "$*" )
74 }
75 function pop_cleanup() {
76     unset _CLEANUPS[$((${#_CLEANUPS[@]} - 1))]
77 }
78
79 #################### initialization
80 function init_and_check () {
81
82     # Change to our source directory
83     local srcdir=$(cd $DIRNAME && pwd -P)
84     pushd $srcdir
85
86     # Root of the isofs
87     ISOREF=$PWD/${VARIANT}
88
89     # The reference image is expected to have been built by prep.sh (see .spec)
90     # we disable the initial logic that called prep.sh if that was not the case
91     # this is because prep.sh needs to know pldistro 
92     if [ ! -f $ISOREF/isofs/bootcd.img -o ! -f $ISOREF/version.txt ] ; then
93         echo "Could not find isofs and version.txt in $ISOREF"
94         if [ "$VARIANT" == "build" ] ; then
95             echo "You have to run prep.sh prior to calling $COMMAND"
96         else
97             echo "You need to create your variant image, see kvariant.sh"
98         fi
99         echo "Exiting .."
100         exit 1
101     fi
102
103     # build/version.txt written by prep.sh
104     BOOTCD_VERSION=$(cat ${VARIANT}/version.txt)
105
106     if [ -f /etc/planetlab/plc_config ] ; then
107         # Source PLC configuration
108         . /etc/planetlab/plc_config
109     fi
110
111     # use /var/tmp that should be large enough on both chroot- or vserver-based myplc
112     BUILDTMP=/var/tmp
113
114     FULL_VERSION_STRING="${PLC_NAME} BootCD ${BOOTCD_VERSION}"
115
116 }
117
118 # NOTE
119 # the custom-dir feature is designed to let a myplc try/ship a patched bootcd
120 # without the need for a full devel environment
121 # for example, you would create /root/custom-bootcd/etc/rc.d/init.d/pl_hwinit
122 # and run this script with -C /root/custom-bootcd
123 # this creates a third .img image of the custom dir, that 'hides' the files from 
124 # bootcd.img in the resulting unionfs
125 # it seems that this feature has not been used nor tested in a long time, use with care
126
127 usage() {
128     echo "Usage: $COMMAND [OPTION]..."
129     echo "    -f plnode.txt    Node to customize CD for (default: none)"
130     echo "    -t 'types'       Build the specified images (default: $DEFAULT_TYPES)"
131     echo "                     NOTE: mentioning 'serial' as part of the type is not supported anymore"
132     echo "    -a               Build all known types as listed below"
133     echo "    -s console-info  Enable a serial line as console and also bring up getty on that line"
134     echo "                     console-info: tty:baud-rate:parity:bits"
135     echo "                     or 'default' shortcut for $SERIAL_CONSOLE"
136     echo "    -S               equivalent to -s default"
137     echo "    -O output-base   The prefix of the generated files (default: PLC_NAME-BootCD-VERSION)"
138     echo "                     useful when multiple types are provided"
139     echo "                     can be a full path"
140     echo "    -o output-name   The full name of the generated file"
141     echo "    -C custom-dir    Custom directory"
142     echo "    -V variant       Use a variant - see kvariant.sh"
143     echo "    -n               Dry run - mostly for debug/test purposes"
144     echo "    -k               Add additional parameters to the kargs.txt file"
145     echo "    -h               This message"
146     echo "All known types: $ALL_TYPES"
147     exit 1
148 }
149
150 #################### 
151 function parse_command_line () {
152
153     # init
154     TYPES=""
155     # Get options
156     while getopts "f:t:as:SO:o:C:V:k:nh" opt ; do
157         case $opt in
158             f) NODE_CONFIGURATION_FILE=$OPTARG ;;
159             t) TYPES="$TYPES $OPTARG" ;;
160             a) TYPES="$ALL_TYPES" ;;
161             s) CONSOLE_INFO="$OPTARG" ;;
162             S) CONSOLE_INFO=$SERIAL_CONSOLE ;;
163             O) OUTPUT_BASE="$OPTARG" ;;
164             o) OUTPUT_NAME="$OPTARG" ;;
165             C) CUSTOM_DIR="$OPTARG" ;;
166             V) VARIANT="$OPTARG" ;;
167             k) KERNEL_ARGS="$KERNEL_ARGS $OPTARG" ;;
168             n) DRY_RUN=true ;;
169             h|*) usage ;;
170         esac
171     done
172
173     # use defaults if not set
174     [ -z "$TYPES" ] && TYPES="$DEFAULT_TYPES"
175     [ -z "$VARIANT" ] && VARIANT="build"
176     [ "$CONSOLE_INFO" == "default" ] && CONSOLE_INFO=$SERIAL_CONSOLE
177
178     if [ -n "$NODE_CONFIGURATION_FILE" ] ; then
179     # check existence of NODE_CONFIGURATION_FILE and normalize as we will change directory
180         if [ ! -f "$NODE_CONFIGURATION_FILE" ] ; then
181             echo "Node configuration file $NODE_CONFIGURATION_FILE not found - exiting"
182             exit 1
183         fi
184         cf_dir="$(dirname $NODE_CONFIGURATION_FILE)"
185         cf_dir="$(cd $cf_dir; pwd -P)"
186         cf_file="$(basename $NODE_CONFIGURATION_FILE)"
187         NODE_CONFIGURATION_FILE="$cf_dir"/"$cf_file"
188     fi
189
190     # check TYPES 
191     local matcher="XXX$(echo $ALL_TYPES | sed -e 's,\W,XXX,g')XXX"
192     for t in $TYPES; do
193         echo Checking type $t
194         echo $matcher | grep XXX${t}XXX &> /dev/null
195         if [ "$?" != 0 ] ; then
196             echo Unknown type $t
197             usage
198         fi
199     done
200
201 }
202
203 ####################
204 function init_serial () {
205     local console=$1; shift
206     if [ "$console" == "$GRAPHIC_CONSOLE" ] ; then
207         IS_SERIAL=
208         console_spec=""
209         echo "Standard, graphic, non-serial mode"
210     else
211         IS_SERIAL=true
212         console_dev=$(echo "$console" | awk -F: ' {print $1}')
213         console_baud=$(echo "$console" | awk -F: ' {print $2}')
214         [ -z "$console_baud" ] && console_baud="115200"
215         local console_parity=$(echo "$console" | awk -F: ' {print $3}')
216         [ -z "$console_parity" ] && console_parity="n"
217         local console_bits=$(echo "$console" | awk -F: ' {print $4}')
218         [ -z "$console_bits" ] && console_bits="8"
219         console_spec="console=${console_dev},${console_baud}${console_parity}${console_bits}"
220         local tty_nb=$(echo $console_dev | sed -e 's,[a-zA-Z],,g')
221         console_serial_line="SERIAL ${tty_nb} ${console_baud}"
222         echo "Serial mode"
223         echo "console_serial_line=${console_serial_line}"
224         echo "console_spec=${console_spec}"
225     fi
226 }
227
228 #################### run once : build the overlay image
229 function build_overlay () {
230
231     BUILDTMP=$(mktemp -d ${BUILDTMP}/bootcd.XXXXXX)
232     push_cleanup rm -fr "${BUILDTMP}"
233
234     # initialize ISOFS
235     ISOFS="${BUILDTMP}/isofs"
236     mkdir -p "$ISOFS"
237     for i in "$ISOREF"/isofs/{bootcd.img,kernel}; do
238         ln -s "$i" "$ISOFS"
239     done
240     # use new location as of fedora 12
241     # used to be in /usr/lib/syslinux/isolinux.bin
242     # removed backward compat in jan. 2015
243     # as of syslinux 5.0 (fedora 21) ldlinux.c32 is required by isolinux.bin
244     # the debug version can come in handy at times, and is 40k as well
245     isolinuxdir="/usr/share/syslinux"
246     isolinuxfiles="isolinux.bin ldlinux.c32 isolinux-debug.bin"
247     for isolinuxfile in $isolinuxfiles; do
248         [ -f $isolinuxdir/$isolinuxfile ] && cp $isolinuxdir/$isolinuxfile "${BUILDTMP}/isofs"
249     done
250
251     # Root of the ISO and USB images
252     echo "* Populating root filesystem..."
253     OVERLAY="${BUILDTMP}/overlay"
254     install -d -m 755 $OVERLAY
255     push_cleanup rm -fr $OVERLAY
256
257     # Create version files
258     echo "* Creating version files"
259
260     # Boot Manager compares pl_version in both places to make sure that
261     # the right CD is mounted. We used to boot from an initrd and mount
262     # the CD on /usr. Now we just run everything out of the initrd.
263     for file in $OVERLAY/pl_version $OVERLAY/usr/isolinux/pl_version ; do
264         mkdir -p $(dirname $file)
265         echo "$FULL_VERSION_STRING" >$file
266     done
267
268     # Install boot server configuration files
269     echo "* Installing boot server configuration files"
270
271     # We always intended to bring up and support backup boot servers,
272     # but never got around to it. Just install the same parameters for
273     # both for now.
274     for dir in $OVERLAY/usr/boot $OVERLAY/usr/boot/backup ; do
275         install -D -m 644 $PLC_BOOT_CA_SSL_CRT $dir/cacert.pem
276         install -D -m 644 $PLC_ROOT_GPG_KEY_PUB $dir/pubring.gpg
277         echo "$PLC_BOOT_HOST" >$dir/boot_server
278         echo "$PLC_BOOT_SSL_PORT" >$dir/boot_server_port
279         echo "/boot/" >$dir/boot_server_path
280     done
281
282     # Install old-style boot server configuration files
283     # as opposed to what a former comment suggested, 
284     # this is still required, somewhere in the bootmanager apparently
285     install -D -m 644 $PLC_BOOT_CA_SSL_CRT $OVERLAY/usr/bootme/cacert/$PLC_BOOT_HOST/cacert.pem
286     echo "$FULL_VERSION_STRING" >$OVERLAY/usr/bootme/ID
287     echo "$PLC_BOOT_HOST" >$OVERLAY/usr/bootme/BOOTSERVER
288     echo "$PLC_BOOT_HOST" >$OVERLAY/usr/bootme/BOOTSERVER_IP
289     echo "$PLC_BOOT_SSL_PORT" >$OVERLAY/usr/bootme/BOOTPORT
290
291     # Generate /etc/issue
292     echo "* Generating /etc/issue"
293
294     if [ "$PLC_WWW_PORT" = "443" ] ; then
295         PLC_WWW_URL="https://$PLC_WWW_HOST/"
296     elif [ "$PLC_WWW_PORT" != "80" ] ; then
297         PLC_WWW_URL="http://$PLC_WWW_HOST:$PLC_WWW_PORT/"
298     else
299         PLC_WWW_URL="http://$PLC_WWW_HOST/"
300     fi
301
302     mkdir -p $OVERLAY/etc
303     cat >$OVERLAY/etc/issue <<EOF
304 $FULL_VERSION_STRING
305 $PLC_NAME Node: \n
306 Kernel \r on an \m
307 $PLC_WWW_URL
308
309 This machine is a node in the $PLC_NAME distributed network.  It has
310 not fully booted yet. If you have cancelled the boot process at the
311 request of $PLC_NAME Support, please follow the instructions provided
312 to you. Otherwise, please contact $PLC_MAIL_SUPPORT_ADDRESS.
313
314 Console login at this point is restricted to root. Provide the root
315 password of the default $PLC_NAME Central administrator account at the
316 time that this CD was created.
317
318 EOF
319     
320     # Set root password
321     echo "* Setting root password"
322
323     if [ -z "$ROOT_PASSWORD" ] ; then
324         # Generate an encrypted password with crypt() if not defined
325         # in a static configuration.
326         ROOT_PASSWORD=$(python <<EOF
327 import crypt, random, string
328 salt = [random.choice(string.letters + string.digits + "./") for i in range(0,8)]
329 print crypt.crypt('$PLC_ROOT_PASSWORD', '\$1\$' + "".join(salt) + '\$')
330 EOF
331 )
332     fi
333
334     # build/passwd copied out by prep.sh
335     sed -e "s@^root:[^:]*:\(.*\)@root:$ROOT_PASSWORD:\1@" ${VARIANT}/passwd >$OVERLAY/etc/passwd
336
337     # Install node configuration file (e.g., if node has no floppy disk or USB slot)
338     if [ -f "$NODE_CONFIGURATION_FILE" ] ; then
339         echo "* Installing node configuration file $NODE_CONFIGURATION_FILE -> /usr/boot/plnode.txt of the bootcd image"
340         install -D -m 644 $NODE_CONFIGURATION_FILE $OVERLAY/usr/boot/plnode.txt
341         NODE_ID=$(source $NODE_CONFIGURATION_FILE; echo $NODE_ID)
342         echo "* Building network configuration for $NODE_ID"
343         plnet -- --root $OVERLAY --files-only --program BootCD $NODE_ID
344     fi
345
346     [ -n "$IS_SERIAL" ] && KERNEL_ARGS="$KERNEL_ARGS ${console_spec}"
347
348     # tmp: should be restricted to f15 nodes and above
349     # making sure the network interfaces are still numbered eth0 and above
350     KERNEL_ARGS="$KERNEL_ARGS biosdevname=0"
351     # making sure selinux is turned off - somehow this is needed with lxc/f14
352     KERNEL_ARGS="$KERNEL_ARGS selinux=0"
353 # cannot use this mecahnism to set systemd default target because this applies to kexec boots as well
354 #    # set default target for systemd
355 #    KERNEL_ARGS="$KERNEL_ARGS systemd.unit=pl_boot.target"
356     # output more systemd-related messages on the console
357     KERNEL_ARGS="$KERNEL_ARGS systemd.log_target=console"
358     # this slows down system init but is very helpful when e.g. trying to run on a new distro
359     [ -n "$DEBUG_SYSTEMD" ] && KERNEL_ARGS="$KERNEL_ARGS systemd.log_level=debug systemd.journald.forward_to_console=1"
360     [ -n "$KERNEL_ARGS" ] && echo "$KERNEL_ARGS" > $OVERLAY/kargs.txt
361
362     # Pack overlay files into a compressed archive
363     echo "* Compressing overlay image"
364     (cd $OVERLAY && find . | cpio --quiet -c -o) | gzip -9 >$ISOFS/overlay.img
365
366     rm -rf $OVERLAY
367     pop_cleanup
368
369     if [ -n "$CUSTOM_DIR" ]; then
370         echo "* Compressing custom image"
371         (cd "$CUSTOM_DIR" && find . | cpio --quiet -c -o) | gzip -9 >$ISOFS/custom.img
372     fi
373
374     # Calculate ramdisk size (total uncompressed size of both archives)
375     ramdisk_size=$(gzip -l $ISOFS/bootcd.img $ISOFS/overlay.img ${CUSTOM_DIR:+$ISOFS/custom.img} | tail -1 | awk '{ print $2; }') # bytes
376     ramdisk_size=$((($ramdisk_size + 1023) / 1024)) # kilobytes
377
378     echo "$FULL_VERSION_STRING" >$ISOFS/pl_version
379
380     popd
381 }
382
383 #################### plain ISO
384 function build_iso() {
385     local iso="$1" ; shift
386     local custom="$1"
387
388     # Write isolinux configuration
389     cat >$ISOFS/isolinux.cfg <<EOF
390 ${console_serial_line}
391 DEFAULT kernel
392 APPEND ramdisk_size=$ramdisk_size initrd=bootcd.img,overlay.img${custom:+,custom.img} root=/dev/ram0 rw ${KERNEL_ARGS}
393 DISPLAY pl_version
394 PROMPT 0
395 TIMEOUT 40
396 EOF
397
398     # Create ISO image
399     echo "* Creating ISO image in $(pwd)"
400     mkisofs -o "$iso" $MKISOFS_OPTS $ISOFS
401 }
402
403 #################### USB with partitions
404 function build_usb_partition() {
405     echo -n "* Creating USB image with partitions..."
406     local usb="$1" ; shift
407     local custom="$1"
408
409     local size=$(($(du -Lsk $ISOFS | awk '{ print $1; }') + $FREE_SPACE))
410     size=$(( $size / 1024 ))
411
412     local heads=64
413     local sectors=32
414     local cylinders=$(( ($size*1024*2)/($heads*$sectors) ))
415     local offset=$(( $sectors*512 ))
416
417     if [ -f  /usr/lib/syslinux/mkdiskimage ] ; then
418         /usr/lib/syslinux/mkdiskimage -M -4 "$usb" $size $heads $sectors
419     else
420         mkdiskimage -M -4 "$usb" $size $heads $sectors
421     fi
422
423     cat >${BUILDTMP}/mtools.conf<<EOF
424 drive z:
425 file="${usb}"
426 cylinders=$cylinders
427 heads=$heads
428 sectors=$sectors
429 offset=$offset
430 mformat_only
431 mtools_skip_check=1
432 EOF
433     # environment variable for mtools
434     export MTOOLSRC="${BUILDTMP}/mtools.conf"
435
436     ### COPIED FROM build_usb() below!!!!
437     echo -n " populating USB image... "
438     mcopy -bsQ -i "$usb" "$ISOFS"/* z:/
439         
440     # Use syslinux instead of isolinux to make the image bootable
441     tmp="${BUILDTMP}/syslinux.cfg"
442     cat >$tmp <<EOF
443 ${console_serial_line}
444 DEFAULT kernel
445 APPEND ramdisk_size=$ramdisk_size initrd=bootcd.img,overlay.img${custom:+,custom.img} root=/dev/ram0 rw ${KERNEL_ARGS}
446 DISPLAY pl_version
447 PROMPT 0
448 TIMEOUT 40
449 EOF
450     mdel -i "$usb" z:/isolinux.cfg 2>/dev/null || :
451     mcopy -i "$usb" "$tmp" z:/syslinux.cfg
452     rm -f "$tmp"
453     rm -f "${MTOOLSRC}"
454     unset MTOOLSRC
455
456     echo "making USB image bootable."
457     syslinux -o $offset "$usb"
458
459 }
460
461 #################### plain USB
462 function build_usb() {
463     echo -n "* Creating USB image... "
464     local usb="$1" ; shift
465     local custom="$1"
466
467     rm -f "$usb"
468     mkfs.vfat -C "$usb" $(($(du -Lsk $ISOFS | awk '{ print $1; }') + $FREE_SPACE))
469
470     cat >${BUILDTMP}/mtools.conf<<EOF
471 mtools_skip_check=1
472 EOF
473     # environment variable for mtools
474     export MTOOLSRC="${BUILDTMP}/mtools.conf"
475
476     # Populate it
477     echo -n " populating USB image... "
478     mcopy -bsQ -i "$usb" "$ISOFS"/* ::/
479
480     # Use syslinux instead of isolinux to make the image bootable
481     tmp="${BUILDTMP}/syslinux.cfg"
482     cat >$tmp <<EOF
483 ${console_serial_line}
484 DEFAULT kernel
485 APPEND ramdisk_size=$ramdisk_size initrd=bootcd.img,overlay.img${custom:+,custom.img} root=/dev/ram0 rw ${KERNEL_ARGS}
486 DISPLAY pl_version
487 PROMPT 0
488 TIMEOUT 40
489 EOF
490     mdel -i "$usb" ::/isolinux.cfg 2>/dev/null || :
491     mcopy -i "$usb" "$tmp" ::/syslinux.cfg
492     rm -f "$tmp"
493     rm -f "${MTOOLSRC}"
494     unset MTOOLSRC
495
496     echo "making USB image bootable."
497     syslinux "$usb"
498 }
499
500 #################### utility to setup CRAMFS related support
501 function prepare_cramfs() {
502     [ -n "$CRAMFS_PREPARED" ] && return 0
503     local custom=$1; 
504
505     echo "* Setting up CRAMFS-based images"
506     local tmp="${BUILDTMP}/cramfs-tree"
507     mkdir -p "$tmp"
508     push_cleanup rm -rf $tmp
509     pushd $tmp
510     gzip -d -c $ISOFS/bootcd.img     | cpio -diu
511     gzip -d -c $ISOFS/overlay.img    | cpio -diu
512     [ -n "$custom" ] && \
513         gzip -d -c $ISOFS/custom.img | cpio -diu
514
515     # clean out unnecessary rpm lib
516     echo "* clearing var/lib/rpm/*"
517     rm -f var/lib/rpm/*
518
519     # bootcd requires this directory
520     mkdir -p mnt/confdevice
521
522     # relocate various directory to /tmp
523     rm -rf root
524     ln -fs /tmp/root root
525     ln -fs /sbin/init linuxrc 
526     ln -fs /tmp/resolv.conf etc/resolv.conf
527     ln -fs /tmp/etc/mtab etc/mtab
528
529     # have pl_rsysinit copy over appropriate etc & var directories into /tmp/etc/
530     # make /tmp/etc
531     echo "* renaming dirs in ./etc"
532     pushd etc
533     for dir in `find * -type d -prune | grep -v rc.d`; do
534         mv ${dir} ${dir}_o
535         ln -fs /tmp/etc/${dir} ${dir}
536     done
537     popd
538
539     echo "* renaming dirs in ./var"
540     # rename all top-level directories and put in a symlink to /tmp/var
541     pushd var
542     for dir in `find * -type d -prune`; do
543         mv ${dir} ${dir}_o
544         ln -fs /tmp/var/${dir} ${dir}
545     done
546     popd
547
548     # overwrite fstab to mount / as cramfs and /tmp as tmpfs
549     echo "* Overwriting etc/fstab to use cramfs and tmpfs"
550     rm -f ./etc/fstab
551     cat >./etc/fstab <<EOF
552 /dev/ram0     /              cramfs     ro              0 0
553 none          /dev/pts       devpts     gid=5,mode=620  0 0
554 none          /proc          proc       defaults        0 0
555 none          /sys           sysfs      defaults        0 0
556 EOF
557
558     pushd dev
559     rm -f console
560     mknod console c 5 1
561     #for i in 0 1 2 3 4 5 6 7 8; do rm -f ram${i} ; done
562     #for i in 0 1 2 3 4 5 6 7 8; do mknod ram${i} b 1 ${i} ; done
563     #ln -fs ram1 ram
564     #ln -fs ram0 ramdisk
565     popd
566
567     # update etc/inittab to start with pl_rsysinit
568     for file in etc/inittab etc/event.d/rcS etc/init/rcS.conf; do
569         [ -f $file ] && sed -i 's,pl_sysinit,pl_rsysinit,' $file
570     done
571
572     # modify inittab to have a serial console
573     # xxx this might well be broken with f12 and above xxx
574     if [ -n "$serial" ] ; then
575         echo "T0:23:respawn:/sbin/agetty -L $console_dev $console_baud vt100" >> etc/inittab
576         # and let root log in
577         echo "$console_dev" >> etc/securetty
578     fi
579
580     # calculate the size of /tmp based on the size of /etc & /var + 8MB slack
581     etcsize=$(du -s ./etc | awk '{ print $1 }')
582     varsize=$(du -s ./var | awk '{ print $1 }')
583     let msize=($varsize+$etcsize+8192)/1024
584
585     # make dhclient happy
586     for i in $(seq 0 9); do ln -fs /tmp/etc/dhclient-eth${i}.conf etc/dhclient-eth${i}.conf ; done
587     ln -fs /tmp/etc/resolv.conf etc/resolv.conf
588     ln -fs /tmp/etc/resolv.conf.predhclient etc/resolv.conf.predhclient
589
590     # generate pl_rsysinit
591     cat > etc/rc.d/init.d/pl_rsysinit <<EOF
592 #!/bin/sh
593 # generated by $COMMAND
594 echo -n "pl_rsysinit: preparing /etc and /var for pl_sysinit..."
595 mount -t tmpfs -orw,size=${msize}M,mode=1777 tmpfs /tmp
596 mkdir -p /tmp/root
597 mkdir -p /tmp/etc
598 touch /tmp/etc/resolv.conf
599 touch /tmp/etc/mtab
600 mkdir -p /tmp/var
601
602 # make mtab happy
603 echo "tmpfs /tmp tmpfs rw,size=${msize}M,mode=1777 1 1" > /tmp/etc/mtab
604
605 # copy over directory contents of all _o directories from /etc and /var
606 # /tmp/etc and /tmp/var
607 pushd /etc
608 for odir in \$(cd /etc && ls -d *_o); do dir=\$(echo \$odir | sed 's,\_o$,,'); (mkdir -p /tmp/etc/\$dir && cd \$odir && find . | cpio -p -d -u /tmp/etc/\$dir); done
609 popd
610 pushd /var
611 for odir in \$(cd /var && ls -d *_o); do dir=\$(echo \$odir | sed 's,\_o$,,'); (mkdir -p /tmp/var/\$dir && cd \$odir && find . | cpio -p -d -u /tmp/var/\$dir); done
612 popd
613
614 echo "done"
615
616 # hand over to pl_sysinit
617 echo "pl_rsysinit: handing over to pl_sysinit"
618 /etc/init.d/pl_sysinit
619 EOF
620     chmod +x etc/rc.d/init.d/pl_rsysinit
621
622     popd
623
624     # create the cramfs image
625     echo "* Creating cramfs image"
626     mkfs.cramfs $tmp/ ${BUILDTMP}/cramfs.img
627     cramfs_size=$(($(du -sk ${BUILDTMP}/cramfs.img | awk '{ print $1; }') + 1))
628     rm -rf $tmp
629     pop_cleanup
630 }
631
632 #################### Create ISO CRAMFS image
633 function build_iso_cramfs() {
634     local iso="$1" ; shift
635     local custom="$1"
636
637     prepare_cramfs "$custom"
638     echo "* Creating ISO CRAMFS-based image"
639
640     local tmp="${BUILDTMP}/cramfs-iso"
641     mkdir -p "$tmp"
642     push_cleanup rm -rf $tmp
643     (cd $ISOFS && find . | grep -v "\.img$" | cpio -p -d -u $tmp/)
644     cat >$tmp/isolinux.cfg <<EOF
645 ${console_serial_line}
646 DEFAULT kernel
647 APPEND ramdisk_size=$cramfs_size initrd=cramfs.img root=/dev/ram0 ro ${KERNEL_ARGS}
648 DISPLAY pl_version
649 PROMPT 0
650 TIMEOUT 40
651 EOF
652
653     cp ${BUILDTMP}/cramfs.img $tmp
654     mkisofs -o "$iso" \
655         $MKISOFS_OPTS \
656         $tmp
657
658     rm -fr "$tmp"
659     pop_cleanup
660 }
661
662 #################### Create USB CRAMFS based image
663 function build_usb_cramfs() {
664     local usb="$1" ; shift
665     local custom="$1"
666
667     prepare_cramfs "$custom"
668     echo "* Creating USB CRAMFS based image"
669
670     let vfat_size=${cramfs_size}+$FREE_SPACE
671
672     # Make VFAT filesystem for USB
673     mkfs.vfat -C "$usb" $vfat_size
674
675     # Populate it
676     echo "* Populating USB with overlay images and cramfs"
677     mcopy -bsQ -i "$usb" $ISOFS/kernel $ISOFS/pl_version ::/
678     mcopy -bsQ -i "$usb" ${BUILDTMP}/cramfs.img ::/
679
680     # Use syslinux instead of isolinux to make the image bootable
681     tmp="${BUILDTMP}/syslinux.cfg"
682     cat >$tmp <<EOF
683 ${console_serial_line}
684 DEFAULT kernel
685 APPEND ramdisk_size=$cramfs_size initrd=cramfs.img root=/dev/ram0 ro ${KERNEL_ARGS}
686 DISPLAY pl_version
687 PROMPT 0
688 TIMEOUT 40
689 EOF
690
691     mcopy -bsQ -i "$usb" "$tmp" ::/syslinux.cfg
692     rm -f "$tmp"
693
694     echo "* Making USB CRAMFS based image bootable"
695     syslinux "$usb"
696 }
697
698 #################### map on all types provided on the command-line and invoke one of the above functions
699 function build_types () {
700
701     [ -z "$OUTPUT_BASE" ] && OUTPUT_BASE="$PLC_NAME-BootCD-$BOOTCD_VERSION"
702
703     # alter output filename to reflect serial settings
704     if [ -n "$IS_SERIAL" ] ; then
705         if [ "$CONSOLE_INFO" == "$SERIAL_CONSOLE" ] ; then
706             serial="-serial"
707         else
708             serial="-serial-$(echo $CONSOLE_INFO | sed -e 's,:,,g')"
709         fi
710     else
711         serial=""
712     fi
713     
714     function type_to_name() {
715         echo $1 | sed '
716         s/usb$/.usb/;
717         s/usb_partition$/-partition.usb/;
718         s/iso$/.iso/;
719         s/usb_cramfs$/-cramfs.usb/;
720         s/iso_cramfs$/-cramfs.iso/;
721         '
722     }
723
724     for t in $TYPES; do
725         arg=$t
726
727         tname=`type_to_name $t`
728         # if -o is specified (as it has no default)
729         if [ -n "$OUTPUT_NAME" ] ; then
730             output=$OUTPUT_NAME
731         else
732             output="${OUTPUT_BASE}${serial}${tname}"
733         fi
734
735         echo "*** Dealing with type=$arg"
736         echo '*' build_$t "$output" "$CUSTOM_DIR"
737         [ -n "$DRY_RUN" ] || build_$t "$output" "$CUSTOM_DIR" 
738     done
739 }
740
741 #################### 
742 function main () {
743
744     parse_command_line "$@"
745
746     init_and_check
747
748     echo "* Building images for $FULL_VERSION_STRING"
749     # Do not tolerate errors
750     set -e
751     trap "do_cleanup" ERR INT EXIT
752
753     init_serial $CONSOLE_INFO
754     build_overlay
755     build_types
756
757     exit 0
758 }
759
760 ####################
761 main "$@"