/**
 * (c) by aheadware.com
 */

/**
 * Prequisties:
 *
 * - destDir must exist
 * - tmpDir must exist
 * - remoteTmpDir must exist
 *
 * - node modules (global)
 * -- npm install async -g
 *    https://caolan.github.io/async/index.html
 * -- npm install fs-extra -g
 *    https://github.com/jprichardson/node-fs-extra
 * -- npm install ssh2 -g
 *    https://www.npmjs.com/package/ssh2
 * -- npm install zip-folder -g
 *    https://www.npmjs.com/package/zip-folder
 *
 *
 * General:
 *
 * zipName = 'probuddy_landing.zip';
 *
 *
 * Local:
 *
 * localTmpDir = 'C:/Users/Benny/Desktop/_SYSTEM/temp';
 *
 *
 * Server
 *
 * serverDestDir = '/www/htdocs/v034011/projects/probuddy/client/www';
 * serverTmpDir = '/www/htdocs/v034011/_temp';
 */


const Client = require('ssh2').Client;
const zipFolder = require('zip-folder');
const fs = require ( 'fs' );
const fsExtra = require( 'fs-extra' );

// globals
const zipName = 'probuddy-app-client.zip';
const localTmpDir = 'C:/Users/Benny/Desktop/_SYSTEM/temp';
const localPrjDir = 'C:/Users/Benny/Desktop/VC/probuddy/src/client/app';
const serverDestDir = '/www/htdocs/v034011/projects/probuddy/client/app';
const serverTmpDir = '/www/htdocs/v034011/_temp';

function deploy()
{
    var localCommands = [
        'rd /S /Q ' + localTmpDir + '/probuddy-client-app',
        'mkdir ' + localTmpDir + '/probuddy-client-app',
        'xcopy /e ' + localPrjDir + ' ' + localTmpDir + '/probuddy-client-app'
    ];

    fsExtra.removeSync( localTmpDir + '/probuddy-client-app' );
    fsExtra.mkdirpSync( localTmpDir + '/probuddy-client-app' );
    fsExtra.copySync( localPrjDir, localTmpDir + '/probuddy-client-app' );

    zipFolder(
        localTmpDir + '/probuddy-client-app',
        localTmpDir + '/probuddy-client-app.zip',
        function(err)
        {
            if( err )
            {
                console.log('zipFolder failed with: ', err);
            }
            else
            {
                // Upload and decompress and remove zip
                var conn = new Client();
                conn.on('ready', function()
                {

                    conn.sftp ( function( err, sftp )
                    {
                        if ( err ) throw err;


                        // UPLOAD ZIP FILE

                        var readStream = fs.createReadStream( localTmpDir + '/probuddy-client-app.zip', { encoding: 'binary'} );
                        var writeStream = sftp.createWriteStream( serverTmpDir + '/probuddy-client-app.zip', { mode: 0o755, encoding: 'binary' } );

                        writeStream.on('close',function ()
                        {
                            console.log( "- file transferred succesfully" );

                            // DELETE OLD DIRECTORY
                            conn.exec( 'rm -rf  ' + serverDestDir + '/;md ' + serverDestDir, function( err, stream )
                                //conn.exec( 'cd ' + serverDestDir + '/;ls -la', function( err, stream )
                            {
                                if ( err ) throw err;

                                stream.on('data', function(data)
                                {
                                    console.log('STDOUT: ' + data);
                                });

                                stream.stderr.on('data', function(data)
                                {
                                    console.log('STDERR: ' + data);
                                });

                                stream.on('close', function(code, signal)
                                {
                                    console.log('Process closed with code ' + code);

                                    // UNZIP NEW VERSION TO DESTINATION DIRECTORY

                                    conn.exec( 'cd ' + serverTmpDir + '/;unzip -o probuddy-client-app.zip -d ' + serverDestDir + '/;chmod -R 755 ' + serverDestDir + '/', function( err, stream )
                                    {
                                        if ( err ) throw err;

                                        stream.on('data', function(data)
                                        {
                                            console.log('STDOUT: ' + data);
                                        });

                                        stream.stderr.on('data', function(data)
                                        {
                                            console.log('STDERR: ' + data);
                                        });

                                        stream.on('close', function(code, signal)
                                        {
                                            console.log('Process closed with code ' + code);

                                            conn.sftp(function(err, sftp)
                                            {
                                                if (err) throw err;

                                                // REMOVE ZIP FILE

                                                sftp.unlink( serverTmpDir + '/probuddy-client-app.zip', function(err)
                                                {
                                                    if ( err )
                                                    {
                                                        console.log( "Error, problem starting SFTP: %s", err );
                                                    }
                                                    else
                                                    {
                                                        console.log( "file unlinked" );
                                                        process.exit( -1 );
                                                    }

                                                    //conn.close();
                                                });

                                            });
                                        });
                                    });

                                });
                            });

                        });

                        writeStream.on('end', function ()
                        {
                            console.log( "sftp connection closed" );
                            conn.close();
                        });

                        // initiate transfer of file
                        readStream.pipe( writeStream );
                    });
                    /*
                    conn.exec( 'ls -lah', function( err, stream )
                    {
                        if ( err ) throw err;

                        stream.on('data', function(data) {
                            console.log('STDOUT: ' + data);
                        });
                        stream.stderr.on('data', function(data) {
                            console.log('STDERR: ' + data);
                        });
                        stream.on('close', function(code, signal) {
                            console.log('Process closed with code ' + code);
                        });
                    });
                    */

                    /*
                    conn.sftp(function(err, sftp) {
                        if (err) throw err;
                        sftp.readdir('/www/htdocs/v034011/_temp', function(err, list) {
                            if (err) throw err;
                            console.dir(list);
                            conn.end();
                        });
                    });
                    */
                }).connect(
                    {
                        host: 'v034011.kasserver.com',
                        port: 22,
                        username: 'ssh-v034011',
                        password: 'XXXXXXXXXXXX'
                    });
            }
        });
}

deploy();
