summaryrefslogtreecommitdiff
path: root/.config/nushell/vpn.nu
blob: cb7284549e4587f411ee48e1fc7dabfa942bcc38 (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
use post-vpn-connect.nu
use pre-vpn-disconnect.nu

# Connect to one of the Mullvad VPN Servers via Wireguard and optionally filter by name.
export def connect [
  --filter: string # Filter by VPN server config name, e.g. 'de' to filter German servers
] {
    try {
      let active_interface = (active-interface)
      if ($active_interface | is-not-empty) {
        print $"You are already connected to ($active_interface)."
        return
      }

      let servers = (sudo ls /etc/wireguard/ | lines | str replace '.conf' '') | where { |name| $name =~ ($filter | default '') }
      sudo wg-quick up ($servers | select (random int 0..(($servers | length) - 1)) | get 0)

      print "Executing Post-VPN Connect Tasks..."
      post-vpn-connect 
      print "Finished Post-VPN Connect Tasks..."

    } catch {
      |err|
      print $"Failed to connect to VPN...\n\nError: ($err.msg)"
    }
}

# Check if you are connected to a Mullvad VPN server.
export def test-connection [] {
  try {
    let response = (http get https://am.i.mullvad.net/connected --max-time 5sec)
    return $response
  } catch {
    |err|
    print $"Failed to get response from status...\n\nError: ($err.msg)"
  }
}

# Check if a Wireguard interface is up and running.
#  If yes: string (name of interface)
#  If not: nothing
export def active-interface [] {
  try {
    let wg_show_output = (sudo wg show | lines)
    if ($wg_show_output | is-not-empty) {
      $wg_show_output | get 0 | parse "interface: {interface}" | get 0 | return $in.interface
    }
  } catch {
    |err|
    print $"Failed to check active Wireguard interface...\n\nError: ($err.msg)"
  }
}

# Disconnect the active VPN server connection.
export def disconnect [] {
  try {
    let active_interface = (active-interface)
    if ($active_interface | is-empty) {
      print "You are not connected to any Mullvad VPN server."
      return
    }

    print "Executing Pre-VPN Disconnect Tasks..."
    pre-vpn-disconnect
    print "Finished Pre-VPN Disconnect Tasks..."

    sudo wg-quick down $active_interface
  } catch {
    |err| 
    print $"Failed to disconnect active VPN connection...\n\n Error: ($err.msg)"
  }
}