aboutsummaryrefslogtreecommitdiff
path: root/cli.nix
blob: 8218ebd89893f708b42f5fb7a5ef214473182c8f (plain) (blame)
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
{ lib, pkgs }:
let
  inherit (lib) getExe;
in
pkgs.writeShellScriptBin "pia" ''
  ID=$(${pkgs.coreutils}/bin/id -u)

  if [ "$EUID" -ne 0 ]; then
    if which doas >/dev/null 2>&1; then
      exec doas "$0" "$@"
    elif which sudo >/dev/null 2>&1; then
      exec sudo "$0" "$@"
    else
      echo "error: neither doas nor sudo found" >&2
    fi
  fi

  COMMAND="$1"
  LOCATION="$2"

  list() {
  	${getExe pkgs.findutils} /etc/systemd/system/ -name 'openvpn-*.service' -exec ${pkgs.coreutils}/bin/basename {} .service \; |
  		sed 's/openvpn-//'
  }

  search() {
  	list | ${getExe pkgs.fzf}
  }

  search_location() {
  	if [ -z "$LOCATION" ]; then
  		LOCATION=$(search)
  	fi
  }

  case "$COMMAND" in
  "start")
  	search_location
  	sudo systemctl start "openvpn-$LOCATION.service"
  	;;
  "stop")
  	search_location
    sudo systemctl stop "openvpn-$LOCATION.service"
  	;;
  "list")
  	list
  	;;
  "search")
  	search
  	;;
  *)
  	${pkgs.coreutils}/bin/echo "usage: $0 <start|stop|list|search>"
  	exit 1
  	;;
  esac
''