package hello

import "core:fmt"
import "core:strings"
import "core:c"
import "core:c/libc"
import "../../bsd"

port :: #config(port, 4000)

main :: proc() {
	server, client: bsd.Socket
	failed1: bsd.server_socket_failures
	failed2: bsd.accept_client_failures
	err: bsd.error
	peername: string

	portstr := strings.unsafe_string_to_cstring(fmt.tprintf("%d\x00", port))
	server, failed1, err = bsd.server_socket(nil, portstr, {bsd.SO_REUSEADDR})
	if err != 0 {
		fmt.eprintf(
			"server socket creation failed: %v: %s (%v)\n",
			failed1,
			libc.strerror(c.int(err)),
			err,
		)
		return
	}
	fmt.println("listening on port", port)

	for {
		client, peername, failed2, err = bsd.accept_client(server)
		if err != 0 {
			fmt.eprintf("accept failed: %v: %s (%v)\n", failed2, libc.strerror(c.int(err)), err)
			continue
		}
		defer bsd.close(client)
		fmt.println("got connection from", peername)

		sent: uint
		msg :: "Hello, world!\n"
		if sent, err = bsd.errno(bsd.send(client, raw_data(string(msg)), len(msg), 0)); err != 0 {
			fmt.eprintf("send error: %d\n", err)
		}
		fmt.printf("sent %d bytes\n", sent)
	}
}

