1#!/usr/bin/env zsh
2
3SERVER="http://secret.arpa/api/env"
4OPENROUTER_API="https://openrouter.ai/api/v1/credits"
5
6ICONS=(
7 " "
8 " "
9 " "
10 " "
11 " "
12)
13
14error() {
15 notify-send "$1" "$2"
16 exit 1
17}
18
19API_KEY=$(curl -fsS "$SERVER" | jq -er '.openrouter // empty') ||
20 error "Error Loading .env" "Check the server and try again."
21
22[[ -n "$API_KEY" ]] ||
23 error "Error Loading .env" "OpenRouter API key is missing."
24
25RESPONSE=$(curl -fsS \
26 -H "Authorization: Bearer $API_KEY" \
27 "$OPENROUTER_API") ||
28 error "Error Requesting Credits" "Check the server and try again."
29
30# Extract values
31TOTAL_CREDS=$(jq -er '.data.total_credits' <<< "$RESPONSE") ||
32 error "Invalid Response" "Could not read total credits."
33
34TOTAL_USAGE=$(jq -er '.data.total_usage' <<< "$RESPONSE") ||
35 error "Invalid Response" "Could not read total usage."
36
37# Calculate percentages + icon in one awk call
38read PERCENTAGE REM_PERCENTAGE ICON_INDEX <<< "$(
39 awk -v total="$TOTAL_CREDS" -v usage="$TOTAL_USAGE" '
40 BEGIN {
41 if (total <= 0) {
42 exit 1
43 }
44
45 used = (usage / total) * 100
46 remaining = 100 - used
47
48 if (remaining > 80) icon = 0
49 else if (remaining > 60) icon = 1
50 else if (remaining > 40) icon = 2
51 else if (remaining > 20) icon = 3
52 else icon = 4
53
54 printf "%.2f %.1f %d\n", used, remaining, icon
55 }
56 '
57)" || error "Invalid Credits" "Total credits is zero or unavailable."
58
59ICON="${ICONS[$((ICON_INDEX + 1))]}"
60
61printf '{"text":"%s %.1f%%","tooltip":"Available Credits: %s\\nUsed: %s"}\n' \
62 "$ICON" \
63 "$REM_PERCENTAGE" \
64 "$TOTAL_CREDS" \
65 "$TOTAL_USAGE"