#!/usr/bin/env bash
# onx-mariadb-slave-status — Slave replication durumunu sorgula
# Input:  {}
# Output: {"slave_io_running":"Yes","slave_sql_running":"Yes","seconds_behind_master":0,
#           "last_io_error":"","last_sql_error":""}

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/_lib/common.sh"

require_root
require_cmd mysql
onx_json_input

onx_log "mariadb-slave-status: sorgu"

SLAVE_STATUS=$(mysql -e "SHOW SLAVE STATUS\G" 2>/dev/null) \
    || onx_die 3 "SHOW SLAVE STATUS basarisiz"

IO_RUNNING=$(echo "$SLAVE_STATUS"  | grep 'Slave_IO_Running:'      | awk '{print $2}')
SQL_RUNNING=$(echo "$SLAVE_STATUS" | grep 'Slave_SQL_Running:'     | awk '{print $2}')
LAG=$(echo "$SLAVE_STATUS"         | grep 'Seconds_Behind_Master:' | awk '{print $2}')
IO_ERROR=$(echo "$SLAVE_STATUS"    | grep 'Last_IO_Error:'         | sed 's/.*Last_IO_Error: //')
SQL_ERROR=$(echo "$SLAVE_STATUS"   | grep 'Last_SQL_Error:'        | sed 's/.*Last_SQL_Error: //')

LAG="${LAG:-0}"
[[ "$LAG" == "NULL" ]] && LAG=0

IO_RUNNING_JSON=$(printf '%s' "${IO_RUNNING:-No}"   | jq -Rs '.')
SQL_RUNNING_JSON=$(printf '%s' "${SQL_RUNNING:-No}" | jq -Rs '.')
IO_ERROR_JSON=$(printf '%s' "${IO_ERROR:-}"         | jq -Rs '.')
SQL_ERROR_JSON=$(printf '%s' "${SQL_ERROR:-}"       | jq -Rs '.')

json_ok "{\"slave_io_running\":${IO_RUNNING_JSON},\"slave_sql_running\":${SQL_RUNNING_JSON},\"seconds_behind_master\":${LAG},\"last_io_error\":${IO_ERROR_JSON},\"last_sql_error\":${SQL_ERROR_JSON}}"
