#!/bin/bash
# ============================================================
#   FiHR Battery Guard  v1.2  (Mac)
#   Protects your MacBook battery by telling you when to unplug.
#
#   WHAT IT DOES
#   - Watches your battery every 30 seconds
#   - When charge reaches the threshold while plugged in:
#       * plays a chime and speaks the alert aloud
#   - Gently reminds every 10 minutes while still plugged
#
#   HOW TO USE
#   1. Save this file somewhere safe (e.g. your Documents).
#   2. Open Terminal, then run:
#        bash ~/Documents/FiHR-BatteryGuard.command
#   3. Leave it running in the background while you charge.
#
#   Works on macOS 12+. No installation, no internet needed.
# ============================================================

ThresholdPct=95     # Alert when charge reaches this level
RepeatMins=10        # Re-alert every N minutes while still plugged (0 = once per charge)
VoiceAlert=true      # Speak the alert aloud

lastAlert=0
spoken=0

while true; do
  # Read battery status: e.g. "Now drawing from 'AC Power'"; "100%; charging"
  batt=$(pmset -g batt)
  pct=$(echo "$batt" | grep -Eo '[0-9]{1,3}%' | head -1 | tr -d '%')
  charging=$(echo "$batt" | grep -q "AC Power" && echo yes || echo no)

  if [ -n "$pct" ] && [ "$charging" = "yes" ] && [ "$pct" -ge "$ThresholdPct" ]; then
    now=$(date +%s)
    dueRepeat=0
    [ "$RepeatMins" -gt 0 ] && dueRepeat=$(( lastAlert + RepeatMins * 60 ))
    if [ "$spoken" -eq 0 ] || ([ "$dueRepeat" -gt 0 ] && [ "$now" -ge "$dueRepeat" ]); then
      afplay /System/Library/Sounds/Glass.aiff 2>/dev/null
      osascript -e 'display notification "Battery is charged. Unplug your charger to protect the battery." with title "FiHR Battery Guard" sound name "Glass"' 2>/dev/null
      if [ "$VoiceAlert" = "true" ]; then
        say "Your battery is charged. Unplug your charger to protect the battery."
      fi
      lastAlert=$now
      spoken=1
    fi
  else
    spoken=0
  fi
  sleep 30
done
