#!/usr/bin/env node
import net from "node:net";

const [proxyHost, proxyPortRaw, targetHost, targetPortRaw] = process.argv.slice(2);
const proxyPort = Number.parseInt(proxyPortRaw || "", 10);
const targetPort = Number.parseInt(targetPortRaw || "", 10);
if (!proxyHost || !Number.isInteger(proxyPort) || !targetHost || !Number.isInteger(targetPort)) process.exit(64);

let settled = false;
let tunnel = false;
function finish(code) {
  if (settled) return;
  settled = true;
  process.exit(code);
}

const socket = net.createConnection({ host: proxyHost, port: proxyPort });
let buffer = Buffer.alloc(0);
socket.setTimeout(15000, () => {
  socket.destroy();
  finish(65);
});
socket.on("connect", () => socket.write(`CONNECT ${targetHost}:${targetPort} HTTP/1.1\r\nHost: ${targetHost}:${targetPort}\r\nProxy-Connection: Keep-Alive\r\n\r\n`));
socket.on("error", () => finish(tunnel ? 69 : 66));
socket.on("close", () => finish(tunnel ? 0 : 68));
socket.on("data", function onData(chunk) {
  buffer = Buffer.concat([buffer, chunk]);
  const headerEnd = buffer.indexOf("\r\n\r\n");
  if (headerEnd === -1 && buffer.length < 8192) return;
  if (headerEnd === -1) {
    socket.destroy();
    finish(68);
    return;
  }
  const statusLine = buffer.slice(0, headerEnd).toString("latin1").split("\r\n", 1)[0] || "";
  const statusCode = Number.parseInt(statusLine.split(" ")[1] || "", 10);
  if (!statusLine.startsWith("HTTP/1.") || !Number.isInteger(statusCode) || statusCode < 200 || statusCode > 299) {
    socket.destroy();
    finish(67);
    return;
  }
  socket.off("data", onData);
  socket.setTimeout(0);
  tunnel = true;
  const rest = buffer.slice(headerEnd + 4);
  if (rest.length) process.stdout.write(rest);
  process.stdin.on("error", () => {});
  process.stdout.on("error", () => {});
  process.stdin.pipe(socket);
  socket.pipe(process.stdout);
});
