summaryrefslogtreecommitdiff
path: root/polybar/scripts/wg-pc-toggle.sh
blob: 5cd102f3962a5a23f8b9652f9808c96a304aaccc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#!/usr/bin/env bash
set -euo pipefail

profile="${WG_QUICK_PROFILE:-PC}"
iface="$profile"
requested="${1:-toggle}"

export DISPLAY="${DISPLAY:-:0}"
if [ -z "${XAUTHORITY:-}" ] && [ -r "$HOME/.Xauthority" ]; then
  export XAUTHORITY="$HOME/.Xauthority"
fi

case "$profile" in
  *[!A-Za-z0-9_.@-]*|"")
    echo "Invalid WireGuard profile: $profile" >&2
    exit 2
    ;;
esac

log_file="${XDG_RUNTIME_DIR:-/tmp}/polybar-wg-$profile.log"

notify() {
  if command -v dunstify >/dev/null 2>&1; then
    dunstify -a polybar -u low "WireGuard" "$1"
  fi
}

polkit_agent_running() {
  pgrep -u "$UID" -f 'polkit-gnome-authentication-agent-1|polkit-kde-authentication-agent-1|lxqt-policykit-agent|polkit-mate-authentication-agent-1|xfce-polkit' >/dev/null 2>&1
}

ensure_polkit_agent() {
  if polkit_agent_running; then
    return 0
  fi

  if [ -x /home/aag/.config/polybar/scripts/polkit-agent.sh ]; then
    /usr/bin/setsid -f /home/aag/.config/polybar/scripts/polkit-agent.sh >>"$log_file" 2>&1
    sleep 0.5
  fi

  polkit_agent_running
}

case "$requested" in
  up|down)
    action="$requested"
    ;;
  toggle)
    if [ -d "/sys/class/net/$iface" ]; then
      action="down"
    else
      action="up"
    fi
    ;;
  *)
    notify "Unknown action: $requested"
    exit 2
    ;;
esac

if [ "$(id -u)" -eq 0 ]; then
  auth=()
elif command -v pkexec >/dev/null 2>&1; then
  if ! ensure_polkit_agent; then
    notify "No polkit agent running"
    echo "No polkit authentication agent is running." >"$log_file"
    echo "Install/start polkit-gnome, then restart i3 or run ~/.config/polybar/scripts/polkit-agent.sh." >>"$log_file"
    exit 1
  fi
  auth=(pkexec --disable-internal-agent)
else
  notify "pkexec not found"
  exit 1
fi

if "${auth[@]}" /usr/bin/wg-quick "$action" "$profile" >"$log_file" 2>&1; then
  notify "$profile $action complete"
else
  notify "$profile $action failed: $log_file"
  exit 1
fi