// Continuity: a one-station radio that plays your own WAV files on a fixed daily
// schedule taken from the real clock, and names each programme only after it ends.
package main

import (
	"context"
	"flag"
	"fmt"
	"net"
	"net/http"
	"os"
	"os/signal"
	"path/filepath"
	"strings"
	"syscall"
	"time"
	_ "time/tzdata"
)

func main() {
	dir := flag.String("dir", ".", "the folder of WAV files")
	addr := flag.String("addr", ":8080", "the address to broadcast on")
	flag.Parse()

	files, refused, err := scan(*dir)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	for _, r := range refused {
		fmt.Printf("refused: %s (%s)\n", r.name, r.reason)
	}
	if loops := convertLoops(refused); len(loops) > 0 {
		fmt.Println("Convert once, in this folder:")
		for _, l := range loops {
			fmt.Println(l)
		}
	}
	if len(files) == 0 {
		fmt.Printf("No programme. Put 16-bit, 44100 Hz, stereo WAV files in %s.\n", *dir)
		os.Exit(2)
	}

	s := newStation(*dir, time.Local, zoneName(), time.Now, func(msg string) {
		fmt.Printf("%s %s\n", clock(time.Now()), msg)
	})
	if err := s.startUp(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	ln, err := net.Listen("tcp", *addr)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	go func() {
		for range time.Tick(250 * time.Millisecond) {
			s.tick()
		}
	}()
	host, port, _ := net.SplitHostPort(*addr)
	if host == "" || host == "0.0.0.0" || host == "::" {
		host = "localhost"
	}
	fmt.Printf("Continuity is on air at http://%s/ (%s accepted, %d refused).\n", net.JoinHostPort(host, port), plural(len(files), "file"), len(refused))
	// On Ctrl-C or SIGTERM every stream ends cleanly (its last chunk is sent), so a
	// player hears the broadcast end rather than a fault, and takes its rejoin path.
	off, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()
	srv := &http.Server{Handler: s.mux(), ReadHeaderTimeout: 10 * time.Second, BaseContext: func(net.Listener) context.Context { return off }}
	failed := make(chan error, 1)
	go func() { failed <- srv.Serve(smallSendBuffer{ln}) }()
	select {
	case err := <-failed:
		fmt.Println(err)
		os.Exit(1)
	case <-off.Done():
	}
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	srv.Shutdown(ctx)
}

// startUp builds today's log (and tomorrow's inside the last minute), and checks
// the slot on air now. Slots that began while the program was stopped stay unchecked.
func (s *station) startUp() error {
	if _, err := s.day(dayStart(s.now(), s.loc)); err != nil {
		return err
	}
	s.tick()
	return nil
}

// tick runs four times a second: it prints "ended:" for each slot that has ended
// since the last tick, makes the slot-start check, builds tomorrow's log 60 seconds
// before the day's end, and closes the files of slots long gone.
func (s *station) tick() {
	now := s.now()
	start := dayStart(now, s.loc)
	l, err := s.day(start)
	if err != nil {
		s.con(err.Error())
		return
	}
	a := absFrame(now)
	i := l.at(a - l.startA())
	if p := s.lastLog; p != nil {
		from := s.lastI
		if p.date < l.date {
			for _, sl := range p.slots[from:] {
				s.con("ended: " + title(sl.name))
			}
			from = 0
		}
		for _, sl := range l.slots[min(from, i):i] { // a clock set back prints nothing
			s.con("ended: " + title(sl.name))
		}
	}
	s.lastLog, s.lastI = l, i
	if i < len(l.slots) && l.slots[i].start <= a-l.startA() {
		s.source(l, i)
	}
	if next := nextDay(start); !now.Before(next.Add(-time.Minute)) {
		if _, err := s.day(next); err != nil {
			s.con(err.Error())
		}
	}
	s.closeEnded(a)
}

// zoneName names the machine's zone for the log and the colophon: TZ when set,
// else the /etc/localtime link, else the abbreviation in use now.
func zoneName() string {
	if tz := strings.TrimPrefix(os.Getenv("TZ"), ":"); tz != "" {
		return tz
	}
	if p, err := filepath.EvalSymlinks("/etc/localtime"); err == nil {
		if _, z, ok := strings.Cut(p, "zoneinfo/"); ok {
			return z
		}
	}
	z, _ := time.Now().Zone()
	return z
}

func plural(n int, word string) string {
	if n == 1 {
		return fmt.Sprintf("1 %s", word)
	}
	return fmt.Sprintf("%d %ss", n, word)
}
