#include "sockethelper.h"
#include "debug.h"
#include <fcntl.h>

void setnonblocking(int sock) {
	int opts = fcntl(sock,F_GETFL);
	errlog(opts);
	opts = (opts | O_NONBLOCK);
	errlog(fcntl(sock,F_SETFL,opts));
}

int inet_passive_socket(const char *address, int port, int flags) {
  int socket_fd;
  struct sockaddr_in name;
  struct hostent* hostinfo;
	int client_len = sizeof (struct sockaddr_in);
	int reuse_addr = ( flags&REBIND ? 1 : 0 );
	
  /* Create the socket.  */
  socket_fd = socket (PF_INET, SOCK_STREAM, 0);
	errlog(socket_fd);
  
	/* Store the server's name in the socket address.  */
  name.sin_family = AF_INET;
	
  /* Convert from strings to numbers.  */
  hostinfo = gethostbyname (address);
  errorlog(hostinfo,NULL);

	name.sin_addr = *((struct in_addr *) hostinfo->h_addr);
  name.sin_port = htons (port);

	/* Set re-bind property, if needed */
	errlog(setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &reuse_addr, sizeof(reuse_addr)));
	
	if (flags&NONBLOCKING) {
		/* Set socket to non-blocking with our setnonblocking routine */
		setnonblocking(socket_fd);
	}

	errlog(bind(socket_fd, &name, sizeof(struct sockaddr_in)));
	errlog(listen(socket_fd,5));

	return socket_fd;
}
