#!/usr/bin/env bash

STATE_FILE="/tmp/fancycle_state"
HWMON_PATH="/sys/class/hwmon/hwmon3"  # Ajusta según tu caso

# Si no existe el archivo de estado, inícialo en 1 (fan1)
if [[ ! -f "$STATE_FILE" ]]; then
  echo 1 > "$STATE_FILE"
fi

# Si el script es invocado con el argumento "next", incrementa el estado
if [[ "$1" == "next" ]]; then
  current_state=$(cat "$STATE_FILE")
  next_state=$(( (current_state % 3) + 1 ))
  echo "$next_state" > "$STATE_FILE"
fi

state=$(cat "$STATE_FILE")

# Lee info de los ventiladores
fan1_label=$(cat "$HWMON_PATH/fan1_label" 2>/dev/null | sed 's/_fan//I')
fan1_speed=$(cat "$HWMON_PATH/fan1_input" 2>/dev/null)

fan2_label=$(cat "$HWMON_PATH/fan2_label" 2>/dev/null | sed 's/_fan//I')
fan2_speed=$(cat "$HWMON_PATH/fan2_input" 2>/dev/null)

fan3_label=$(cat "$HWMON_PATH/fan3_label" 2>/dev/null | sed 's/_fan//I')
fan3_speed=$(cat "$HWMON_PATH/fan3_input" 2>/dev/null)

tooltip="${fan1_label}: ${fan1_speed} RPM
${fan2_label}: ${fan2_speed} RPM
${fan3_label}: ${fan3_speed} RPM"

# Determinar texto con color según estado
case "$state" in
  1)
    text="<span foreground='#fa9f8e'>${fan1_label}:</span> <span foreground='#81a1c1'>${fan1_speed} RPM</span>"
    ;;
  2)
    text="<span foreground='#fa9f8e'>${fan2_label}:</span> <span foreground='#81a1c1'>${fan2_speed} RPM</span>"
    ;;
  3)
    text="<span foreground='#fa9f8e'>${fan3_label}:</span> <span foreground='#81a1c1'>${fan3_speed} RPM</span>"
    ;;
esac

jq -c -n \
  --arg text "$text" \
  --arg tooltip "$tooltip" \
  '{ "text": $text, "tooltip": $tooltip }'

