-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
323 lines (267 loc) · 8.01 KB
/
main.go
File metadata and controls
323 lines (267 loc) · 8.01 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
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
/*
SPDX-License-Identifier: GPL-3.0-or-later
Copyright (C) 2025 Aaron Mathis aaron.mathis@gmail.com
This file is part of CloudAWSync.
CloudAWSync 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.
CloudAWSync 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 CloudAWSync. If not, see https://www.gnu.org/licenses/.
*/
package main
import (
"flag"
"fmt"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"CloudAWSync/internal/config"
"CloudAWSync/internal/interfaces"
"CloudAWSync/internal/service"
"CloudAWSync/internal/utils"
"go.uber.org/zap"
)
const (
version = "1.0.0"
appName = "CloudAWSync"
)
var (
configPath = flag.String("config", "", "Path to configuration file")
showVersion = flag.Bool("version", false, "Show version information")
showHelp = flag.Bool("help", false, "Show help information")
daemon = flag.Bool("daemon", true, "Run as daemon (default: true)")
logLevel = flag.String("log-level", "", "Override log level (debug, info, warn, error)")
generateConfig = flag.Bool("generate-config", false, "Generate sample configuration file")
)
func main() {
flag.Parse()
if *showVersion {
fmt.Printf("%s version %s\n", appName, version)
os.Exit(0)
}
if *showHelp {
showUsage()
os.Exit(0)
}
if *generateConfig {
if err := generateSampleConfig(); err != nil {
fmt.Fprintf(os.Stderr, "Failed to generate config: %v\n", err)
os.Exit(1)
}
fmt.Println("Sample configuration generated successfully")
os.Exit(0)
}
// Load configuration
cfg, err := config.LoadConfig(*configPath)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to load configuration: %v\n", err)
os.Exit(1)
}
// Override log level if specified
if *logLevel != "" {
cfg.Logging.Level = *logLevel
}
// Initialize logger
logger, err := utils.InitLogger(cfg.Logging)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to initialize logger: %v\n", err)
os.Exit(1)
}
defer logger.Sync()
logger.Info("Starting CloudAWSync",
zap.String("version", version),
zap.String("config_path", getConfigPath(*configPath)))
// Create and start service
svc, err := service.NewService(cfg)
if err != nil {
logger.Fatal("Failed to create service", zap.Error(err))
}
// Setup signal handling
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT)
// Start signal handler
go func() {
sig := <-sigChan
logger.Info("Received signal, shutting down gracefully",
zap.String("signal", sig.String()))
// Stop the service
if err := svc.Stop(); err != nil {
logger.Error("Error during shutdown", zap.Error(err))
}
os.Exit(0)
}()
// Start service
if err := svc.Start(); err != nil {
logger.Fatal("Failed to start service", zap.Error(err))
}
// Run as daemon
if *daemon {
logger.Info("Running as daemon, waiting for signals...")
svc.Wait()
} else {
// For testing/development, run for a short time
logger.Info("Running in non-daemon mode for testing")
time.Sleep(30 * time.Second)
logger.Info("Test run completed, stopping service")
if err := svc.Stop(); err != nil {
logger.Error("Error stopping service", zap.Error(err))
}
}
// Graceful shutdown
logger.Info("Shutting down service")
if err := svc.Stop(); err != nil {
logger.Error("Error during shutdown", zap.Error(err))
}
logger.Info("CloudAWSync stopped")
}
func showUsage() {
fmt.Printf(`%s - Cloud File Synchronization Agent
Usage: %s [options]
Options:
-config string
Path to configuration file (default: searches standard locations)
-daemon
Run as daemon (default: true)
-generate-config
Generate sample configuration file
-help
Show this help message
-log-level string
Override log level (debug, info, warn, error)
-version
Show version information
Configuration File Locations (searched in order):
1. Path specified by -config flag
2. $XDG_CONFIG_HOME/cloudawsync/config.yaml
3. $HOME/.config/cloudawsync/config.yaml
4. /etc/cloudawsync/config.yaml
Environment Variables:
AWS_ACCESS_KEY_ID - AWS access key ID
AWS_SECRET_ACCESS_KEY - AWS secret access key
AWS_SESSION_TOKEN - AWS session token (optional)
AWS_REGION - AWS region (default: us-east-1)
Examples:
# Run with default configuration
%s
# Run with custom config file
%s -config /path/to/config.yaml
# Generate sample configuration
%s -generate-config
# Run in foreground with debug logging
%s -daemon=false -log-level=debug
SystemD Service:
To run as a systemd service, copy the generated service file to
/etc/systemd/system/ and enable it:
sudo systemctl enable cloudawsync
sudo systemctl start cloudawsync
`, appName, os.Args[0], os.Args[0], os.Args[0], os.Args[0], os.Args[0])
}
func generateSampleConfig() error {
cfg := config.DefaultConfig()
// Add sample directories
cfg.Directories = []interfaces.SyncDirectory{
{
LocalPath: "/home/user/Documents",
RemotePath: "documents",
SyncMode: interfaces.SyncModeRealtime,
Schedule: "",
Recursive: true,
Filters: []string{"*.tmp", "*.lock", ".DS_Store"},
Enabled: true,
},
{
LocalPath: "/home/user/Pictures",
RemotePath: "pictures",
SyncMode: interfaces.SyncModeScheduled,
Schedule: "0 2 * * *", // Daily at 2 AM
Recursive: true,
Filters: []string{"*.tmp", "Thumbs.db"},
Enabled: false, // Disabled by default
},
}
configPath := "cloudawsync-config.yaml"
if err := cfg.SaveConfig(configPath); err != nil {
return err
}
fmt.Printf("Sample configuration saved to: %s\n", configPath)
fmt.Println("\nIMPORTANT: Edit the configuration file to:")
fmt.Println("1. Set your AWS credentials and S3 bucket")
fmt.Println("2. Configure your directories to sync")
fmt.Println("3. Adjust security and performance settings")
fmt.Println("4. Enable directories you want to sync")
return nil
}
func getConfigPath(providedPath string) string {
if providedPath != "" {
return providedPath
}
// Try standard locations
locations := []string{
os.Getenv("XDG_CONFIG_HOME") + "/cloudawsync/config.yaml",
os.Getenv("HOME") + "/.config/cloudawsync/config.yaml",
"/etc/cloudawsync/config.yaml",
}
for _, location := range locations {
if location != "/cloudawsync/config.yaml" { // Skip if env var is empty
if _, err := os.Stat(location); err == nil {
return location
}
}
}
return "default configuration"
}
// generateSystemDService generates a systemd service file
func generateSystemDService(cfg *config.Config) error {
serviceContent := fmt.Sprintf(`[Unit]
Description=CloudAWSync - Cloud File Synchronization Agent
After=network.target
Wants=network-online.target
[Service]
Type=simple
User=%s
Group=%s
WorkingDirectory=%s
ExecStart=%s -daemon=true
Restart=%s
RestartSec=5
StandardOutput=journal
StandardError=journal
SyslogIdentifier=cloudawsync
# Security settings
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=read-only
ReadWritePaths=%s
# Resource limits
MemoryMax=512M
CPUQuota=50%%
[Install]
WantedBy=multi-user.target
`,
cfg.SystemD.User,
cfg.SystemD.Group,
cfg.SystemD.WorkingDir,
filepath.Join(cfg.SystemD.WorkingDir, "cloudawsync"),
cfg.SystemD.RestartPolicy,
cfg.SystemD.WorkingDir,
)
serviceFile := "cloudawsync.service"
if err := os.WriteFile(serviceFile, []byte(serviceContent), 0644); err != nil {
return err
}
fmt.Printf("SystemD service file generated: %s\n", serviceFile)
fmt.Println("To install:")
fmt.Printf(" sudo cp %s /etc/systemd/system/\n", serviceFile)
fmt.Println(" sudo systemctl daemon-reload")
fmt.Println(" sudo systemctl enable cloudawsync")
fmt.Println(" sudo systemctl start cloudawsync")
return nil
}