# Define example host for redirect testing - can remove when moving to a customer's service
set req.http.host = "www.example.com";

# Store the host, url path, and joint host and url path in local vars
declare local var.full-request STRING;
declare local var.fsly-redir-value STRING;

set var.full-request = req.http.host req.url.path;
set var.fsly-redir-value = "";
unset req.http.x-redirect;

# Starting with hostname AND url path first, perform lookup against 
# redirect table to determine if redirects are needed
if (table.lookup(redirects, var.full-request)) {
  set var.fsly-redir-value = table.lookup(redirects, var.full-request);
  # Next check exact match on url path 
} else if (table.lookup(redirects, req.url.path)) {
  set var.fsly-redir-value = table.lookup(redirects, req.url.path);
  # Finally check if wildcard match was present
} else if (var.fsly-redir-value == "") {
  call check_wildcard_redirects;
  set var.fsly-redir-value = req.http.redir-value;
}

# If var.fsly-redir-value is not empty, then we need to perform a redirect
# capture each component, and break them out to be referenced in vcl_error
if (var.fsly-redir-value ~ "(.*)\|(.*)\|(.*)") {
  set req.http.x-status = re.group.1;
  set req.http.x-qs-flag = re.group.2;
  set req.http.redirect-path = re.group.3;
  if (req.http.x-qs-flag == "keep") {
    # keep qs
  } else {
    unset req.http.x-qs-flag; # signal that qs shouldn't be included
  }
  # Call vcl_error to issue redirect
  set req.http.x-redirect = "true";
  error std.atoi(req.http.x-status);
}