
user  root;
worker_processes  1;

env PATH;
env PATH_REDPITAYA;

error_log  /var/log/redpitaya_nginx/error.log;
error_log  /var/log/redpitaya_nginx/debug.log warn;
#error_log  /var/log/redpitaya_nginx/debug.log info;

pid        /var/run/redpitaya_nginx.pid;

daemon on;

events {
    worker_connections  1024;
}

# worker_rlimit_core 500M;

http {
    include       mime.types;
    default_type  application/octet-stream;

    init_by_lua 'cjson = require "cjson"';
    lua_shared_dict rp_params 10m;

    access_log /dev/null;

    map $http_upgrade $connection_upgrade {
        default upgrade;
        '' close;
    }

    # TODO, it might make sense to configure wersockets to use
    # a simple UNIX socket instead of an IP socket,
    # there should be less overhead
    upstream websocket {
        server 127.0.0.1:9002;
    }

    # Jupyter notebook server
    upstream notebook {
        server 127.0.0.1:8888;
    }

    proxy_temp_path /tmp/proxy 1 2;
    scgi_temp_path  /tmp/scgi 1 2;

    server {
        listen 80;
        listen [::]:80;
        expires off;

        keepalive_timeout 0;

        access_log /dev/null;

        #gzip on;
        #gzip_http_version 1.0;
        #gzip_vary on;
        #gzip_comp_level 6;
        #gzip_proxied any;
        #gzip_types application/json;
        #gzip_buffers 16 8k;
        #gzip_buffers 128 4k;
        #gzip_disable "MSIE [1-6]\.(?!.*SV1)";

        root /opt/redpitaya/www/apps;

        include ../apps/*/nginx.conf;

        location ~ ^/tmp {
            root /;
        }

        location ~ ^/log {
            root /var/;
        }

        location ~ \.css {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';

            default_type text/css;
            add_header  Content-Type    text/css;
        }

        location ~ \.js {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';

            default_type application/x-javascript;
            add_header  Content-Type    application/x-javascript;
        }

        client_body_buffer_size 1M;
        client_body_temp_path /tmp;
        rp_bazaar_dir     /opt/redpitaya/www/apps;
        rp_bazaar_server  http://bazaar.redpitaya.com;
        rp_tmp_dir        /tmp;

        location /bazaar {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';

                 rp_module_cmd;
        }

        location /wss {
            proxy_pass http://websocket;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
        }

        location /check_inet {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';

            default_type application/json;

            content_by_lua_file /opt/redpitaya/www/conf/lua/online.lua;
        }

        location /data {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';

                 rp_module_cmd;
        }

        location /upload_gen_ch1 {
             add_header 'Access-Control-Allow-Origin' '*';
             add_header 'Access-Control-Allow-Credentials' 'true';
             add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
             add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
             add_header 'Content-type' 'text/plain; charset=utf-8';

             content_by_lua '
                if ngx.req.get_method() == "POST" then
                   local file = io.open("/tmp/gen_ch1.csv", "w");
                   ngx.req.read_body();
                   io.output(file):write(ngx.var.request_body);
                   io.flush(file);
                   io.close(file);
                   os.execute("sed -i \'1,4d;$d\' /tmp/gen_ch1.csv");
                   ngx.say("OK");
                else
                   ngx.say("ERROR: Unsupported request method");
                end
             ';
        }

        location /upload_gen_ch2 {
             add_header 'Access-Control-Allow-Origin' '*';
             add_header 'Access-Control-Allow-Credentials' 'true';
             add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
             add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
             add_header 'Content-type' 'text/plain; charset=utf-8';

             content_by_lua '
                if ngx.req.get_method() == "POST" then
                   local file = io.open("/tmp/gen_ch2.csv", "w");
                   ngx.req.read_body();
                   io.output(file):write(ngx.var.request_body);
                   io.flush(file);
                   io.close(file);
                   os.execute("sed -i \'1,4d;$d\' /tmp/gen_ch2.csv");
                   ngx.say("OK");
                else
                   ngx.say("ERROR: Unsupported request method");
                end
             ';
        }

        location /reboot {
            content_by_lua '
                os.execute("reboot");
                ngx.say("OK")
            ';
        }

        location /lic_upload {
            content_by_lua '
                local hex_to_char = function(x)
                    return string.char(tonumber(x, 16))
                end

                local unescape = function(url)
                    return url:gsub("%%(%x%x)", hex_to_char):gsub("%+", " ")
                end

                if ngx.req.get_method() == "POST" then
                    ngx.req.read_body();


                    local fname = unescape(ngx.var.request_body):find("lic.lic");
                    local start = unescape(ngx.var.request_body):find("{");
                    local stop  = unescape(ngx.var.request_body):find("]\\n}\\r\\n");

                    if fname ~= nil and start ~= nil and stop ~= nil then

                        local file = io.open("/tmp/lic.lic", "w");
                        io.output(file):write(unescape(ngx.var.request_body):sub(start,stop + 2));
                        io.flush(file);
                        io.close(file);

                        local zfile = io.open("/tmp/zlog.txt", "w");

                        io.output(zfile):write(unescape(ngx.var.request_body):sub(start,stop + 2));
                        io.flush(zfile);
                        io.close(zfile);

                        os.execute("bazaar lic 0");

                        ngx.header["Access-Control-Allow-Origin"]= "*";
                        ngx.header["Access-Control-Allow-Credentials"]= "true";
                        ngx.header["Access-Control-Allow-Methods"]= "GET, POST, OPTIONS";
                        ngx.header["Access-Control-Allow-Headers"]= "DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type";
                        ngx.header["Content-type"]= "text/html; charset=utf-8";
                        ngx.say("OK")
                   else
                        ngx.header["Access-Control-Allow-Origin"]= "*";
                        ngx.header["Access-Control-Allow-Credentials"]= "true";
                        ngx.header["Access-Control-Allow-Methods"]= "GET, POST, OPTIONS";
                        ngx.header["Access-Control-Allow-Headers"]= "DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type";
                        ngx.header["Content-type"]= "text/html; charset=utf-8";
                        ngx.say("Fail_1")
                    end;
                else
                    ngx.say("Fail_2")
                end
            ';
        }

        location /check_jq {
        }

    }
}
