#!/usr/bin/env deno run --allow-net

/*
 * Copyright © 2026 Em Zakharov
 *
 * SPDX-License-Identifier: GPL-3.0-or-later
 */

let websocket: WebSocket | null = null;

const server = Deno.listen({ port: 8008 });

for await (const conn of server) {
  handle(conn);
}

/* ==================================== */

async function handle(conn: Deno.Conn) {
  const httpConn = Deno.serveHttp(conn);
  for await (const requestEvent of httpConn) {
    try {
      await requestEvent.respondWith(handleReq(requestEvent.request));
    } catch (ex) {
      console.log(ex);
    }
  }
}

async function handleReq(req: Request): Promise<Response> {
  const websocketUpgrade = req.headers.get("upgrade")?.toLowerCase() === "websocket";

  if (websocketUpgrade) {
    return handleWebSocketUpgrade(req);
  } else {
    if (websocket) {
      websocket.send("");
      return new Response("200 OK", { status: 200 });
    } else {
      return new Response("No WebSocket Connected", { status: 503 });
    }
  }
}

function handleWebSocketUpgrade(req: Request): Response {
  const { socket, response } = Deno.upgradeWebSocket(req);
  socket.onopen = () => websocket = socket;
  return response;
}
