# Custom VCL: Scheduled Invalidation 3PM, 1AM UTC
# Declare variables
declare local var.now INTEGER;
declare local var.target1 INTEGER;
declare local var.target2 INTEGER;
declare local var.ttl1 INTEGER;
declare local var.ttl2 INTEGER;
declare local var.expire1 INTEGER;
declare local var.expire2 INTEGER;

if (req.backend.is_origin) {

  # Set this to the hour (UTC) that you want content to expire.
  # The following example sets the expiration on 1AM and 3PM UTC
  set var.expire1 = 15;
  set var.expire2 = 1;
  set var.expire1 *= 3600;
  set var.expire2 *= 3600;
  
  # Set current time to now
  set var.now = std.atoi(now.sec);
  
  set var.now = 1568384924;
  log "Setting var.now to 1568384924 for testing purposes.  Remove this in production!";
  
  # Calculate expiry target time
  set var.target1 = var.now;
  set var.target1 /= 86400;
  set var.target1 *= 86400;
  set var.target2 = var.target1;
  set var.target1 += var.expire1;
  set var.target2 += var.expire2;
  
  # Add a day if ttl is in the past
  if (var.target1 < var.now) {
    set var.target1 += 86400;
  }
  if (var.target2 < var.now) {
    set var.target2 += 86400;
  }
  
  log "Next expiry times: " + std.integer2time(var.target1) + ", " + std.integer2time(var.target2);
  
  # TTL to target
  set var.ttl1 = var.target1;
  set var.ttl2 = var.target2;
  set var.ttl1 -= var.now;
  set var.ttl2 -= var.now;
  
  # For some paths, we can expire at one of the target times
  if (req.url.path ~ "(?i)^/status/") {
    set beresp.ttl = var.ttl2;
    set beresp.http.Surrogate-Control = "max-age=" + var.ttl2;
  }
  
  # For other paths, we could use whichever target time is sooner
  if (req.url.path ~ "(?i)^/image/") {
    if (var.ttl2 > var.ttl1) {
      set beresp.ttl = var.ttl1;
      set beresp.http.Surrogate-Control = "max-age=" + var.ttl1;
    } else {
      set beresp.ttl = var.ttl2;
      set beresp.http.Surrogate-Control = "max-age=" + var.ttl2;
    }
  }
}