package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"os/signal"
	"syscall"

	"git.teamworkapps.com/shortcut/cremote/daemon"
)

var (
	daemonHost = flag.String("listen", "localhost", "Listen address")
	port       = flag.Int("port", 8989, "Listen port")
	debug      = flag.Bool("debug", false, "Enable debug logging")
)

func main() {
	flag.Parse()

	log.Printf("Starting cremote daemon version %s on %s:%d (debug: %v)", daemon.Version, *daemonHost, *port, *debug)

	// Create and start the daemon
	d, err := daemon.NewDaemon(*daemonHost, *port, *debug)
	if err != nil {
		log.Fatalf("Failed to create daemon: %v", err)
	}

	// Handle graceful shutdown
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)

	go func() {
		<-sigChan
		fmt.Println("Shutting down daemon...")
		d.Stop()
	}()

	// Start the daemon (this blocks until the server is stopped)
	log.Printf("Starting daemon on port %d", *port)
	if err := d.Start(); err != nil {
		log.Fatalf("Failed to start daemon: %v", err)
	}
}
