ManiCandles/scripts/deploy-frontend.sh

73 lines
2.2 KiB
Bash

#!/bin/sh
set -eu
root=${1:?Deployment directory required}
release_id=${2:?Build number and commit required}
host=${3:?Frontend hostname required}
case "$release_id" in *[!0-9a-f-]*|'') echo 'Invalid release ID' >&2; exit 1 ;; esac
build=${release_id%%-*}
case "$build" in *[!0-9]*|'') echo 'Invalid build number' >&2; exit 1 ;; esac
case "$host" in *[!a-zA-Z0-9.-]*|'') echo 'Invalid hostname' >&2; exit 1 ;; esac
cd "$root"
root=$(pwd -P)
exec 9> .deploy.lock
flock -x 9
release="$root/releases/$release_id/dist"
test -s "$release/index.html"
test "$(cat "$release/release.txt")" = "$release_id"
# A slow older pipeline must not replace a newer successful release.
last_build=0
if [ -L current ]; then
last_release=$(cat current/release.txt)
last_build=${last_release%%-*}
fi
if [ "$build" -lt "$last_build" ]; then
echo "Skipping superseded build $build (active build $last_build)"
exit 0
fi
if [ -e current ] && [ ! -L current ]; then
echo 'The current release must be a symlink' >&2
exit 1
fi
old=$(readlink current || true)
temporary="$root/.current-$release_id"
switched=false
restore() {
result=$?
trap - EXIT HUP INT TERM
if [ "$switched" = true ] && [ "$result" -ne 0 ]; then
if [ -n "$old" ]; then
ln -sfn "$old" "$temporary"
mv -Tf "$temporary" current
else
rm -f current
fi
echo 'Release verification failed. Restored the previous release.' >&2
fi
rm -f "$temporary"
exit "$result"
}
trap restore EXIT
trap 'exit 1' HUP INT TERM
chmod a+rx "$root/releases/$release_id"
chmod -R a+rX "$release"
ln -sfn "$release" "$temporary"
mv -Tf "$temporary" current
switched=true
# Verify this server through the existing HTTPS virtual host and certificate.
served=$(curl --fail --silent --show-error --max-time 20 \
--resolve "$host:443:127.0.0.1" "https://$host/release.txt")
test "$served" = "$release_id"
for path in / /workspace /cart /api/v1/health/ready; do
curl --fail --silent --show-error --output /dev/null --max-time 20 \
--resolve "$host:443:127.0.0.1" "https://$host$path"
done
if [ -n "$old" ] && [ "$old" != "$release" ]; then
ln -sfn "$old" "$root/.previous-$release_id"
mv -Tf "$root/.previous-$release_id" previous
fi
echo "Activated $release_id on $host"