implemented block function

This commit is contained in:
Niklas 2020-10-27 22:12:18 +01:00
parent 85691d11b0
commit 21c99ce8f6

36
main.go
View File

@ -6,6 +6,8 @@ import (
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"path"
"strconv"
"strings"
@ -113,7 +115,7 @@ func getTime(timeString string) (int, int) {
return int(hr), int(min)
}
func getNextWait(config sunsetConfig) string {
func getNextWait(config sunsetConfig) (int, int) {
index := nextIndex(config)
now := time.Now()
nextHr, nextMin := getTime(config.Files[index].Time)
@ -123,7 +125,6 @@ func getNextWait(config sunsetConfig) string {
// FIXME still not working
if now.Hour() >= nextHr && now.Minute() >= nextMin {
fmt.Print("u")
diffHr = 24 - (now.Hour() - nextHr)
diffMin = 60 - (now.Minute() - nextMin)
} else {
@ -131,12 +132,31 @@ func getNextWait(config sunsetConfig) string {
diffMin = nextMin - now.Minute()
}
return fmt.Sprintf("%dh%dm", diffHr, diffMin)
return diffHr, diffMin
}
func block(config sunsetConfig, command string) {
for {
nextHr, nextMin := getNextWait(config)
timer := time.NewTimer((time.Duration(nextHr) * time.Hour) + (time.Duration(nextMin) * time.Minute))
<-timer.C
go runCommand(command)
}
}
func runCommand(command string) {
cmd := exec.Command("/usr/bin/env sh", "-c", command)
err := cmd.Run()
if err != nil {
log.Printf("Command %s returned a non 0 code", command)
}
}
func main() {
printNextTime := flag.Bool("next", false, "Print the time to the next change")
printNextWait := flag.Bool("wait", false, "Print the time to wait for the next change")
blockFlag := flag.Bool("block", false, "Block and call the provided command when the background changes")
blockCommand := flag.String("command", "", "Specify a command to run when the background changed")
configFile := flag.String("file", "./sunset.json", "Specify the file to load")
flag.Parse()
@ -145,7 +165,15 @@ func main() {
if *printNextTime {
fmt.Printf("%s", getNextTime(conf))
} else if *printNextWait {
fmt.Printf("%s", getNextWait(conf))
hr, min := getNextWait(conf)
fmt.Printf("%dh%dm", hr, min)
} else if *blockFlag {
if *blockCommand == "" {
fmt.Println("Must provide a command.")
os.Exit(1)
}
block(conf, *blockCommand)
} else {
index := currentIndex(conf)
absoluteImagePath := path.Join(path.Dir(*configFile), conf.Files[index].File)