#!/bin/bash
# Checking if programms are available
case x"$@" in
x"  Stop wireguard")
  coproc (wg-quick down wg0 >/dev/null 2>&1) &
  exit 0
  ;;
x"  Start wireguard")
  coproc (wg-quick up wg0 >/dev/null 2>&1) &
  exit 0
  ;;
x"  Stop netbird")
  coproc (netbird down >/dev/null 2>&1) &
  exit 0
  ;;
x"  Start netbird")
  coproc (netbird up >/dev/null 2>&1) &
  exit 0
  ;;
x"  Stop sing-box")
  coproc (sudo systemctl stop sing-box >/dev/null 2>&1) &
  exit 0
  ;;
x"  Start sing-box")
  coproc (sudo systemctl start sing-box >/dev/null 2>&1) &
  exit 0
  ;;
esac

# Checking if programms are installed
wireguard_installed=true
if ! command -v wg-quick >/dev/null 2>&1; then
  wireguard_installed=false
else
  wireguard_installed=true
fi

netbird_installed=true
if ! command -v netbird >/dev/null 2>&1; then
  netbird_installed=false
else
  netbird_installed=true
fi

sing_box_installed=true
if ! systemctl list-unit-files -q sing-box.service >/dev/null 2>&1; then
  sing_box_installed=false
else
  sing_box_installed=true
fi

# active param
active="\0active\x1f"

# netbird
if $wireguard_installed; then
  wireguard_status=$(sudo wg show interfaces)
  if [ "$wireguard_status" != "wg0" ]; then
    echo "  Start wireguard"
  else
    active+="0"
    echo "  Stop wireguard"
  fi
else
  echo "  Wireguard not installed"
fi

# netbird
if $netbird_installed; then
  netbird_status=$(netbird status | grep "Networks" | cut -d: -f2 | sed "s/ -//")
  if [ -z "$netbird_status" ]; then
    echo "  Start netbird"
  else
    active+="1"
    echo "  Stop netbird"
  fi
else
  echo "  Netbird not installed"
fi

# sing-box
if $sing_box_installed; then
  if systemctl status sing-box >/dev/null 2>&1; then
    active+="2"
    echo "  Stop sing-box"
  else
    echo "  Start sing-box"
  fi
else
  echo "  Sing-box not installed"
fi

echo -en "$active\n"
