yacdt/main.go

143 lines
3.1 KiB
Go

package main
import (
"fmt"
"os"
"strings"
"sync"
"time"
"text/template"
"github.com/alexflint/go-arg"
)
/*
%H:%M:%S
H{%:}M{%:}%S
{{if .Hour}}{{.Hours}}h {{end}}{{if .Minute}}{{.Minutes}}m {{end}}{{.Seconds}}s
*/
type Arguments struct {
Hour int `arg:"--hour,-h" help:"Target hour" default:"-1"`
Minute int `arg:"--minute,-m" help:"Target minute" default:"-1"`
Year int `arg:"--year" help:"Target year" default:"-1"`
Day int `arg:"--day" help:"Target day" default:"-1"`
Month int `arg:"--month" help:"Target month" default:"-1"`
Output string `arg:"--output,-o" help:"Output filename" default:"/tmp/countdown.txt"`
Done string `arg:"--done,-d" help:"String to display when done" default:"MOVIE SIGN"`
Format string `arg:"--format,-f" help:"Format string for the countdown" default:"{{if .Hours}}{{.Hours}}h {{end}}{{if or .Minutes .Hours}}{{.Minutes}}m {{end}}{{.Seconds}}s"`
}
func main() {
args := &Arguments{}
arg.MustParse(args)
now := time.Now()
if args.Hour == -1 {
args.Hour = now.Hour()
}
if args.Minute == -1 {
args.Minute = now.Minute()
}
if args.Year == -1 {
args.Year = now.Year()
}
if args.Month == -1 {
args.Month = int(now.Month())
}
if args.Day == -1 {
args.Day = now.Day()
}
until := time.Date(
args.Year, time.Month(args.Month), args.Day,
args.Hour, args.Minute, 0, 0, time.Local,
)
if now.After(until) {
fmt.Println("time is in the past!")
return
}
fmt.Printf("Output file: %s\nCountdown to: %s\n", args.Output, until)
var err error
tp := template.New("time")
tp, err = tp.Parse(args.Format)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
wg := sync.WaitGroup{}
wg.Add(1)
ticker := time.NewTicker(time.Second)
go func(c <-chan time.Time) {
count := time.Until(until)
fmt.Println(count)
for ; count >= 0; count = time.Until(until) {
h := int(count.Hours())
m := int(int(count.Minutes()) % 60)
s := int(int(count.Seconds()) % 60)
data := struct {
Hours int
Minutes int
Seconds int
}{
Hours: h,
Minutes: m,
Seconds: s,
}
// Do I want to use this format as well as the complicated AF one?
//str := format
//if hide && h == 0 {
// str = strings.ReplaceAll(str, "%H", "")
// str = strings.ReplaceAll(str, "%h", "")
//} else {
// str = strings.ReplaceAll(str, "%H", fmt.Sprintf("%02d", h))
// str = strings.ReplaceAll(str, "%h", fmt.Sprintf("%d", h))
//}
//if !(hide && h == 0 && m == 0) {
// str = strings.ReplaceAll(str, "%M", fmt.Sprintf("%02d", m))
// str = strings.ReplaceAll(str, "%m", fmt.Sprintf("%d", m))
//}
//str = strings.ReplaceAll(str, "%S", fmt.Sprintf("%02d", s))
//str = strings.ReplaceAll(str, "%s", fmt.Sprintf("%d", s))
sb := strings.Builder{}
err = tp.Execute(&sb, &data)
if err != nil {
fmt.Println(err)
continue
}
err = os.WriteFile(args.Output, []byte(sb.String()), 0644)
if err != nil {
fmt.Println("unable to write file: %v\n", err)
}
_ = <-c
}
wg.Done()
}(ticker.C)
wg.Wait()
err = os.WriteFile(args.Output, []byte(args.Done), 0644)
if err != nil {
fmt.Println("unable to write file: %v\n", err)
}
fmt.Println("\nDONE")
}