blob: 36ab253df7e197df90adc86b43143325b7917407 [file] [log] [blame]
#!/usr/bin/env bash
# Copyright 2020 The Android KVM Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
source "$(dirname "${BASH_SOURCE[0]}")/../common.inc"
function usage()
{
cat <<EOF
Packages the files passed in the command line in a bash script as base64
payloads, and executes the specified command at the end of the script.
The files are packaged under their basenames and extracted into the same
temporary directory. The command is run from that temporary directory.
Usage: $0 [-h] -c COMMAND <file> [<file> ...]
-h output this help text
-c command to run by the packaged script
EOF
}
# Generates the header for the packaged script.
function generate_header()
{
echo "#!/usr/bin/env bash"
echo "set -euo pipefail"
echo "IMGDIR=\$(mktemp -d)"
echo "cd \${IMGDIR}"
echo
}
# Generates a base64 payload image for the image files passed.
# First parameter holds the full path of the image to be packages.
# Second parameter holds the name of the image to be generated.
function generate_image()
{
local image_path="${1}"
local image_name="${2}"
echo "base64 -d << 'EOF' | zcat > \"${image_name}\""
gzip -c "${image_path}" | base64
echo "EOF"
echo
}
while getopts ":c:h" opt; do
case $opt in
c) COMMAND="${OPTARG}";;
h)
usage
exit 0
;;
\?)
echo "Invalid option: ${!OPTIND}" 1>&2
usage 1>&2
exit 1
;;
:)
echo "Invalid option: -${OPTARG} requires an argument" 1>&2
usage 1>&2
exit 1
;;
esac
done
shift $((OPTIND - 1))
if [ -z "$@" ]; then
echo "Must specify at least one image file to package." 1>&2
exit 1
fi
IMAGES=("$@")
# Validate that all image files exist before emitting anything.
for image in "${IMAGES[@]}"; do
if [ ! -f "${image}" ]; then
echo "Image file not found: ${image}" 1>&2
exit 1
fi
done
# Generate the packaged script.
generate_header
for image in "${IMAGES[@]}"; do
generate_image "${image}" "$(basename ${image})"
done
echo "${COMMAND}"