fedora21 comes with syslinux v6 which requires ldlinux.c32 in addition to its new...
[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     mkdir "${BUILDTMP}/isofs"
234     for i in "$ISOREF"/isofs/{bootcd.img,kernel}; do
235         ln -s "$i" "${BUILDTMP}/isofs"
236     done
237     # use new location as of fedora 12
238     # used to be in /usr/lib/syslinux/isolinux.bin
239     # removed backward compat in jan. 2015
240     official=/usr/share/syslinux/isolinux.bin
241     [ -f $official ] && cp $official "${BUILDTMP}/isofs"
242     # as of syslinux 5.0 (fedora 21) this file is required as well
243     official=/usr/share/syslinux/ldlinux.c32
244     [ -f $official ] && cp $official "${BUILDTMP}/isofs"
245     ISOFS="${BUILDTMP}/isofs"
246
247     # Root of the ISO and USB images
248     echo "* Populating root filesystem..."
249     OVERLAY="${BUILDTMP}/overlay"
250     install -d -m 755 $OVERLAY
251     push_cleanup rm -fr $OVERLAY
252
253     # Create version files
254     echo "* Creating version files"
255
256     # Boot Manager compares pl_version in both places to make sure that
257     # the right CD is mounted. We used to boot from an initrd and mount
258     # the CD on /usr. Now we just run everything out of the initrd.
259     for file in $OVERLAY/pl_version $OVERLAY/usr/isolinux/pl_version ; do
260         mkdir -p $(dirname $file)
261         echo "$FULL_VERSION_STRING" >$file
262     done
263
264     # Install boot server configuration files
265     echo "* Installing boot server configuration files"
266
267     # We always intended to bring up and support backup boot servers,
268     # but never got around to it. Just install the same parameters for
269     # both for now.
270     for dir in $OVERLAY/usr/boot $OVERLAY/usr/boot/backup ; do
271         install -D -m 644 $PLC_BOOT_CA_SSL_CRT $dir/cacert.pem
272         install -D -m 644 $PLC_ROOT_GPG_KEY_PUB $dir/pubring.gpg
273         echo "$PLC_BOOT_HOST" >$dir/boot_server
274         echo "$PLC_BOOT_SSL_PORT" >$dir/boot_server_port
275         echo "/boot/" >$dir/boot_server_path
276     done
277
278     # Install old-style boot server configuration files
279     # as opposed to what a former comment suggested, 
280     # this is still required, somewhere in the bootmanager apparently
281     install -D -m 644 $PLC_BOOT_CA_SSL_CRT $OVERLAY/usr/bootme/cacert/$PLC_BOOT_HOST/cacert.pem
282     echo "$FULL_VERSION_STRING" >$OVERLAY/usr/bootme/ID
283     echo "$PLC_BOOT_HOST" >$OVERLAY/usr/bootme/BOOTSERVER
284     echo "$PLC_BOOT_HOST" >$OVERLAY/usr/bootme/BOOTSERVER_IP
285     echo "$PLC_BOOT_SSL_PORT" >$OVERLAY/usr/bootme/BOOTPORT
286
287     # Generate /etc/issue
288     echo "* Generating /etc/issue"
289
290     if [ "$PLC_WWW_PORT" = "443" ] ; then
291         PLC_WWW_URL="https://$PLC_WWW_HOST/"
292     elif [ "$PLC_WWW_PORT" != "80" ] ; then
293         PLC_WWW_URL="http://$PLC_WWW_HOST:$PLC_WWW_PORT/"
294     else
295         PLC_WWW_URL="http://$PLC_WWW_HOST/"
296     fi
297
298     mkdir -p $OVERLAY/etc
299     cat >$OVERLAY/etc/issue <<EOF
300 $FULL_VERSION_STRING
301 $PLC_NAME Node: \n
302 Kernel \r on an \m
303 $PLC_WWW_URL
304
305 This machine is a node in the $PLC_NAME distributed network.  It has
306 not fully booted yet. If you have cancelled the boot process at the
307 request of $PLC_NAME Support, please follow the instructions provided
308 to you. Otherwise, please contact $PLC_MAIL_SUPPORT_ADDRESS.
309
310 Console login at this point is restricted to root. Provide the root
311 password of the default $PLC_NAME Central administrator account at the
312 time that this CD was created.
313
314 EOF
315     
316     # Set root password
317     echo "* Setting root password"
318
319     if [ -z "$ROOT_PASSWORD" ] ; then
320         # Generate an encrypted password with crypt() if not defined
321         # in a static configuration.
322         ROOT_PASSWORD=$(python <<EOF
323 import crypt, random, string
324 salt = [random.choice(string.letters + string.digits + "./") for i in range(0,8)]
325 print crypt.crypt('$PLC_ROOT_PASSWORD', '\$1\$' + "".join(salt) + '\$')
326 EOF
327 )
328     fi
329
330     # build/passwd copied out by prep.sh
331     sed -e "s@^root:[^:]*:\(.*\)@root:$ROOT_PASSWORD:\1@" ${VARIANT}/passwd >$OVERLAY/etc/passwd
332
333     # Install node configuration file (e.g., if node has no floppy disk or USB slot)
334     if [ -f "$NODE_CONFIGURATION_FILE" ] ; then
335         echo "* Installing node configuration file $NODE_CONFIGURATION_FILE -> /usr/boot/plnode.txt of the bootcd image"
336         install -D -m 644 $NODE_CONFIGURATION_FILE $OVERLAY/usr/boot/plnode.txt
337         NODE_ID=$(source $NODE_CONFIGURATION_FILE; echo $NODE_ID)
338         echo "* Building network configuration for $NODE_ID"
339         plnet -- --root $OVERLAY --files-only --program BootCD $NODE_ID
340     fi
341
342     [ -n "$IS_SERIAL" ] && KERNEL_ARGS="$KERNEL_ARGS ${console_spec}"
343
344     # tmp: should be restricted to f15 nodes and above
345     # making sure the network interfaces are still numbered eth0 and above
346     KERNEL_ARGS="$KERNEL_ARGS biosdevname=0"
347     # making sure selinux is turned off - somehow this is needed with lxc/f14
348     KERNEL_ARGS="$KERNEL_ARGS selinux=0"
349 # cannot use this mecahnism to set systemd default target because this applies to kexec boots as well
350 #    # set default target for systemd
351 #    KERNEL_ARGS="$KERNEL_ARGS systemd.unit=pl_boot.target"
352     # output more systemd-related messages on the console
353     KERNEL_ARGS="$KERNEL_ARGS systemd.log_target=console"
354     # this slows down system init but is very helpful when e.g. trying to run on a new distro
355     [ -n "$DEBUG_SYSTEMD" ] && KERNEL_ARGS="$KERNEL_ARGS systemd.log_level=debug systemd.journald.forward_to_console=1"
356     [ -n "$KERNEL_ARGS" ] && echo "$KERNEL_ARGS" > $OVERLAY/kargs.txt
357
358     # Pack overlay files into a compressed archive
359     echo "* Compressing overlay image"
360     (cd $OVERLAY && find . | cpio --quiet -c -o) | gzip -9 >$ISOFS/overlay.img
361
362     rm -rf $OVERLAY
363     pop_cleanup
364
365     if [ -n "$CUSTOM_DIR" ]; then
366         echo "* Compressing custom image"
367         (cd "$CUSTOM_DIR" && find . | cpio --quiet -c -o) | gzip -9 >$ISOFS/custom.img
368     fi
369
370     # Calculate ramdisk size (total uncompressed size of both archives)
371     ramdisk_size=$(gzip -l $ISOFS/bootcd.img $ISOFS/overlay.img ${CUSTOM_DIR:+$ISOFS/custom.img} | tail -1 | awk '{ print $2; }') # bytes
372     ramdisk_size=$((($ramdisk_size + 1023) / 1024)) # kilobytes
373
374     echo "$FULL_VERSION_STRING" >$ISOFS/pl_version
375
376     popd
377 }
378
379 #################### plain ISO
380 function build_iso() {
381     local iso="$1" ; shift
382     local custom="$1"
383
384     # Write isolinux configuration
385     cat >$ISOFS/isolinux.cfg <<EOF
386 ${console_serial_line}
387 DEFAULT kernel
388 APPEND ramdisk_size=$ramdisk_size initrd=bootcd.img,overlay.img${custom:+,custom.img} root=/dev/ram0 rw ${KERNEL_ARGS}
389 DISPLAY pl_version
390 PROMPT 0
391 TIMEOUT 40
392 EOF
393
394     # Create ISO image
395     echo "* Creating ISO image in $(pwd)"
396     mkisofs -o "$iso" $MKISOFS_OPTS $ISOFS
397 }
398
399 #################### USB with partitions
400 function build_usb_partition() {
401     echo -n "* Creating USB image with partitions..."
402     local usb="$1" ; shift
403     local custom="$1"
404
405     local size=$(($(du -Lsk $ISOFS | awk '{ print $1; }') + $FREE_SPACE))
406     size=$(( $size / 1024 ))
407
408     local heads=64
409     local sectors=32
410     local cylinders=$(( ($size*1024*2)/($heads*$sectors) ))
411     local offset=$(( $sectors*512 ))
412
413     if [ -f  /usr/lib/syslinux/mkdiskimage ] ; then
414         /usr/lib/syslinux/mkdiskimage -M -4 "$usb" $size $heads $sectors
415     else
416         mkdiskimage -M -4 "$usb" $size $heads $sectors
417     fi
418
419     cat >${BUILDTMP}/mtools.conf<<EOF
420 drive z:
421 file="${usb}"
422 cylinders=$cylinders
423 heads=$heads
424 sectors=$sectors
425 offset=$offset
426 mformat_only
427 mtools_skip_check=1
428 EOF
429     # environment variable for mtools
430     export MTOOLSRC="${BUILDTMP}/mtools.conf"
431
432     ### COPIED FROM build_usb() below!!!!
433     echo -n " populating USB image... "
434     mcopy -bsQ -i "$usb" "$ISOFS"/* z:/
435         
436     # Use syslinux instead of isolinux to make the image bootable
437     tmp="${BUILDTMP}/syslinux.cfg"
438     cat >$tmp <<EOF
439 ${console_serial_line}
440 DEFAULT kernel
441 APPEND ramdisk_size=$ramdisk_size initrd=bootcd.img,overlay.img${custom:+,custom.img} root=/dev/ram0 rw ${KERNEL_ARGS}
442 DISPLAY pl_version
443 PROMPT 0
444 TIMEOUT 40
445 EOF
446     mdel -i "$usb" z:/isolinux.cfg 2>/dev/null || :
447     mcopy -i "$usb" "$tmp" z:/syslinux.cfg
448     rm -f "$tmp"
449     rm -f "${MTOOLSRC}"
450     unset MTOOLSRC
451
452     echo "making USB image bootable."
453     syslinux -o $offset "$usb"
454
455 }
456
457 #################### plain USB
458 function build_usb() {
459     echo -n "* Creating USB image... "
460     local usb="$1" ; shift
461     local custom="$1"
462
463     rm -f "$usb"
464     mkfs.vfat -C "$usb" $(($(du -Lsk $ISOFS | awk '{ print $1; }') + $FREE_SPACE))
465
466     cat >${BUILDTMP}/mtools.conf<<EOF
467 mtools_skip_check=1
468 EOF
469     # environment variable for mtools
470     export MTOOLSRC="${BUILDTMP}/mtools.conf"
471
472     # Populate it
473     echo -n " populating USB image... "
474     mcopy -bsQ -i "$usb" "$ISOFS"/* ::/
475
476     # Use syslinux instead of isolinux to make the image bootable
477     tmp="${BUILDTMP}/syslinux.cfg"
478     cat >$tmp <<EOF
479 ${console_serial_line}
480 DEFAULT kernel
481 APPEND ramdisk_size=$ramdisk_size initrd=bootcd.img,overlay.img${custom:+,custom.img} root=/dev/ram0 rw ${KERNEL_ARGS}
482 DISPLAY pl_version
483 PROMPT 0
484 TIMEOUT 40
485 EOF
486     mdel -i "$usb" ::/isolinux.cfg 2>/dev/null || :
487     mcopy -i "$usb" "$tmp" ::/syslinux.cfg
488     rm -f "$tmp"
489     rm -f "${MTOOLSRC}"
490     unset MTOOLSRC
491
492     echo "making USB image bootable."
493     syslinux "$usb"
494 }
495
496 #################### utility to setup CRAMFS related support
497 function prepare_cramfs() {
498     [ -n "$CRAMFS_PREPARED" ] && return 0
499     local custom=$1; 
500
501     echo "* Setting up CRAMFS-based images"
502     local tmp="${BUILDTMP}/cramfs-tree"
503     mkdir -p "$tmp"
504     push_cleanup rm -rf $tmp
505     pushd $tmp
506     gzip -d -c $ISOFS/bootcd.img     | cpio -diu
507     gzip -d -c $ISOFS/overlay.img    | cpio -diu
508     [ -n "$custom" ] && \
509         gzip -d -c $ISOFS/custom.img | cpio -diu
510
511     # clean out unnecessary rpm lib
512     echo "* clearing var/lib/rpm/*"
513     rm -f var/lib/rpm/*
514
515     # bootcd requires this directory
516     mkdir -p mnt/confdevice
517
518     # relocate various directory to /tmp
519     rm -rf root
520     ln -fs /tmp/root root
521     ln -fs /sbin/init linuxrc 
522     ln -fs /tmp/resolv.conf etc/resolv.conf
523     ln -fs /tmp/etc/mtab etc/mtab
524
525     # have pl_rsysinit copy over appropriate etc & var directories into /tmp/etc/
526     # make /tmp/etc
527     echo "* renaming dirs in ./etc"
528     pushd etc
529     for dir in `find * -type d -prune | grep -v rc.d`; do
530         mv ${dir} ${dir}_o
531         ln -fs /tmp/etc/${dir} ${dir}
532     done
533     popd
534
535     echo "* renaming dirs in ./var"
536     # rename all top-level directories and put in a symlink to /tmp/var
537     pushd var
538     for dir in `find * -type d -prune`; do
539         mv ${dir} ${dir}_o
540         ln -fs /tmp/var/${dir} ${dir}
541     done
542     popd
543
544     # overwrite fstab to mount / as cramfs and /tmp as tmpfs
545     echo "* Overwriting etc/fstab to use cramfs and tmpfs"
546     rm -f ./etc/fstab
547     cat >./etc/fstab <<EOF
548 /dev/ram0     /              cramfs     ro              0 0
549 none          /dev/pts       devpts     gid=5,mode=620  0 0
550 none          /proc          proc       defaults        0 0
551 none          /sys           sysfs      defaults        0 0
552 EOF
553
554     pushd dev
555     rm -f console
556     mknod console c 5 1
557     #for i in 0 1 2 3 4 5 6 7 8; do rm -f ram${i} ; done
558     #for i in 0 1 2 3 4 5 6 7 8; do mknod ram${i} b 1 ${i} ; done
559     #ln -fs ram1 ram
560     #ln -fs ram0 ramdisk
561     popd
562
563     # update etc/inittab to start with pl_rsysinit
564     for file in etc/inittab etc/event.d/rcS etc/init/rcS.conf; do
565         [ -f $file ] && sed -i 's,pl_sysinit,pl_rsysinit,' $file
566     done
567
568     # modify inittab to have a serial console
569     # xxx this might well be broken with f12 and above xxx
570     if [ -n "$serial" ] ; then
571         echo "T0:23:respawn:/sbin/agetty -L $console_dev $console_baud vt100" >> etc/inittab
572         # and let root log in
573         echo "$console_dev" >> etc/securetty
574     fi
575
576     # calculate the size of /tmp based on the size of /etc & /var + 8MB slack
577     etcsize=$(du -s ./etc | awk '{ print $1 }')
578     varsize=$(du -s ./var | awk '{ print $1 }')
579     let msize=($varsize+$etcsize+8192)/1024
580
581     # make dhclient happy
582     for i in $(seq 0 9); do ln -fs /tmp/etc/dhclient-eth${i}.conf etc/dhclient-eth${i}.conf ; done
583     ln -fs /tmp/etc/resolv.conf etc/resolv.conf
584     ln -fs /tmp/etc/resolv.conf.predhclient etc/resolv.conf.predhclient
585
586     # generate pl_rsysinit
587     cat > etc/rc.d/init.d/pl_rsysinit <<EOF
588 #!/bin/sh
589 # generated by $COMMAND
590 echo -n "pl_rsysinit: preparing /etc and /var for pl_sysinit..."
591 mount -t tmpfs -orw,size=${msize}M,mode=1777 tmpfs /tmp
592 mkdir -p /tmp/root
593 mkdir -p /tmp/etc
594 touch /tmp/etc/resolv.conf
595 touch /tmp/etc/mtab
596 mkdir -p /tmp/var
597
598 # make mtab happy
599 echo "tmpfs /tmp tmpfs rw,size=${msize}M,mode=1777 1 1" > /tmp/etc/mtab
600
601 # copy over directory contents of all _o directories from /etc and /var
602 # /tmp/etc and /tmp/var
603 pushd /etc
604 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
605 popd
606 pushd /var
607 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
608 popd
609
610 echo "done"
611
612 # hand over to pl_sysinit
613 echo "pl_rsysinit: handing over to pl_sysinit"
614 /etc/init.d/pl_sysinit
615 EOF
616     chmod +x etc/rc.d/init.d/pl_rsysinit
617
618     popd
619
620     # create the cramfs image
621     echo "* Creating cramfs image"
622     mkfs.cramfs $tmp/ ${BUILDTMP}/cramfs.img
623     cramfs_size=$(($(du -sk ${BUILDTMP}/cramfs.img | awk '{ print $1; }') + 1))
624     rm -rf $tmp
625     pop_cleanup
626 }
627
628 #################### Create ISO CRAMFS image
629 function build_iso_cramfs() {
630     local iso="$1" ; shift
631     local custom="$1"
632
633     prepare_cramfs "$custom"
634     echo "* Creating ISO CRAMFS-based image"
635
636     local tmp="${BUILDTMP}/cramfs-iso"
637     mkdir -p "$tmp"
638     push_cleanup rm -rf $tmp
639     (cd $ISOFS && find . | grep -v "\.img$" | cpio -p -d -u $tmp/)
640     cat >$tmp/isolinux.cfg <<EOF
641 ${console_serial_line}
642 DEFAULT kernel
643 APPEND ramdisk_size=$cramfs_size initrd=cramfs.img root=/dev/ram0 ro ${KERNEL_ARGS}
644 DISPLAY pl_version
645 PROMPT 0
646 TIMEOUT 40
647 EOF
648
649     cp ${BUILDTMP}/cramfs.img $tmp
650     mkisofs -o "$iso" \
651         $MKISOFS_OPTS \
652         $tmp
653
654     rm -fr "$tmp"
655     pop_cleanup
656 }
657
658 #################### Create USB CRAMFS based image
659 function build_usb_cramfs() {
660     local usb="$1" ; shift
661     local custom="$1"
662
663     prepare_cramfs "$custom"
664     echo "* Creating USB CRAMFS based image"
665
666     let vfat_size=${cramfs_size}+$FREE_SPACE
667
668     # Make VFAT filesystem for USB
669     mkfs.vfat -C "$usb" $vfat_size
670
671     # Populate it
672     echo "* Populating USB with overlay images and cramfs"
673     mcopy -bsQ -i "$usb" $ISOFS/kernel $ISOFS/pl_version ::/
674     mcopy -bsQ -i "$usb" ${BUILDTMP}/cramfs.img ::/
675
676     # Use syslinux instead of isolinux to make the image bootable
677     tmp="${BUILDTMP}/syslinux.cfg"
678     cat >$tmp <<EOF
679 ${console_serial_line}
680 DEFAULT kernel
681 APPEND ramdisk_size=$cramfs_size initrd=cramfs.img root=/dev/ram0 ro ${KERNEL_ARGS}
682 DISPLAY pl_version
683 PROMPT 0
684 TIMEOUT 40
685 EOF
686
687     mcopy -bsQ -i "$usb" "$tmp" ::/syslinux.cfg
688     rm -f "$tmp"
689
690     echo "* Making USB CRAMFS based image bootable"
691     syslinux "$usb"
692 }
693
694 #################### map on all types provided on the command-line and invoke one of the above functions
695 function build_types () {
696
697     [ -z "$OUTPUT_BASE" ] && OUTPUT_BASE="$PLC_NAME-BootCD-$BOOTCD_VERSION"
698
699     # alter output filename to reflect serial settings
700     if [ -n "$IS_SERIAL" ] ; then
701         if [ "$CONSOLE_INFO" == "$SERIAL_CONSOLE" ] ; then
702             serial="-serial"
703         else
704             serial="-serial-$(echo $CONSOLE_INFO | sed -e 's,:,,g')"
705         fi
706     else
707         serial=""
708     fi
709     
710     function type_to_name() {
711         echo $1 | sed '
712         s/usb$/.usb/;
713         s/usb_partition$/-partition.usb/;
714         s/iso$/.iso/;
715         s/usb_cramfs$/-cramfs.usb/;
716         s/iso_cramfs$/-cramfs.iso/;
717         '
718     }
719
720     for t in $TYPES; do
721         arg=$t
722
723         tname=`type_to_name $t`
724         # if -o is specified (as it has no default)
725         if [ -n "$OUTPUT_NAME" ] ; then
726             output=$OUTPUT_NAME
727         else
728             output="${OUTPUT_BASE}${serial}${tname}"
729         fi
730
731         echo "*** Dealing with type=$arg"
732         echo '*' build_$t "$output" "$CUSTOM_DIR"
733         [ -n "$DRY_RUN" ] || build_$t "$output" "$CUSTOM_DIR" 
734     done
735 }
736
737 #################### 
738 function main () {
739
740     parse_command_line "$@"
741
742     init_and_check
743
744     echo "* Building images for $FULL_VERSION_STRING"
745     # Do not tolerate errors
746     set -e
747     trap "do_cleanup" ERR INT EXIT
748
749     init_serial $CONSOLE_INFO
750     build_overlay
751     build_types
752
753     exit 0
754 }
755
756 ####################
757 main "$@"