-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
87 lines (77 loc) · 1.66 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
package main
import (
"flag"
"io/ioutil"
"log"
"os"
"path/filepath"
"github.com/fsnotify/fsnotify"
)
func writeHosts(hostsPath string, hostsFile string) {
hostsFiles, err := ioutil.ReadDir(hostsPath)
if err != nil {
log.Fatal(err)
}
tmpFile, err := ioutil.TempFile("", "hosts")
if err != nil {
log.Fatal(err)
}
defer tmpFile.Close()
for _, file := range hostsFiles {
if !file.IsDir() {
fullPath := filepath.Join(hostsPath, file.Name())
contents, err := ioutil.ReadFile(fullPath)
if err != nil {
log.Print(err)
}
tmpFile.WriteString("# " + fullPath + "\n")
tmpFile.Write(contents)
tmpFile.Write([]byte("\n"))
}
}
err = tmpFile.Chmod(0644)
if err != nil {
log.Fatal(err)
}
err = os.Rename(tmpFile.Name(), hostsFile)
if err == nil {
log.Println("Successfuly wrote hosts file")
} else {
log.Fatal("Could not write hosts file:", err)
}
}
func main() {
hostsPath := flag.String("hostsfiles", "/etc/hosts.d", "directory for hosts files")
hostsFile := flag.String("hostsfile", "/etc/hosts", "target hosts file")
writeHosts(*hostsPath, *hostsFile)
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
defer watcher.Close()
done := make(chan bool)
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
if event.Name[len(event.Name)-4:] != ".swp" || event.Name[len(event.Name)-1:] != "~" {
log.Println("event:", event)
writeHosts(*hostsPath, *hostsFile)
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Println("error:", err)
}
}
}()
err = watcher.Add(*hostsPath)
if err != nil {
log.Fatal(err)
}
<-done
}