# Author: <Dick Hollenbeck> dick@softplc.com
# Configuration file for nginx.  Nginx works as a nice cache-ing proxy for
# the github footprint repos in a local nginx instance.


# In my case I also added a small RAM disk on a linux server to hold the cache.
# This line in /etc/fstab adds my RAM disk, this is 10 mbytes but 5mb would
# probably suffice:
# none            /var/cache/nginx                          tmpfs   size=10m

# I then set my KIGITHUB environment variable to
# export KIGITHUB=http://my_server:54321/KiCad

# Note that http is used between kicad and nginx, not https.  However nginx uses
# https when refreshing from github.  http is faster than https.

# You can run nginx either on your local machine, or on a server on your network,
# or a server on the Internet.  In my case I run it on my network.  I imagine
# that even a Raspery Pi would act as a decent caching server so long as you
# install nginx and give the machine Internet access.


worker_processes 2;

events {
    worker_connections  1024;
}


http {
    proxy_cache_path /var/cache/nginx keys_zone=cache_zone:10m inactive=1w;

    server {
        # nginx will listen on this port:
        listen 54321;

        proxy_cache cache_zone;

        # hold the stuff for one week, then mark it as out of date which will
        # cause it to be reloaded from github.
        proxy_cache_valid any 1w;

        location /KiCad/ {
            rewrite /KiCad/(.+) /KiCad/$1/zip/master break;

            # Skip past the redirect issued by https://github.com
            proxy_pass  https://codeload.github.com;

            proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
            proxy_cache_lock on;

            proxy_set_header Proxy-Connection "Keep-Alive";

            proxy_ignore_headers "Set-Cookie";
            proxy_ignore_headers "Cache-Control";
            proxy_ignore_headers "Expires";

            proxy_cache_bypass $http_secret_header;

            add_header X-Cache-Status $upstream_cache_status;

            # This line causes github.com to return a "502 Bad Gateway Error"
            # so do not include it:
                # proxy_set_header Host $http_host;
        }
    }
}