{%- set role = grains.id.split('_') | last %}
{%- if role == 'fleet' %}
	{% set mainint = salt['pillar.get']('host:mainint') %}
	{% set main_ip = salt['grains.get']('ip_interfaces:' ~ mainint)[0] %}
{%- endif %}

{%- set manager_ip = salt['pillar.get']('manager:mainip', '') %}
{%- set url_base = salt['pillar.get']('global:url_base') %}

{%- set fleet_manager = salt['pillar.get']('global:fleet_manager') %}
{%- set fleet_node = salt['pillar.get']('global:fleet_node') %}
{%- set fleet_ip = salt['pillar.get']('global:fleet_ip', None) %}
{%- set airgap = salt['pillar.get']('global:airgap', 'False') %}


worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

include /usr/share/nginx/modules/*.conf;

events {
	worker_connections 1024;
}

http {
	log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
						'$status $body_bytes_sent "$http_referer" '
						'"$http_user_agent" "$http_x_forwarded_for"';

	access_log  /var/log/nginx/access.log  main;

	sendfile            on;
	tcp_nopush          on;
	tcp_nodelay         on;
	keepalive_timeout   65;
	types_hash_max_size 2048;
	client_max_body_size 2500M;

	server_tokens off;

	include             /etc/nginx/mime.types;
	default_type        application/octet-stream;

	include /etc/nginx/conf.d/*.conf;

	{%- if role in ['eval', 'managersearch', 'manager', 'standalone', 'fleet', 'import'] %}

		{%- if (fleet_manager or role == 'fleet') and role != 'import' %}
	server {
		listen       8090 ssl http2 default_server;
		server_name  {{ url_base }};
		root         /opt/socore/html;
		index        blank.html;

		ssl_certificate "/etc/pki/nginx/server.crt";
		ssl_certificate_key "/etc/pki/nginx/server.key";
		ssl_session_cache shared:SSL:1m;
		ssl_session_timeout  10m;
		ssl_ciphers HIGH:!aNULL:!MD5;
		ssl_prefer_server_ciphers on;

		location ~ ^/kolide.agent.Api/(RequestEnrollment|RequestConfig|RequestQueries|PublishLogs|PublishResults|CheckHealth)$ {
			{%- if role == 'fleet' %}
			grpc_pass  grpcs://{{ main_ip }}:8080;
			{%- else %}
			grpc_pass  grpcs://{{ manager_ip }}:8080;
			{%- endif %}
			grpc_set_header Host $host;
			grpc_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_buffering off;
		}
	}
		{%- endif %}

	server {
		listen 80 default_server;
		server_name _;
		return 307 https://{{ url_base }}$request_uri;
	}

	server {
		listen 443 ssl http2 default_server;
		server_name _;
		return 307 https://{{ url_base }}$request_uri;

		ssl_certificate "/etc/pki/nginx/server.crt";
		ssl_certificate_key "/etc/pki/nginx/server.key";
		ssl_session_cache shared:SSL:1m;
		ssl_session_timeout  10m;
		ssl_ciphers HIGH:!aNULL:!MD5;
		ssl_prefer_server_ciphers on;
		ssl_protocols TLSv1.2;
	}

	{%- endif %}

	{%- if role == 'fleet' %}
	server {
		listen       443 ssl http2;
		server_name  {{ main_ip }};
		root         /opt/socore/html;
		index        index.html;

		ssl_certificate "/etc/pki/nginx/server.crt";
		ssl_certificate_key "/etc/pki/nginx/server.key";
		ssl_session_cache shared:SSL:1m;
		ssl_session_timeout  10m;
		ssl_ciphers HIGH:!aNULL:!MD5;
		ssl_prefer_server_ciphers on;
		ssl_protocols TLSv1.2;

		location /fleet/ {
			proxy_pass https://{{ main_ip }}:8080;
			proxy_read_timeout    90;
			proxy_connect_timeout 90;
			proxy_set_header      Host $host;
			proxy_set_header      X-Real-IP $remote_addr;
			proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header      Proxy "";
			proxy_set_header      X-Forwarded-Proto $scheme;
		}
		error_page 500 502 503 504 /50x.html;
				location = /usr/share/nginx/html/50x.html {
		}
	}
	{%- elif role in ['eval', 'managersearch', 'manager', 'standalone', 'import'] %}

	{%- if airgap is sameas true %}
	server {
		listen 7788;
		server_name {{ url_base }};
		root /opt/socore/html/repo;
		location /rules/ {
			allow all;
			sendfile on;
			sendfile_max_chunk 1m;
			autoindex on;
			autoindex_exact_size off;
			autoindex_format html;
			autoindex_localtime on;
		}
	}
	{%- endif %}

	server {
		listen       443 ssl http2;
		server_name  {{ url_base }};
		root         /opt/socore/html;
		index        index.html;

		ssl_certificate "/etc/pki/nginx/server.crt";
		ssl_certificate_key "/etc/pki/nginx/server.key";
		ssl_session_cache shared:SSL:1m;
		ssl_session_timeout  10m;
		ssl_ciphers HIGH:!aNULL:!MD5;
		ssl_prefer_server_ciphers on;
		ssl_protocols TLSv1.2;

		location ~* (^/login/.*|^/js/.*|^/css/.*|^/images/.*) {
			proxy_pass            http://{{ manager_ip }}:9822;
			proxy_read_timeout    90;
			proxy_connect_timeout 90;
			proxy_set_header      Host $host;
			proxy_set_header      X-Real-IP $remote_addr;
			proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header      Proxy "";
			proxy_set_header      Upgrade $http_upgrade;
			proxy_set_header      Connection "Upgrade";
			proxy_set_header      X-Forwarded-Proto $scheme;
		}

		location / {
			auth_request          /auth/sessions/whoami;
			auth_request_set      $userid $upstream_http_x_kratos_authenticated_identity_id;
			proxy_set_header      x-user-id $userid;
			proxy_pass            http://{{ manager_ip }}:9822/;
			proxy_read_timeout    300;
			proxy_connect_timeout 300;
			proxy_set_header      Host $host;
			proxy_set_header      X-Real-IP $remote_addr;
			proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header      Proxy "";
			proxy_set_header      Upgrade $http_upgrade;
			proxy_set_header      Connection "Upgrade";
			proxy_set_header      X-Forwarded-Proto $scheme;
		}

		location ~ ^/auth/.*?(whoami|login|logout|settings) {
			rewrite               /auth/(.*) /$1 break;
			proxy_pass            http://{{ manager_ip }}:4433;
			proxy_read_timeout    90;
			proxy_connect_timeout 90;
			proxy_set_header      Host $host;
			proxy_set_header      X-Real-IP $remote_addr;
			proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header      Proxy "";
			proxy_set_header      X-Forwarded-Proto $scheme;
		}

		location /cyberchef/ {
			auth_request          /auth/sessions/whoami;
			proxy_read_timeout    90;
			proxy_connect_timeout 90;
			proxy_set_header      Host $host;
			proxy_set_header      X-Real-IP $remote_addr;
			proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header      Proxy "";
			proxy_set_header      X-Forwarded-Proto $scheme;
		}

		location /navigator/ {
			auth_request          /auth/sessions/whoami;
			proxy_read_timeout    90;
			proxy_connect_timeout 90;
			proxy_set_header      Host $host;
			proxy_set_header      X-Real-IP $remote_addr;
			proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header      Proxy "";
			proxy_set_header      X-Forwarded-Proto $scheme;
		}

		location /packages/ {
			try_files $uri =206;
			auth_request          /auth/sessions/whoami;
			proxy_read_timeout    90;
			proxy_connect_timeout 90;
			proxy_set_header      Host $host;
			proxy_set_header      X-Real-IP $remote_addr;
			proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header      Proxy "";
			proxy_set_header      X-Forwarded-Proto $scheme;
		} 

		{%- if airgap is sameas true %}
		location /repo/ {
			allow all;
			sendfile on;
			sendfile_max_chunk 1m;
			autoindex on;
			autoindex_exact_size off;
			autoindex_format html;
			autoindex_localtime on;
		}
		{%- endif %}
		
		location /grafana/ {
			auth_request          /auth/sessions/whoami;
			rewrite               /grafana/(.*) /$1 break;
			proxy_pass            http://{{ manager_ip }}:3000/;
			proxy_read_timeout    90;
			proxy_connect_timeout 90;
			proxy_set_header      Host $host;
			proxy_set_header      X-Real-IP $remote_addr;
			proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header      Proxy "";
			proxy_set_header      X-Forwarded-Proto $scheme;
		}

		location /kibana/ {
			auth_request          /auth/sessions/whoami;
			rewrite               /kibana/(.*) /$1 break;
			proxy_pass            http://{{ manager_ip }}:5601/;
			proxy_read_timeout    300;
			proxy_connect_timeout 300;
			proxy_set_header      Host $host;
			proxy_set_header      X-Real-IP $remote_addr;
			proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header      Proxy "";
			proxy_set_header      X-Forwarded-Proto $scheme;
		}

		location /nodered/ {
			proxy_pass http://{{ manager_ip }}:1880/;
			proxy_read_timeout    90;
			proxy_connect_timeout 90;
			proxy_set_header      Host $host;
			proxy_set_header      X-Real-IP $remote_addr;
			proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header Upgrade $http_upgrade;
			proxy_set_header Connection "Upgrade";
			proxy_set_header      Proxy "";
			proxy_set_header      X-Forwarded-Proto $scheme;
		}
		
		location /playbook/ {
			proxy_pass            http://{{ manager_ip }}:3200/playbook/;
			proxy_read_timeout    90;
			proxy_connect_timeout 90;
			proxy_set_header      Host $host;
			proxy_set_header      X-Real-IP $remote_addr;
			proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header      Proxy "";
			proxy_set_header      X-Forwarded-Proto $scheme;
		}

		{%- if fleet_node %}

		location /fleet/ {
			return 307 https://{{ fleet_ip }}/fleet;
		}

		{%- else %}

		location /fleet/ {
			proxy_pass https://{{ manager_ip }}:8080;
			proxy_read_timeout    90;
			proxy_connect_timeout 90;
			proxy_set_header      Host $host;
			proxy_set_header      X-Real-IP $remote_addr;
			proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header      Proxy "";
			proxy_set_header      X-Forwarded-Proto $scheme;
		}

		{%- endif %}

		location /thehive/ {
			proxy_pass            http://{{ manager_ip }}:9000/thehive/;
			proxy_read_timeout    90;
			proxy_connect_timeout 90;
			proxy_http_version    1.1; # this is essential for chunked responses to work
			proxy_set_header      Host $host;
			proxy_set_header      X-Real-IP $remote_addr;
			proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header      Proxy "";
			proxy_set_header      X-Forwarded-Proto $scheme;
		}

		location /cortex/ {
			proxy_pass            http://{{ manager_ip }}:9001/cortex/;
			proxy_read_timeout    90;
			proxy_connect_timeout 90;
			proxy_http_version    1.1; # this is essential for chunked responses to work
			proxy_set_header      Host $host;
			proxy_set_header      X-Real-IP $remote_addr;
			proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header      Proxy "";
			proxy_set_header      X-Forwarded-Proto $scheme;
		}
		
		location /soctopus/ {
			proxy_pass            http://{{ manager_ip }}:7000/;
			proxy_read_timeout    300;
			proxy_connect_timeout 300;
			proxy_set_header      Host $host;
			proxy_set_header      X-Real-IP $remote_addr;
			proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header      Proxy "";
			proxy_set_header      X-Forwarded-Proto $scheme;
		}

		location /kibana/app/soc/ {
			rewrite ^/kibana/app/soc/(.*) /soc/$1 permanent;
		}

		location /kibana/app/fleet/ {
			rewrite ^/kibana/app/fleet/(.*) /fleet/$1 permanent;
		}

		location /kibana/app/soctopus/ {
			rewrite ^/kibana/app/soctopus/(.*) /soctopus/$1 permanent;
		}

		location /sensoroniagents/ {
			if ($http_authorization = "") {
				return 403;
			}
			proxy_pass            http://{{ manager_ip }}:9822/;
			proxy_read_timeout    90;
			proxy_connect_timeout 90;
			proxy_set_header      Host $host;
			proxy_set_header      X-Real-IP $remote_addr;
			proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header      Proxy "";
			proxy_set_header      X-Forwarded-Proto $scheme;
		}

		error_page 401 = @error401;

		location @error401 {
			add_header    Set-Cookie "AUTH_REDIRECT=$request_uri;Path=/;Max-Age=14400";
			return        302 /auth/self-service/login/browser;
		}

		error_page 500 502 503 504 /50x.html;
				location = /usr/share/nginx/html/50x.html {
		}
	}
	{%- endif %}
}
