require "socket"

server = UNIXServer.new("/tmp/myapp.sock")
CLIENTS = [] of UNIXSocket

Signal::INT.trap {
  puts "closing server..."
  server.close
  exit
}

def on_message(client)
  loop {
    msg = client.gets
    if msg == "quit"
      puts "deleting client..."
      CLIENTS.delete client
      pp CLIENTS.size
      break
    else
      yield msg
    end
  }
end

loop {
  puts "waiting for client on /tmp/myapp.sock"
  new_client = server.accept
  spawn {
    on_message(new_client) { |msg|
      CLIENTS.each { |client|
        client.puts msg unless client == new_client
      }
    }
  }
  CLIENTS << new_client
  pp CLIENTS.size
}
