#!/usr/bin/env bash
# ============================================================
# HalaVoice ops — shared helpers
# Sourced by backup.sh / git-sync.sh / restore.sh / setup-modules.sh
# ============================================================
set -euo pipefail

# Repo root = parent of the ops/ directory that holds this file
OPS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$OPS_DIR/.." && pwd)"
BACKUP_ROOT="$REPO_ROOT/backups"

log()  { echo -e "\033[1;36m[ops]\033[0m $*"; }
ok()   { echo -e "\033[1;32m[ ok ]\033[0m $*"; }
warn() { echo -e "\033[1;33m[warn]\033[0m $*" >&2; }
die()  { echo -e "\033[1;31m[FAIL]\033[0m $*" >&2; exit 1; }

# Read a KEY from the .env file without sourcing it (values may contain
# characters that break `source`). Prints the raw value.
env_get() {
  local key="$1" file="${2:-$REPO_ROOT/.env}"
  [ -f "$file" ] || return 1
  grep -E "^${key}=" "$file" | head -1 | cut -d= -f2- | sed -e 's/^"//' -e 's/"$//'
}

db_url() {
  local url
  url="$(env_get DATABASE_URL || true)"
  [ -n "$url" ] || die "DATABASE_URL not found in $REPO_ROOT/.env"
  echo "$url"
}

need() { command -v "$1" >/dev/null 2>&1 || die "required command not found: $1"; }
