/**
 *  Copyright 2005-2015 Red Hat, Inc.
 *
 *  Red Hat licenses this file to you under the Apache License, version
 *  2.0 (the "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 *  implied.  See the License for the specific language governing
 *  permissions and limitations under the License.
 */
package io.fabric8.forge.rest.main;

import io.fabric8.annotations.External;
import io.fabric8.annotations.Protocol;
import io.fabric8.annotations.ServiceName;
import io.fabric8.forge.rest.Constants;
import io.fabric8.project.support.UserDetails;
import org.apache.deltaspike.core.api.config.ConfigProperty;
import org.eclipse.jgit.util.Base64;
import org.jboss.forge.furnace.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.Charset;

/**
 * A helper class for working with git user stuff
 */
public class GitUserHelper {
    private static final transient Logger LOG = LoggerFactory.getLogger(GitUserHelper.class);
    private final String gitUser;
    private final String gitPassword;
    private String address;
    private String internalAddress;

    // TODO it'd be nice to pick either http or https based on the port number of the gogs service
    // so if folks configured it on https then we'd just work
    @Inject
    public GitUserHelper(@ServiceName("gogs") @Protocol("http") @External String gogsUrl,
                         @ServiceName("gogs") @Protocol("http") String gogsInternalUrl,
                         @ConfigProperty(name = "JENKINS_GOGS_USER") String gitUser,
                         @ConfigProperty(name = "JENKINS_GOGS_PASSWORD") String gitPassword) {
        this.gitUser = gitUser;
        this.gitPassword = gitPassword;
        this.address = gogsUrl;
        this.internalAddress = gogsInternalUrl;
        if (!address.endsWith("/")) {
            address += "/";
        }
        if (!internalAddress.endsWith("/")) {
            internalAddress += "/";
        }
    }

    public UserDetails createUserDetails(HttpServletRequest request) {
        String user = gitUser;
        String password = gitPassword;
        String authorization = null;
        String emailHeader = null;

        // lets try custom headers or request parameters
        if (request != null) {
            authorization = request.getHeader("GogsAuthorization");
            if (Strings.isNullOrEmpty(authorization)) {
                authorization = request.getParameter(Constants.RequestParameters.GOGS_AUTH);
            }
            emailHeader = request.getHeader("GogsEmail");
            if (Strings.isNullOrEmpty(emailHeader)) {
                emailHeader = request.getParameter(Constants.RequestParameters.GOGS_EMAIL);
            }
        }
        if (!Strings.isNullOrEmpty(authorization)) {
            String basicPrefix = "basic";
            String lower = authorization.toLowerCase();
            if (lower.startsWith(basicPrefix)) {
                String base64Credentials = authorization.substring(basicPrefix.length()).trim();
                String credentials = new String(Base64.decode(base64Credentials),
                        Charset.forName("UTF-8"));
                // credentials = username:password
                String[] values = credentials.split(":", 2);
                if (values != null && values.length > 1) {
                    user = values[0];
                    password = values[1];
                }
            }
        }
        String email = "dummy@gmail.com";
        if (!Strings.isNullOrEmpty(emailHeader)) {
            email = emailHeader;
        }
        return new UserDetails(address, internalAddress, user, password, email);
    }
}

@@ -814,28 +814,212 @@
 ic8.
-forge.rest.Constants
+cdi.Services;%0Aimport io.fabric8.forge.rest.Constants;%0Aimport io.fabric8.kubernetes.api.KubernetesHelper;%0Aimport io.fabric8.kubernetes.api.ServiceNames;%0Aimport io.fabric8.kubernetes.client.KubernetesClient
 ;%0Aim
@@ -1372,16 +1372,73 @@
 arset;%0A%0A
+import static io.fabric8.kubernetes.api.ServiceNames.*;%0A%0A
 /**%0A * A
@@ -1678,24 +1678,77 @@
 itPassword;%0A
+    private final KubernetesClient kubernetesClient;%0A
     private 
@@ -2002,186 +2002,8 @@
 per(
-@ServiceName(%22gogs%22) @Protocol(%22http%22) @External String gogsUrl,%0A                         @ServiceName(%22gogs%22) @Protocol(%22http%22) String gogsInternalUrl,%0A                         
 @Con
@@ -2149,16 +2149,76 @@
 Password
+,%0A                         KubernetesClient kubernetesClient
 ) %7B%0A    
@@ -2302,242 +2302,44 @@
 his.
-address = gogsUrl;%0A        this.internalAddress = gogsInternalUrl;%0A        if (!address.endsWith(%22/%22)) %7B%0A            address += %22/%22;%0A        %7D%0A        if (!internalAddress.endsWith(%22/%22)) %7B%0A            internalAddress += %22/%22;%0A        %7D
+kubernetesClient = kubernetesClient;
 %0A   
@@ -3974,79 +3974,1011 @@
     
-return new UserDetails(address, internalAddress, user, password, email)
+if (Strings.isNullOrEmpty(address)) %7B%0A            address = getGogsURL(true);%0A            internalAddress = getGogsURL(false);%0A            if (!address.endsWith(%22/%22)) %7B%0A                address += %22/%22;%0A            %7D%0A            if (!internalAddress.endsWith(%22/%22)) %7B%0A                internalAddress += %22/%22;%0A            %7D%0A        %7D%0A        return new UserDetails(address, internalAddress, user, password, email);%0A    %7D%0A%0A    protected String getGogsURL(boolean external) %7B%0A        String namespace = kubernetesClient.getNamespace();%0A        if (Strings.isNullOrEmpty(namespace)) %7B%0A            namespace = KubernetesHelper.defaultNamespace();%0A        %7D%0A        String answer = KubernetesHelper.getServiceURL(kubernetesClient, GOGS, namespace, %22http%22, external);%0A        if (Strings.isNullOrEmpty(answer)) %7B%0A            String kind = external ? %22external%22 : %22internal%22;%0A            throw new IllegalStateException(%22Could not find external URL for %22 + kind + %22 service: gogs!%22);%0A        %7D%0A        return answer
 ;%0A  

fix timing issue with fabric8-forge starting up before there is a valid gogs endpoint available