/**
 * (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-server.zip';
const localTmpDir = 'C:/Users/aheadware-benny/_SYSTEM/temp';
const localPrjDir = 'C:/Users/aheadware-benny/VC/tbuddy-probuddy/src/server';
const serverDestDir = '/www/htdocs/v034011/projects/probuddy/server';
const serverTmpDir = '/www/htdocs/v034011/_temp';

function deploy()
{


    var localCommands = [
        'rd /S /Q ' + localTmpDir + '/probuddy-server-app',
        'mkdir ' + localTmpDir + '/probuddy-server-app',
        'xcopy /e ' + localPrjDir + ' ' + localTmpDir + '/probuddy-server-app'
    ];

    fsExtra.removeSync( localTmpDir + '/probuddy-server-app' );
    fsExtra.mkdirpSync( localTmpDir + '/probuddy-server-app' );
    fsExtra.copySync( localPrjDir, localTmpDir + '/probuddy-server-app' );
    fsExtra.copySync( localTmpDir + '/probuddy-server-app/server/config/locals/probuddy-live.php', localTmpDir + '/probuddy-server-app/server/config/boot_local.php' );

    zipFolder(
        localTmpDir + '/probuddy-server-app',
        localTmpDir + '/probuddy-server-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-server-app.zip' );
                        var writeStream = sftp.createWriteStream( serverTmpDir + '/probuddy-server-app.zip', { mode: 0o755 } );

                        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-server-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-server-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();
