#!/bin/bash
TW=/Applications/TerminalWidget.app/Contents/MacOS/TerminalWidget
BG_IMAGE="$HOME/Pictures/battery-bg.jpg"   # any local photo
TW_TARGET="batteries"

raw=$(/usr/bin/pmset -g accps \
  | LC_ALL=C /usr/bin/tr '\325' "'" \
  | /usr/bin/iconv -f MACROMAN -t UTF-8)

case "$raw" in
  *"'AC Power'"*) title=":electric_plug: On AC Power" ;;
  *)              title=":battery: On Battery Power" ;;
esac

printf '%s\n' "$raw" \
| /usr/bin/awk -F '\t' '
    /^Now drawing from/ { next }
    NF >= 2 {
      name = $1
      sub(/^[[:space:]]*-/, "", name)
      sub(/[[:space:]]*\(id=[^)]*\)[[:space:]]*$/, "", name)
      if (name ~ /^InternalBattery/) name = "This Mac"
      pct = $2
      sub(/%.*/, "", pct)
      pct += 0
      filled = int((pct + 5) / 10)
      meter = ""
      for (i = 1; i <= 10; i++) meter = meter (i <= filled ? "▰" : "▱")
      rows = rows name "\t" meter "\t" pct "%\n"
    }
    END { printf "Device\tCharge\tLevel\n%s", rows }
  ' \
| "$TW" --target $TW_TARGET \
    --table - \
    --grid zebra-row \
    --table-layout fill \
    --table-align left,left,right \
    --title "$title" \
    --background-image "$BG_IMAGE" \
    --filter alpha:30 \
    --bg "#0f172a" \
    --fg "#e2e8f0"