#!/usr/bin/env bash set -Eeuo pipefail DEPLOY_ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)" SCRIPT_PATH="${DEPLOY_ROOT}/$(basename -- "${BASH_SOURCE[0]}")" cd "$DEPLOY_ROOT" fail() { printf 'ERROR: %s\n' "$*" >&2 exit 1 } command -v git >/dev/null 2>&1 || fail "git is required" command -v docker >/dev/null 2>&1 || fail "docker is required" docker compose version >/dev/null 2>&1 || fail "Docker Compose v2 is required" [[ -f .env ]] || fail ".env was not found in ${DEPLOY_ROOT}" post_pull=0 if [[ "${1:-}" == "--post-pull" ]]; then post_pull=1 elif [[ $# -ne 0 ]]; then fail "usage: ${0} [--post-pull]" fi if ((post_pull == 0)); then branch="$(git symbolic-ref --quiet --short HEAD)" || fail "the repository is in detached HEAD state" upstream="$(git rev-parse --abbrev-ref --symbolic-full-name '@{upstream}' 2>/dev/null)" || fail "branch ${branch} does not have an upstream branch" remote="$(git config --get "branch.${branch}.remote")" || fail "branch ${branch} does not have a configured remote" git diff --quiet && git diff --cached --quiet || fail "tracked local changes must be committed or stashed before updating" printf 'Checking %s against %s...\n' "$branch" "$upstream" git fetch --quiet --prune "$remote" local_commit="$(git rev-parse HEAD)" upstream_commit="$(git rev-parse '@{upstream}')" if [[ "$local_commit" == "$upstream_commit" ]]; then printf 'Deployment is already up to date.\n' elif git merge-base --is-ancestor "$local_commit" "$upstream_commit"; then git merge --quiet --ff-only "$upstream_commit" # Restart using the newly pulled copy so changes to this script apply. exec "$SCRIPT_PATH" --post-pull elif git merge-base --is-ancestor "$upstream_commit" "$local_commit"; then fail "local branch ${branch} is ahead of ${upstream}; refusing to update" else fail "local branch ${branch} has diverged from ${upstream}" fi fi printf 'Updating the local Gitea image and deployment stack...\n' docker compose --env-file .env pull gitea nginx certbot "${DEPLOY_ROOT}/manage.sh" start container_id="$(docker compose -f compose.yaml -f compose.tls.yaml ps -q broker)" [[ -n "$container_id" ]] || fail "Docker Compose did not return the local broker container" printf 'Waiting for the local broker health check' for ((attempt = 1; attempt <= 75; attempt++)); do status="$( docker inspect \ --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' \ "$container_id" )" case "$status" in healthy) printf ' healthy.\n' docker compose -f compose.yaml -f compose.tls.yaml ps printf 'Local deployment updated successfully.\n' exit 0 ;; exited | dead | unhealthy) printf ' %s.\n' "$status" docker compose -f compose.yaml -f compose.tls.yaml logs --tail=100 broker fail "the local broker failed its health check" ;; esac printf '.' sleep 2 done printf ' timed out.\n' docker compose -f compose.yaml -f compose.tls.yaml logs --tail=100 broker fail "the local broker did not become healthy within 150 seconds"