#!/bin/bash
# Read CPU stats twice with a small delay to calculate usage
read -r cpu_line < /proc/stat
cpu_times_1=($cpu_line)
sleep 0.1
read -r cpu_line < /proc/stat
cpu_times_2=($cpu_line)

# Calculate total and idle time differences
# Fields: user nice system idle iowait irq softirq steal
total_1=$((${cpu_times_1[1]} + ${cpu_times_1[2]} + ${cpu_times_1[3]} + ${cpu_times_1[4]} + ${cpu_times_1[5]} + ${cpu_times_1[6]} + ${cpu_times_1[7]}))
total_2=$((${cpu_times_2[1]} + ${cpu_times_2[2]} + ${cpu_times_2[3]} + ${cpu_times_2[4]} + ${cpu_times_2[5]} + ${cpu_times_2[6]} + ${cpu_times_2[7]}))
idle_1=${cpu_times_1[4]}
idle_2=${cpu_times_2[4]}

total_diff=$((total_2 - total_1))
idle_diff=$((idle_2 - idle_1))

# Avoid division by zero
if [ "$total_diff" -eq 0 ]; then
    cpu_percent=0
else
    cpu_percent=$(((total_diff - idle_diff) * 100 / total_diff))
fi

# Color coding
if [ "$cpu_percent" -ge 90 ]; then
    printf "^bg(FF0000)CPU: %d%%^bg()" "$cpu_percent"
elif [ "$cpu_percent" -ge 75 ]; then
    printf "^fg(FFFF00)CPU: %d%%^fg()" "$cpu_percent"
else
    printf "CPU: %d%%" "$cpu_percent"
fi
