f2e94b605f3f15a3fc34e2d36a0bf3f88168bd48
[packages/trusty/cirros-testvm.git] / cirros-testvm / src-cirros / bin / build-initramfs
1 #!/bin/bash
2 # vi: ts=4 noexpandtab
3
4 TEMP_D=""
5
6 error() { echo "$@" 1>&2; }
7 debug() {
8         [ "${DEBUG}" -ge "${1}" ] || return 0;
9         shift;
10         error "$@"
11 }
12 fail() { [ $# -eq 0 ] || error "$@"; exit 1; }
13 Usage() {
14         cat <<EOF
15 Usage: ${0##*/} initramfs_dir root_dir
16    create an initramfs from initramfs_dir, copying files from root_dir
17
18    Example:
19     ${0##*/} initramfs/ rootfs/ > my.initramfs.img
20 EOF
21 }
22 bad_Usage() { Usage 1>&2; fail "$@"; }
23 cleanup() {
24         [ -z "${TEMP_D}" -o ! -d "${TEMP_D}" ] || rm -Rf "${TEMP_D}"
25 }
26
27 short_opts="hv"
28 long_opts="help,verbose"
29 getopt_out=$(getopt --name "${0##*/}" \
30         --options "${short_opts}" --long "${long_opts}" -- "$@") &&
31         eval set -- "${getopt_out}" ||
32         bad_Usage
33
34 while [ $# -ne 0 ]; do
35         cur=${1}; next=${2};
36         case "$cur" in
37                 -h|--help) Usage; exit 0;;
38                 -v|--verbose) DEBUG=$((${DEBUG}+1));;
39                 --) shift; break;;
40         esac
41         shift;
42 done
43
44 [ $# -eq 2 ] || bad_Usage "must give initramfs_dir and root_dir"
45 initramfs_d=${1}
46 root_d=${2}
47
48 [ -d "$initramfs_d" ] || fail "$initramfs_d is not a dir"
49 [ -d "$root_d" ] || fail "$root_d is not a dir"
50
51 TEMP_D=$(mktemp -d "${TMPDIR:-/tmp}/.${0##*/}.XXXXXX") ||
52         fail "failed to make tempd"
53 trap cleanup EXIT
54
55 work_d="${TEMP_D}/workd"
56 src_d="$initramfs_d/src"
57 needs="$initramfs_d/needs"
58
59 [ -f "$needs" ] || fail "$needs is not a file"
60 [ -d "$src_d" ] || fail "$src_d is not a dir"
61
62 mkdir -p "${work_d}/"{bin,sbin,usr/bin,usr/sbin}
63
64 while read need; do
65         need=${need%%#*}; need=${need% };
66         [ -n "$need" ] || continue
67         [ "${need#*..}" = "${need}" ] || fail "paths cannot have ..: $need"
68         if [ -e "$root_d/$need" ]; then
69                 mkdir -p "$work_d/${need%/*}" &&
70                 cp -a "$root_d/$need" "$work_d/$need" ||
71                 fail "failed to copy $need to working dir"
72         else
73                 fail "$need not found in $root_d"
74         fi
75 done < $needs
76
77 loaders=$(cd "$root_d" &&
78         echo lib/ld-uClibc.so.0 lib/ld-uClibc-*.so \
79                 lib/ld64-uClibc.so.0 lib/ld64-uClibc-*.so)
80
81 for f in $loaders; do
82         [ -f "$root_d/$f" ] || continue
83         mkdir -p "${work_d}/${f%/*}" &&
84         cp -a "$root_d/$f" "$work_d/$f" ||
85                 fail "failed to copy $f"
86 done
87
88 rsync -a "$src_d/" "$work_d" ||
89         fail "failed to sync $src_d to working dir"
90
91 ( cd "${work_d}" && find . | cpio --quiet --dereference -o -H newc | gzip -9 )
92
93 exit 0