#!/bin/bash set -Eeuo pipefail source /etc/wal-g/db-sync.env expected_pgdata="/var/lib/pgsql/data" if [[ "$PGDATA" != "$expected_pgdata" || ! -d "$PGDATA" || "$(stat -c %U "$PGDATA")" != "postgres" ]]; then echo "Refusing destructive restore for unexpected PGDATA: $PGDATA" >&2 exit 1 fi if [[ "$WALG_S3_PREFIX" != s3://*/prod ]]; then echo "Refusing restore from a non-production prefix" >&2 exit 1 fi systemctl --user --machine="${APP_USER}@" stop app-todo.service || true systemctl stop "$POSTGRES_SERVICE" shopt -s dotglob nullglob contents=("$PGDATA"/*) {% raw %} if (( ${#contents[@]} > 0 )); then {% endraw %} rm -rf --one-file-system -- "${contents[@]}" fi sudo -u postgres --preserve-env=AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY,AWS_ENDPOINT,AWS_REGION,AWS_S3_FORCE_PATH_STYLE,WALG_S3_PREFIX,WALG_COMPRESSION_METHOD \ /usr/local/bin/wal-g backup-fetch "$PGDATA" LATEST chown -R postgres:postgres "$PGDATA" chmod 0700 "$PGDATA" install -o postgres -g postgres -m 0600 /etc/todo-postgresql/postgresql.conf "$PGDATA/postgresql.conf" install -o postgres -g postgres -m 0600 /etc/todo-postgresql/pg_hba.conf "$PGDATA/pg_hba.conf" cat >"$PGDATA/postgresql.auto.conf" <<'RECOVERY' restore_command = '/usr/local/sbin/wal-g-postgres wal-fetch %f %p' recovery_target_timeline = 'latest' RECOVERY touch "$PGDATA/recovery.signal" chown postgres:postgres "$PGDATA/postgresql.auto.conf" "$PGDATA/recovery.signal" systemctl start "$POSTGRES_SERVICE" for _ in {1..120}; do if sudo -u postgres psql --dbname=postgres --tuples-only --no-align --command="SELECT NOT pg_is_in_recovery()" 2>/dev/null | grep -qx t; then break fi sleep 2 done if ! sudo -u postgres psql --dbname=postgres --tuples-only --no-align --command="SELECT NOT pg_is_in_recovery()" | grep -qx t; then echo "PostgreSQL did not complete recovery" >&2 exit 1 fi sudo -u postgres psql --dbname=postgres --set="role=$APP_DB_USER" --set="password=$APP_DB_PASSWORD" <<'SQL' SELECT format('ALTER ROLE %I LOGIN PASSWORD %L', :'role', :'password') \gexec SQL systemctl --user --machine="${APP_USER}@" start app-todo.service