const Docker = require('dockerode');
const docker = new Docker({
    'socketPath':  '/home/docker.sock'
    //'socketPath':  '/var/run/docker.sock'
});
const PROJECT_PATH = process.env.PROJECT_PATH;
const DOCKERIMAGE = "bitnami/kubectl:latest";
const path = require("path");
const fs = require("fs");
const KUBE_PATH = path.join(PROJECT_PATH, 'logs', 'kube');

const _done = function(data){
    let output = data[0];
    let container = data[1];
    console.log(`kubectl# (${container.id}) has finished with code: ${output.StatusCode}`);
    return container.remove();
};

const kubeconfig = function( provId ) {
    
    fs.writeFileSync(`/var/www/app/logs/kube/config_${provId}`, kubeConfigContent);
    console.log(`kubectl# will spin up container`);

    return docker.run(DOCKERIMAGE, ['config', 'current-context', '--kubeconfig', `/app/config_${provId}` ], processStream, { 
        //"name": initContName,
        "WorkingDir": "/app",
        "HostConfig": {
            "Binds": [
                `${KUBE_PATH}:/app`,
            ]
        }
    }).then(_done);
};

const apply = function( provId, kubeConfigContent ) {

    fs.writeFileSync(`/logs/kube/${provId}.config`, kubeConfigContent);
    console.log(`kubectl# will spin up container`);
    const yaml = path.join(PROJECT_PATH, 'az-tf-templates', 'azqmi-qseok', 'scripts', 'azure-sc.yaml');
    return docker.run(DOCKERIMAGE, ['apply','-f', '/yamlfile', '--kubeconfig', `/app/${provId}.config` ], process.stdout, { 
        //"name": initContName,
        "WorkingDir": "/app",
        "HostConfig": {
            "Binds": [
                `${KUBE_PATH}:/app`,
                `${yaml}:/yamlfile`
            ]
        }
    }).then(_done);
};

const getpod = function( provId, kubeConfigContent ) {

    fs.writeFileSync(`/logs/kube/${provId}.config`, kubeConfigContent);
    console.log(`kubectl# will spin up container`);

    return docker.run(DOCKERIMAGE, ['get', 'pod', '--kubeconfig', `/app/${provId}.config` ], process.stdout, { 
        //"name": initContName,
        "WorkingDir": "/app",
        "HostConfig": {
            "Binds": [
                `${KUBE_PATH}:/app`,
            ]
        }
    }).then(_done);
};

const getsvc = function( provId, kubeConfigContent ) {

    fs.writeFileSync(`/logs/kube/config_${provId}`, kubeConfigContent);
    console.log(`kubectl# will spin up container`);

    console.log(`kubectl# will spin up container`);
    return docker.run(DOCKERIMAGE, ['get', 'svc', '--kubeconfig', `/app/config_${provId}` ], process.stdout, { 
        //"name": initContName,
        "WorkingDir": "/app",
        "HostConfig": {
            "Binds": [
                `${KUBE_PATH}:/app`,
            ]
        }
    }).then(_done);
};

module.exports.kubeconfig = kubeconfig;
module.exports.apply = apply;
module.exports.getpod = getpod;
module.exports.getsvc = getsvc;