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