events {
  worker_connections 1024;
}

http {
  init_by_lua_block {
    function find_entry_in_dir(parent_dir, name_to_find)
      local safe_parent_dir = string.gsub(parent_dir, "'", "'\\''")
      local lower_name_to_find = string.lower(name_to_find)
      local pipe = io.popen("ls -A '" .. safe_parent_dir .. "' 2>/dev/null")
      if not pipe then return nil end

      for entry in pipe:lines() do
        if string.lower(entry) == lower_name_to_find then
          pipe:close()
          return entry
        end
      end
      pipe:close()
      return nil
    end

    function find_recursive_path(path_to_check)
      local current_resolved_path = "/"

      for component in string.gmatch(path_to_check, "([^/]+)") do
        local found_entry = find_entry_in_dir(current_resolved_path, component)
        if not found_entry then
          return nil
        end

        if current_resolved_path == "/" then
          current_resolved_path = current_resolved_path .. found_entry
        else
          current_resolved_path = current_resolved_path .. "/" .. found_entry
        end
      end
      return current_resolved_path
    end
  }

  include /usr/local/openresty/nginx/conf/mime.types;

  server {
    listen 6931;
    server_name localhost;

    add_header 'Cross-Origin-Embedder-Policy' 'require-corp';
    add_header 'Cross-Origin-Opener-Policy' 'same-origin';
    add_header 'Cross-Origin-Resource-Policy' 'cross-origin';

    location / {
      root /usr/local/openresty/nginx/html;
      index index.html isle.html;
      try_files $uri $uri/ =404;
    }

    location /assets/ {
      content_by_lua_block {
        local request_uri = ngx.var.uri
        local resolved_path = find_recursive_path(request_uri)

        if not resolved_path then
          local fallback_uri = ngx.re.sub(request_uri, [[^/assets/]], "/assets/DATA/disk/", "i")
          resolved_path = find_recursive_path(fallback_uri)
        end

        if resolved_path then
          ngx.exec("/internal" .. resolved_path)
        else
          ngx.exit(ngx.HTTP_NOT_FOUND)
        end
      }
    }

    location /internal/assets/ {
      internal;
      root /;
      rewrite ^/internal(.*)$ $1 break;
    }
  }
}
