# Fault-tolerant WAL-archive wrapper mounted into the db container at
# /etc/postgresql/wal-archive.sh (see k8s/base/db/statefulset.yaml). Postgres'
# archive_command invokes it as `bash /etc/postgresql/wal-archive.sh %p` (a
# startup flag on the StatefulSet). wal-g reads AWS_* from the db container's
# env, and WALG_S3_PREFIX and the wal-g role (VC_WALG_ROLE, from the role file
# /var/lib/vibecarbon/role/walg-role) from walg-env.sh. The StatefulSet's pod
# template carries this file's sha, so a changed script rolls the db pod on the
# next deploy.
#
# A second key, walg-env.sh, is the file every wal-g caller in the db pod
# sources first (wal-archive.sh, the backup CronJob's exec script, the
# walg-restore init, a restore's restore_command, the CLI's exec scripts): it
# turns WALG_S3_PREFIX_BASE into WALG_S3_PREFIX, this database lineage's own
# folder. Mounted at /etc/postgresql/walg-env.sh in the db container and the
# walg-restore init.
#
# A third key, db-guard.sh, is the db container's entrypoint (the StatefulSet's
# `command`, mounted at /usr/local/bin/db-guard.sh), exactly as compose runs
# it: it refuses to boot over an interrupted restore, applies the wal-g role
# intent (ConfigMap vibecarbon-db-role) to the role file, and finishes a
# pending in-place standby reseed before handing over to the image's
# db-entrypoint.sh.
#
# All three script bodies below are BYTE-IDENTICAL copies of
# carbon/volumes/db/wal-archive.sh, carbon/volumes/db/walg-env.sh and
# carbon/volumes/db/db-guard.sh (the compose mounts), indented 4 spaces into
# the block scalars. That is not a
# convention any more — tests/unit/deploy/walg-archive-script-parity.test.ts
# dedents this block and compares it to the file, and fails the build on any
# divergence. It used to be only a comment, and the two drifted: this copy lost
# BOTH the wal-g write-guard and the pg_is_in_recovery() gate, so on k8s a
# standby (or a not-yet-reseeded standby that is briefly its own primary) pushed
# WAL straight into the primary's canonical prefix.
#
# Same exit semantics as the compose copy: only a node whose role file says
# primary archives; standby skips (exit 0); a missing or unknown role, a retired
# node, a fenced prefix and a failed push hold the segment (exit 1: postgres
# keeps it and retries). A segment is given up (exit 0) two ways only: disk
# pressure, with a durable gap record, and never while the role is unknown; and
# an overwrite refusal, where the archive already holds that segment name with
# other bytes and no retry can change it.
apiVersion: v1
kind: ConfigMap
metadata:
  name: vibecarbon-wal-archive
  namespace: vibecarbon
  labels:
    app: vibecarbon-backup
    component: backup
data:
  wal-archive.sh: |
    #!/bin/bash
    # Fault-tolerant archive_command for Postgres + wal-g.
    #
    # This wrapper:
    #   1. Tries `wal-g wal-push` with $RETRIES attempts and exponential backoff.
    #   2. On final failure, logs WAL_ARCHIVE_FAILED to stderr (the db container's
    #      logs) and exits 1: postgres keeps the segment and retries it, and
    #      pg_stat_archiver's failed_count / last_failed_time show the failure
    #      (vibecarbon status turns red). No segment is lost to a bucket outage.
    #   3. Drops a segment (exit 0) only under disk pressure: when the pg_wal
    #      filesystem has less than 10% or less than 2 GiB free, a held segment
    #      would take the database down with the disk. It logs WAL_ARCHIVE_DROPPED
    #      and appends `<segment> <UTC time>` to $PGDATA/vibecarbon-wal-gap, the
    #      durable record vibecarbon status reads (a restore across a dropped
    #      segment stops at it). The next pushed base backup clears the entries
    #      older than itself (backup/compose-backup.sh, the k8s backup CronJob).
    #   4. Refuses (exit 1) on a node a failover retired: its PGDATA carries the
    #      vibecarbon-retired marker, or the backup prefix's fence object names
    #      its database on a newer timeline.
    #   5. Archives only on a node whose wal-g role file (walg-env.sh reads it
    #      into VC_WALG_ROLE) says primary. standby skips (exit 0); a missing,
    #      empty or unknown role holds the segment (exit 1), even under disk
    #      pressure: the role guard sits before every push and every drop.
    #
    # THIS FILE IS THE SINGLE SOURCE OF TRUTH FOR BOTH DEPLOY TIERS. compose mounts
    # it directly; k8s ships a byte-identical copy in the vibecarbon-wal-archive
    # ConfigMap (carbon/k8s/base/backup/configmap-walg.yaml), pinned by
    # tests/unit/deploy/walg-archive-script-parity.test.ts. Edit here, then re-run
    # that test — it prints the exact indented block to paste into the ConfigMap.
    #
    # Trade-off: during a bucket outage pg_wal grows until the outage ends or the
    # disk-pressure guard trips; only then is there a PITR gap, and it is recorded.
    #
    # Invoked by postgres as: wal-archive.sh <wal-file-path>
    # %p is passed by Postgres and is the absolute path to the WAL segment.

    set -u
    WAL_PATH="${1:?archive_command requires a WAL file path}"
    RETRIES="${WAL_ARCHIVE_RETRIES:-3}"
    SLEEP_BASE="${WAL_ARCHIVE_SLEEP:-2}"
    PGDATA_DIR="${PGDATA:-/var/lib/postgresql/data}"
    # The durable record of segments dropped under disk pressure (see above).
    WAL_GAP_FILE="${PGDATA_DIR}/vibecarbon-wal-gap"
    # The wal-g binary. WAL_ARCHIVE_WALG exists for the script tests only (a stub
    # in place of the real binary); nothing in a deploy sets it.
    WALG="${WAL_ARCHIVE_WALG:-/usr/local/bin/wal-g}"

    # RETIRED-NODE FENCE: a failover retired this node (the old primary), and the
    # CLI placed this marker in PGDATA when it next reached it. Its WAL belongs to a
    # timeline the promoted node has left, and the backup prefix is the promoted
    # node's now. It exits 1 on purpose: a refused push fails loudly (postgres
    # logs every retry) rather than reading as a skip. The
    # reseed that rebuilds this node as the standby replaces PGDATA and the marker
    # with it. Checked first, before any other guard, psql or wal-g.
    if [ -f "${PGDATA_DIR}/vibecarbon-retired" ]; then
        echo "wal-archive: retired node: backups refused, not archiving '${WAL_PATH}' (run vibecarbon deploy to rebuild it as the standby)." >&2
        exit 1
    fi

    # THIS DATABASE'S ARCHIVE FOLDER: walg-env.sh turns WALG_S3_PREFIX_BASE into
    # WALG_S3_PREFIX, the folder of this database's lineage (its system
    # identifier), so a recreated database never archives into, or fences, the
    # archive an earlier one left. Sourced before anything reads the prefix. A
    # system identifier it cannot read, or a missing walg-env.sh (bash would carry
    # on with no prefix and skip the segment as "no backup target"), exits 1:
    # postgres retries the segment rather than drop it or archive it into a
    # guessed folder. WALG_ENV_SH exists for the
    # script tests only (the backup scripts read the same name), like WAL_ARCHIVE_WALG.
    . "${WALG_ENV_SH:-/etc/postgresql/walg-env.sh}" || exit 1

    # No backup target: nothing to push to. Local dev sets WALG_S3_PREFIX_BASE to
    # "" (docker-compose.override.yml), which walg-env.sh turns into an empty
    # WALG_S3_PREFIX, and a deploy with no bucket name renders a bucketless
    # "s3:///..." prefix. Without this, every segment waits out the
    # wal-g attempts below and logs WAL_ARCHIVE_FAILED. Same guard as
    # backup/compose-backup.sh; a real deploy without archiving is still failed
    # by the deploy's wal-g audit (src/lib/deploy/walg-audit.js).
    case "${WALG_S3_PREFIX:-}" in
        ""|s3:///*)
            echo "wal-archive: no backup target (WALG_S3_PREFIX='${WALG_S3_PREFIX:-}'), not archiving '${WAL_PATH}'." >&2
            exit 0
            ;;
    esac

    # WRITE-GUARD (src/lib/deploy/walg-role.js): only a node whose role file says
    # primary archives. standby is an explicit skip (exit 0: a standby's segments
    # belong to no backup). No role, or one that is not a word we know, HOLDS the
    # segment (exit 1): postgres keeps it and retries, pg_stat_archiver turns
    # status red, and nothing is lost while the CLI writes the role.
    case "${VC_WALG_ROLE:-}" in
        primary) ;;
        standby)
            echo "wal-archive: wal-g role standby, skipping archive of '${WAL_PATH}' (only the primary writes the lineage prefix)." >&2
            exit 0
            ;;
        *)
            echo "WAL_ARCHIVE_ROLE_UNKNOWN: no wal-g role in ${VC_WALG_ROLE_FILE:-/var/lib/vibecarbon/role/walg-role}; keeping '${WAL_PATH}', postgres retries it (vibecarbon deploy writes the role)." >&2
            exit 1
            ;;
    esac

    # Recovery gate: a node in recovery (a streaming standby) must NEVER archive
    # WAL. Doing so would let a standby write into the shared/canonical WAL stream
    # and corrupt the PITR timeline (invisible until a restore during an incident).
    # PostgreSQL with archive_mode=on already skips archive_command during recovery,
    # but gate explicitly as defense in depth (and in case archive_mode=always is
    # ever set, or a split-brain leaves two writers). Only SKIP when we can
    # POSITIVELY confirm recovery — never fail-closed in a way that would drop a
    # real primary's WAL.
    in_recovery=""
    if command -v psql >/dev/null 2>&1; then
        in_recovery="$(psql -U "${PGUSER:-postgres}" -d postgres -tAXc 'SELECT pg_is_in_recovery()' 2>/dev/null | tr -d '[:space:]')"
    fi
    # Fall back to the standby.signal marker if psql couldn't answer (e.g. socket
    # not reachable from the archive_command context). Postgres removes this file
    # atomically on promotion, so its presence == "still a standby".
    if [ -z "$in_recovery" ] && [ -f "${PGDATA_DIR}/standby.signal" ]; then
        in_recovery="t"
    fi
    if [ "$in_recovery" = "t" ]; then
        echo "wal-archive: node is in recovery (standby) — skipping archive of '${WAL_PATH}' (only the primary archives)." >&2
        exit 0
    fi

    # BACKUP-PREFIX FENCE: a failover wrote vibecarbon-fence.json into this prefix,
    # naming the promoted primary's database, the timeline it promoted onto and the
    # segment that timeline branched in. An old primary that rebooted unreached is
    # the same database on an OLDER timeline: its segments from the branch on
    # would land in, and fork, the promoted node's stream. The segment's timeline
    # is the first 8 hex digits of its name, its number the next 16. Segments of
    # the parent timeline before the branch are history both timelines share (an
    # archive backlog at a planned failover), and the .history and .partial files
    # are what a promotion itself archives, so those pass. No fence object (an env that never failed
    # over) or another database is allowed; a fence that cannot be read falls
    # through to the push, which fails the same way.
    WAL_NAME="$(basename "$WAL_PATH")"
    case "$WAL_NAME" in
        *.history|*.partial) ;;
        *)
            fence="$("$WALG" st cat vibecarbon-fence.json 2>/dev/null)"
            fence_tl="$(printf '%s' "$fence" | grep -o '"timeline":[0-9]*' | grep -o '[0-9]*$')"
            fence_sysid="$(printf '%s' "$fence" | grep -o '"systemIdentifier":"[0-9]*"' | grep -o '[0-9][0-9]*')"
            fence_switch="$(printf '%s' "$fence" | grep -o '"switchSegment":"[0-9A-F]\{16\}"' | grep -o '[0-9A-F]\{16\}')"
            seg_tl="${WAL_NAME:0:8}"
            seg_no="${WAL_NAME:8:16}"
            before_switch=0
            # Only on the PARENT timeline (the one the switch point is on); any
            # older timeline, and any fence without a switch point, refuses.
            if [ -n "$fence_switch" ] && [ -n "$fence_tl" ] && [[ "$seg_tl" =~ ^[0-9A-Fa-f]{8}$ ]] \
                && [ "$((16#$seg_tl))" -eq "$((fence_tl - 1))" ] && [[ "$seg_no" =~ ^[0-9A-F]{16}$ ]]; then
                # Numerically, in two 32-bit halves (log id, segment).
                s_hi=$((16#${seg_no:0:8})); s_lo=$((16#${seg_no:8:8}))
                f_hi=$((16#${fence_switch:0:8})); f_lo=$((16#${fence_switch:8:8}))
                if [ "$s_hi" -lt "$f_hi" ] || { [ "$s_hi" -eq "$f_hi" ] && [ "$s_lo" -lt "$f_lo" ]; }; then
                    before_switch=1
                fi
            fi
            if [ "$before_switch" = 0 ] && [ -n "$fence_tl" ] && [[ "$seg_tl" =~ ^[0-9A-Fa-f]{8}$ ]] && [ "$((16#$seg_tl))" -lt "$fence_tl" ]; then
                local_sysid=""
                if command -v psql >/dev/null 2>&1; then
                    local_sysid="$(psql -U "${PGUSER:-postgres}" -d postgres -tAXc 'SELECT system_identifier FROM pg_control_system()' 2>/dev/null | tr -d '[:space:]')"
                fi
                if [ -z "$local_sysid" ] || [ "$local_sysid" = "$fence_sysid" ]; then
                    echo "wal-archive: backup prefix fenced to another primary (timeline ${fence_tl}): not archiving '${WAL_PATH}' from timeline $((16#$seg_tl)) (a failover retired this node; run vibecarbon status, then vibecarbon deploy to rebuild it as the standby)." >&2
                    exit 1
                fi
            fi
            ;;
    esac

    attempt=1
    while [ "$attempt" -le "$RETRIES" ]; do
        push_out="$("$WALG" wal-push "$WAL_PATH" 2>&1)"
        push_rc=$?
        [ -n "$push_out" ] && printf '%s\n' "$push_out" >&2
        if [ "$push_rc" -eq 0 ]; then
            exit 0
        fi
        # WALG_PREVENT_WAL_OVERWRITE: the archive already holds this segment name
        # with other bytes. No retry can change that, so no backoff either: say so
        # on its own line, then give the segment up like any other failure.
        case "$push_out" in
            *"already archived, contents differ"*)
                echo "WAL_ARCHIVE_OVERWRITE_REFUSED: wal-g refused to overwrite '$WAL_PATH': the archive already holds this segment name with other bytes (WALG_PREVENT_WAL_OVERWRITE); check for a second writer on this lineage" >&2
                echo "WAL_ARCHIVE_FAILED: wal-g wal-push '$WAL_PATH' refused (overwrite); allowing PG to recycle (PITR gap for this segment)" >&2
                exit 0
                ;;
        esac
        if [ "$attempt" -lt "$RETRIES" ]; then
            sleep_for=$((SLEEP_BASE ** attempt))
            sleep "$sleep_for"
        fi
        attempt=$((attempt + 1))
    done

    # All retries exhausted. Hold the segment (exit 1: postgres retries it, and
    # pg_stat_archiver shows the failure) unless the pg_wal filesystem is nearly
    # full: under 10% or under 2 GiB free. A full disk stops the database, which
    # is worse than the PITR gap a dropped segment leaves, so only then is the
    # segment given up, with a durable record. Free space that cannot be read
    # holds the segment. VC_WAL_GUARD_FREE_BYTES and VC_WAL_GUARD_TOTAL_BYTES
    # exist for the script tests only.
    wal_fs="$(df -Pk "${PGDATA_DIR}/pg_wal" 2>/dev/null | awk 'NR == 2 { print $2, $4 }')"
    total_kb="${wal_fs%% *}"
    free_kb="${wal_fs##* }"
    if [[ "${VC_WAL_GUARD_TOTAL_BYTES:-}" =~ ^[0-9]+$ ]]; then
        total_kb=$((VC_WAL_GUARD_TOTAL_BYTES / 1024))
    fi
    if [[ "${VC_WAL_GUARD_FREE_BYTES:-}" =~ ^[0-9]+$ ]]; then
        free_kb=$((VC_WAL_GUARD_FREE_BYTES / 1024))
    fi
    if [[ "$total_kb" =~ ^[0-9]+$ && "$free_kb" =~ ^[0-9]+$ ]] \
        && { [ "$free_kb" -lt $((2 * 1024 * 1024)) ] || [ "$((free_kb * 10))" -lt "$total_kb" ]; }; then
        # The drop is still exit 0 (the disk is the emergency), but a gap record that
        # cannot be written is said so: the restore warning reads that file.
        if printf '%s %s\n' "$WAL_NAME" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$WAL_GAP_FILE" 2>/dev/null; then
            echo "WAL_ARCHIVE_DROPPED: wal-g wal-push '$WAL_PATH' failed after $RETRIES attempts and pg_wal has $((free_kb / 1024)) MiB free (under 10% or 2 GiB): dropping it so the disk does not fill (PITR gap, recorded in $WAL_GAP_FILE)" >&2
        else
            echo "WAL_ARCHIVE_DROPPED: wal-g wal-push '$WAL_PATH' failed after $RETRIES attempts and pg_wal has $((free_kb / 1024)) MiB free (under 10% or 2 GiB): dropping it so the disk does not fill (PITR gap, gap record could not be written to $WAL_GAP_FILE)" >&2
        fi
        exit 0
    fi
    echo "WAL_ARCHIVE_FAILED: wal-g wal-push '$WAL_PATH' failed after $RETRIES attempts; keeping the segment, postgres retries it" >&2
    exit 1
  walg-env.sh: |
    # The WAL-G prefix of this database's own archive. SOURCED, never executed,
    # inside the db container: by wal-archive.sh, the base backup scripts
    # (backup/compose-backup.sh, the k8s backup CronJob), the k8s walg-restore
    # init, the restore_command a restore writes, and every script the CLI runs
    # in the container that calls wal-g.
    #
    # Each database lineage archives under its own folder of the environment's
    # prefix, named by its system identifier (pg_controldata):
    #
    #   <WALG_S3_PREFIX_BASE>/<system identifier>/{basebackups_005,wal_005,vibecarbon-fence.json}
    #
    # A destroyed and redeployed environment is a new database with a new system
    # identifier, so it never archives into, or takes over the newest base of, the
    # archive the old one left. A restore keeps the system identifier, so a
    # restored database archives on in the lineage it came from, and a promoted
    # standby (a copy of its primary) does too.
    #
    #   WALG_S3_PREFIX_BASE  the environment's prefix (compose db env, k8s db pod).
    #                        Empty means no backup target: WALG_S3_PREFIX is
    #                        exported empty, and every script skips as before. A
    #                        bucketless s3:///... is passed through as is, for the
    #                        same skip.
    #   RESTORE_LINEAGE      set by a restore, whose fetch runs before PGDATA holds
    #                        the database it names: that lineage's folder.
    #   otherwise            the system identifier of the cluster in $PGDATA. One
    #                        that cannot be read exits 1: nothing may guess a
    #                        folder.
    #
    # THIS FILE IS THE SINGLE SOURCE OF TRUTH FOR BOTH DEPLOY TIERS. compose mounts
    # it at /etc/postgresql/walg-env.sh; k8s ships a byte-identical copy in the
    # vibecarbon-wal-archive ConfigMap (carbon/k8s/base/backup/configmap-walg.yaml),
    # pinned by tests/unit/deploy/walg-archive-script-parity.test.ts.
    # The wal-g WRITE-GUARD role (src/lib/deploy/walg-role.js WALG_ROLE_PARSE_SH,
    # carried verbatim): one word in a file OUTSIDE PGDATA (k8s: a sibling subPath
    # of the db volume; compose: a host directory bound read-only), so
    # pg_basebackup never copies it into a standby. Exactly "primary" or
    # "standby"; anything else, a missing file or a symlink is no role, which
    # every writer of WAL or base backups treats as "do not write".
    # Test seams, for the script tests only: VC_WALG_ROLE_FILE here (the file),
    # VC_WALG_ROLE_DIR in db-guard.sh (its directory).
    vc_walg_role_file="${VC_WALG_ROLE_FILE:-/var/lib/vibecarbon/role/walg-role}"
    VC_WALG_ROLE=""
    if [ -f "$vc_walg_role_file" ] && [ ! -L "$vc_walg_role_file" ]; then
        case "$(cat "$vc_walg_role_file" 2>/dev/null)" in
            primary) VC_WALG_ROLE=primary ;;
            standby) VC_WALG_ROLE=standby ;;
        esac
    fi
    export VC_WALG_ROLE
    unset vc_walg_role_file
    vc_walg_base="${WALG_S3_PREFIX_BASE:-}"
    if [ -z "$vc_walg_base" ]; then
        WALG_S3_PREFIX=""
    elif [ "${vc_walg_base#s3:///}" != "$vc_walg_base" ]; then
        # A deploy with no bucket name renders a bucketless base: still no backup
        # target, which every caller skips on, so no folder is read.
        WALG_S3_PREFIX="$vc_walg_base"
    elif [ -n "${RESTORE_LINEAGE:-}" ]; then
        case "$RESTORE_LINEAGE" in
            *[!0-9]*)
                echo "walg-env: RESTORE_LINEAGE=$RESTORE_LINEAGE is not a database system identifier" >&2
                exit 1
                ;;
        esac
        WALG_S3_PREFIX="${vc_walg_base}/${RESTORE_LINEAGE}"
    else
        vc_walg_pgdata="${PGDATA:-/var/lib/postgresql/data}"
        vc_walg_sysid="$(pg_controldata "$vc_walg_pgdata" 2>/dev/null | awk -F': *' '/Database system identifier/{print $2}')" || vc_walg_sysid=""
        case "$vc_walg_sysid" in
            "" | *[!0-9]*)
                echo "walg-env: no database system identifier in $vc_walg_pgdata" >&2
                exit 1
                ;;
        esac
        WALG_S3_PREFIX="${vc_walg_base}/${vc_walg_sysid}"
    fi
    export WALG_S3_PREFIX
    unset vc_walg_base vc_walg_pgdata vc_walg_sysid
  db-guard.sh: |
    #!/bin/sh
    # vc-reseed-protocol: 1
    # Entrypoint of the db container on both tiers: refuse to boot over an
    # interrupted restore, apply the k8s wal-g role intent, finish a pending
    # in-place standby reseed, then hand over to the image's own entrypoint
    # (db-entrypoint.sh) unchanged.
    #
    # Line 2 is the reseed protocol marker: the CLI greps it in the RUNNING pod's
    # mounted copy before it stops postgres for an in-place reseed.
    #
    # `vibecarbon restore` fetches the backup into a staging dir inside PGDATA and
    # only then swaps it in, with .vc-restore-in-progress in PGDATA for the length
    # of the swap. A boot that finds the marker would start postgres on a half
    # moved data directory, or initdb an empty one over it. So it stops and says
    # what to do; rerunning the restore settles the swap. The restore's own
    # container sets RESTORE_BACKUP and passes through.
    #
    # Invoked as `sh /usr/local/bin/db-guard.sh` (carbon/docker-compose.yml, and
    # the db StatefulSet's `command`, k8s/base/db/statefulset.yaml), so the file
    # mode of the scaffold copy or the ConfigMap mount does not matter. The k8s
    # copy is the `db-guard.sh` key of the vibecarbon-wal-archive ConfigMap
    # (k8s/base/backup/configmap-walg.yaml), byte-identical to this file
    # (tests/unit/deploy/walg-archive-script-parity.test.ts).
    set -eu

    PGDATA="${PGDATA:-/var/lib/postgresql/data}"

    if [ -z "${RESTORE_BACKUP:-}" ] && [ -e "$PGDATA/.vc-restore-in-progress" ]; then
      echo "restore interrupted; rerun vibecarbon restore" >&2
      exit 1
    fi

    # k8s wal-g role intent (ConfigMap vibecarbon-db-role, src/lib/deploy/walg-role.js).
    # Compose never sets it. Applied on every container start, so a db pod the CLI
    # could not reach comes back with the role the CLI last recorded.
    VC_ROLE_DIR="${VC_WALG_ROLE_DIR:-/var/lib/vibecarbon/role}"
    if [ -n "${VC_WALG_ROLE_INTENT:-}" ] && [ -d "$VC_ROLE_DIR" ] && [ ! -L "$VC_ROLE_DIR" ]; then
      chown 0:0 "$VC_ROLE_DIR" 2>/dev/null || true
      chmod 0755 "$VC_ROLE_DIR"
      case "$VC_WALG_ROLE_INTENT" in
        primary|standby)
          rm -f "$VC_ROLE_DIR/walg-role.tmp"
          printf '%s\n' "$VC_WALG_ROLE_INTENT" > "$VC_ROLE_DIR/walg-role.tmp"
          chmod 0644 "$VC_ROLE_DIR/walg-role.tmp"
          sync
          mv -f "$VC_ROLE_DIR/walg-role.tmp" "$VC_ROLE_DIR/walg-role"
          sync
          ;;
        *)
          echo "db-guard: VC_WALG_ROLE_INTENT is not primary or standby; removing the role file (no role: WAL is held)" >&2
          rm -f "$VC_ROLE_DIR/walg-role"
          ;;
      esac
    fi

    # Pending in-place reseed (src/lib/deploy/replication.js reseedStandbyInPlace).
    # A swap STARTS only on a standby (VC_WALG_ROLE_INTENT=standby) whose staged
    # tree proves itself and carries the ready marker's attempt id. One already
    # under way always finishes or rolls back: half way is no bootable tree.
    # Every move fails the script (never skipped), and each phase checks it left
    # nothing behind before the marker moves on, so a crash or a failed move at
    # any point leaves the old tree or the whole new one, never a mix.
    R_STAGE="$PGDATA/.vc-reseed"; R_READY="$PGDATA/.vc-reseed-ready"
    R_MARK="$PGDATA/.vc-reseed-in-progress"; R_DONE="$PGDATA/.vc-reseeded-from"; R_DISC="$PGDATA/.vc-discard"
    # A marker is replaced by rename between two syncs: every move before it is on
    # disk before it, and it is on disk before the next move.
    vc_put() { rm -f "$1.tmp"; printf '%s' "$2" > "$1.tmp"; sync; mv -f "$1.tmp" "$1"; sync; }
    vc_cluster() { find "$PGDATA" -mindepth 1 -maxdepth 1 ! -name '.vc-*'; }
    if [ -e "$R_MARK" ] || [ -e "$R_READY" ] || [ -L "$R_MARK" ] || [ -L "$R_READY" ]; then
      for f in "$R_MARK" "$R_READY" "$R_STAGE" "$R_DISC" "$PGDATA/.vc-restore.lock"; do
        if [ -L "$f" ]; then echo "db-guard: $f is a symlink; refusing" >&2; exit 1; fi
      done
      exec 9>"$PGDATA/.vc-restore.lock"
      flock -n 9 || { echo "db-guard: a restore holds $PGDATA/.vc-restore.lock; refusing" >&2; exit 75; }
      state=""
      if [ -e "$R_MARK" ]; then
        state="$(cat "$R_MARK")"
        case "$state" in
          "out "?*|"in "?*) ;;
          *) echo "db-guard: $R_MARK holds an unknown reseed state '$state'; refusing to boot (no tree is moved). The old cluster is in $PGDATA or $R_DISC: run vibecarbon restore, or move $R_DISC's entries back into $PGDATA and remove $R_MARK, $R_READY and $R_STAGE" >&2; exit 1 ;;
        esac
      fi
      if [ -z "$state" ]; then
        id="$(cat "$R_READY" 2>/dev/null || true)"
        # A staged tree carries no .vc-* but its own id: pg_basebackup copies them
        # from a source that was once a standby, and one moved in would clobber a
        # marker or wedge the move. A find that fails counts as carrying one.
        vc_extra="$(find "$R_STAGE" -mindepth 1 -maxdepth 1 -name '.vc-*' ! -name '.vc-reseed-id' 2>&1)" || vc_extra="unreadable"
        if [ "${VC_WALG_ROLE_INTENT:-}" = standby ] && [ -n "$id" ] && [ -z "$vc_extra" ] \
          && [ "$(cat "$R_STAGE/.vc-reseed-id" 2>/dev/null || true)" = "$id" ] \
          && [ -f "$R_STAGE/PG_VERSION" ] && [ -f "$R_STAGE/standby.signal" ] \
          && grep -q '^[[:space:]]*primary_conninfo' "$R_STAGE/postgresql.auto.conf" 2>/dev/null; then
          rm -rf "$R_DISC"
          vc_put "$R_MARK" "out $id"; state="out $id"
        else
          echo "db-guard: RESEED_REFUSED: no standby intent, or the staged tree does not prove itself (attempt '${id}'); booting the existing data directory" >&2
          rm -rf "$R_STAGE"; rm -f "$R_READY" "$R_READY.tmp"
        fi
      fi
      case "$state" in
        "out "*)
          id="${state#out }"
          if [ ! -f "$R_STAGE/PG_VERSION" ]; then
            if [ -d "$R_DISC" ]; then
              find "$R_DISC" -mindepth 1 -maxdepth 1 | while IFS= read -r e; do mv "$e" "$PGDATA/" || exit 1; done
              left="$(find "$R_DISC" -mindepth 1 -maxdepth 1)"
              if [ -n "$left" ]; then echo "db-guard: $R_DISC still holds entries after the roll back; refusing" >&2; exit 1; fi
              rmdir "$R_DISC"
            fi
            sync
            rm -rf "$R_STAGE"; rm -f "$R_READY" "$R_MARK"
            echo "db-guard: RESEED_ROLLED_BACK $id: staging incomplete, the previous data directory is back" >&2
            state=""
          else
            mkdir -p "$R_DISC"
            vc_cluster | while IFS= read -r e; do mv "$e" "$R_DISC/" || exit 1; done
            left="$(vc_cluster)"
            if [ -n "$left" ]; then echo "db-guard: the old cluster did not fully move to $R_DISC; refusing" >&2; exit 1; fi
            vc_put "$R_MARK" "in $id"; state="in $id"
          fi
          ;;
      esac
      case "$state" in
        "in "*)
          id="${state#in }"
          if [ -d "$R_STAGE" ]; then
            find "$R_STAGE" -mindepth 1 -maxdepth 1 ! -name '.vc-reseed-id' | while IFS= read -r e; do mv "$e" "$PGDATA/" || exit 1; done
            left="$(find "$R_STAGE" -mindepth 1 -maxdepth 1 ! -name '.vc-reseed-id')"
            if [ -n "$left" ]; then echo "db-guard: $R_STAGE did not fully move in; refusing" >&2; exit 1; fi
            rm -rf "$R_STAGE"
          fi
          if [ ! -f "$PGDATA/PG_VERSION" ]; then
            echo "db-guard: reseed $id moved in no PG_VERSION; refusing to boot. The old cluster is in $R_DISC: run vibecarbon restore, or replace what the reseed moved into $PGDATA with $R_DISC's entries and remove $R_MARK and $R_READY" >&2
            exit 1
          fi
          vc_put "$R_DONE" "$id"
          rm -f "$R_READY" "$R_MARK"
          echo "db-guard: RESEED_SWAPPED $id" >&2
          ;;
      esac
      exec 9>&-
    else
      # A stage cut between its marker write and the rename leaves only the
      # temp file: no marker, so nothing to swap. It goes as garbage.
      rm -f "$R_READY.tmp"
    fi

    exec db-entrypoint.sh "$@"
