-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
98 lines (80 loc) · 1.88 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
88
89
90
91
92
93
94
95
96
97
98
package main
import (
"bufio"
"fmt"
"log"
"os"
"os/exec"
"regexp"
"strings"
"github.com/robfig/cron/v3"
)
const (
DefaultScriptsDir = "./scripts"
)
func main() {
scriptsDir := getScriptsDir()
c := cron.New()
files, err := os.ReadDir(scriptsDir)
if err != nil {
log.Fatalf("Failed to read directory: %v", err)
}
for _, file := range files {
if !strings.HasSuffix(file.Name(), ".sh") {
log.Printf("Skipping non-shell file: %s", file.Name())
continue
}
filePath := fmt.Sprintf("%s/%s", scriptsDir, file.Name())
cronLine, err := parseCronLine(filePath)
if err != nil {
log.Printf("Error parsing cron line from %s: %v", file.Name(), err)
continue
}
_, err = c.AddFunc(cronLine, func() { runScript(filePath) })
if err != nil {
log.Printf("Error scheduling script %s: %v", file.Name(), err)
continue
}
log.Printf("Scheduled %s with cron spec %s", file.Name(), cronLine)
}
c.Start()
defer c.Stop()
// Prevent the program from exiting.
select {}
}
func getScriptsDir() string {
if len(os.Args) > 1 {
return os.Args[1]
}
return DefaultScriptsDir
}
func parseCronLine(filePath string) (string, error) {
file, err := os.Open(filePath)
if err != nil {
return "", err
}
defer file.Close()
scanner := bufio.NewScanner(file)
cronRegex := regexp.MustCompile(`^#CRON: (.*)$`)
for scanner.Scan() {
line := scanner.Text()
matches := cronRegex.FindStringSubmatch(line)
if len(matches) > 1 {
return matches[1], nil
}
}
if err := scanner.Err(); err != nil {
return "", err
}
return "", fmt.Errorf("no cron line found in file: %s", filePath)
}
func runScript(scriptPath string) {
cmd := exec.Command("/bin/sh", scriptPath)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
log.Printf("Error running script %s: %s", scriptPath, err)
return
}
log.Printf("Finished running script: %s", scriptPath)
}