#!/bin/bash # Fast-forward this clone to its upstream (Gitea) and restart the web server # when the code changed. Run every few minutes by receipt-update.timer on the # machine the service runs on. # # The new commit is tested in a scratch worktree first, so the live clone and # venv never hold untested code. After the restart, /healthz must answer or # the old commit is put back. Either failure skips that commit until a newer # one lands. set -euo pipefail cd "$(dirname "$0")/.." git fetch --quiet old=$(git rev-parse HEAD) new=$(git rev-parse '@{upstream}') [ "$old" = "$new" ] && exit 0 failed_marker="$(git rev-parse --git-dir)/receipt-update-failed" if [ "$(cat "$failed_marker" 2>/dev/null)" = "$new" ]; then exit 0 fi fail() { echo "$1 on $(git rev-parse --short "$new"); staying on $(git rev-parse --short "$old")." >&2 echo "$new" >"$failed_marker" exit 1 } deps_changed() { ! git diff --quiet "$old" "$new" -- pyproject.toml; } scratch=$(mktemp -d) trap 'git worktree remove --force "$scratch" 2>/dev/null; rm -rf "$scratch"; git worktree prune' EXIT git worktree add --quiet --detach "$scratch" "$new" python=$PWD/.venv/bin/python if deps_changed; then # New dependencies get a throwaway venv; the live one is only touched once they pass. python3 -m venv "$scratch/.venv" "$scratch/.venv/bin/pip" install --quiet "$scratch[web,dev]" python=$scratch/.venv/bin/python fi # pytest's pythonpath = ["."] makes the worktree's modules win over any installed copy. if ! output=$(cd "$scratch" && "$python" -m pytest -q -p no:cacheprovider 2>&1); then echo "$output" | tail -n 20 fail "Tests failed" fi git merge --ff-only --quiet "$new" deps_changed && .venv/bin/pip install --quiet '.[web,dev]' systemctl --user restart receipt-web listen=$(sed -n 's/^RECEIPT_WEB_LISTEN=//p' "$HOME/.config/receipt-web.env" 2>/dev/null) healthz="http://${listen:-127.0.0.1:8765}/healthz" for _ in {1..20}; do if curl -fsS --max-time 2 "$healthz" >/dev/null 2>&1; then echo "Updated $(git rev-parse --short "$old") -> $(git rev-parse --short "$new")." exit 0 fi sleep 1 done journalctl --user -u receipt-web -n 20 --no-pager >&2 || true git reset --quiet --hard "$old" deps_changed && .venv/bin/pip install --quiet '.[web,dev]' systemctl --user restart receipt-web fail "$healthz didn't answer after the restart"