# lua_package_path '/usr/share/lua/5.1/?.lua;;';

server {
  listen 8080 default_server;
  root /var/www/html/;
  index index.html;
  set_by_lua $endpoint 'return os.getenv("ENDPOINT")'; 

  location / {
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
    add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
    try_files $uri $uri/ =404;
    add_header Last-Modified $date_gmt;
    if_modified_since off;
    expires off;
    etag off;
    sub_filter_types "*";
    sub_filter endpoint_placeholder $endpoint;
  }

  location /kube/chaos/programming_mode {
    access_by_lua_file "/usr/local/openresty/nginx/conf/kubeinvaders/programming_mode.lua";
  }

  location /kube/pods {
    access_by_lua_file "/usr/local/openresty/nginx/conf/kubeinvaders/pod.lua";
  }

  location /kube/delete/pods {
    access_by_lua_file "/usr/local/openresty/nginx/conf/kubeinvaders/pod.lua";
  }

  location /kube/nodes {
    access_by_lua_file "/usr/local/openresty/nginx/conf/kubeinvaders/node.lua";
  }

  location /kube/chaos/nodes {
    access_by_lua_file "/usr/local/openresty/nginx/conf/kubeinvaders/chaos-node.lua";
  }

  location /kube/kube-linter {
    access_by_lua_file "/usr/local/openresty/nginx/conf/kubeinvaders/kube-linter.lua";
  }

  location /kube/endpoint {
    content_by_lua_block {
      ngx.header['Access-Control-Allow-Origin'] = '*'
      ngx.header['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
      ngx.header['Access-Control-Allow-Headers'] = 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range'
      ngx.header['Access-Control-Expose-Headers'] = 'Content-Length,Content-Range';
      if os.getenv("ENDPOINT") == nil then
        ngx.say("Error! ENDPOINT is nil!")
      else
        ngx.say(os.getenv("ENDPOINT"))
      end
    }  
  }

  location /kube/namespaces {
    content_by_lua_block {
      ngx.header['Access-Control-Allow-Origin'] = '*'
      ngx.header['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
      ngx.header['Access-Control-Allow-Headers'] = 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range'
      ngx.header['Access-Control-Expose-Headers'] = 'Content-Length,Content-Range';
      -- TO DO
      -- Check when NAMESPACE is nil
      ngx.say(os.getenv("NAMESPACE"))
    }  
  }

  location /metrics {
    default_type text/html;
    content_by_lua_block {
      local redis = require "resty.redis"
      local red = redis:new()

      -- local okredis, errredis = red:connect(os.getenv("REDIS_HOST"), 6379)
      local okredis, errredis = red:connect("unix:/tmp/redis.sock")

      for i, res in ipairs(red:keys("*")) do
        ngx.log(ngx.ERR, res)
        
        if string.find(res, "chaos_node_jobs_total_on") then
          node = string.gsub(res, "chaos_node_jobs_total_on_", "")
          metric = "chaos_jobs_node_count{node=\"".. node .."\"}"
          ngx.say(metric ..  " " .. red:get(res))

        elseif string.find(res, "deleted_pods_total_on")  then
          namespace = string.gsub(res, "deleted_pods_total_on_", "")
          metric = "deleted_namespace_pods_count{namespace=\"".. namespace .."\"}"
          ngx.say(metric ..  " " .. red:get(res))

        -- TO DO: Use improved regex...
        elseif not string.find(res, "programming_mode") and not string.find(res, "log:") and not string.find(res, "log_") then
          ngx.say(res ..  " " .. red:get(res))

        end
      end
    }
  }

  location /kube/chaos/containers {
    lua_need_request_body 'on';
    access_by_lua_file "/usr/local/openresty/nginx/conf/kubeinvaders/chaos-containers.lua";
  }

  location /chaos/logs/keepalive {
    content_by_lua_block {
      local redis = require "resty.redis"
      local red = redis:new()
      local args = ngx.req.get_uri_args()
      ngx.header['Access-Control-Allow-Origin'] = '*'
      ngx.header['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
      ngx.header['Access-Control-Allow-Headers'] = 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range'
      ngx.header['Access-Control-Expose-Headers'] = 'Content-Length,Content-Range';
      ngx.req.read_body()
      data = ngx.req.get_body_data()
      local okredis, errredis = red:connect("unix:/tmp/redis.sock")
      logid = args["logid"]
      red:set("log_cleaner:" .. logid, "1")
      red:expire("log_cleaner:" .. logid, "10")
    }
  }

  location /chaos/loadpreset {
    content_by_lua_block {
      local redis = require "resty.redis"
      local red = redis:new()
      local args = ngx.req.get_uri_args()
      ngx.header['Access-Control-Allow-Origin'] = '*'
      ngx.header['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
      ngx.header['Access-Control-Allow-Headers'] = 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range'
      ngx.header['Access-Control-Expose-Headers'] = 'Content-Length,Content-Range';
      ngx.req.read_body()
      local okredis, errredis = red:connect("unix:/tmp/redis.sock")
      local key_name = args["lang"] .. "_" .. args["name"]

      local res, err = red:get(key_name)

      if res == ngx.null then
        ngx.say(err)
      else
        ngx.say(res)
      end
    }
  }

  location /chaos/loadpreset/save {
    content_by_lua_block {
      local redis = require "resty.redis"
      local red = redis:new()
      local args = ngx.req.get_uri_args()
      ngx.header['Access-Control-Allow-Origin'] = '*'
      ngx.header['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
      ngx.header['Access-Control-Allow-Headers'] = 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range'
      ngx.header['Access-Control-Expose-Headers'] = 'Content-Length,Content-Range';
      ngx.req.read_body()
      local data = ngx.req.get_body_data()
      local okredis, errredis = red:connect("unix:/tmp/redis.sock")
      local key_name = args["lang"] .. "_" .. args["name"]
      
      if data ~= nil then
        ngx.log(ngx.ERR, "[save loadpreset] lang:" ..  args["lang"] .. ", name:" .. args["name"] .. ", payload:" .. data)
        red:set(key_name, data)
        local res, err = red:get(key_name)

        file = io.open("/var/www/html/" .. key_name, "w")
        io.output(file)
        io.write(data)
        io.close(file)

        if res == ngx.null then
          ngx.say("error: " .. args["name"] .. " has not been saved.")
        else
          ngx.say(args["name"] .. " has been saved.")
        end
      else
        ngx.say("Error in payload sent by web interface.")
      end
    }
  }

  location /chaos/programs/json-flow {
    content_by_lua_block {

      local function key_exists(data, mykey)
        for key, value in pairs(data) do
          if key == mykey then
            return true
          end
        end
        return false
      end
      
      local function is_key_empty(data, mykey)
        cnt = 0
        for key, value in pairs(data[mykey]) do
          cnt = cnt + 1
        end
        if cnt > 0 then
          return false
        end
        return true
      end

      local lyaml = require "lyaml"
      local json = require 'lunajson'

      ngx.header['Access-Control-Allow-Origin'] = '*'
      ngx.header['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
      ngx.header['Access-Control-Allow-Headers'] = 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range'
      ngx.header['Access-Control-Expose-Headers'] = 'Content-Length,Content-Range';
      ngx.req.read_body()
      data = ngx.req.get_body_data()
      ngx.log(ngx.ERR, "[programming_mode_diagram] data sent from web interface => " .. data)
      
      math.randomseed(os.clock()*100000000000)
      local rand = math.random(999, 9999)
      local filename = "/tmp/chaosprogram" .. rand

      ngx.log(ngx.ERR, "[programming_mode_diagram] write temp file " .. filename)

      yamlfile = io.open(filename, "w")
      yamlfile:write(data)
      yamlfile:close()

      local handle = io.popen("python3 -c 'import yaml, sys; print(yaml.safe_load(sys.stdin))' < " .. filename)
      local result = handle:read("*a")
      local rc = handle:close()

      ngx.log(ngx.ERR, "[programming_mode_diagram] Result of yaml syntax check =>||" .. result .. "||")

      if data == nil then
        error = "[programming_mode_diagram] No chaos program already loaded."
        ngx.log(ngx.ERR, error)
        ngx.say(error) 
  
      elseif not string.match(result, '{.*}') then
        error = "[programming_mode_diagram] Chaos program seems not correct. Please check yaml syntax."
        ngx.log(ngx.ERR, error)
        ngx.say(error)
      end

      local yaml_data = lyaml.load(data)

      if not key_exists(yaml_data, "jobs") then
        error = "[programming_mode_diagram] Chaos program does not contain 'jobs' key. Please fix yaml definition."
        ngx.log(ngx.ERR, error)
        ngx.say(error)
      
      elseif not key_exists(yaml_data, "experiments") then
        error = "[programming_mode_diagram] Chaos program does not contain 'experiments' key. Please fix yaml definition"
        ngx.log(ngx.ERR, error)
        ngx.say(error)
      
      elseif is_key_empty(yaml_data, "jobs") then
        error = "[programming_mode_diagram] Chaos program does not contain valid 'jobs' key. Please fix yaml definition, add jobs"
        ngx.log(ngx.ERR, error)
        ngx.say(error)

      elseif is_key_empty(yaml_data, "experiments") then
        error = "[programming_mode_diagram] Chaos program does not contain valid 'experiments' key. Please fix yaml definition, add experiments"
        ngx.log(ngx.ERR, error)
        ngx.say(error)

      else
        os.remove(filename)
        response = json.encode(yaml_data)
        ngx.say(response)
      end
    }
  }
}
