#!/usr/bin/env bash

export NO_COLOR=1

# Optional --testnet flag propagates to all lightning-cli commands.
LIGHTNING_CLI="lightning-cli"
if [[ "$1" == "--testnet" ]]; then
  LIGHTNING_CLI="lightning-cli --testnet"
  shift
fi

# Use w/ https://github.com/ksedgwic/privdm to send as nostr private DM, eg:
# 0 * * * * /usr/local/src/clboss/contrib/sys_stats_report | /usr/local/bin/privdm --from <YOUR_SERVER_PRIVKEY_FILE> --to <TARGET_PUBKEY_HEX> --via wss://your.relay.host

echo '```'

uptime

df -kh /mnt/md0 2>/dev/null | tail -n1

for svc in cln-mainnet; do
  systemctl --no-pager --plain status "$svc" | awk 'NR==3'
done

START=$(date -d '1 hour ago' +%H:%M:%S)
sar -W -s "$START" | awk '/Average/ { printf "pswpin/s:  %s, pswpout/s: %s\n", $2, $3 }'

EARNINGS=$(/usr/local/src/clboss/contrib/clboss-earnings-history 2>/dev/null)
echo "$EARNINGS" | head -n2 | tail -n1
echo "$EARNINGS" | tail -n4 | head -n1

# --- baseline checksum in msat ---
#
# The purpose of the baseline checksum is to check that changes in
# (utxo_amount + avail_out) match the Net Earnings calculation.  The
# computed value for the beginning of the bucket should remain
# constant all day long.  It will change if there are payments, deposists,
# or problems in the net earnings calculation.

# —– summars once, up‐front
SUMMARY=$($LIGHTNING_CLI summars)

# print just those two lines
echo "$SUMMARY" | egrep '(avail_out|utxo_amount)'

# parse BTC values from the same output
read -r utxo_btc avail_btc < <(
  echo "$SUMMARY" | awk -F'[ =]' '
    /utxo_amount/ {u=$2}
    /avail_out/  {a=$2}
    END {print u, a}
  '
)

# convert and compute baseline
utxo_msat=$(awk "BEGIN{printf \"%0.0f\", $utxo_btc*1e11}")
avail_msat=$(awk "BEGIN{printf \"%0.0f\", $avail_btc*1e11}")
current_msat=$((utxo_msat + avail_msat))

# compute net_msat from the earnings table
net_msat=$(
  echo "$EARNINGS" \
    | tail -n4 | head -n1 \
    | awk -F'|' '{
        x=$(NF-1);
        gsub(/[^0-9-]/, "", x);
        print x
      }'
)

# compute baseline
baseline_msat=$(( current_msat - net_msat ))
formatted=$(echo "$baseline_msat" \
  | rev \
  | sed 's/\([0-9]\{3\}\)/\1_/g; s/_$//' \
  | rev
)
printf "Our balance at start of bucket: %s msat\n" "$formatted"

# current feerate
read -r h2l mid l2h last judge < <(
    $LIGHTNING_CLI clboss-feerates 2>/dev/null |
        jq -r '[(.hi_to_lo // -1 | floor), (.init_mid // -1 | floor), (.lo_to_hi // -1 | floor), (.last_feerate_perkw // -1 | floor), (.judgment // "unknown")] | join(" ")'
)
echo "feerates:" "$h2l" "$mid" "$l2h" "$last" "$judge"

# --- end baseline ---

# ---- optional stats collection ---------------------------------------------
if [[ -n "$STATSFILE" ]]; then
  # helper – 1 234 567 890  →  1_234_567_890   (keeps any leading “‑” sign)
  fmt() {
    local n=$1 sign=
    [[ $n == -* ]] && { sign="-"; n=${n#-}; }
    printf '%s%s\n' "$sign" "$(rev <<<"$n" | sed 's/\([0-9]\{3\}\)/\1_/g; s/_$//' | rev)"
  }

  ts="$(date '+%Y-%m-%d %H:%M:%S')"          # local‑time timestamp

  printf '%s %s %s %s (%s, %s, %s): %s: %s fee\n' \
         "$ts" \
         "$(fmt "$utxo_msat")" \
         "$(fmt "$avail_msat")" \
         "$(fmt "$current_msat")" \
         "$h2l" "$mid" "$l2h" "$last" "$judge" >> "$STATSFILE"
fi
# -----------------------------------------------------------------------------

echo '```'
