package main

import (
	"flag"
	"io"
	"net"
	"os/exec"
)

func main() {
	bind := flag.String("bind", "127.0.0.1:8987", "Addr:Port to listen to")
	flag.Parse()

	args := flag.Args()

	if flag.NArg() < 1 {
		panic("no arguments provided")
	}
	uaddr, err := net.ResolveUDPAddr("udp", *bind)
	if err != nil {
		panic(err)
	}

	lst, err := net.ListenUDP("udp", uaddr)
	if err != nil {
		panic(err)
	}
	defer lst.Close()

	cmd := exec.Command(args[0], args[1:]...)
	stdoutIn, _ := cmd.StdoutPipe()
	stderrIn, _ := cmd.StderrPipe()
	output := io.MultiReader(stdoutIn, stderrIn)

	buf := make([]byte, 1024)
	_, addr, err := lst.ReadFromUDP(buf)
	if err != nil {
		panic(err)
	}
	println("Received connection from %v", addr)

	go func() {
		for {
			_, err := output.Read(buf)
			if err != nil {
				if err == io.EOF {
					return
				}
				panic(err)
			}
			lst.WriteTo(buf, addr)
		}
	}()

	defer func() {
		lst.WriteTo([]byte("<EOF>\n"), addr)
	}()

	cmd.Start()
	err = cmd.Wait()
	if err != nil {
		panic(err)
	}
}
