#!/usr/bin/env bash
set -euo pipefail

if [ "$(id -u)" -ne 0 ]; then
  echo "Run nucleus-server-backup with sudo." >&2
  exit 1
fi
for command_name in psql tar; do
  if ! command -v "$command_name" >/dev/null 2>&1; then
    echo "Required backup command is missing: $command_name" >&2
    exit 1
  fi
done

env_file="/etc/nucleus/nucleus.env"
password_file="/etc/nucleus/db-password"
if [ ! -r "$env_file" ] || [ ! -r "$password_file" ]; then
  echo "Nucleus database configuration is incomplete." >&2
  exit 1
fi

read_setting() {
  key="$1"
  fallback="$2"
  value=$(sed -n "s/^${key}=//p" "$env_file" | tail -1)
  if [ -z "$value" ]; then
    value="$fallback"
  fi
  printf '%s' "$value"
}

database_host=$(read_setting NUCLEUS_DB_HOST 127.0.0.1)
database_port=$(read_setting NUCLEUS_DB_PORT 5432)
database_user=$(read_setting NUCLEUS_DB_USER nucleus)
database_name=$(read_setting NUCLEUS_DB_NAME nucleus)
backup_root="/var/lib/nucleus/backups"
timestamp=$(date -u +%Y%m%dT%H%M%SZ)
created_at=$(date -u +%Y-%m-%dT%H:%M:%SZ)
prefix="$backup_root/nucleus-$timestamp"
database_dump="$prefix.database.dump"
files_archive="$prefix.files.tar.gz"
evidence="$prefix.evidence.json"
restore_database="nucleus_restore_check_${timestamp%%Z}"
pgpass="$backup_root/.pgpass.$$"

install -d -o nucleus -g nucleus -m 0750 "$backup_root"
umask 077
escaped_password=$(sed 's/\\/\\\\/g; s/:/\\:/g' "$password_file")
printf '%s:%s:*:%s:%s\n' \
  "$database_host" \
  "$database_port" \
  "$database_user" \
  "$escaped_password" > "$pgpass"
chmod 0600 "$pgpass"
unset escaped_password
trap 'rm -f "$pgpass"' EXIT
export PGPASSFILE="$pgpass"

server_version_num=$(
  psql \
    --host "$database_host" \
    --port "$database_port" \
    --username "$database_user" \
    --dbname "$database_name" \
    --tuples-only \
    --no-align \
    --command "SHOW server_version_num"
)
if ! printf '%s\n' "$server_version_num" | grep -Eq '^[0-9]{6}$'; then
  echo "Could not determine the PostgreSQL server major version." >&2
  exit 1
fi
server_major=$((server_version_num / 10000))

pg_dump_bin=""
for candidate in \
  "/usr/pgsql-$server_major/bin/pg_dump" \
  "/usr/lib/postgresql/$server_major/bin/pg_dump"; do
  if [ -x "$candidate" ]; then
    pg_dump_bin="$candidate"
    break
  fi
done
if [ -z "$pg_dump_bin" ]; then
  pg_dump_bin=$(command -v pg_dump || true)
fi
if [ -z "$pg_dump_bin" ]; then
  echo "PostgreSQL $server_major client tools are required for backup and restore verification." >&2
  echo "Install the client package matching the database server major version." >&2
  exit 1
fi
client_major=$(
  "$pg_dump_bin" --version |
    sed -nE 's/.* ([0-9]+)(\.[0-9]+)*.*/\1/p'
)
if ! printf '%s\n' "$client_major" | grep -Eq '^[0-9]+$' ||
  [ "$client_major" -lt "$server_major" ]; then
  echo "PostgreSQL server $server_major cannot be backed up with pg_dump ${client_major:-unknown}." >&2
  echo "Install PostgreSQL $server_major client tools and retry nucleus-server-backup." >&2
  exit 1
fi
postgres_tool_dir=$(dirname "$pg_dump_bin")
for command_name in createdb pg_restore dropdb; do
  if [ ! -x "$postgres_tool_dir/$command_name" ]; then
    echo "The selected PostgreSQL $client_major client toolchain is incomplete: $command_name is missing." >&2
    exit 1
  fi
done

echo "Creating PostgreSQL backup."
"$pg_dump_bin" \
  --host "$database_host" \
  --port "$database_port" \
  --username "$database_user" \
  --dbname "$database_name" \
  --format custom \
  --file "$database_dump"
chmod 0600 "$database_dump"

echo "Verifying the database backup with a temporary restore."
"$postgres_tool_dir/createdb" \
  --host "$database_host" \
  --port "$database_port" \
  --username "$database_user" \
  "$restore_database"
restore_status=0
if ! "$postgres_tool_dir/pg_restore" \
  --host "$database_host" \
  --port "$database_port" \
  --username "$database_user" \
  --dbname "$restore_database" \
  --exit-on-error \
  "$database_dump"; then
  restore_status=1
fi
"$postgres_tool_dir/dropdb" \
  --host "$database_host" \
  --port "$database_port" \
  --username "$database_user" \
  --if-exists \
  "$restore_database"
if [ "$restore_status" -ne 0 ]; then
  echo "The database restore check failed. Update preflight remains blocked." >&2
  exit 1
fi

echo "Archiving Nucleus configuration, runtime key, and storage."
tar -czf "$files_archive" \
  /etc/nucleus/nucleus.env \
  /etc/nucleus/db-password \
  /var/lib/nucleus/runtime \
  /var/lib/nucleus/storage
chmod 0600 "$files_archive"
tar -tzf "$files_archive" >/dev/null
restore_tested_at=$(date -u +%Y-%m-%dT%H:%M:%SZ)

printf '%s\n' \
  "{\"createdAt\":\"$created_at\",\"database\":true,\"storage\":true,\"config\":true,\"restoreTestedAt\":\"$restore_tested_at\"}" \
  > "$evidence"
chmod 0600 "$evidence"
chown nucleus:nucleus "$database_dump" "$files_archive" "$evidence"

echo "Backup and restore check completed."
echo "Evidence: $evidence"
