vcl 4.0;

import std;
import directors;

#
# These nets/machines are allowed /repo access
#
acl repoallowed {
  "10.16.0.0"/24;
  "10.1.102.0"/24;
}

acl purge {
  "127.0.0.1"/32;
}

{% if env == 'staging' %}
backend koji01 {
    .host = "koji01.stg.iad2.fedoraproject.org";
    .probe = {
        .url = "/work/";
        .timeout = 3600s;
        .interval = 30s;
        .window = 30;
        .threshold = 30;
    }
    .first_byte_timeout = 300s;
    .connect_timeout = 10s;
    .between_bytes_timeout  = 2s;
}
{% else %}
backend kojipkgs01 {
    .host = "kojipkgs01.iad2.fedoraproject.org";
    .probe = {
        .url = "/";
        .timeout = 3600s;
        .interval = 30s;
        .window = 30;
        .threshold = 30;
    }
    .first_byte_timeout = 300s;
    .connect_timeout = 30s;
    .between_bytes_timeout  = 2s;
}

backend kojipkgs02 {
    .host = "kojipkgs02.iad2.fedoraproject.org";
    .probe = {
        .url = "/";
        .timeout = 3600s;
        .interval = 30s;
        .window = 30;
        .threshold = 30;
    }
    .first_byte_timeout = 300s;
    .connect_timeout = 30s;
    .between_bytes_timeout  = 2s;
}

sub vcl_init {
    new primarykojipkgs = directors.round_robin();
    primarykojipkgs.add_backend(kojipkgs01);
    primarykojipkgs.add_backend(kojipkgs02);
}
{% endif %}

sub vcl_recv {
    # This gets arround the silly, ::1 that Apache adds on the proxies (still need to look at that)
    set req.http.X-Forwarded-For = regsub(req.http.X-Forwarded-For, "^([a-f0-9:.]+), .+$", "\1");

{% if env == 'staging' %}
    set req.backend_hint = koji01;
{% else %}
    set req.backend_hint = primarykojipkgs.backend();
{% endif %}
    unset req.http.cookie;
    set req.http.clear-cookies = "yes";

    if (req.method == "PURGE") {
        if (!client.ip ~ purge) {
            return (synth(405, "Not allowed"));
        }
        return(purge);
    }

    if (req.url ~ "^/repo/" && !(std.ip(req.http.X-Forwarded-For, "0.0.0.0") ~ repoallowed)) {
        return(synth(403, "Access denied."));
    }
    if (req.url ~ "^/mash/") {
        return (pipe);
    }
    if (req.url ~ "^/compose/") {
        return (pipe);
    }
    if (req.url ~ "h264") {
        return (pipe);
    }

    # Rewrite toplink URLs to improve cache hit ratio
    # See: https://pagure.io/fedora-infrastructure/issue/7383
    set req.url = regsub(req.url, "^/repos/[^/]+/[^/]+/[^/]+/toplink/", "/");

    return (hash);
}
