#!/usr/bin/env bash
#
# bedrock_server.sh — Minecraft BDS telemetry agent launcher
#
# Replaces the stock server start command. Starts the renamed original server,
# filters player connect/disconnect lines in real time, buffers the raw lines
# in RAM, and batches them to the platform backend every 300s or every 50
# lines. Network traffic goes exclusively through the static ./curl-amd64
# binary (no dynamic-linker fallback), per spec_agent.md.
#
# Environment: API_URL, X_AGENT_TOKEN, SERVER_ID

export API_URL="https://api.lynal.ru"
export X_AGENT_TOKEN=""
export SERVER_ID=""

set -u

# ---------------------------------------------------------------------------
# Paths / limits
# ---------------------------------------------------------------------------
DEBUG_LOG="agent_debug.log"
RETRY_CACHE="agent_retry_cache.json"
SEND_LOCK="agent_send.lock"

DEBUG_LOG_LIMIT=$((5 * 1024 * 1024))     # 5 MB
RETRY_CACHE_LIMIT=$((10 * 1024 * 1024))  # 10 MB
POLL_SECONDS=10
BATCH_INTERVAL=300
BATCH_MAX_LINES=50

# ---------------------------------------------------------------------------
# Required environment
# ---------------------------------------------------------------------------
for v in API_URL X_AGENT_TOKEN SERVER_ID; do
    if [ -z "${!v:-}" ]; then
        echo "FATAL: environment variable $v is not set" >&2
        exit 1
    fi
done

# ---------------------------------------------------------------------------
# Debug log (hard 5MB cap, truncate once exceeded)
# ---------------------------------------------------------------------------
debug_log() {
    local msg=$1 size
    printf '[%s] %s\n' "$(date '+%F %T')" "$msg" >> "$DEBUG_LOG" 2>/dev/null || return 0
    size=$(stat -c%s "$DEBUG_LOG" 2>/dev/null || echo 0)
    if [ "$size" -gt "$DEBUG_LOG_LIMIT" ]; then
        : > "$DEBUG_LOG"
    fi
}

# ---------------------------------------------------------------------------
# curl bootstrap — binary only, no dynamic-linker fallback (spec 2.2, task 2)
# ---------------------------------------------------------------------------
agent_curl() { return 1; }  # placeholder; replaced below

setup_curl() {
    if [ ! -f "./curl-amd64" ]; then
        echo "FATAL: ./curl-amd64 not found (upload the static binary)" >&2
        exit 1
    fi
    chmod +x ./curl-amd64 2>>"$DEBUG_LOG" || debug_log "chmod +x failed on curl-amd64"

    # Scenario 1: direct execution works -> use it.
    # Dynamic-linker fallback is intentionally NOT used (per task requirement).
    if ./curl-amd64 --version >/dev/null 2>>"$DEBUG_LOG"; then
        agent_curl() { ./curl-amd64 "$@"; }
        return 0
    fi

    echo "FATAL: ./curl-amd64 is not executable and dynamic-linker fallback is disabled" >&2
    exit 1
}
setup_curl

# ---------------------------------------------------------------------------
# JSON string escaping (minimal; line content is preserved, not parsed)
# ---------------------------------------------------------------------------
json_escape() {
    local s=$1
    s=${s//\\/\\\\}
    s=${s//\"/\\\"}
    s=${s//$'\r'/\\r}
    s=${s//$'\n'/\\n}
    s=${s//$'\t'/\\t}
    # strip any remaining C0 control chars so the payload stays valid JSON
    s=$(printf '%s' "$s" | LC_ALL=C tr -d '\001-\010\013-\037')
    printf '%s' "$s"
}

# ---------------------------------------------------------------------------
# Retry cache (FIFO, hard 10MB cap)
# ---------------------------------------------------------------------------
append_to_cache() {
    local line escaped
    for line in "$@"; do
        escaped=$(json_escape "$line")
        printf '"%s"\n' "$escaped" >> "$RETRY_CACHE"
    done
    trim_retry_cache
}

trim_retry_cache() {
    [ -f "$RETRY_CACHE" ] || return 0
    local size guard=0
    size=$(stat -c%s "$RETRY_CACHE" 2>/dev/null || echo 0)
    # drop oldest line(s) until under the cap
    while [ "$size" -gt "$RETRY_CACHE_LIMIT" ] && [ "$guard" -lt 2000 ]; do
        tail -n +2 "$RETRY_CACHE" > "$RETRY_CACHE.tmp" 2>/dev/null \
            && mv "$RETRY_CACHE.tmp" "$RETRY_CACHE"
        size=$(stat -c%s "$RETRY_CACHE" 2>/dev/null || echo 0)
        guard=$((guard + 1))
    done
}

# ---------------------------------------------------------------------------
# Send one batch (merge retry cache + new lines) in JSON array form
# ---------------------------------------------------------------------------
send_batch() {
    local -a lines=("$@")
    local payload='[' first=1 line escaped cl http_code rc

    # oldest first: retry cache literals (already escaped, stored one per line)
    if [ -s "$RETRY_CACHE" ]; then
        while IFS= read -r cl; do
            [ -n "$cl" ] || continue
            if [ "$first" -eq 1 ]; then first=0; else payload+=','; fi
            payload+="$cl"
        done < "$RETRY_CACHE"
    fi

    for line in "${lines[@]}"; do
        escaped=$(json_escape "$line")
        if [ "$first" -eq 1 ]; then first=0; else payload+=','; fi
        payload+="\"$escaped\""
    done
    payload+=']'

    http_code=$(agent_curl -sS --connect-timeout 10 --max-time 30 \
        -o /dev/null -w '%{http_code}' \
        -X POST \
        -H "X-Agent-Token: $X_AGENT_TOKEN" \
        -H "Content-Type: application/json" \
        -d "$payload" \
        "$API_URL/api/v1/agent/telemetry" 2>>"$DEBUG_LOG")
    rc=$?

    if [ "$rc" -eq 0 ] && [ "$http_code" = "200" ]; then
        : > "$RETRY_CACHE"   # delivered
    else
        debug_log "telemetry send failed (rc=$rc http=${http_code:-none}); queued to retry cache"
        append_to_cache "${lines[@]}"
    fi
}

# ---------------------------------------------------------------------------
# Send lock: serializes sends so only one POST is in flight at a time.
# Prevents overlapping curl calls and concurrent retry-cache writes.
# ---------------------------------------------------------------------------
acquire_send_lock() {
    local guard=0
    while [ -f "$SEND_LOCK" ] && kill -0 "$(cat "$SEND_LOCK")" 2>/dev/null && [ "$guard" -lt 3000 ]; do
        sleep 0.05
        guard=$((guard + 1))
    done
    echo $$ > "$SEND_LOCK"
}

# ---------------------------------------------------------------------------
# Flush current RAM buffer (async, background; serialized via send lock)
# ---------------------------------------------------------------------------
flush_buffer() {
    if [ "$BUFFER_COUNT" -eq 0 ] && [ ! -s "$RETRY_CACHE" ]; then
        return 0
    fi

    local -a snapshot=("${BUFFER_ARRAY[@]}")
    BUFFER_ARRAY=()
    BUFFER_COUNT=0
    BUFFER_START=0
    CACHE_LAST_FLUSH_TS=$(date +%s)

    (
        acquire_send_lock
        trap 'rm -f "$SEND_LOCK"' EXIT
        send_batch "${snapshot[@]}"
    ) &
    SEND_PIDS+=("$!")
}

# ---------------------------------------------------------------------------
# Final synchronous flush for EXIT/SIGTERM (best effort, durable via cache)
# ---------------------------------------------------------------------------
final_flush() {
    [ "$FLUSHED_ON_EXIT" -eq 1 ] && return 0
    FLUSHED_ON_EXIT=1
    # wait for any in-flight background sends so no batch is lost on exit
    wait "${SEND_PIDS[@]}" 2>/dev/null
    SEND_PIDS=()
    acquire_send_lock
    if [ "$BUFFER_COUNT" -gt 0 ] || [ -s "$RETRY_CACHE" ]; then
        local -a snapshot=("${BUFFER_ARRAY[@]}")
        BUFFER_ARRAY=()
        BUFFER_COUNT=0
        send_batch "${snapshot[@]}"
    fi
    rm -f "$SEND_LOCK"
}

trap 'final_flush; exit 0' EXIT
trap 'final_flush; exit 0' TERM INT

# ---------------------------------------------------------------------------
# State
# ---------------------------------------------------------------------------
BUFFER_ARRAY=()
BUFFER_COUNT=0
BUFFER_START=0
CACHE_LAST_FLUSH_TS=0
FLUSHED_ON_EXIT=0
SEND_PIDS=()

# ---------------------------------------------------------------------------
# Main pipeline: original server -> line-buffered grep -> processing loop
# (process substitution keeps the loop in this shell so buffer/traps are shared)
# ---------------------------------------------------------------------------
while true; do
    if IFS= read -r -t "$POLL_SECONDS" line; then
        BUFFER_ARRAY+=("$line")
        if [ "$BUFFER_COUNT" -eq 0 ]; then
            BUFFER_START=$(date +%s)
        fi
        BUFFER_COUNT=$((BUFFER_COUNT + 1))
    else
        rc=$?
        if [ "$rc" -le 128 ]; then
            break   # EOF: server/grep closed
        fi
        # read timeout: fall through to periodic checks
    fi

    now=$(date +%s)
    if [ "$BUFFER_COUNT" -ge "$BATCH_MAX_LINES" ] \
        || { [ "$BUFFER_COUNT" -gt 0 ] && [ $((now - BUFFER_START)) -ge "$BATCH_INTERVAL" ]; }; then
        flush_buffer
    elif [ -s "$RETRY_CACHE" ] && [ $((now - CACHE_LAST_FLUSH_TS)) -ge "$BATCH_INTERVAL" ]; then
        flush_buffer   # retry pending cache even without new lines
    fi
done < <(./bedrock_server_original 2>&1 | grep --line-buffered -E 'Player connected|Player disconnected')
