#!/usr/bin/env bash
export LC_NUMERIC=C

ROOT="/"
HOME="/home"
[ -d "$HOME" ] || HOME=""

# Capturar salidas
df_home=$(sudo btrfs filesystem df "$HOME" 2>/dev/null)
usage_root=$(sudo btrfs filesystem usage "$ROOT" 2>/dev/null)

# Extraer solo el bloque Overall:
overall_block=$(awk '/^Overall:/{p=1} p' <<<"$usage_root")

# Función para obtener token numérico+unidad
get_tok(){
  awk -v key="$1" 'index($0,key){
      for(i=1;i<=NF;i++) if($i ~ /^[0-9]+(\.[0-9]+)?(KiB|MiB|GiB|TiB|PiB)$/) {print $i; exit}
    }' <<<"$usage_root"
}
free_tok=$(get_tok "Free (estimated):")
tot_tok=$(get_tok "Device size:")

# Validar tokens
if [[ -z "$free_tok" || -z "$tot_tok" ]]; then
  echo '{"text":"Err","tooltip":"Error extrayendo valores Btrfs","class":"error","color":"#ff5555"}'
  exit 1
fi

# Separar número y unidad
free_num=${free_tok%[KMGTP]iB}; free_unit=${free_tok#"$free_num"}
tot_num=${tot_tok%[KMGTP]iB};   tot_unit=${tot_tok#"$tot_num"}

# Convertir coma a punto
free_num=${free_num//,/.}
tot_num=${tot_num//,/.}

# Conversión a GiB
to_gib(){
  case "$2" in
    KiB) factor=0.000001;; MiB) factor=0.001;; GiB) factor=1;;
    TiB) factor=1024;;     PiB) factor=1048576;; *) factor=1;;
  esac
  echo "$1 * $factor" | bc -l
}
free_gb=$(to_gib "$free_num" "$free_unit")
tot_gb=$(to_gib "$tot_num" "$tot_unit")

# Validar conversión
if [[ -z "$free_gb" || -z "$tot_gb" ]]; then
  echo '{"text":"Err","tooltip":"Error conversión a GiB","class":"error","color":"#ff5555"}'
  exit 1
fi

# Calcular % libre
pct=$(awk -v f="$free_gb" -v t="$tot_gb" 'BEGIN{printf "%.0f", (f/t)*100}')

# Color según umbral
if   (( pct < 10 )); then color="#ff5555"
elif (( pct < 20 )); then color="#f1fa8c"
else                    color="#50fa7b"
fi

# Icono FontAwesome (U+F0A0)
icon=$'\uf0a0'

# Escapar para JSON
escape(){ sed ':a;N;$!ba;s/\\/\\\\/g;s/"/\\"/g;s/\n/\\n/g'; }
tooltip=$(echo -e "$overall_block" | escape)

# Salida JSON
printf '{"text":"%s %s%%","tooltip":"%s","color":"%s"}' "$icon" "$pct" "$tooltip" "$color"

