-
Notifications
You must be signed in to change notification settings - Fork 0
/
switch.go
49 lines (43 loc) · 1.09 KB
/
switch.go
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
package cmd
import (
"context"
"log"
"github.com/gitfort/wgfailover/internal/pkg/config"
"github.com/gitfort/wgfailover/pkg/slices"
"github.com/gitfort/wgfailover/pkg/wireguard"
"github.com/spf13/cobra"
)
var switchCmd = &cobra.Command{
Use: "switch",
Short: "Switch to the selected interface between failovers",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load(configFile)
if err != nil {
return err
}
return NetworkSwitch(cmd.Context(), cfg, args[0])
},
}
func init() {
rootCmd.AddCommand(switchCmd)
}
func NetworkSwitch(ctx context.Context, cfg *config.Config, network string) error {
activeDevices, err := wireguard.ActiveDevices(ctx)
if err != nil {
return err
}
for _, device := range cfg.Devices {
if slices.Find(device.Name, activeDevices) >= 0 {
log.Printf("deactivating %v", device.Name)
if err = wireguard.DownDevice(ctx, device.Name); err != nil {
return err
}
}
}
log.Printf("activating %v", network)
if err = wireguard.UpDevice(ctx, network); err != nil {
return err
}
return nil
}