Files
security-command.org/deploy.sh
T

88 lines
2.5 KiB
Bash
Executable File

#!/usr/bin/env bash
# Deploys the terminal homepage on this host. Clone the repository into
# /srv/security-command.org and run this script for the first setup and for
# every update.
#
# Usage: sudo ./deploy.sh [--no-pull]
# --no-pull deploy the checked out commit without pulling (allows local changes)
set -euo pipefail
cd "$(dirname "$(readlink -f "$0")")"
pull=1
for arg in "$@"; do
case $arg in
--no-pull) pull=0 ;;
*) echo "unknown option: $arg" >&2; exit 2 ;;
esac
done
if [[ $EUID -ne 0 ]]; then
echo "run as root" >&2
exit 1
fi
# Git refuses repositories owned by another user, so it runs as the owner.
repo_owner=$(stat -c %U .)
as_owner() { sudo -u "$repo_owner" "$@"; }
if [[ $pull == 1 ]]; then
if [[ -n $(as_owner git status --porcelain) ]]; then
echo "the working tree has local changes; commit them or use --no-pull" >&2
exit 1
fi
as_owner git pull --ff-only
fi
if [[ ! -f .env ]]; then
as_owner cp deploy/env.example .env
read -rp "Absolute path of the content directory: " content_dir
as_owner sed -i "s|^CONTENT_DIR=.*|CONTENT_DIR=${content_dir}|" .env
fi
set -a
source .env
set +a
if [[ ! -d ${CONTENT_DIR:-} || ${CONTENT_DIR} != /* ]]; then
echo "CONTENT_DIR in .env must be an absolute path to a directory" >&2
exit 1
fi
registry_host=${REGISTRY%%/*}
if ! grep -qs "\"${registry_host}\"" ~/.docker/config.json; then
echo "log in to the registry first: docker login ${registry_host} (token with read:package)" >&2
exit 1
fi
deploy/host/install-sandbox-host.sh
sandbox_docker() { DOCKER_HOST=unix:///run/docker-sandbox/docker.sock docker "$@"; }
# Images are tagged with the commit they were built from. Right after a push,
# CI may still be building them, so pulling is retried for a while.
pull_image() {
local engine=$1 image=$2 deadline=$((SECONDS + 900))
until "$engine" pull --quiet "$image" >/dev/null; do
if ((SECONDS >= deadline)); then
echo "gave up waiting for ${image}" >&2
return 1
fi
echo "waiting for CI to publish ${image}"
sleep 20
done
}
commit=$(as_owner git rev-parse HEAD)
sandbox_tag="${REGISTRY}/homepage-sandbox:${commit}"
pull_image sandbox_docker "$sandbox_tag"
sandbox_image=$(sandbox_docker image inspect --format '{{index .RepoDigests 0}}' "$sandbox_tag")
install -d -m 0755 runtime
cat > runtime/deploy.env <<EOF
SANDBOX_IMAGE=${sandbox_image}
SANDBOX_GROUP_ID=$(getent group sandbox-spawner | cut -d: -f3)
EOF
IMAGE=$sandbox_image deploy/host/verify-sandbox.sh
echo "deployed ${commit}"