'use strict';

// Modules
var request = require('request');

module.exports = function( image, callback ){

  if( image.indexOf('/') !== -1 ){
    containerName = image.split('/')[ 1 ].split(':')[ 0 ];
  }else{
    containerName = image.split(':')[ 0 ];
  }

  var req = {

    url : 'http://' + process.env.HOST_IP + ':2375/images/create?fromImage=' + image,
    headers : {

      'X-Registry-Auth' : new Buffer( JSON.stringify({

        username : process.env.REGISTRY_USER || '',
        password : process.env.REGISTRY_PASS || '',
        email    : process.env.REGISTRY_MAIL || ''

      }) ).toString('base64')

    }

  };

  request.post( req, function( error, http, body ){

    if( error ){
      return callback( error );
    }

    var req = {

      url : 'http://' + process.env.HOST_IP + ':2375/containers/create?name=' + containerName,
      json : {
        'Image' : image,
        'HostConfig' : {
          'RestartPolicy' : {
            'Name' : 'on-failure'
          },
          'NetworkMode': 'localnet'
        },
        'NetworkingConfig': {
          'EndpointsConfig': {
            'localnet': {
              'Aliases': [ containerName ]
            }
          }
        }
      }

    };

    request.post( req, function( error, http, secondBody ){

      if ( error ) {
        return callback( error );
      }

      var req = {
        url : 'http://' + process.env.HOST_IP + ':2375/containers/' + secondBody.Id + '/start'
      };

      request.post( req, function( error, http, thirdBody ){

        if ( error ) {
          return callback( error );
        }

        callback( null, [ body, secondBody, thirdBody ] );

      });

    });

  });

};

@@ -136,24 +136,28 @@
 = -1 )%7B%0A    
+var 
 containerNam
@@ -212,16 +212,20 @@
 se%7B%0A    
+var 
 containe
@@ -277,19 +277,23 @@
  = %7B
+%7D;
 %0A%0A  
-  
+req.
 url 
-:
+=
  'ht
@@ -367,22 +367,60 @@
 mage
-,%0A    
+;%0A%0A  if( /:%5Cd+%5C//.test( image ) )%7B%0A%0A    req.
 headers 
 : %7B%0A
@@ -415,17 +415,17 @@
 headers 
-:
+=
  %7B%0A%0A    
@@ -672,14 +672,14 @@
    %7D
+;
 %0A%0A  %7D
-;
 %0A%0A  

Allow download images from Docker Hub