51 lines
1.2 KiB
Go
51 lines
1.2 KiB
Go
package wifi
|
|
|
|
import (
|
|
"log"
|
|
"os/exec"
|
|
"strings"
|
|
)
|
|
|
|
const (
|
|
CMD_NMCLI = "/usr/bin/nmcli"
|
|
)
|
|
|
|
type wifi struct {
|
|
essid string
|
|
password string
|
|
}
|
|
|
|
func New(essid string, password string) *wifi {
|
|
w := wifi{
|
|
essid: essid,
|
|
password: password,
|
|
}
|
|
return &w
|
|
}
|
|
|
|
func (w *wifi) ApplyConfig() {
|
|
// Cleanup existing WiFi connections
|
|
nmcliOut, err := exec.Command(CMD_NMCLI, "-t", "connection", "show").Output()
|
|
if err != nil {
|
|
log.Fatalf("Error running %s : %s", CMD_NMCLI, err)
|
|
}
|
|
connections := strings.Split(strings.Trim(string(nmcliOut), "\n"), "\n")
|
|
for _, connection := range connections {
|
|
details := strings.Split(connection, ":")
|
|
if details[2] != "802-11-wireless" {
|
|
continue
|
|
}
|
|
log.Printf("Cleaning up WiFi connection %s", details[0])
|
|
err := exec.Command(CMD_NMCLI, "connection", "del", details[1]).Run()
|
|
if err != nil {
|
|
log.Fatalf("Error running %s : %s", CMD_NMCLI, err)
|
|
}
|
|
}
|
|
// Create new WiFi connection with network manager
|
|
log.Printf("Connecting to %s with password %s\n", w.essid, w.password)
|
|
err = exec.Command(CMD_NMCLI, "d", "wifi", "connect", w.essid, "password", w.password).Run()
|
|
if err != nil {
|
|
log.Fatalf("Error running %s : %s", CMD_NMCLI, err)
|
|
}
|
|
}
|