#!/bin/bash

# Parse argument
[ $# != 5 ] && { echo "Usage: $0 <cluster-name> <node-name> <from> <to> <output-file>"; exit 1; }

# Init arguments
clusterName="$1"
nodeName="$2"
outputFile="$5"
wattmeter=$(curl -s https://api.grid5000.fr/stable/sites/lyon/clusters/${clusterName}/nodes/${nodeName}.json | jq -r '.sensors.power.via.pdu[0].uid')
port=$(curl -s https://api.grid5000.fr/stable/sites/lyon/pdus/${wattmeter}.json | jq -r '.ports|to_entries|map(select(.value=="'${nodeName}'"))[0].key')
energyEntry=$(( 5 + port) # Define the entry in the CSV that correspond to the correct energy value

if [ -z $wattmeter ] || [ -z $port ]
then
    echo -ne "\nCannot find energy informations (wattmeter/port) for node $nodeName\n"
    echo -ne "\nCheck the node name (do not use hostname! only node name ex: nova-7)\n"
    exit 1
fi

echo "Node ${nodeName} is connected on wattmeter ${wattmeter} on port ${port}"

# Fetching energy and save in csv format
from=$(date -d "@$3" "+%s")
to=$(date -d "@$4" "+%s")
echo "ts,energy" > $outputFile # Write CSV header
for time in $(seq $from 3600 $to)
do
    # We need gz extension if it is not the current hour
    [ $(date -d "@$time" "+%Y-%m-%dT%H") != $(date "+%Y-%m-%dT%H") ] && ext='.gz' || ext=''
    powerFilename=$(date -d "@$time" "+power.csv.%Y-%m-%dT%H${ext}")
    url="http://wattmetre.lyon.grid5000.fr/data/${wattmeter}-log/${powerFilename}"
    echo "- Fetching logs from ${url}" 
    
    # Fetch logs data
    [ ! -z $ext ] && csvContent=$(curl -s "${url}" | zcat) || csvContent=$(curl -s "${url}")

    # Parse data and extract the right values in csv format
    toSave=$(echo "$csvContent" | awk -F, 'int($3)>='$from'&& int($3)<='$to'{printf "%s,%s\n",$3,$5+'$port'};')
    echo "$toSave" >> $outputFile # Save data in csv
done
echo "Done"