apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ include "styrened-test.fullname" . }}-config
  labels:
    {{- include "styrened-test.labels" . | nindent 4 }}
data:
  config.yaml: |
    reticulum:
      mode: {{ .Values.styrene.reticulum.mode }}
      transport_enabled: {{ .Values.styrene.reticulum.transport_enabled }}
      announce_interval: {{ .Values.styrene.reticulum.announce_interval }}

    rpc:
      enabled: {{ .Values.styrene.rpc.enabled }}

    discovery:
      announce_interval: {{ .Values.styrene.discovery.announce_interval }}

    chat:
      auto_reply_mode: {{ .Values.styrene.chat.auto_reply_mode }}

---
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ include "styrened-test.fullname" . }}-rns
  labels:
    {{- include "styrened-test.labels" . | nindent 4 }}
data:
  config: |
    [reticulum]
    enable_transport = {{ .Values.rns.enable_transport }}
    share_instance = {{ .Values.rns.share_instance }}

    [interfaces]
    {{- range $i, $iface := .Values.rns.interfaces }}
      [[Interface {{ $i }}]]
      type = {{ $iface.type }}
      enabled = {{ $iface.enabled }}
      {{- if eq $iface.type "TCPServerInterface" }}
      listen_ip = {{ $iface.listen_ip }}
      listen_port = {{ $iface.listen_port }}
      {{- end }}
      {{- if eq $iface.type "TCPClientInterface" }}
      target_host = {{ $iface.target_host }}
      target_port = {{ $iface.target_port }}
      {{- end }}
      {{- if eq $iface.type "AutoInterface" }}
      {{- end }}
    {{- end }}
{{- if .Values.ipcRelay.enabled }}
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ include "styrened-test.fullname" . }}-relay
  labels:
    {{- include "styrened-test.labels" . | nindent 4 }}
data:
  tcp_relay.py: |
    """TCP-to-Unix socket relay for exposing IPC sockets from containers."""
    import asyncio
    import sys

    async def relay(reader, writer, label):
        try:
            while True:
                data = await reader.read(65536)
                if not data:
                    break
                writer.write(data)
                await writer.drain()
        except (ConnectionResetError, BrokenPipeError, asyncio.CancelledError):
            pass
        finally:
            try:
                writer.close()
                await writer.wait_closed()
            except Exception:
                pass

    async def handle_tcp_client(tcp_reader, tcp_writer, unix_path):
        try:
            unix_reader, unix_writer = await asyncio.open_unix_connection(unix_path)
        except Exception as e:
            print(f"[relay] Failed to connect to {unix_path}: {e}", flush=True)
            tcp_writer.close()
            return
        t1 = asyncio.create_task(relay(tcp_reader, unix_writer, "tcp->unix"))
        t2 = asyncio.create_task(relay(unix_reader, tcp_writer, "unix->tcp"))
        done, pending = await asyncio.wait([t1, t2], return_when=asyncio.FIRST_COMPLETED)
        for task in pending:
            task.cancel()
            try:
                await task
            except asyncio.CancelledError:
                pass

    async def main(unix_path, tcp_port):
        server = await asyncio.start_server(
            lambda r, w: handle_tcp_client(r, w, unix_path),
            host="0.0.0.0", port=tcp_port,
        )
        addr = server.sockets[0].getsockname()
        print(f"[relay] Listening on {addr[0]}:{addr[1]} -> {unix_path}", flush=True)
        async with server:
            await server.serve_forever()

    if __name__ == "__main__":
        if len(sys.argv) != 3:
            print(f"Usage: {sys.argv[0]} <unix_socket_path> <tcp_port>", file=sys.stderr)
            sys.exit(1)
        asyncio.run(main(sys.argv[1], int(sys.argv[2])))
{{- end }}
