#!/bin/bash

BINLOG_PREFIX1=/sys/module/binlogdev
BINLOG_PREFIX2=/sys/module/binlogdev/holders/cachedev

#grep -q "^1" /sys/module/binlogdev/version
#if [[ $? -eq 0 ]];then
#    BINLOG_PREFIX=$BINLOG_PREFIX1
#else
#    BINLOG_PREFIX=$BINLOG_PREFIX2
#fi
BINLOG_PREFIX=$BINLOG_PREFIX2


find_file() {
    BINLOG_STAT_PATH=`ls $1/[0-9]*_[0-9]*/stat`
}

binlog_get_stat() {
    find_file "$BINLOG_PREFIX"

    if [ -z $BINLOG_STAT_PATH ]; then
        return
    fi

    OLD_IFS="$IFS"
    IFS=$'\x0A'
    for context in `cat $BINLOG_STAT_PATH`
    do
        echo $context | grep -q "valid_version:"
        if [ $? -eq 0 ]; then
            binlog_valid_version=`echo $context | awk '{print $2}'`
            continue
        fi

        echo $context | grep -q "next_free_version:"
        if [ $? -eq 0 ]; then
            binlog_next_free_version=`echo $context | awk '{print $2}'`
            continue
        fi
    done
    IFS=$OLD_IFS
}

binlog_init() {
    binlog_valid_version=0
    binlog_next_free_version=0
    binlog_used_block=0
}

binlog_show_stat() {
    status='[{"value":'$binlog_used_block', "tags":"stat_path='$BINLOG_STAT_PATH'"}]'
    echo -n "$status"
}

binlog_calc_blocks() {
    binlog_get_stat

    unit=4
    binlog_used_block=`expr $binlog_next_free_version - $binlog_valid_version`
    binlog_used_block=`expr $binlog_used_block \* $unit`

    binlog_show_stat
}

binlog_start() {
    binlog_init
    binlog_calc_blocks
}

binlog_start $@
