package main

import (
	"flag"
	"fmt"
	"log"
	"net"
	"os"
	"strconv"

	"github.com/duffy/usb-server/internal/relay"
)

func main() {
	port := flag.Int("port", 8443, "listen port")
	addr := flag.String("addr", "0.0.0.0", "listen address")
	flag.Parse()

	// Also check environment variables (for Docker)
	if envPort := os.Getenv("RELAY_PORT"); envPort != "" {
		fmt.Sscanf(envPort, "%d", port)
	}
	if envAddr := os.Getenv("RELAY_ADDR"); envAddr != "" {
		*addr = envAddr
	}

	listenAddr := buildListenAddr(*addr, *port)

	log.SetFlags(log.LstdFlags | log.Lshortfile)
	log.Printf("USB Relay Server starting on %s", listenAddr)

	server := relay.NewServer(listenAddr)
	if err := server.Run(); err != nil {
		log.Fatalf("server error: %v", err)
	}
}

// buildListenAddr combines the address and port flags.
//
// -addr is documented as a bare address, but "-addr :9000" and
// "-addr 1.2.3.4:9000" are the obvious things to type. Appending the port
// blindly turns those into ":9000:8443", which fails with an unhelpful
// "too many colons" error, so an address that already carries a port wins.
func buildListenAddr(addr string, port int) string {
	if _, _, err := net.SplitHostPort(addr); err == nil {
		return addr
	}
	return net.JoinHostPort(addr, strconv.Itoa(port))
}
