#!/bin/bash
# Logs battery drain while a wallpaper runs, for the "live wallpaper battery" guide on macscapes.app.
#
#   ./run.sh <label> [minutes]      e.g.  ./run.sh static 60   ./run.sh macscapes-mist 60   ./run.sh video 60
#
# Samples the battery every 30 seconds into results/<label>-<timestamp>.csv, keeps the display awake with
# caffeinate, and prints a summary at the end. Read README.md first: the conditions matter more than the script.
# Needs no sudo and installs nothing. Works with the bash that ships with macOS.
set -euo pipefail

label="${1:?usage: ./run.sh <label> [minutes]}"
minutes="${2:-60}"
interval=30
dir="$(cd "$(dirname "$0")" && pwd)/results"
mkdir -p "$dir"
stamp="$(date +%Y%m%d-%H%M%S)"
csv="$dir/$label-$stamp.csv"

# One value from the battery's registry entry. Only top-level keys (nested dictionaries sit on one line).
reg() { ioreg -rn AppleSmartBattery | sed -n "s/^ *\"$1\" = \([0-9]*\)$/\1/p" | head -1; }
# Signed milliamps: Apple silicon reports negative current as an unsigned 64-bit number; bash wraps it back.
signed() { echo $(( ${1:-0} )); }
on_ac() { pmset -g batt | grep -q "AC Power"; }
cpu_of() { ps -A -o %cpu=,comm= | awk -v n="$1" 'index($0, n) { s += $1 } END { printf "%.1f", s + 0 }'; }

if on_ac; then
  echo "Unplug the power adapter first (pmset reports AC Power)." >&2
  exit 1
fi
if [ -z "$(reg AppleRawCurrentCapacity)" ]; then
  echo "No battery readings found. Run this on a MacBook." >&2
  exit 1
fi

{
  echo "# label=$label minutes=$minutes interval=${interval}s"
  echo "# model=$(sysctl -n hw.model) macos=$(sw_vers -productVersion) build=$(sw_vers -buildVersion)"
  echo "# started=$(date -u +%Y-%m-%dT%H:%M:%SZ)"
  echo "# lowpowermode=$(pmset -g | awk '/lowpowermode/ { print $2 }') raw_max_mah=$(reg AppleRawMaxCapacity)"
  echo "elapsed_s,percent,raw_mah,voltage_mv,current_ma,watts,cpu_macscapes,cpu_windowserver"
} > "$csv"

caffeinate -d -i -w $$ &
echo "Logging to $csv for $minutes minutes. Hide this window (⌘H) and leave the Mac alone."

end=$(( $(date +%s) + minutes * 60 ))
start=$(date +%s)
while :; do
  now=$(date +%s)
  if on_ac; then
    echo "Power adapter connected; stopping early." >&2
    break
  fi
  pct=$(reg CurrentCapacity)
  mah=$(reg AppleRawCurrentCapacity)
  mv=$(reg Voltage)
  ma=$(signed "$(reg InstantAmperage)")
  watts=$(awk -v v="$mv" -v a="$ma" 'BEGIN { printf "%.2f", -v * a / 1e6 }')
  echo "$(( now - start )),$pct,$mah,$mv,$ma,$watts,$(cpu_of MacScapes),$(cpu_of WindowServer)" >> "$csv"
  [ "$now" -ge "$end" ] && break
  sleep "$interval"
done

echo "# ended=$(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$csv"
"$(dirname "$0")/summarize.sh" "$csv"
