-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
959 lines (852 loc) · 26.6 KB
/
Copy pathmain.go
File metadata and controls
959 lines (852 loc) · 26.6 KB
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
package main
import (
"bufio"
"context"
"encoding/json"
"fmt"
"os"
"os/exec"
"os/signal"
"path/filepath"
"regexp"
"strings"
"syscall"
"time"
"github.com/spf13/cobra"
)
const configFileName = ".blunt"
var macRegex = regexp.MustCompile(`^([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$`)
type Config struct {
DeviceName string `json:"device_name"`
DeviceMAC string `json:"device_mac"`
CheckInterval int `json:"check_interval_seconds"`
// GraceChecks is how many consecutive missed checks to tolerate before
// declaring the device absent.
GraceChecks int `json:"grace_checks"`
}
func getConfigPath() string {
home, err := os.UserHomeDir()
if err != nil {
return ""
}
return filepath.Join(home, configFileName)
}
func loadConfig() (*Config, error) {
configPath := getConfigPath()
data, err := os.ReadFile(configPath)
if err != nil {
return nil, err
}
var config Config
err = json.Unmarshal(data, &config)
if err != nil {
return nil, err
}
return &config, nil
}
func saveConfig(config *Config) error {
configPath := getConfigPath()
data, err := json.MarshalIndent(config, "", " ")
if err != nil {
return err
}
return os.WriteFile(configPath, data, 0600)
}
func configExists() bool {
_, err := loadConfig()
return err == nil
}
// getPairedDevices gets devices that are already paired/trusted from bluetoothctl
func getPairedDevices() ([]string, error) {
cmd := exec.Command("bluetoothctl", "paired-devices")
output, err := cmd.CombinedOutput()
if err != nil {
// bluetoothctl might fail if not running, that's ok
return nil, nil
}
var devices []string
lines := strings.Split(string(output), "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
// Format: "Device MAC Name"
if strings.HasPrefix(line, "Device ") {
parts := strings.SplitN(line[7:], " ", 2)
if len(parts) == 2 {
mac := parts[0]
name := parts[1]
devices = append(devices, fmt.Sprintf("%s (%s)", name, mac))
}
}
}
return devices, nil
}
// getConnectedDevices gets currently connected devices
func getConnectedDevices() ([]string, error) {
cmd := exec.Command("bluetoothctl", "devices", "Connected")
output, err := cmd.CombinedOutput()
if err != nil {
return nil, err
}
var devices []string
lines := strings.Split(string(output), "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
// Format: "Device MAC Name"
if strings.HasPrefix(line, "Device ") {
parts := strings.SplitN(line[7:], " ", 2)
if len(parts) == 2 {
mac := parts[0]
name := parts[1]
devices = append(devices, fmt.Sprintf("%s (%s)", name, mac))
}
}
}
return devices, nil
}
// getDeviceName tries to get the name of a device from its MAC
func getDeviceName(mac string) string {
// Read the cached device info from bluetoothctl and pull out the Name field
cmd := exec.Command("bluetoothctl", "info", mac)
output, err := cmd.CombinedOutput()
if err == nil {
lines := strings.Split(string(output), "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "Name: ") {
name := strings.TrimSpace(strings.TrimPrefix(line, "Name: "))
if name != "" {
return name
}
}
}
}
return ""
}
// scanBluetoothDevices scans for nearby discoverable Bluetooth devices using bluetoothctl
func scanBluetoothDevices() ([]string, error) {
fmt.Println("Scanning for discoverable devices...")
fmt.Println("(This takes about 10 seconds...)")
// bluetoothctl --timeout runs the scan for N seconds then exits on its own;
// the outer context is a safety net in case it hangs.
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
scanCmd := exec.CommandContext(ctx, "bluetoothctl", "--timeout", "10", "scan", "on")
if err := scanCmd.Run(); err != nil && ctx.Err() == context.DeadlineExceeded {
return nil, fmt.Errorf("scan timed out")
}
// List everything bluetoothctl now knows about (includes devices found above).
// Already-known devices are de-duplicated against the paired/connected lists
// by the caller.
cmd := exec.Command("bluetoothctl", "devices")
output, err := cmd.CombinedOutput()
if err != nil {
return nil, err
}
var devices []string
lines := strings.Split(string(output), "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
// Format: "Device MAC Name"
if strings.HasPrefix(line, "Device ") {
parts := strings.SplitN(line[7:], " ", 2)
if len(parts) == 2 {
mac := parts[0]
name := parts[1]
devices = append(devices, fmt.Sprintf("%s (%s)", name, mac))
}
}
}
return devices, nil
}
// validateMAC checks if a string is a valid MAC address
func validateMAC(mac string) bool {
return macRegex.MatchString(mac)
}
// normalizeMAC normalizes a MAC address to uppercase
func normalizeMAC(mac string) string {
return strings.ToUpper(mac)
}
// checkDevicePresent checks if a specific device is nearby
func checkDevicePresent(mac string) bool {
// Method 1: Check if device is currently connected (most reliable, no permissions needed)
cmd := exec.Command("bluetoothctl", "info", mac)
output, err := cmd.CombinedOutput()
if err == nil {
// "Connected: yes" in the device info means it's in range and linked
for _, line := range strings.Split(string(output), "\n") {
if strings.TrimSpace(line) == "Connected: yes" {
return true
}
}
}
// Method 2: Try l2ping (requires CAP_NET_RAW or root)
cmd = exec.Command("l2ping", "-c", "1", "-t", "2", mac)
if err := cmd.Run(); err == nil {
return true
}
// Method 3: Short scan — is the device advertising nearby right now?
// Catches unpaired-but-visible devices (speakers, watch, IoT gadgets);
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
scanCmd := exec.CommandContext(ctx, "bluetoothctl", "--timeout", "6", "scan", "on")
scanOut, _ := scanCmd.CombinedOutput()
if strings.Contains(strings.ToUpper(string(scanOut)), strings.ToUpper(mac)) {
return true
}
return false
}
// preventSleep prevents the system from going to sleep and prevents idle (screen lock)
// Returns the process so it can be killed later
func preventSleep() (*exec.Cmd, error) {
// Inhibit both sleep AND idle - idle inhibition prevents screen lockers like swayidle
cmd := exec.Command("systemd-inhibit", "--what=sleep:idle", "--who=blunt", "--why=Bluetooth unlock active", "--mode=block", "sleep", "infinity")
err := cmd.Start()
if err != nil {
return nil, err
}
return cmd, nil
}
// allowSleep stops the sleep inhibition by killing the inhibit process
func allowSleep(cmd *exec.Cmd) {
if cmd != nil && cmd.Process != nil {
cmd.Process.Kill()
cmd.Wait()
}
}
// nextPresence applies hysteresis to a raw presence reading so transient
// bluetooth drops don't flap the debounced state.
//
// present - the raw reading from this tick
// wasPresent - the debounced state before this tick
// misses - consecutive missed readings accumulated while present
// graceChecks - misses tolerated before flipping to absent (>= 1)
//
// returns the new debounced state, the updated miss counter, and whether a
// state transition occurred
func nextPresence(present, wasPresent bool, misses, graceChecks int) (nowPresent bool, newMisses int, changed bool) {
if graceChecks < 1 {
graceChecks = 1
}
if present {
// Any positive reading clears the miss streak and asserts presence.
return true, 0, !wasPresent
}
if !wasPresent {
return false, 0, false
}
misses++
if misses >= graceChecks {
return false, 0, true
}
return true, misses, false
}
// runDaemon runs the main detection loop
func runDaemon() error {
config, err := loadConfig()
if err != nil {
return fmt.Errorf("no unlock device configured. Run 'blunt' to set up a device")
}
if config.CheckInterval <= 0 {
config.CheckInterval = 5
}
if config.GraceChecks <= 0 {
config.GraceChecks = 3
}
fmt.Printf("Starting blunt daemon...\n")
fmt.Printf("Monitoring for device: %s (%s)\n", config.DeviceName, config.DeviceMAC)
fmt.Printf("Check interval: %d seconds\n", config.CheckInterval)
fmt.Printf("Grace period: %d missed checks\n", config.GraceChecks)
// Set up signal handling
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
ticker := time.NewTicker(time.Duration(config.CheckInterval) * time.Second)
defer ticker.Stop()
devicePresent := false
missCount := 0
var inhibitCmd *exec.Cmd
for {
select {
case <-ticker.C:
present := checkDevicePresent(config.DeviceMAC)
nowPresent, m, changed := nextPresence(present, devicePresent, missCount, config.GraceChecks)
devicePresent = nowPresent
missCount = m
if changed {
if nowPresent {
// Device appeared - prevent sleep
var err error
inhibitCmd, err = preventSleep()
if err != nil {
fmt.Fprintf(os.Stderr, "[%s] Failed to prevent sleep: %v\n",
time.Now().Format("2006-01-02 15:04:05"), err)
}
fmt.Printf("[%s] Device %s is PRESENT - keeping system awake\n",
time.Now().Format("2006-01-02 15:04:05"), config.DeviceName)
} else {
// Device gone past the grace period - allow sleep
allowSleep(inhibitCmd)
inhibitCmd = nil
fmt.Printf("[%s] Device %s is ABSENT - allowing system to sleep\n",
time.Now().Format("2006-01-02 15:04:05"), config.DeviceName)
}
}
case sig := <-sigChan:
fmt.Printf("\nReceived signal %v, shutting down...\n", sig)
// Clean up inhibit process on exit
allowSleep(inhibitCmd)
return nil
}
}
}
// isDaemonRunning checks if the daemon is already running
func isDaemonRunning() (int, bool) {
cmd := exec.Command("pgrep", "-f", "blunt.*run-daemon")
output, err := cmd.Output()
if err != nil {
return 0, false
}
lines := strings.Split(strings.TrimSpace(string(output)), "\n")
for _, line := range lines {
if line == "" {
continue
}
pid := strings.TrimSpace(line)
// Verify the process actually exists and is not a zombie
if _, err := os.Stat("/proc/" + pid); err == nil {
// Check if it's really our daemon (not just a grep)
cmdline, err := os.ReadFile("/proc/" + pid + "/cmdline")
if err == nil && strings.Contains(string(cmdline), "run-daemon") {
// Get our own PID to exclude ourselves
selfPid := fmt.Sprintf("%d", os.Getpid())
if pid != selfPid {
pidInt := 0
fmt.Sscanf(pid, "%d", &pidInt)
return pidInt, true
}
}
}
}
return 0, false
}
// daemonize runs the program as a daemon
func daemonize() error {
// Check if already running
if pid, running := isDaemonRunning(); running {
return fmt.Errorf("blunt daemon is already running (PID %d)", pid)
}
cmd2 := exec.Command("nohup", os.Args[0], "run-daemon")
cmd2.Stdin = nil
cmd2.Stdout = nil
cmd2.Stderr = nil
cmd2.SysProcAttr = &syscall.SysProcAttr{
Setsid: true,
}
err := cmd2.Start()
if err != nil {
return fmt.Errorf("failed to start daemon: %v", err)
}
fmt.Println("Blunt daemon started successfully")
return nil
}
// runUninstall handles the uninstall command
func runUninstall(cmd *cobra.Command, args []string) {
reader := bufio.NewReader(os.Stdin)
fmt.Println("This will uninstall blunt from your system.")
fmt.Print("Are you sure? (y/n): ")
response, _ := reader.ReadString('\n')
response = strings.TrimSpace(strings.ToLower(response))
if response != "y" && response != "yes" {
fmt.Println("Uninstall cancelled.")
return
}
home, err := os.UserHomeDir()
if err != nil {
fmt.Printf("Error getting home directory: %v\n", err)
os.Exit(1)
}
// Stop daemon if running
if pid, running := isDaemonRunning(); running {
fmt.Println("Stopping daemon...")
process, err := os.FindProcess(pid)
if err == nil {
process.Signal(syscall.SIGTERM)
time.Sleep(500 * time.Millisecond)
}
fmt.Println("✓ Daemon stopped")
}
// Remove systemd service if exists
servicePath := filepath.Join(home, ".config", "systemd", "user", "blunt.service")
if _, err := os.Stat(servicePath); err == nil {
// Stop and disable the service first
exec.Command("systemctl", "--user", "stop", "blunt.service").Run()
exec.Command("systemctl", "--user", "disable", "blunt.service").Run()
if err := os.Remove(servicePath); err != nil {
fmt.Printf("⚠ Failed to remove service file: %v\n", err)
} else {
fmt.Println("✓ Removed systemd service")
}
// Reload systemd
exec.Command("systemctl", "--user", "daemon-reload").Run()
}
// Remove binary from ~/.local/bin/
installPath := filepath.Join(home, ".local", "bin", "blunt")
if _, err := os.Stat(installPath); err == nil {
if err := os.Remove(installPath); err != nil {
fmt.Printf("⚠ Failed to remove binary: %v\n", err)
} else {
fmt.Println("✓ Removed binary from ~/.local/bin/")
}
}
// Ask about config file
configPath := getConfigPath()
if _, err := os.Stat(configPath); err == nil {
fmt.Print("Remove configuration file (~/.blunt)? (y/n): ")
response, _ := reader.ReadString('\n')
response = strings.TrimSpace(strings.ToLower(response))
if response == "y" || response == "yes" {
if err := os.Remove(configPath); err != nil {
fmt.Printf("⚠ Failed to remove config: %v\n", err)
} else {
fmt.Println("✓ Removed configuration file")
}
}
}
fmt.Println()
fmt.Println("Uninstall complete!")
}
// runInstall handles the install command
func runInstall(cmd *cobra.Command, args []string) {
// Get the current executable path
exePath, err := os.Executable()
if err != nil {
fmt.Printf("Error getting executable path: %v\n", err)
os.Exit(1)
}
// Resolve symlinks to get the real path
exePath, err = filepath.EvalSymlinks(exePath)
if err != nil {
fmt.Printf("Error resolving executable path: %v\n", err)
os.Exit(1)
}
// Determine install path
home, err := os.UserHomeDir()
if err != nil {
fmt.Printf("Error getting home directory: %v\n", err)
os.Exit(1)
}
installDir := filepath.Join(home, ".local", "bin")
installPath := filepath.Join(installDir, "blunt")
// Create ~/.local/bin if it doesn't exist
if err := os.MkdirAll(installDir, 0755); err != nil {
fmt.Printf("Error creating %s: %v\n", installDir, err)
os.Exit(1)
}
// Check if already installed there
if exePath == installPath {
fmt.Println("blunt is already installed at ~/.local/bin/blunt")
} else {
// Copy the binary
data, err := os.ReadFile(exePath)
if err != nil {
fmt.Printf("Error reading binary: %v\n", err)
os.Exit(1)
}
if err := os.WriteFile(installPath, data, 0755); err != nil {
fmt.Printf("Error writing binary: %v\n", err)
os.Exit(1)
}
fmt.Printf("✓ Installed blunt to %s\n", installPath)
}
// Check if ~/.local/bin is in PATH
pathEnv := os.Getenv("PATH")
if !strings.Contains(pathEnv, installDir) {
fmt.Println()
fmt.Println("⚠ WARNING: ~/.local/bin is not in your PATH")
fmt.Println("Add this to your ~/.bashrc or ~/.zshrc:")
fmt.Printf(" export PATH=\"$PATH:%s\"\n", installDir)
}
// Check for systemd user directory
systemdUserDir := filepath.Join(home, ".config", "systemd", "user")
if _, err := os.Stat(systemdUserDir); err == nil {
// Systemd user directory exists
fmt.Println()
fmt.Print("Would you like to install blunt as a systemd user service? (y/n): ")
reader := bufio.NewReader(os.Stdin)
response, _ := reader.ReadString('\n')
response = strings.TrimSpace(strings.ToLower(response))
if response == "y" || response == "yes" {
// Create systemd service file
serviceContent := `[Unit]
Description=Blunt - Bluetooth device monitor
After=bluetooth.target
[Service]
Type=simple
ExecStart=%s run-daemon
Restart=on-failure
RestartSec=5
[Install]
WantedBy=default.target
`
serviceContent = fmt.Sprintf(serviceContent, installPath)
servicePath := filepath.Join(systemdUserDir, "blunt.service")
if err := os.WriteFile(servicePath, []byte(serviceContent), 0644); err != nil {
fmt.Printf("Error creating service file: %v\n", err)
os.Exit(1)
}
fmt.Printf("✓ Created systemd service at %s\n", servicePath)
// Reload systemd user daemon
cmd := exec.Command("systemctl", "--user", "daemon-reload")
if err := cmd.Run(); err != nil {
fmt.Printf("⚠ Failed to reload systemd: %v\n", err)
} else {
fmt.Println("✓ Reloaded systemd user daemon")
}
// Enable the service
cmd = exec.Command("systemctl", "--user", "enable", "blunt.service")
if err := cmd.Run(); err != nil {
fmt.Printf("⚠ Failed to enable service: %v\n", err)
} else {
fmt.Println("✓ Enabled blunt service")
}
fmt.Println()
fmt.Println("Service installed but NOT started automatically.")
fmt.Println("To start it now, run:")
fmt.Println(" systemctl --user start blunt")
fmt.Println()
fmt.Println("To check status:")
fmt.Println(" systemctl --user status blunt")
}
}
fmt.Println()
fmt.Println("Installation complete!")
}
func main() {
var rootCmd = &cobra.Command{
Use: "blunt",
Short: "Bluetooth-based system unlock and sleep prevention",
Long: `Blunt detects if a specific Bluetooth device is nearby and prevents the system from going to sleep.`,
}
// Interactive setup command (default)
var setupCmd = &cobra.Command{
Use: "setup",
Short: "Set up a Bluetooth unlock device",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Blunt - Bluetooth Device Setup")
fmt.Println("==============================")
fmt.Println()
// Check if bluetooth is available
_, err := exec.LookPath("bluetoothctl")
if err != nil {
fmt.Println("Error: bluetoothctl not found. Please install bluez-utils.")
os.Exit(1)
}
reader := bufio.NewReader(os.Stdin)
var deviceMAC, deviceName string
// Option 1: Try to get paired devices
fmt.Println("Looking for paired devices...")
paired, _ := getPairedDevices()
if len(paired) > 0 {
fmt.Println("Found paired devices:")
for i, device := range paired {
fmt.Printf(" %d. %s\n", i+1, device)
}
fmt.Println()
}
// Option 2: Try to get connected devices
connected, _ := getConnectedDevices()
// Filter out duplicates from paired list
newConnected := []string{}
for _, c := range connected {
found := false
for _, p := range paired {
if c == p {
found = true
break
}
}
if !found {
newConnected = append(newConnected, c)
}
}
if len(newConnected) > 0 {
fmt.Println("Currently connected devices:")
for i, device := range newConnected {
fmt.Printf(" %d. %s\n", len(paired)+i+1, device)
}
fmt.Println()
}
// Combine all devices
allDevices := append(paired, newConnected...)
// Option 3: Scan for discoverable devices
fmt.Println("Would you like to scan for discoverable devices? (y/n)")
fmt.Print("> ")
response, _ := reader.ReadString('\n')
if strings.TrimSpace(strings.ToLower(response)) == "y" {
scanned, err := scanBluetoothDevices()
if err != nil {
fmt.Printf("Scan failed: %v\n", err)
} else if len(scanned) > 0 {
// Filter duplicates
newScanned := []string{}
for _, s := range scanned {
found := false
for _, existing := range allDevices {
if s == existing {
found = true
break
}
}
if !found {
newScanned = append(newScanned, s)
}
}
if len(newScanned) > 0 {
fmt.Println("Found discoverable devices:")
for i, device := range newScanned {
fmt.Printf(" %d. %s\n", len(allDevices)+i+1, device)
}
fmt.Println()
allDevices = append(allDevices, newScanned...)
} else {
fmt.Println("No new discoverable devices found.")
}
} else {
fmt.Println("No discoverable devices found.")
}
}
// Let user select or enter manually
if len(allDevices) > 0 {
fmt.Println("Select a device (number), or enter 'm' to type MAC manually:")
fmt.Print("> ")
input, _ := reader.ReadString('\n')
input = strings.TrimSpace(input)
if input == "m" || input == "M" {
// Manual entry
fmt.Println("Enter the MAC address (e.g., AA:BB:CC:DD:EE:FF):")
fmt.Print("> ")
macInput, _ := reader.ReadString('\n')
deviceMAC = normalizeMAC(strings.TrimSpace(macInput))
if !validateMAC(deviceMAC) {
fmt.Println("Invalid MAC address format")
os.Exit(1)
}
// Try to get name
deviceName = getDeviceName(deviceMAC)
if deviceName == "" {
fmt.Println("Enter a name for this device:")
fmt.Print("> ")
nameInput, _ := reader.ReadString('\n')
deviceName = strings.TrimSpace(nameInput)
if deviceName == "" {
deviceName = "Unknown Device"
}
}
} else {
// Selection from list
var selection int
_, err = fmt.Sscanf(input, "%d", &selection)
if err != nil || selection < 1 || selection > len(allDevices) {
fmt.Println("Invalid selection")
os.Exit(1)
}
selectedDevice := allDevices[selection-1]
// Parse "Name (MAC)"
startIdx := strings.LastIndex(selectedDevice, " (")
if startIdx == -1 {
fmt.Println("Error parsing device info")
os.Exit(1)
}
deviceName = selectedDevice[:startIdx]
deviceMAC = selectedDevice[startIdx+2 : len(selectedDevice)-1]
}
} else {
// No devices found at all, manual entry only
fmt.Println("No devices found. You can still enter a MAC address manually.")
fmt.Println("Note: The device doesn't need to be discoverable, just have Bluetooth on.")
fmt.Println()
fmt.Println("Enter the MAC address (e.g., AA:BB:CC:DD:EE:FF):")
fmt.Print("> ")
macInput, _ := reader.ReadString('\n')
deviceMAC = normalizeMAC(strings.TrimSpace(macInput))
if !validateMAC(deviceMAC) {
fmt.Println("Invalid MAC address format")
os.Exit(1)
}
// Try to get name
deviceName = getDeviceName(deviceMAC)
if deviceName == "" {
fmt.Println("Enter a name for this device:")
fmt.Print("> ")
nameInput, _ := reader.ReadString('\n')
deviceName = strings.TrimSpace(nameInput)
if deviceName == "" {
deviceName = "Unknown Device"
}
}
}
fmt.Println()
fmt.Printf("Selected: %s (%s)\n", deviceName, deviceMAC)
fmt.Println()
// Test if we can reach the device
fmt.Println("Testing connection...")
if checkDevicePresent(deviceMAC) {
fmt.Println("✓ Device is reachable!")
} else {
fmt.Println("⚠ Device is not currently reachable (might be out of range or Bluetooth is off)")
fmt.Println("That's OK - we'll keep checking when the daemon runs.")
}
fmt.Println()
fmt.Print("Enter check interval in seconds (default: 5): ")
intervalInput, _ := reader.ReadString('\n')
intervalInput = strings.TrimSpace(intervalInput)
interval := 5
if intervalInput != "" {
fmt.Sscanf(intervalInput, "%d", &interval)
if interval < 1 {
interval = 5
}
}
fmt.Print("Enter grace period (missed checks before sleeping, default: 3): ")
graceInput, _ := reader.ReadString('\n')
graceInput = strings.TrimSpace(graceInput)
grace := 3
if graceInput != "" {
fmt.Sscanf(graceInput, "%d", &grace)
if grace < 1 {
grace = 3
}
}
config := &Config{
DeviceName: deviceName,
DeviceMAC: deviceMAC,
CheckInterval: interval,
GraceChecks: grace,
}
err = saveConfig(config)
if err != nil {
fmt.Printf("Error saving configuration: %v\n", err)
os.Exit(1)
}
fmt.Printf("\nDevice '%s' (%s) configured successfully!\n", deviceName, deviceMAC)
fmt.Printf("Check interval: %d seconds\n", interval)
fmt.Println()
fmt.Println("Run 'blunt -d' to start the daemon.")
},
}
rootCmd.AddCommand(setupCmd)
// Add install command (defined early so we can reference it)
var installCmd = &cobra.Command{
Use: "install",
Short: "Install blunt to ~/.local/bin",
Long: `Installs the blunt binary to ~/.local/bin and optionally sets up a systemd user service`,
Run: runInstall,
}
rootCmd.AddCommand(installCmd)
// Add uninstall command
var uninstallCmd = &cobra.Command{
Use: "uninstall",
Short: "Uninstall blunt from the system",
Long: `Removes the blunt binary, systemd service, and optionally the configuration file`,
Run: runUninstall,
}
rootCmd.AddCommand(uninstallCmd)
var daemonFlag bool
var installFlag bool
var uninstallFlag bool
rootCmd.Flags().BoolVarP(&daemonFlag, "daemon", "d", false, "Run as daemon in background")
rootCmd.Flags().BoolVarP(&installFlag, "install", "i", false, "Install blunt to ~/.local/bin")
rootCmd.Flags().BoolVarP(&uninstallFlag, "uninstall", "u", false, "Uninstall blunt from the system")
// Default action is setup
rootCmd.RunE = func(cmd *cobra.Command, args []string) error {
if installFlag {
runInstall(cmd, args)
return nil
}
if uninstallFlag {
runUninstall(cmd, args)
return nil
}
if daemonFlag {
if !configExists() {
return fmt.Errorf("no unlock device configured. Run 'blunt' to set up a device")
}
return daemonize()
}
// Run setup
setupCmd.Run(cmd, args)
return nil
}
// Add hidden command for internal daemon execution
var runDaemonCmd = &cobra.Command{
Use: "run-daemon",
Hidden: true,
Run: func(cmd *cobra.Command, args []string) {
err := runDaemon()
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
},
}
rootCmd.AddCommand(runDaemonCmd)
// Add status command
var statusCmd = &cobra.Command{
Use: "status",
Short: "Show current configuration",
Run: func(cmd *cobra.Command, args []string) {
config, err := loadConfig()
if err != nil {
fmt.Println("No device configured. Run 'blunt' to set up.")
return
}
fmt.Printf("Configured device: %s (%s)\n", config.DeviceName, config.DeviceMAC)
fmt.Printf("Check interval: %d seconds\n", config.CheckInterval)
// Check if device is currently reachable
if checkDevicePresent(config.DeviceMAC) {
fmt.Println("Device status: reachable ✓")
} else {
fmt.Println("Device status: not reachable ✗")
}
// Check if daemon is running
if _, running := isDaemonRunning(); running {
fmt.Println("Daemon status: running")
} else {
fmt.Println("Daemon status: not running")
}
},
}
rootCmd.AddCommand(statusCmd)
// Add stop command
var stopCmd = &cobra.Command{
Use: "stop",
Short: "Stop the daemon",
Run: func(cmd *cobra.Command, args []string) {
pid, running := isDaemonRunning()
if !running {
fmt.Println("Daemon is not running")
return
}
// Kill the process
process, err := os.FindProcess(pid)
if err != nil {
fmt.Printf("Failed to find daemon process: %v\n", err)
return
}
err = process.Signal(syscall.SIGTERM)
if err != nil {
// Try SIGKILL as fallback
err = process.Kill()
if err != nil {
fmt.Printf("Failed to stop daemon: %v\n", err)
return
}
}
fmt.Println("Daemon stopped")
},
}
rootCmd.AddCommand(stopCmd)
if err := rootCmd.Execute(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}