#!/bin/zsh
# Pulse — avisa cuándo cuidar tu Mac. https://meridiandynamics.net/pulse
# launchd lo ejecuta cada hora. Revisa disco, memoria y días desde el último reinicio, y
# manda una notificación solo cuando conviene actuar. No usa internet ni envía datos.
#
#   DRY=1 ~/.pulse/pulse.sh   → imprime métricas y avisos sin notificar ni escribir nada.
#   ~/.pulse/config           → cambia los umbrales (líneas CLAVE=número).

emulate -L zsh
export LC_ALL=C

P=${PULSE_HOME:-$HOME/.pulse}
DISCO_MIN_GB=60   # avisar si quedan menos GB libres
SWAP_MAX_GB=5     # avisar si el swap pasa de esto
DIAS_REINICIO=3   # con swap alto y estos días sin reiniciar, toca reiniciar
DIAS_MAX=5        # pase lo que pase, reiniciar tras estos días
PAUSA_H=12        # no repetir el mismo aviso antes de estas horas

# La config se lee como datos, nunca se ejecuta: solo claves conocidas con valor entero.
if [[ -r $P/config ]]; then
  while IFS='=' read -r k v; do
    [[ $k == (DISCO_MIN_GB|SWAP_MAX_GB|DIAS_REINICIO|DIAS_MAX|PAUSA_H) && $v == <-> ]] && typeset -g "$k=$v"
    [[ $k == PULSE_LANG && $v == (es|en) && -z $PULSE_LANG ]] && PULSE_LANG=$v
  done < $P/config
fi

# Salida cruda de un comando; con DRY=1 los tests pueden sustituirla con PULSE_FAKE_*.
salida() {  # $1 = variable falsa, resto = comando
  local falsa=$1; shift
  if [[ -n $DRY && -n ${(P)falsa} ]]; then print -r -- ${(P)falsa}; else "$@" 2>/dev/null; fi
}

ahora=$(salida PULSE_FAKE_NOW date +%s)

vol=/System/Volumes/Data; [[ -d $vol ]] || vol=/
df_lineas=("${(@f)$(salida PULSE_FAKE_DF df -k $vol)}")
cabecera=(${(z)df_lineas[1]}); fila=(${(z)df_lineas[2]})
disponible=${fila[${cabecera[(i)Avail*]}]}
[[ $disponible == <-> ]] && libre_gb=$(( disponible / 1048576.0 )) || libre_gb=-1

swap_gb=0
if [[ $(salida PULSE_FAKE_SWAPUSAGE sysctl -n vm.swapusage) =~ 'used = ([0-9.]+)([MG])' ]]; then
  swap_gb=$(( match[1] * 1.0 ))
  [[ $match[2] == M ]] && swap_gb=$(( swap_gb / 1024 ))
fi

presion=$(salida PULSE_FAKE_PRESSURE sysctl -n kern.memorystatus_vm_pressure_level)
[[ $presion == (1|2|4) ]] || presion=1   # desconocida: decide el swap

dias=0
[[ $(salida PULSE_FAKE_BOOTTIME sysctl -n kern.boottime) =~ 'sec = ([0-9]+)' ]] &&
  dias=$(( (ahora - match[1]) / 86400.0 ))

idioma=$PULSE_LANG
if [[ -z $idioma ]]; then
  primero=$(defaults read -g AppleLanguages 2>/dev/null | sed -n 2p | tr -d ' ",')
  [[ $primero == es* ]] && idioma=es || idioma=en
fi

avisar() {  # $1 = clave, $2 = título, $3 = mensaje
  if [[ -n $DRY ]]; then print -r -- "AVISO [$1] $2 — $3"; return; fi
  local marca=$P/state/$1 ultimo=0
  [[ -r $marca ]] && ultimo=$(<$marca)
  [[ $ultimo == <-> ]] || ultimo=0
  (( ahora - ultimo < PAUSA_H * 3600 )) && return
  osascript -e "display notification \"$3\" with title \"$2\" sound name \"Glass\"" &&
    mkdir -p $P/state && print -r -- $ahora > $marca
}

L=${libre_gb%.*} S=$(printf %.0f $swap_gb) D=${dias%.*}
[[ -n $DRY ]] && print "libre=${L}GB swap=${S}GB presion=$presion dias=$D idioma=$idioma"

if [[ $idioma == es ]]; then
  t_disco="💾 Revisa el almacenamiento"; m_disco="Quedan $L GB libres. Buen momento para vaciar descargas, cachés o la Papelera."
  t_reinicio="🔄 Buen momento para reiniciar"; m_reinicio="$D días desde el último reinicio y $S GB en swap. Reiniciar lo deja todo fluido."
  t_memoria="🧠 La memoria está llena"; m_memoria="$S GB en swap. Cierra apps, pestañas o sesiones que ya no uses."
else
  t_disco="💾 Check your storage"; m_disco="$L GB left. A good moment to clear downloads, caches or the Trash."
  t_reinicio="🔄 Good time to restart"; m_reinicio="$D days since your last restart and $S GB of swap. A restart makes everything smooth again."
  t_memoria="🧠 Memory is full"; m_memoria="$S GB of swap in use. Close apps, tabs or sessions you no longer need."
fi

(( libre_gb >= 0 && libre_gb < DISCO_MIN_GB )) && avisar disco "$t_disco" "$m_disco"

# Reinicio excluye memoria: es el mismo problema y un reinicio lo resuelve.
if (( dias >= DIAS_MAX || (dias >= DIAS_REINICIO && swap_gb >= SWAP_MAX_GB) )); then
  avisar reinicio "$t_reinicio" "$m_reinicio"
elif (( presion >= 2 || swap_gb >= SWAP_MAX_GB )); then
  avisar memoria "$t_memoria" "$m_memoria"
fi
exit 0
