#!/usr/bin/env bash
# This script assumes that the keys used by publishers
# corresponds to the UNIQUE hostname of each monitored node

# Check parameters
[ $# -ne 3 ] && { echo "Usage: $0 <key> <from> <to>"; exit 1; }

# Load parameters
key=$1
from=$2
to=$3

# Load configuration
wai=$(dirname $(readlink -f "$0")) # Current script directory
source ${wai}/config.mk
source ${wai}/.clusterman.sh.conf

# Compute intervals
ifrom=$(echo $from $LOG_INTERVAL | awk '{print($1-($1%$2))}')
ito=$(echo $to $LOG_INTERVAL | awk '{print($1-($1%$2))}')

# Search for power measurements
nfolder=$(readlink -f ${wai}/${SUBSCRIBER_DIR}/${nodes[$key]}/) # Node Folder
[ ! -d "$nfolder" ] && { echo "Node \"$key\" has not power measurements."; exit 2; }
# Set from file and to file
ffile=${nfolder}/$ifrom
tfile=${nfolder}/$ito
[ ! -f "$ffile" ] && { echo "No power measurements starting at $2."; exit 4; }
[ ! -f "$tfile" ] && { echo "No power measurements up to $3."; exit 5; }
# Give files to the user
missings=0
header=0
for interval in $(seq $ifrom $LOG_INTERVAL $ito)
do
    file=${nfolder}/${interval}
    if [ ! -f "$file" ]
    then
        missings=$(( missings + 1 ))
        continue
    fi
    # Cat files
    if [ $header -eq 0 ]
    then
        cat $file
        header=1
    else
        tail -n +2 $file
    fi
done

# Report missings
[ $missings -gt 0 ] && { echo "Some power measurements are missings ($missings intervals of ${LOG_INTERVAL}s)" >&2; exit 6; }