#!/usr/bin/env bash
# app 컨테이너 안에서 실행한다. 0.2초마다 한 건씩 INSERT 하고 성공/실패와 접속한 노드를 기록한다.
# 사용: docker compose exec -T app bash /lab/scripts/writer.sh <초>
# 출력: 시작 시각(컨테이너 UTC), ok/FAIL, 소요 ms, 접속한 서버 주소 또는 마지막 오류 줄
# 접속 URI 는 monitor 에서 pg_autoctl show uri --formation default 로 얻는다.
set -uo pipefail
dur="${1:-60}"
uri=$(pg_autoctl show uri --formation default --monitor "$PG_AUTOCTL_MONITOR")
uri="${uri}&connect_timeout=2"
psql "$uri" -qc "create table if not exists ticks(id bigserial primary key, ts timestamptz default clock_timestamp(), src text)" >/dev/null 2>&1
end=$(( $(date +%s) + dur ))
while [ "$(date +%s)" -lt "$end" ]; do
  t=$(date +%T.%3N); s0=$(date +%s%3N)
  if out=$(psql "$uri" -Atqc "insert into ticks(src) values (inet_server_addr()::text) returning src" 2>&1); then
    echo "$t ok   $(( $(date +%s%3N) - s0 ))ms $out"
  else
    echo "$t FAIL $(( $(date +%s%3N) - s0 ))ms $(echo "$out" | tail -1)"
  fi
  sleep 0.2
done
