#!/usr/bin/env bash
set -e

script=$(basename "$0")
version="1.3.0"

help() {
    echo
    echo "$script v$version"
    echo
    echo 'Description: Backup PostgreSQL database in Kubernetes cluster.'
    echo "Syntax: $script <pod> <database> <path>"
    echo "Example: $script postgres mydb ./tmp/mydb.sql"
    echo "         $script postgres mydb ./tmp/"
    echo 'Options:'
    echo "  help  Show $script manual."
    echo
}

if [[ "$1" == 'help' ]]; then
    help
    exit 0
fi

pod="$1"
database="$2"
path="$3"

[[ -z "$pod" ]] && { echo 'Error: Parameter pod is empty'; exit 1; }
[[ -z "$database" ]] && { echo 'Error: Parameter database is empty'; exit 1; }
[[ -z "$path" ]] && { echo 'Error: Parameter path is empty'; exit 1; }

if [[ -d "$path" ]]; then
    path="${path%/}/${database}.sql"
fi

echo "Search for pod matching name '$pod'"
matches=$(kubectl get pods --no-headers -o custom-columns=':metadata.name' | grep -F "$pod" || true)
match_count=$(echo "$matches" | grep -c . || true)

if [[ "$match_count" -eq 0 ]]; then
    echo "Error: No pod found matching '$pod'"
    exit 1
elif [[ "$match_count" -gt 1 ]]; then
    echo "Error: Multiple pods found matching '$pod':"
    echo "$matches"
    exit 1
fi

pod_id="$matches"

echo "Found pod: $pod_id"

output_dir=$(dirname "$path")
if [[ ! -d "$output_dir" ]]; then
    mkdir -p "$output_dir"
fi

echo "Stream database $database dump to $path"
kubectl exec "$pod_id" -- pg_dump "$database" > "$path"

echo "The PostgreSQL database backup has finished: $path"
