#!/bin/bash

set -o errexit
set -o nounset

#INSTANCE
#PUSHGATEWAY_URL=
#REPOSITORY=

counter=0
for archive in $(borg list "$REPOSITORY" |awk '{print $1}'); do
    counter=$((counter+1))
done

borg_info="$(borg info "$REPOSITORY::$archive")"

function calc_bytes {
    num="$1"
    unit="$2"

    case "$unit" in
        kB)
            echo "$num" | awk '{ print $1 * 1024 }'
            ;;
        MB)
            echo "$num" | awk '{ print $1 * 1024 * 1024 }'
            ;;
        GB)
            echo "$num" | awk '{ print $1 * 1024 * 1024 * 1024 }'
            ;;
        TB)
            echo "$num" | awk '{ print $1 * 1024 * 1024 * 1024 * 1024 }'
            ;;
    esac
}

last_size="$(calc_bytes $(echo "$borg_info" | grep "This archive" | awk '{print $3 " " $4 }'))"
last_size_compressed="$(calc_bytes $(echo "$borg_info" | grep "This archive" | awk '{print $5 " " $6 }'))"
last_size_dedup="$(calc_bytes $(echo "$borg_info" | grep "This archive" | awk '{print $7 " " $8 }'))"

total_size="$(calc_bytes $(echo "$borg_info" | grep "All archives" | awk '{print $3 " " $4 }'))"
total_size_compressed="$(calc_bytes $(echo "$borg_info" | grep "All archives" | awk '{print $5 " " $6 }'))"
total_size_dedup="$(calc_bytes $(echo "$borg_info" | grep "All archives" | awk '{print $7 " " $8 }'))"

curl --data-binary @- \
     --silent \
     --show-error \
     "$PUSHGATEWAY_URL/metrics/job/borgbackup/machine/$MACHINE" <<EOF
backup_count $counter
backup_files $(echo "$borg_info" | grep "Number of files" | awk '{print $4}')
backup_chunks_unique $(echo "$borg_info" | grep "Chunk index" | awk '{print $3}')
backup_chunks_total $(echo "$borg_info" | grep "Chunk index" | awk '{print $4}')
backup_last_size $last_size
backup_last_size_compressed $last_size_compressed
backup_last_size_dedup $last_size_dedup
backup_total_size $total_size
backup_total_size_compressed $total_size_compressed
backup_total_size_dedup $total_size_dedup
EOF
