#!/bin/bash
# _lib_local.sh — admin_machine_spec.php 共享函式（tools host 端）
#
# 提供：
#   - SSH center 觸發 spec_runner.py
#   - psql 寫 spec_apply_audit / spec_apply_lock
#   - target → env_code（n1-jp/n1-en/n1-tw）對應

CENTER_USER="${CENTER_USER:-xvincent_tu}"
CENTER_HOST="${CENTER_HOST:-10.150.10.251}"
CENTER_BASE="/home/${CENTER_USER}/center"
SPEC_RUNNER="${CENTER_BASE}/cloud_orchestrator/spec_runner.py"

SPEC_SSH_OPTS=(
    -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new
    -o ServerAliveInterval=30
)

# ── DB helpers（讀環境變數 SPEC_DB_*）──────────────────────────────────────────

_spec_psql() {
    local sql="$1"; shift
    PGPASSWORD="${SPEC_DB_PASS}" psql -h "${SPEC_DB_IP}" -U "${SPEC_DB_USER}" -d "${SPEC_DB_NAME}" \
        -AtX -v ON_ERROR_STOP=1 -c "$sql" "$@" 2>/dev/null
}

# 一次寫多個欄位的 audit UPDATE（呼叫者組好 SET 子句）
spec_audit_update() {
    local batch_id="$1" set_clause="$2"
    [[ -z "$batch_id" || -z "$set_clause" ]] && return 1
    _spec_psql "UPDATE public.spec_apply_audit SET ${set_clause} WHERE batch_id = '${batch_id}'"
}

# ── target → env_code 推算 ────────────────────────────────────────────────────
# 規則（先用 prefix 判，未來可改成查 hosts 檔）：
#   n1-jp-* → n1-jp
#   n1-en-* → n1-en
#   n1-tw-* → n1-tw
spec_target_to_env() {
    local target="$1"
    case "$target" in
        n1-jp-*) echo "n1-jp" ;;
        n1-en-*) echo "n1-en" ;;
        n1-tw-*) echo "n1-tw" ;;
        *) echo "" ;;
    esac
}

# ── 跑 spec_runner.py（前景，stdout 直出給 caller tee log）─────────────────────
# 用法: spec_run_remote ARGS...
# ARGS 直接傳給 spec_runner.py
spec_run_remote() {
    ssh "${SPEC_SSH_OPTS[@]}" "${CENTER_USER}@${CENTER_HOST}" \
        "${SPEC_RUNNER}" "$@"
}
