package com.hubspot.baragon.agent;

import com.google.common.base.Throwables;
import com.google.inject.Inject;
import com.google.inject.servlet.RequestScoped;
import com.sun.jersey.api.core.HttpRequestContext;
import org.apache.curator.framework.recipes.leader.LeaderLatch;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import java.net.URI;

@RequestScoped
public class LeaderRedirector {
  private final LeaderLatch leaderLatch;

  @Context
  private HttpRequestContext request;

  @Inject
  public LeaderRedirector(LeaderLatch leaderLatch) {
    this.leaderLatch = leaderLatch;
  }

  public void redirectToLeader() {
    if (!leaderLatch.hasLeadership()) {
      try {
        throw new WebApplicationException(javax.ws.rs.core.Response
            .temporaryRedirect(URI.create(String.format("http://%s%s", leaderLatch.getLeader().getId(), request.getAbsolutePath().getPath())))
            .build());
      } catch (Exception e) {
        throw Throwables.propagate(e);
      }
    }
  }
}

@@ -163,50 +163,84 @@
 ort 
-com.sun.jersey.api.core.HttpRequestContext
+org.apache.commons.logging.Log;%0Aimport org.apache.commons.logging.LogFactory
 ;%0Aim
@@ -302,16 +302,62 @@
 Latch;%0A%0A
+import javax.servlet.http.HttpServletRequest;%0A
 import j
@@ -396,41 +396,8 @@
 on;%0A
-import javax.ws.rs.core.Context;%0A
 impo
@@ -475,78 +475,148 @@
 ate 
-final LeaderLatch leaderLatch;%0A%0A  @Context%0A  private HttpRequestContex
+static final Log LOG = LogFactory.getLog(LeaderRedirector.class);%0A  private final LeaderLatch leaderLatch;%0A  private final HttpServletReques
 t re
@@ -682,16 +682,44 @@
 derLatch
+, HttpServletRequest request
 ) %7B%0A    
@@ -750,16 +750,44 @@
 rLatch;%0A
+    this.request = request;%0A
   %7D%0A%0A  p
@@ -1006,16 +1006,20 @@
 p://%25s%25s
+%25s%25s
 %22, leade
@@ -1061,30 +1061,64 @@
 .get
-AbsolutePath()
+ContextPath(), request.getServletPath(), request
 .getPath
 ()))
@@ -1113,16 +1113,20 @@
 .getPath
+Info
 ())))%0A  

make redirector actually work