#!/bin/bash

# Initialize
printf "$$" > ~/.cache/pidofbar
sec=0

# Update functions
update_time() {
  time=$(date "+%b %d %H:%M ")
}

update_bat() {
  if [[ -e /sys/class/power_supply/BAT1/status && -e /sys/class/power_supply/BAT1/capacity ]]; then
    bat_capacity=$(< /sys/class/power_supply/BAT1/capacity)
    bat_status=$(< /sys/class/power_supply/BAT1/status)
    if [[ $bat_status == "Discharging" ]]; then
      bat="󰁹 $bat_capacity%"
    elif [[ $bat_status == "Charging" ]]; then
      bat="󰂄 $bat_capacity%"
    fi
  else
    bat="(capacity not available)"
  fi
}

update_vol() {
  vol="󰕾 $(pactl list sinks | awk '/Volume:/ {print $5}' | head -n 1 | tr -d '%')%"
}

update_wifi() {
  if ping -c 1 ping.archlinux.org &> /dev/null; then
    wifi="󰢾"
  else
    wifi="󰢿"
  fi
}

# Display function
display() {
  status=""
  [[ -n "$vol" ]] && status+=" $vol │"
  [[ -n "$bat" ]] && status+=" $bat │"
  [[ -n "$wifi" ]] && status+=" $wifi │"
  [[ -n "$time" ]] && status+=" $time"
  xsetroot -name "$status"
}

# Set up signal handlers
trap "update_bat; display" "RTMIN+2"
trap "update_vol; display" "RTMIN"

# Initial updates
update_vol

# Main loop
while true; do
  sleep 1
  sec=$((sec + 1))
  case $((sec % 60)) in
    0) update_bat;;
    [1-5]) 
      update_time
      update_vol
      update_wifi
      display
      ;;
  esac
done

