Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
146 lines (114 loc) · 2.41 KB
/
Copy pathmain.go
File metadata and controls
146 lines (114 loc) · 2.41 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
package main
import (
"context"
"fmt"
"os"
"syscall"
"github.com/jessevdk/go-flags"
"qubert/internal/config"
"qubert/internal/installer"
"qubert/internal/logger"
"qubert/application"
)
var (
Version string
Commit string
)
type options struct {
ConfigFile string `short:"c" long:"config" description:"Config file"`
Daemon bool `short:"d" long:"daemon" description:"Run as daemon"`
ShowVersion bool `short:"v" long:"version" description:"Show version and exit"`
Install bool `short:"i" long:"install" description:"Install and run"`
}
func main() {
err := mainFunc(os.Args)
if err != nil {
_, _ = fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
func RunInBackground(args []string) error {
for i, a := range args {
if a == "-b" {
args = append(args[:i], args[i+1:]...)
}
}
path, err := os.Getwd()
if err != nil {
return err
}
attr := &os.ProcAttr{
Dir: path,
Env: os.Environ(),
Files: []*os.File{
os.Stdin,
nil,
nil,
},
Sys: &syscall.SysProcAttr{
Noctty: true,
//Credential: &syscall.Credential{
// Uid: uint32(os.Getuid()),
// Gid: uint32(os.Getuid()),
//},
},
}
p, err := os.StartProcess(args[0], append([]string{"qubert"}, args[1:]...), attr)
if err != nil {
return err
}
err = p.Release()
if err != nil {
return err
}
logger.CreateLogger(false).Info("Background process successfully started.")
os.Exit(0)
return nil
}
func mainFunc(args []string) error {
opt := &options{
ConfigFile: "config.json",
}
flagParser := flags.NewParser(opt, flags.HelpFlag|flags.PassDoubleDash)
_, err := flagParser.ParseArgs(args)
if err != nil {
return err
}
if opt.Install && opt.Daemon {
return fmt.Errorf("using 'install' and 'daemon' is not supported at the same time")
}
if opt.Daemon {
err = RunInBackground(args)
if err != nil {
return err
}
}
cfg, err := config.Load(opt.ConfigFile)
if err != nil {
return err
}
if opt.Install {
log := logger.CreateLogger(false)
err = installer.InstallCurrentVersion(cfg, log)
if err != nil {
return err
}
log.Info("successfully installed")
os.Exit(0)
}
if opt.ShowVersion {
message := `Qubert
Version: %s
Git commit: %s
`
_, _ = fmt.Fprintf(os.Stderr, message, Version, Commit)
return nil
}
ctx := context.Background()
app := application.NewApplication(cfg, Version, Commit)
err = app.Run(ctx)
if err != nil {
return err
}
return nil
}