-
Notifications
You must be signed in to change notification settings - Fork 0
/
giggle.go
112 lines (97 loc) · 2.5 KB
/
giggle.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
package main
import (
"fmt"
"log"
"os"
"os/signal"
"syscall"
"github.com/getlantern/systray"
"github.com/mangalaman93/giggle/conf"
"github.com/mangalaman93/giggle/svc"
"github.com/mangalaman93/giggle/tray"
"github.com/sevlyar/go-daemon"
"github.com/sqweek/dialog"
"gopkg.in/natefinch/lumberjack.v2"
)
func dialogAndPanic(message string, err error) {
log.Println(message)
dialog.Message(message).Error()
panic(err)
}
func main() {
logFolder := conf.LogFolder()
if _, err := os.Stat(logFolder); err != nil {
if os.IsNotExist(err) {
errDir := os.MkdirAll(logFolder, conf.DirPerm())
if errDir != nil {
message := fmt.Sprintf("[ERROR] unable to create log folder :: %v", errDir)
dialogAndPanic(message, errDir)
} else {
log.Println("[INFO] created log directory")
}
} else {
message := fmt.Sprintf("[ERROR] unable to get log folder stats :: %v", err)
dialogAndPanic(message, err)
}
} else {
log.Println("[INFO] log directory already exists")
}
dctx := &daemon.Context{
PidFileName: conf.PidFilePath(),
PidFilePerm: 0644,
}
child, err := dctx.Reborn()
if err != nil {
message := fmt.Sprintf("[ERROR] unable to daemonize :: %v", err)
dialogAndPanic(message, err)
}
if child != nil {
log.Println("running the service as a daemon")
} else {
defer dctx.Release()
runChild()
}
}
func runChild() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
logFilePath := conf.LogFilePath()
log.SetOutput(&lumberjack.Logger{
Filename: logFilePath,
MaxSize: conf.LogFileMaxSize(),
MaxBackups: conf.LogMaxNumBackups(),
MaxAge: conf.LogFileMaxAge(),
LocalTime: true,
})
log.Println("#################### BEGIN OF LOG ##########################")
// register ctrl+c
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
log.Println("[INFO] adding signal handler for SIGTERM")
// giggle system tray
quit := make(chan struct{})
gt := tray.Start(quit)
defer func() {
if err := gt.Stop(); err != nil {
log.Println("[WARN] unable to stop giggle tray ::", err)
}
}()
// giggle service
gsvc := svc.Start()
defer func() {
if err := gsvc.Stop(); err != nil {
log.Println("[WARN] unable to stop giggle service ::", err)
}
}()
go func() {
// wait for ctrl+c
log.Println("[INFO] waiting for ctrl+c signal")
select {
case <-quit:
case <-sigs:
}
systray.Quit()
}()
// This has to be called here in the main thread, fails on mac otherwise.
systray.Run(gt.OnReady, nil)
log.Println("[INFO] exiting giggle")
}