-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
118 lines (102 loc) · 2.68 KB
/
main.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
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package main
import (
"errors"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/spf13/cobra"
)
var ErrNoSSID = errors.New("no SSID")
// TODO: Make these paths configurable
const airport = "/System/Library/PrivateFrameworks/Apple80211.framework/Resources/airport"
const blueutil = "/opt/homebrew/bin/blueutil"
func ssid() (string, error) {
bin := exec.Command(airport, "-I")
stdout, err := bin.Output()
if err != nil {
return "", err
}
for _, line := range strings.Split(string(stdout), "\n") {
if strings.TrimSpace(line) == "" {
continue
}
parts := strings.Split(line, ":")
if len(parts) != 2 {
continue
}
if strings.TrimSpace(parts[0]) == "SSID" {
return strings.TrimSpace(parts[1]), nil
}
}
return "", ErrNoSSID
}
func toggleBluetooth(on bool) error {
var bit int
if on {
bit = 1
}
return exec.Command(blueutil, "--power", strconv.Itoa(bit)).Run()
}
func main() {
cmd := cobra.Command{
Use: "btdaemon <ssid...>",
Short: "daemon that safely enables & disables bluetooth based on your wireless SSID",
RunE: func(cmd *cobra.Command, args []string) error {
lp := "/var/log/net.codeviking.btdaemon/stdout.log"
if err := os.MkdirAll(filepath.Dir(lp), 0755); err != nil {
return err
}
lf, err := os.OpenFile(lp, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0644)
if err != nil {
return err
}
logger := log.New(lf, "", log.Ldate|log.Ltime|log.LUTC)
contents, err := os.ReadFile(args[0])
if err != nil {
return err
}
ssids := strings.Split(strings.TrimSpace(string(contents)), "\n")
if len(ssids) == 0 {
err := errors.New("no trusted SSIDs, nothing to do")
logger.Print(err)
return nil
}
logger.Printf("bluetooth will be enabled when connected to SSIDs: %s\n", strings.Join(ssids, ", "))
t := time.NewTicker(1 * time.Minute)
NEXTTICK:
for {
select {
case <-t.C:
logger.Println("querying ssid...")
current, err := ssid()
if err != nil {
logger.Printf("error querying ssid: %s\n", err.Error())
continue NEXTTICK
}
for _, trusted := range ssids {
if trusted == current {
logger.Printf("%s is trusted, enabling bluetooth...\n", current)
if err := toggleBluetooth(true); err != nil {
logger.Printf("error enabling bluetooth: %s\n", err.Error())
}
continue NEXTTICK
}
}
logger.Printf("%s is not trusted, disabling bluetooth...\n", current)
if err := toggleBluetooth(false); err != nil {
logger.Printf("error disabling bluetooth: %s\n", err.Error())
}
}
}
},
}
if err := cmd.Execute(); err != nil {
fmt.Fprintf(os.Stderr, "error: %s\n", err)
os.Exit(1)
}
}