#!/usr/bin/env bash
set -euo pipefail

status_raw="$(tmutil status 2>/dev/null || true)"

if grep -q "Running = 1;" <<<"$status_raw"; then
  percent="$(
    awk '
      /Percent =/ {
        gsub(/;/, "", $3)
        p = $3 + 0
        v = int((p * 100) + 0.5)
        if (v < 0) v = 0
        if (v > 100) v = 100
        print v
        found = 1
      }
      END {
        if (!found) print 0
      }
    ' <<<"$status_raw"
  )"
  percent="${percent:-0}"

  terminal-widget \
    --target timemachine \
    --icon arrow.trianglehead.counterclockwise \
    --text "Time Machine Backing Up (${percent}%)" \
    --progress "$percent" \
    --foreground "#d9f2ff" \
    --background "#1f3b56"
else
  terminal-widget \
    --target timemachine \
    --icon checkmark.arrow.trianglehead.clockwise \
    --text "Time Machine Idle" \
    --foreground "#d7ffe3" \
    --background "#244730"
fi