services-oci/build.sh

137 lines
2.9 KiB
Bash
Executable file

#!/usr/bin/env bash
# shellcheck shell=bash
# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright © 2022 Thorsten Schubert <tschubert@bafh.org>
set -eo pipefail
shopt -s nullglob
has() {
hash "$1" &>/dev/null
}
die() {
local msg=$1
local code=${2-1}
printf '%s\n' "$msg" >&2
exit "$code"
}
prompt() {
msg() {
local text=$1
local div_width="120"
printf "%${div_width}s\n" ' ' | tr ' ' -
printf "%s\n" "$text"
}
local question=$1
while true; do
msg "$question"
read -p "[y]es or [n]o (default: no) : " -r answer
case "$answer" in
y | Y | yes | YES | Yes)
return 0
;;
n | N | no | NO | No | *[[:blank:]]* | "")
return 1
;;
*)
msg "Please answer [y]es or [n]o."
;;
esac
done
}
if [[ -v CONTAINER_RUNTIME ]]; then
RUNTIME=$CONTAINER_RUNTIME
elif has podman; then
RUNTIME=podman
else
RUNTIME=docker
fi
image=$1
if [[ -z $image || ! -d ${image} ]]; then
die 'Specify a valid image to build.'
fi
shift
branch=$(git branch --show-current)
project_root=$(git rev-parse --show-toplevel)
revision=$(git rev-parse HEAD)
timestamp=$(date --rfc-3339=seconds)
while read -r var; do
if [[ -z ${!var} ]]; then
printf "%s empty or not set\n" "$var" >&2
exit 1
fi
done <<EOF
branch
project_root
revision
timestamp
EOF
image_base=betaco.de/strom
image_uri="${image_base}/${image}"
build_root="${project_root}/${image}"
# image specific flags and tags
if [[ ! -r ${image}/build.sh.in ]]; then
die "Please create an image specific build.sh.in"
fi
source "${build_root}/build.sh.in"
if [[ ! -v VERSION_TAG ]]; then
die "Please set \$VERSION_TAG inside image/build.sh."
fi
image_tags+=(
"${image_uri}:${revision}"
"${image_uri}:${VERSION_TAG}"
"${image_uri}:latest"
)
while (($# > 0)); do
image_tags+=("${image_uri}:${1}")
shift
done
# external tags from image/build.sh
image_tags+=("${EXTRA_TAGS[@]}")
declare -a runtime_args
for arg in "${BUILD_ARGS[@]}"; do
runtime_args+=(--build-arg="${arg}")
done
$RUNTIME build \
--file="${build_root}/Containerfile" \
--label=org.opencontainers.image.authors="Thorsten Schubert <tschubert@bafh.org>" \
--label=org.opencontainers.image.licenses="AGPL-3.0" \
--label=org.opencontainers.image.source="https://betaco.de/strom/services-oci/raw/branch/${branch}/${image}/Containerfile" \
--label=org.opencontainers.image.url="https://betaco.de/strom/services-oci/src/branch/${branch}" \
--label=org.opencontainers.image.created="$timestamp" \
--label=org.opencontainers.image.revision="$revision" \
--label=org.opencontainers.image.title="${image}" \
--label=org.opencontainers.image.version="$VERSION_TAG" \
"${runtime_args[@]}" \
"${EXTRA_ARGS[@]}" \
--tag="${image_uri}:${revision}" \
"$build_root"
$RUNTIME tag "${image_tags[@]}"
if [[ -t 1 && -v AUTH_FILE ]]; then
if ! prompt 'Push images to registry?'; then
exit 0
fi
for tag in "${image_tags[@]}"; do
$RUNTIME push --authfile="$AUTH_FILE" "${tag}"
done
fi
# vi: set ft=sh ts=4 sw=4 sts=-1 sr noet si tw=0 fdm=manual: