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