#!/bin/bash
set -euo pipefail

CONFIG_FILE="$1"

LOKI_HOST=host

MQTT_BROKER=host
MQTT_TOPIC="borgmatic/stats/$CONFIG_FILE"
MQTT_USER="borgmatic"
MQTT_PASSWORD="eH2dAiG7siCIFdB7qX0MHwEFzcr9aqUi"

# Run Borgmatic and extract archive stats as JSON
ARCHIVE_JSON=$(borgmatic \
    --stats \
    -v 0 \
    -c "/config/$CONFIG_FILE.yaml" \
    --log-json \
    --no-color \
    --json \
    | tail -n1 \
    | jq '.[0].archive'
)
echo $ARCHIVE_JSON

echo "----- ARCHIVE_JSON"
echo $ARCHIVE_JSON
echo "-----"

# Publish to MQTT
mosquitto_pub -h "$MQTT_BROKER" \
               -t "$MQTT_TOPIC" \
               -u "$MQTT_USER" \
               -P "$MQTT_PASSWORD" \
               -m "$ARCHIVE_JSON"

# Build Loki payload
LOKI_PAYLOAD=$(jq -n \
  --arg config "$CONFIG_FILE" \
  --argjson archive "$ARCHIVE_JSON" \
  --arg now "$(date +%s%N)" \
  '{streams: [
      {
        stream: {job: "borgmatic", config: $config},
        values: [[$now, ($archive | tostring)]]
      }
    ]}')

echo "----- LOKI_PAYLOAD"
echo $LOKI_PAYLOAD
echo "-----"

# Send to Loki
curl -s -X POST "http://$LOKI_HOST:3100/loki/api/v1/push" \
  -H "Content-Type: application/json" \
  -d "$LOKI_PAYLOAD"
