~ubuntu-on-ec2/vmbuilder/automated-ec2-builds-fginther

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#!/bin/bash
# vi: ts=4 noexpandtab

TEMP_D=""

error() { echo "$@" 1>&2; }
fail() { [ $# -eq 0 ] || error "$@"; exit 1; }
Usage() {
	cat <<EOF
Usage: ${0##*/} output
   Create a multiboot image that will multiboot to a instances installed
   /boot/grub/core.img
EOF
}

bad_Usage() { Usage 1>&2; fail "$@"; }
cleanup() {
	[ -z "${TEMP_D}" -o ! -d "${TEMP_D}" ] || rm -Rf "${TEMP_D}"
}

short_opts="h"
long_opts="help"
getopt_out=$(getopt --name "${0##*/}" \
	--options "${short_opts}" --long "${long_opts}" -- "$@") &&
	eval set -- "${getopt_out}" ||
	bad_Usage

cfg_in=""
modules="biosdisk tar memdisk configfile part_msdos ext2 multiboot test serial echo terminal chain sleep minicmd"
while [ $# -ne 0 ]; do
	cur=${1}; next=${2};
	case "$cur" in
		-h|--help) Usage; exit 0;;
		   --config) cfg_in=${next}; shift;;
		--) shift; break;;
	esac
	shift;
done

[ $# -eq 1 ] || bad_Usage "must supply output"
output=${1}

TEMP_D=$(mktemp -d "${TMPDIR:-/tmp}/.${0##*/}.XXXXXX") ||
	fail "failed to make tempd"

trap cleanup EXIT

cfg="${TEMP_D}/my.cfg"
if [ -n "${cfg_in}" ]; then
	cp "${cfg_in}" "${cfg}" || fail "failed to copy ${cfg_in}"
else
	cat > "${cfg}" <<"EOF"
serial --unit=0 --speed=9600
terminal_input console serial
terminal_output console serial

set cimg=/boot/grub/core.img
for r in "(hd0,1)" "(hd0)"; do
   set root=$r
   if [ -s $cimg ]; then
      echo "multibooting $r$cimg"
      multiboot $cimg
      boot
   fi
   echo "no core.img found on $r"
   sleep 1
done

echo "failed to find a core.img to multiboot to"
for r in "(hd0,1)" "(hd0)"; do
  set root=$r
  echo "attempting chainload from ($root)"
  if chainloader +1; then
    boot
  fi
  echo "failed"
done
exit
EOF
	[ $? -eq 0 ] || fail "failed to write config"
fi

memdisk_dir="${TEMP_D}/md"
memdisk="${TEMP_D}/md.tar"
mkdir -p "${memdisk_dir}/boot/grub" &&
	cp "${cfg}" "${memdisk_dir}/boot/grub/grub.cfg" &&
	tar -C "${memdisk_dir}" -cf "${memdisk}" boot ||
	fail "failed to make memdisk"

grub-mkimage --output="${output}" \
	--memdisk="${memdisk}" --prefix='(memdisk)/boot/grub' \
	-O i386-pc ${modules} ||
	fail "failed to create image ${output}"

error "wrote to ${output}"