package io.cattle.platform.iaas.api.credential;

import io.cattle.platform.api.link.LinkHandler;
import io.cattle.platform.core.constants.CredentialConstants;
import io.cattle.platform.core.model.Credential;
import io.github.ibuildthecloud.gdapi.request.ApiRequest;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

public class SshKeyPemDownloadLinkHandler implements LinkHandler {

    @Override
    public String[] getTypes() {
        return new String[] { "sshKey" };
    }

    @Override
    public boolean handles(String type, String id, String link, ApiRequest request) {
        return CredentialConstants.LINK_PEM_FILE.equalsIgnoreCase(link);
    }

    @Override
    public Object link(String name, Object obj, ApiRequest request) throws IOException {
        if ( obj instanceof Credential ) {
            String secretValue = ((Credential)obj).getSecretValue();
            if ( secretValue == null ) {
                return null;
            }

            byte[] content = secretValue.getBytes("UTF-8");

            HttpServletResponse response = request.getServletContext().getResponse();

            response.setContentLength(content.length);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=mykey.pem");
            response.setHeader("Cache-Control", "private");
            response.setHeader("Pragma", "private");
            response.setHeader("Expires", "Wed 24 Feb 1982 18:42:00 GMT");

            response.getOutputStream().write(content);

            return new Object();
        }

        return null;
    }

}

@@ -201,16 +201,128 @@
 ential;%0A
+import io.github.ibuildthecloud.gdapi.context.ApiContext;%0Aimport io.github.ibuildthecloud.gdapi.id.IdFormatter;%0A
 import i
@@ -1441,18 +1441,49 @@
 ame=
-mykey.pem%22
+%22 + getFilename((Credential)obj, request)
 );%0A 
@@ -1762,32 +1762,32 @@
 t();%0A        %7D%0A%0A
-
         return n
@@ -1798,10 +1798,455 @@
 %0A    %7D%0A%0A
+    protected String getFilename(Credential cred, ApiRequest request) %7B%0A        String name = cred.getName();%0A%0A        if ( name != null ) %7B%0A            return name.trim().replaceAll(%22%5B%5Ea-zA-Z0-9%5D%22, %22_%22) + %22.pem%22;%0A        %7D else %7B%0A            IdFormatter formatter = ApiContext.getContext().getIdFormatter();%0A            Object id = formatter.formatId(cred.getKind(), cred.getId());%0A%0A            return %22id_rsa_%22 + id + %22.pem%22;%0A        %7D%0A    %7D%0A%0A
 %7D%0A

make ssh key file download based on api key name