package main import ( "os" "gopkg.in/yaml.v2" "io/ioutil" "regexp" "errors" ) type Config struct { Scripts []Scripts } type Scripts struct { Name string Recurrence string Commands []string } func main() { var config Config err := yaml.Unmarshal(readFile(os.Args[1]), &config) check(err) timeFolders := []string{"15min", "hourly", "daily", "weekly", "monthly"} //Check whether recurrence entries are valid for i := 0; i < len(config.Scripts); i++ { match, err := regexp.MatchString("15min|hourly|daily|weekly|monthly", config.Scripts[i].Recurrence) check(err) if !match { panic(errors.New("Invalid recurrence.")) } } //Remove old scripts for j := 0; j < len(config.Scripts); j++ { for i := 0; i < len(timeFolders); i++ { path := "/etc/periodic/" + timeFolders[i] + "/" + config.Scripts[j].Name exists, err := existsFile(path) check(err) if exists { os.Remove(path) } } } for i := 0; i < len(config.Scripts); i++ { fileContent := "#!/bin/sh\n" for j := 0; j < len(config.Scripts[i].Commands); j++ { fileContent += config.Scripts[i].Commands[j] + "\n" } path := "/etc/periodic/" + config.Scripts[i].Recurrence + "/" + config.Scripts[i].Name file, err := os.Create(path) check(err) file.WriteString(fileContent) file.Sync() os.Chmod(file.Name(), 0755) } } func existsFile(path string) (bool, error) { _, err := os.Stat(path) if err == nil { return true, nil } if os.IsNotExist(err) { return false, nil } return true, err } func readFile(path string) []byte { data, err := ioutil.ReadFile(path) check(err) return data } func check(e error) { if e != nil { panic(e) } }