#!/bin/bash

SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)

#while true; do echo -e "Battery: 13.2v 86% \n Power Consumption: 1.2W \n Date: $(date) \n Uptime: $(uptime)\n\n"> /tmp/index.html; sleep 1; done

while true; do 

 #SENSORS=(`python2 ~/ina226.py`)

 #CURRENT=${SENSORS[0]}  
 #VOLTAGE=${SENSORS[1]}  
 #POWER=${SENSORS[2]}  
 #BATTERY=${SENSORS[3]}  

 WEATHERS=($(python3 "$SCRIPT_DIR/weather-2026.py"))
 TEMPERATURE=${WEATHERS[0]}  
 FORECAST=${WEATHERS[1]}  
 LATITUDE=${WEATHERS[2]}  
 LONGITUDE=${WEATHERS[3]}  

 # Simulated solar charging, using the server's local time.
 # Day (06:00-18:00): 12.0-13.8V; night: drains 12.4 -> 12.0V (<12.5V).
 # The curves meet at sunrise/sunset, avoiding random voltage jumps.
 VOLTAGE=$(awk -v time="$(date +%H:%M)" 'BEGIN {
   split(time, parts, ":")
   minutes = parts[1] * 60 + parts[2]
   pi = atan2(0, -1)
   if (minutes >= 360 && minutes < 720) {
     voltage = 12.0 + 1.8 * sin(pi * (minutes - 360) / 720)
   } else if (minutes >= 720 && minutes < 1080) {
     voltage = 12.4 + 1.4 * sin(pi * (1080 - minutes) / 720)
   } else {
     night_minutes = (minutes - 1080 + 1440) % 1440
     voltage = 12.4 - 0.4 * night_minutes / 720
   }
   printf "%.2f", voltage
 }')

 # Simulated battery display scale: 11.8V empty, 13.8V full.
 # This is a display estimate, not a measured capacity (especially charging).
 BATTERY=$(awk -v voltage="$VOLTAGE" 'BEGIN {
   percentage = (voltage - 11.8) / (13.8 - 11.8) * 100
   if (percentage < 0) percentage = 0
   if (percentage > 100) percentage = 100
   printf "%.0f", percentage
 }')
 CURRENT=`seq 0.1 0.15 0.2 | shuf | head -n1`;
 POWER=`seq 1 .1 1.5 | shuf | head -n1`;

 echo -e "{\"voltage\": $VOLTAGE, \"battery\": $BATTERY, \"powerConsumption\": $POWER, \"current\": $CURRENT, \"forecast\": \"$FORECAST\", \"temperature\": $TEMPERATURE, \"date\": \"$(date)\", \"uptime\": \"$(uptime -p)\", \"latitude\": $LATITUDE, \"longitude\": $LONGITUDE }" > /tmp/index.html; 
 sleep 30; 
done
