-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwake.go
117 lines (107 loc) · 2.58 KB
/
wake.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
package main
import (
"encoding/json"
"errors"
"flag"
"os"
"strings"
"github.com/ghthor/gowol"
)
func main() {
c, err := initialize()
if err != nil {
os.Stderr.WriteString("Initialization failed: " + err.Error() + "\n")
return
}
for m := range c.Macs {
if err := wol.MagicWake(m, c.Broadcast); err != nil {
os.Stderr.WriteString("Error for MAC '" + m + "': '" + err.Error() + "'\n")
} else if c.Verbose {
os.Stdout.WriteString("Waking '" + m + "' ...\n")
}
}
}
type config struct {
Broadcast string
Macs map[string]struct{}
Profiles map[string][]string
Verbose bool
}
func initialize() (*config, error) {
//Initialize config struct
var c config
c.Macs = make(map[string]struct{})
c.Profiles = make(map[string][]string)
//Initialize flags
var flgs = initFlags()
//Initialize config first by config file.
if err := c.loadConfig("wake.conf"); err != nil && *flgs.Verbose {
os.Stderr.WriteString("Failed to load config file 'wake.conf': " + err.Error() + "\n")
} else if c.Verbose {
os.Stderr.WriteString("Config file loaded.\n")
}
//Then incorporate provided flags.
if err := c.loadFlags(flgs); err != nil {
return nil, err
}
return &c, nil
}
func (c *config) loadConfig(fileName string) error {
fileReader, err := os.Open(fileName)
if err != nil {
return err
}
defer fileReader.Close()
dec := json.NewDecoder(fileReader)
if err := dec.Decode(c); err != nil {
return err
}
return nil
}
type flags struct {
Bcast *string
Prof *string
Verbose *bool
}
func initFlags() *flags {
var f flags
// Define available flags.
f.Bcast = flag.String("b", "", "The network's broadcast address.")
f.Prof = flag.String("p", "", "The profile name of the profile to use.")
f.Verbose = flag.Bool("v", false, "Be verbose during operation.")
flag.Parse()
return &f
}
func (c *config) loadFlags(flgs *flags) error {
// Parse the command line flags
if len(*flgs.Bcast) > 0 {
c.Broadcast = *flgs.Bcast
} else if len(c.Broadcast) <= 0 {
return errors.New("Please specify the network's broadcast address using the '-b' flag.")
}
if len(*flgs.Prof) > 0 {
addrs, ok := c.Profiles[*flgs.Prof]
if ok {
for _, a := range addrs {
c.Add(a)
}
} else {
return errors.New("Profile with name '" + *flgs.Prof + "' does not exist.")
}
}
if *flgs.Verbose {
//For now only pick up the flag if it is set to true.
c.Verbose = *flgs.Verbose
}
var args = flag.Args()
if len(args) > 0 {
for _, address := range args {
c.Add(address)
}
}
return nil
}
func (c *config) Add(address string) {
var mac = strings.ToLower(address)
c.Macs[mac] = struct{}{}
}