Raspberry Pi alarm clock server.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

78 lines
1.8 KiB

package sonar
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
// SetSchedule installs the crontab.
func (s *Sonar) SetSchedule(tod time.Time, days []string) error {
// Assemble our new crontab entries.
entries := []string{
// m h dom mon dow command
fmt.Sprintf("%d %d * * %s %s",
tod.Minute(),
tod.Hour(),
strings.Join(days, ","),
"curl -X POST http://"+s.url+"/playlist/start",
),
fmt.Sprintf("%d %d * * %s %s",
tod.Minute(),
tod.Add(1*time.Hour).Hour(),
strings.Join(days, ","),
"curl -X POST http://"+s.url+"/playlist/stop",
),
"",
}
// Concat all the user's custom crontab entries.
crons, err := BuildCrontab()
if err != nil {
return fmt.Errorf("SetSchedule: BuildCrontab: %s", err)
}
// Final cron file is the user's custom crons plus the new ones.
crontab := strings.Join(append(crons, entries...), "\n")
fmt.Println(crontab)
// Install the crontab.
cmd := exec.Command("crontab", "-")
var out bytes.Buffer
var stderr bytes.Buffer
cmd.Stdin = strings.NewReader(crontab)
cmd.Stdout = &out
cmd.Stderr = &stderr
err = cmd.Run()
if err != nil {
return fmt.Errorf("SetSchedule: crontab -: %s\nSTDOUT: %s\nSTDERR: %s", err, out.String(), stderr.String())
}
return nil
}
// BuildCrontab concatenates all the crontabs from crontab.in/
func BuildCrontab() ([]string, error) {
var crontab []string
err := filepath.Walk("./crontab.in", func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
return nil
}
data, err := ioutil.ReadFile(path)
if err != nil {
return fmt.Errorf("ReadAll(%s): %s", path, err)
}
lines := strings.Split(string(data), "\n")
crontab = append(crontab, lines...)
return nil
})
if err != nil {
return nil, err
}
return crontab, nil
}