FROM haproxy:3.2
USER root
RUN apt-get update && apt-get install -y bash gettext-base openssl && rm -rf /var/lib/apt/lists/*
RUN mkdir -p /usr/local/etc/haproxy/certs && chown -R haproxy:haproxy /usr/local/etc/haproxy

RUN printf '#!/bin/bash\ncd /usr/local/etc/haproxy/certs\nopenssl req -x509 -newkey rsa:2048 -keyout server.key -out server.crt -days 365 -nodes -subj "/CN=localhost" -quiet\ncat server.crt server.key > server.pem\nchown haproxy:haproxy server.key server.crt server.pem\nchmod 600 server.key server.pem\nchmod 644 server.crt\n' > /usr/local/bin/generate-cert.sh && chmod +x /usr/local/bin/generate-cert.sh

RUN printf 'global\n    log stdout local0 info\n    stats timeout 30s\n    user haproxy\ndefaults\n    log global\n    option httplog\n    option dontlognull\n    timeout connect 5s\n    timeout client 3600s\n    timeout server 3600s\n    timeout tunnel 3600s\nfrontend websocket_frontend\n    bind *:${PROXY_PORT} ${PROXY_SSL_BIND_OPTIONS}\n    mode http\n    http-response set-header Access-Control-Allow-Origin "*"\n    http-response set-header Access-Control-Allow-Headers "*"\n    http-response set-header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"\n    http-request return status 200 content-type "text/plain" string "OK" if METH_OPTIONS\n    default_backend websocket_backend\nbackend websocket_backend\n    mode http\n    server local_websocket ${BACKEND_HOST}:${BACKEND_PORT} check inter 2s rise 2 fall 3 on-marked-down shutdown-sessions\n' > /usr/local/etc/haproxy/haproxy.cfg.template && chown haproxy:haproxy /usr/local/etc/haproxy/haproxy.cfg.template

RUN printf '#!/bin/bash\nexport BACKEND_HOST=${BACKEND_HOST:-localhost}\nexport BACKEND_PORT=${BACKEND_PORT:-49100}\nexport PROXY_PORT=${PROXY_PORT:-48322}\n/usr/local/bin/generate-cert.sh\nexport PROXY_SSL_BIND_OPTIONS="ssl crt /usr/local/etc/haproxy/certs/server.pem"\nenvsubst < /usr/local/etc/haproxy/haproxy.cfg.template > /usr/local/etc/haproxy/haproxy.cfg\necho "WSS Proxy: wss://0.0.0.0:${PROXY_PORT} -> ws://${BACKEND_HOST}:${BACKEND_PORT}"\nexec haproxy -f /usr/local/etc/haproxy/haproxy.cfg\n' > /entrypoint.sh && chmod +x /entrypoint.sh

USER haproxy
ENTRYPOINT ["/entrypoint.sh"]
