~chrisppy/beagles

ref: fe737c99f1e9cfcdf8ea4ef69c4bebfd8283d481 beagles/main.go -rw-r--r-- 8.6 KiB
fe737c99Chris Palmer update to tcel 2.2.0 9 months ago
                                                                                
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
// This file is part of beagles.
//
// Copyright © 2020-2021 Chris Palmer <chris@red-oxide.org>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"

	"git.sr.ht/~chrisppy/beagles/config"
	"git.sr.ht/~chrisppy/beagles/db"
	"git.sr.ht/~chrisppy/beagles/ui"
	"git.sr.ht/~sircmpwn/getopt"
	wlog "github.com/DataDrake/waterlog"
	"github.com/DataDrake/waterlog/format"
	"github.com/DataDrake/waterlog/level"
	"github.com/emersion/go-appdir"
)

var (
	// Version of the application
	Version string
)

func main() {

	opts, optind, err := getopt.Getopts(os.Args, "c:d:Df:g:hl:p:s:V")
	if err != nil {
		if _, err := fmt.Fprintln(os.Stderr, err); err != nil {
			panic(fmt.Sprintf("error writing to stderr: %e\n", err))
		}
		os.Exit(1)
	}

	var configDir, dbDir, dlDir, logDir, gmniDir, ioPath, ioDir string
	debug := false
	for _, opt := range opts {
		switch opt.Option {
		case 'c':
			configDir = opt.Value
		case 'd':
			dbDir = opt.Value
		case 'D':
			debug = true
		case 'f':
			ioPath = opt.Value
		case 'g':
			gmniDir = opt.Value
		case 'h':
			printHelp()
		case 'l':
			logDir = opt.Value
		case 'p':
			ioDir = opt.Value
		case 's':
			dlDir = opt.Value
		case 'V':
			printVersion()
		}
	}

	dirs := appdir.New("beagles")

	gmniPath, err := getGeminiPath(gmniDir)
	if err != nil {
		if _, err := fmt.Fprintln(os.Stderr, err); err != nil {
			panic(fmt.Sprintf("error writing to stderr: %e\n", err))
		}
		os.Exit(1)
	}

	cfg, err := getConfig(configDir, dirs)
	if err != nil {
		if _, err := fmt.Fprintln(os.Stderr, err); err != nil {
			panic(fmt.Sprintf("error writing to stderr: %e\n", err))
		}
		os.Exit(1)
	}

	db, err := getDatabase(dbDir, gmniPath, dirs)
	if err != nil {
		if _, err := fmt.Fprintln(os.Stderr, err); err != nil {
			panic(fmt.Sprintf("error writing to stderr: %e\n", err))
		}
		os.Exit(1)
	}
	db.Version = Version

	dlDir, err = getDownloadDir(dlDir, dirs)
	if err != nil {
		if _, err := fmt.Fprintln(os.Stderr, err); err != nil {
			panic(fmt.Sprintf("error writing to stderr: %e\n", err))
		}
		os.Exit(1)
	}

	logger, err := getLogger(logDir, debug, dirs)
	if err != nil {
		if _, err := fmt.Fprintln(os.Stderr, err); err != nil {
			panic(fmt.Sprintf("error writing to stderr: %e\n", err))
		}
		os.Exit(1)
	}

	args := os.Args[optind:]
	if len(args) > 1 {
		if _, err := fmt.Fprintln(os.Stderr, "only a single command is allowed"); err != nil {
			panic(fmt.Sprintf("error writing to stderr: %e\n", err))
		}
	} else if len(args) > 0 {
		switch args[0] {
		case "import":
			if ioPath == "" {
				if _, err := fmt.Fprintln(os.Stderr, `"-f file" is required for import`); err != nil {
					panic(fmt.Sprintf("error writing to stderr: %e\n", err))
				}
				os.Exit(1)
			}
			if err := db.Import(ioPath); err != nil {
				if _, err := fmt.Fprintln(os.Stderr, err); err != nil {
					panic(fmt.Sprintf("error writing to stderr: %e\n", err))
				}
				os.Exit(1)
			}
		case "export":
			if ioDir == "" {
				if _, err := fmt.Fprintln(os.Stderr, `"-p directory" is required for export`); err != nil {
					panic(fmt.Sprintf("error writing to stderr: %e\n", err))
				}
				os.Exit(1)
			}
			if err := db.Export(ioDir); err != nil {
				if _, err := fmt.Fprintln(os.Stderr, err); err != nil {
					panic(fmt.Sprintf("error writing to stderr: %e\n", err))
				}
				os.Exit(1)
			}
		case "backup":
			if ioDir == "" {
				if _, err := fmt.Fprintln(os.Stderr, `"-p directory" is required for backup`); err != nil {
					panic(fmt.Sprintf("error writing to stderr: %e\n", err))
				}
				os.Exit(1)
			}
			if err := db.Backup(ioDir); err != nil {
				if _, err := fmt.Fprintln(os.Stderr, err); err != nil {
					panic(fmt.Sprintf("error writing to stderr: %e\n", err))
				}
				os.Exit(1)
			}
		case "restore":
			if ioPath == "" {
				if _, err := fmt.Fprintln(os.Stderr, `"-f file" is required for restore`); err != nil {
					panic(fmt.Sprintf("error writing to stderr: %e\n", err))
				}
				os.Exit(1)
			}

			reader := bufio.NewReader(os.Stdin)
		it:
			for {
				fmt.Println(`The will replace all data with the contents of the file!  Continue? [Y/n]`)

				input, err := reader.ReadString('\n')
				if err != nil {
					if _, err := fmt.Fprintln(os.Stderr, err); err != nil {
						panic(fmt.Sprintf("error writing to stderr: %e\n", err))
					}
				}

				switch strings.ToLower(strings.TrimSpace(input)) {
				case "n", "no":
					break it
				case "y", "yes":
					if err := db.Restore(ioPath); err != nil {
						if _, err := fmt.Fprintln(os.Stderr, err); err != nil {
							panic(fmt.Sprintf("error writing to stderr: %e\n", err))
						}
						os.Exit(1)
					}
					break it
				default:
					fmt.Println("Must be one of the following: Y/N, y/n, Yes/No, yes/no")
				}
			}
		default:
			if _, err := fmt.Fprintf(os.Stderr, "invalid command: %v\n", args); err != nil {
				panic(fmt.Sprintf("error writing to stderr: %e\n", err))
			}
			os.Exit(1)
		}

		os.Exit(0)
	}
	i := &ui.UI{
		Version:          Version,
		DB:               db,
		Config:           cfg,
		DownloadDataHome: dlDir,
		GeminiDataHome:   gmniPath,
		Logger:           logger,
	}

	i.Init()

	if cfg.AutoUpdateInterval > 0 {
		go i.UpdateLoop(cfg.AutoUpdateInterval)
	}

	if err := i.Run(); err != nil {
		if _, err := fmt.Fprintln(os.Stderr, err); err != nil {
			panic(fmt.Sprintf("error writing to stderr: %e\n", err))
		}
		os.Exit(1)
	}
}

func getDatabase(dir string, gmniPath string, dirs appdir.Dirs) (*db.Storage, error) {
	if dir == "" {
		dir = dirs.UserData()
		if _, err := os.Stat(dir); os.IsNotExist(err) {
			if errDir := os.MkdirAll(dir, 0750); errDir != nil {
				return nil, err
			}
		}
	}

	return db.ReadDB(filepath.Clean(filepath.Join(dir, "beagles.db")), gmniPath)
}

func getConfig(dir string, dirs appdir.Dirs) (*config.Config, error) {
	if dir == "" {
		dir = dirs.UserConfig()
		if _, err := os.Stat(dir); os.IsNotExist(err) {
			if errDir := os.MkdirAll(dir, 0750); errDir != nil {
				return nil, err
			}
		}
	}

	return config.Load(dir)
}

func getLogger(dir string, debug bool, dirs appdir.Dirs) (*wlog.WaterLog, error) {
	logger := wlog.New(os.Stdout, "", log.Ltime)
	logger.SetFormat(format.Un)
	if debug {
		logger.SetLevel(level.Debug)
	} else {
		logger.SetLevel(level.Info)
	}

	if dir == "" {
		dir = dirs.UserLogs()
		if _, err := os.Stat(dir); os.IsNotExist(err) {
			if errDir := os.MkdirAll(dir, 0750); errDir != nil {
				return nil, err
			}
		}
	}

	logPath := filepath.Join(dir, "beagles.log")
	f, err := os.OpenFile(filepath.Clean(logPath), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 00600)
	if err != nil {
		return nil, err
	}
	logger.SetOutput(f)

	return logger, nil
}

func getDownloadDir(dir string, dirs appdir.Dirs) (string, error) {
	if dir == "" {
		dir = dirs.UserData()
		if _, err := os.Stat(dir); os.IsNotExist(err) {
			if errDir := os.MkdirAll(dir, 0750); errDir != nil {
				return "", err
			}
		}
	}

	return dir, nil
}

func getGeminiPath(dir string) (string, error) {
	if dir == "" {
		dirs := appdir.New("gemini")
		dir = dirs.UserData()
	}

	path := filepath.Join(dir, "known_hosts")

	return path, nil
}

func printHelp() {
	usage := `beagles version %s Copyright (c) 2020 the beagles developers
Usage: beagles [options]...

	-c [dir]	Set the config directory.  If not set, use
			XDG_CONFIG_HOME/beagles.
	-d [dir]	Set the database directory.  If not set, use
			XDG_DATA_HOME/beagles.
	-D		Print debug lines.
	-g [dir]	Set the directory for your gemini known_hosts.
			If not set, use XDG_DATA_HOME/gemini.
 	-h		Print basic options
	-l [dir]	Set the logging directory.  If not set, use
			XDG_CACHE_HOME/beagles.
	-s [dir]	Set the download directory.  If not set, use
			XDG_DATA_HOME/beagles.
	-V		Print version information

For more information consult the beagles man pages.
`
	if _, err := fmt.Fprintf(os.Stdout, usage, Version); err != nil {
		panic(fmt.Sprintf("error writing help page to stdout: %s\n", err.Error()))
	}
	os.Exit(0)

}

func printVersion() {
	if _, err := fmt.Fprintf(os.Stdout, "beagles v%s\n", Version); err != nil {
		panic(fmt.Sprintf("error writing version to stdout: %s\n", err.Error()))
	}
	os.Exit(0)
}