#!/bin/bash
#
#  This script calculates energy used when at warpspeed
#  When warpspeed stops, energy increases
#

if [ "$1" = "" ] || [ "$2" = "" ]; then
  echo -e "\n\e[31m  Can only be started from within conky!\e[m\n"
  exit
fi


# Get start stop frames
frstart=$1
frstop=$2
x=$3

tmpfile="./tempfiles/warpspeed-bar"
if [ ! -f "$tmpfile" ]; then
  echo 100 > "$tmpfile"
fi


# Get space frame number
if [ -f "./images/space/current/conky_slideshow_index" ]; then
   space_frame=$(cat "./images/space/current/conky_slideshow_index")
fi

# When loop restarts, set warpspeed bar to full
if [[ $space_frame -lt 100 ]]; then
  echo 100 > "$tmpfile"
fi


# debug
#frstart=1540
#frstop=1580

# All output in english please
export LC_ALL=C

# If space_frame nr is between start/stop frame nrs
if [ "$3" = "-" ]; then
  if [[ $space_frame -ge $frstart  ]] && [[ $space_frame -le $frstop ]]; then
      # How many frames active
      activeframes=$((frstop-frstart))
      # How many steps up per frame to get to 100
      add_val=$(echo "100/$activeframes" | bc -l | xargs printf "%.2f")
      # Get current sensor value
      current_val=$(cat "$tmpfile")
      # Ads step to current sensor value
      new_val=$(echo "$current_val-$add_val" | bc -l | xargs printf "%.2f")
        echo $new_val > "$tmpfile"
      # debug
#      echo "WARP -: spfr:$space_frame | actfrs:$activeframes | add:$add_val | curr:$current_val | new:$new_val |"
      exit
  fi
elif [ "$3" = "+" ]; then
  if [[ $space_frame -ge $frstart  ]] && [[ $space_frame -le $frstop ]]; then
      # How many frames active
      activeframes=$((frstop-frstart))
      # How many steps up per frame to get to 100
      add_val=$(echo "100/$activeframes" | bc -l | xargs printf "%.2f")
      # Get current sensor value
      current_val=$(cat "$tmpfile")
      # Ads step to current sensor value
      new_val=$(echo "$current_val+$add_val" | bc -l | xargs printf "%.2f")
      echo $new_val > "$tmpfile"
      if [ "$space_frame" = "$frstop" ]; then echo 100 > "$tmpfile"; fi
      # debug
#      echo "WARP +: spfr:$space_frame | actfrs:$activeframes | add:$add_val | curr:$current_val | new:$new_val |"
      exit
  fi
fi
