server {
    listen       8080;
    listen  [::]:8080;
    server_name  plex-reshare;

    # https://stackoverflow.com/questions/22541333/have-nginx-access-log-and-error-log-log-to-stdout-and-stderr-of-master-process
    access_log /dev/stdout;

    # https://gist.github.com/CSRaghunandan/ce2394cd5a9c8a412f8ff5ee1478560a

    location / {
        # proxy_set_header Host $host;
        # proxy_set_header X-Real-IP $remote_addr;

        proxy_pass http://127.0.0.1:8000;
    }

    location ~ /(?<video_url>.*?\/(?<plex_id>.*?)/.*\.\w+)$ {
        set $plex_ip '';
        set $plex_port '';
        set $plex_token '';
        set $plex_url '';

        set_by_lua $redis_host 'return os.getenv("REDIS_HOST")';
        set_by_lua $redis_port 'return os.getenv("REDIS_PORT")';

        resolver            127.0.0.11 valid=60s;

        access_by_lua_block {
            local redis = require "resty.redis"
            local red = redis:new()

            red:set_timeouts(1000, 1000, 1000) -- 1 sec
            local ok, err = red:connect(ngx.var.redis_host, tonumber(ngx.var.redis_port))
            local redisdb = tonumber(ngx.var.redis_db)
            red:select(11)

            local plex_ip, err = red:get("pr:node:" .. ngx.var.plex_id .. ":ip");
            local plex_port, err = red:get("pr:node:" .. ngx.var.plex_id .. ":port");
            local plex_token, err = red:get("pr:node:" .. ngx.var.plex_id .. ":token");
            local plex_url, err = red:get("pr:files:" .. ngx.var.video_url);

            ngx.var.plex_ip = plex_ip;
            ngx.var.plex_port = plex_port;
            ngx.var.plex_token = plex_token;
            ngx.var.plex_url = plex_url;

            local ok, err = red:close()
            if not ok then
                return
            end
        }

        proxy_pass  "https://$plex_ip:$plex_port$plex_url?X-Plex-Token=$plex_token";
    }
}
