#!/usr/bin/env bash set -Eeuo pipefail die() { printf 'ERROR: %s\n' "$*" >&2 exit 1 } require_tools() { local tool for tool in "$@"; do command -v "$tool" >/dev/null || die "$tool is required" done } validate_postgresql_version() { local version="$1" [[ "$version" =~ ^[0-9]+\.[0-9]+([.][0-9]+)?$ ]] || die "invalid PostgreSQL version: $version" } latest_tag() { local repository="$1" local tag tag="$( curl -fsSL "https://api.github.com/repos/$repository/releases/latest" | sed -nE 's/^[[:space:]]*"tag_name":[[:space:]]*"([^"]+)".*/\1/p' | head -n 1 || true )" if [[ -n "$tag" ]]; then printf '%s\n' "$tag" return fi curl -fsSL "https://api.github.com/repos/$repository/tags?per_page=1" | sed -nE 's/^[[:space:]]*"name":[[:space:]]*"([^"]+)".*/\1/p' | head -n 1 || true } latest_pgaudit_tag() { local repository="$1" local major="$2" local tag tag="$( curl -fsSL "https://api.github.com/repos/$repository/tags?per_page=100" | sed -nE 's/^[[:space:]]*"name":[[:space:]]*"([^"]+)".*/\1/p' | grep -E "^${major//./\\.}\." | head -n 1 || true )" printf '%s\n' "${tag:-$(latest_tag "$repository")}" } reset_staging_dir() { local staging_dir="$1" [[ "$staging_dir" != "/" ]] || die "STAGING_DIR must not be the filesystem root" rm -rf -- "$staging_dir" mkdir -p "$staging_dir" } require_postgresql_installation() { local prefix="$1" local pg_config="$prefix/bin/pg_config" [[ "$prefix" != "/" ]] || die "PREFIX must not be the filesystem root" [[ -x "$pg_config" ]] || die "PostgreSQL is not installed at $prefix" } download_source() { local staging_dir="$1" local repository="$2" local tag="$3" local archive_name="$4" local source_dir="$5" local archive="$staging_dir/$archive_name" curl -fL --retry 3 --retry-delay 2 \ -o "$archive" \ "https://github.com/$repository/archive/refs/tags/$tag.tar.gz" tar -xzf "$archive" -C "$staging_dir" [[ -d "$source_dir" ]] || die "source directory was not created: $source_dir" }