<commit_before>'use strict';

let fs = require('fs-extra');
let request = require('request');
let path = require('path');
let ipcRenderer = require('electron').ipcRenderer;

import InstallableItem from './installable-item';
import Downloader from './helpers/downloader';
import Logger from '../services/logger';
import VagrantInstall from './vagrant';
import Installer from './helpers/installer';

class CDKInstall extends InstallableItem {
  constructor(installerDataSvc, $timeout, cdkUrl, cdkBoxUrl, ocUrl, vagrantFileUrl, pscpUrl, installFile) {
    super('CDK', 900, cdkUrl, installFile);

    this.installerDataSvc = installerDataSvc;
    this.$timeout = $timeout;
    this.cdkBoxUrl = cdkBoxUrl;
    this.ocUrl = ocUrl;
    this.vagrantFileUrl = vagrantFileUrl;
    this.pscpUrl = pscpUrl;

    this.cdkFileName = 'cdk.zip';
    this.cdkDownloadedFile = path.join(this.installerDataSvc.tempDir(), this.cdkFileName);

    this.boxName = 'rhel-cdk-kubernetes-7.2-18.x86_64.vagrant-virtualbox.box';
    this.cdkBoxDownloadedFile = path.join(this.installerDataSvc.tempDir(), this.boxName);

    this.ocFileName = 'oc.zip';
    this.ocDownloadedFile = path.join(this.installerDataSvc.tempDir(),   this.ocFileName);

    this.vagrantFileName = 'vagrantfile.zip';
    this.vagrantDownloadedFile = path.join(this.installerDataSvc.tempDir(), this.vagrantFileName);

    this.pscpFileName = 'pscp.exe';
    this.pscpDownloadedFile = path.join(this.installerDataSvc.tempDir(), this.pscpFileName);

    this.pscpPathScript = path.join(this.installerDataSvc.tempDir(), 'set-pscp-path.ps1');

    this.downloads = path.normalize(path.join(__dirname,"../../.."));
  }

  static key() {
    return 'cdk';
  }

  checkForExistingInstall() {
  }

  downloadInstaller(progress, success, failure) {
    progress.setStatus('Downloading');

    let downloadSize = 869598013;

    let totalDownloads = 5;

    let downloader = new Downloader(progress, success, failure, downloadSize, totalDownloads);
    let username = this.installerDataSvc.getUsername(),
        password = this.installerDataSvc.getPassword();

    if(!fs.existsSync(path.join(this.downloads, this.boxName))) {
      let cdkBoxWriteStream = fs.createWriteStream(this.cdkBoxDownloadedFile);
      downloader.setWriteStream(cdkBoxWriteStream);
      downloader.download(this.cdkBoxUrl);
    } else {
      this.cdkBoxDownloadedFile = path.join(this.downloads, this.boxName);
      downloader.closeHandler();
    }

    if(!fs.existsSync(path.join(this.downloads, this.cdkFileName))) {
      // TODO Switch back to auth download when CDK latest is in Customer Portal
      // downloader.downloadAuth
      //   ({
      //     url: this.cdkBoxUrl,
      //     rejectUnauthorized: false
      //   }, username, password);
      let cdkWriteStream = fs.createWriteStream(this.cdkDownloadedFile);
      downloader.setWriteStream(cdkWriteStream);
      downloader.downloadAuth
      ({
        url: this.getDownloadUrl(),
        rejectUnauthorized: false
      }, username, password);
    } else {
      this.cdkDownloadedFile = path.join(this.downloads, this.cdkFileName);
      downloader.closeHandler();
    }

    if(!fs.existsSync(path.join(this.downloads, this.vagrantFileName))) {
      let vagrantFileWriteStream = fs.createWriteStream(this.vagrantDownloadedFile);
      downloader.setWriteStream(vagrantFileWriteStream);
      downloader.download(this.vagrantFileUrl);
    } else {
      this.vagrantDownloadedFile = path.join(this.downloads, this.vagrantFileName);
      downloader.closeHandler();
    }

    if(!fs.existsSync(path.join(this.downloads, this.pscpFileName))) {
      let pscpWriteStream = fs.createWriteStream(this.pscpDownloadedFile);
      downloader.setWriteStream(pscpWriteStream);
      downloader.download(this.pscpUrl);
    } else {
      this.pscpDownloadedFile = path.join(this.downloads, this.pscpFileName);
      downloader.closeHandler();
    }

    if(!fs.existsSync(path.join(this.downloads, this.ocFileName))) {
      let ocWriteStream = fs.createWriteStream(this.ocDownloadedFile);
      if(!this.ocUrl.endsWith('.zip')) {
        request(this.ocUrl,(err,rsp,body) => {
          var fname = body.match(/openshift-origin-client-tools-v\w(\.\w){1,2}-\w{1,3}-\w{8}-\w{7}-windows\.zip/)[0];
          downloader.setWriteStream(ocWriteStream);
          this.ocUrl=this.ocUrl.concat(fname);
          downloader.download(this.ocUrl);
        });
      } else {
        downloader.setWriteStream(ocWriteStream);
        downloader.download(this.ocUrl);
      }
    } else {
      this.ocDownloadedFile = path.join(this.downloads, this.ocFileName);
      downloader.closeHandler();
    }
  }

  install(progress, success, failure) {
    let vagrantInstall = this.installerDataSvc.getInstallable(VagrantInstall.key());
    if( vagrantInstall !== undefined && vagrantInstall.isInstalled() ) {
      this.postVagrantInstall(progress, success, failure);
    } else {
      progress.setStatus('Waiting for Vagrant to finish installation');
      ipcRenderer.on('installComplete', (event, arg) => {
        if (arg == 'vagrant') {
          this.postVagrantInstall(progress, success, failure);
        }
      });
    }
  }

  postVagrantInstall(progress, success, failure) {
    progress.setStatus('Installing');
    let installer = new Installer(CDKInstall.key(), progress, success, failure);

    let opts = [
      '-ExecutionPolicy',
      'ByPass',
      '-File',
      this.pscpPathScript
    ];
    let data = [
      '$newPath = "' + this.installerDataSvc.ocDir() + '";',
      '$oldPath = [Environment]::GetEnvironmentVariable("path", "User");',
      '[Environment]::SetEnvironmentVariable("Path", "$newPath;$oldPath", "User");',
      '[Environment]::Exit(0)'
    ].join('\r\n');
    let markerContent = [
      'openshift.auth.scheme=Basic',
      'openshift.auth.username=test-admin',
      'vagrant.binary.path=' + path.join(this.installerDataSvc.vagrantDir(), 'bin'),
      'oc.binary.path=' + this.installerDataSvc.ocDir(),
      'rhel.subscription.username=' + this.installerDataSvc.getUsername()
    ].join('\r\n');

    installer.unzip(this.cdkDownloadedFile, this.installerDataSvc.installDir())
    .then((result) => { return installer.unzip(this.ocDownloadedFile, this.installerDataSvc.ocDir(), result); })
    .then((result) => { return installer.unzip(this.vagrantDownloadedFile, this.installerDataSvc.tempDir(), result); })
    .then((result) => { return installer.moveFile(path.join(this.installerDataSvc.tempDir(), 'openshift-vagrant-master', 'cdk-v2'), this.installerDataSvc.cdkVagrantfileDir(), result); })
    .then((result) => { return installer.moveFile(this.cdkBoxDownloadedFile, path.join(this.installerDataSvc.cdkBoxDir(), this.boxName), result); })
    .then((result) => { return installer.moveFile(this.pscpDownloadedFile, path.join(this.installerDataSvc.ocDir(), 'pscp.exe'), result); })
    .then((result) => { return installer.writeFile(this.pscpPathScript, data, result); })
    .then((result) => { return installer.writeFile(this.installerDataSvc.cdkMarker(), markerContent, result); })
    .then((result) => { return installer.execFile('powershell', opts, result); })
    .then((result) => { return this.setupVagrant(installer, result); })
    .then((result) => { return installer.succeed(result); })
    .catch((error) => { return installer.fail(error); });
  }

  createEnvironment() {
    let env = {};

    //TODO Need to get this info from VagrantInstaller rather than hard code<commit_msg>JBDS-3657 Installer should set updated default username and password in .cdk<commit_after>'use strict';

let fs = require('fs-extra');
let request = require('request');
let path = require('path');
let ipcRenderer = require('electron').ipcRenderer;

import InstallableItem from './installable-item';
import Downloader from './helpers/downloader';
import Logger from '../services/logger';
import VagrantInstall from './vagrant';
import Installer from './helpers/installer';

class CDKInstall extends InstallableItem {
  constructor(installerDataSvc, $timeout, cdkUrl, cdkBoxUrl, ocUrl, vagrantFileUrl, pscpUrl, installFile) {
    super('CDK', 900, cdkUrl, installFile);

    this.installerDataSvc = installerDataSvc;
    this.$timeout = $timeout;
    this.cdkBoxUrl = cdkBoxUrl;
    this.ocUrl = ocUrl;
    this.vagrantFileUrl = vagrantFileUrl;
    this.pscpUrl = pscpUrl;

    this.cdkFileName = 'cdk.zip';
    this.cdkDownloadedFile = path.join(this.installerDataSvc.tempDir(), this.cdkFileName);

    this.boxName = 'rhel-cdk-kubernetes-7.2-18.x86_64.vagrant-virtualbox.box';
    this.cdkBoxDownloadedFile = path.join(this.installerDataSvc.tempDir(), this.boxName);

    this.ocFileName = 'oc.zip';
    this.ocDownloadedFile = path.join(this.installerDataSvc.tempDir(),   this.ocFileName);

    this.vagrantFileName = 'vagrantfile.zip';
    this.vagrantDownloadedFile = path.join(this.installerDataSvc.tempDir(), this.vagrantFileName);

    this.pscpFileName = 'pscp.exe';
    this.pscpDownloadedFile = path.join(this.installerDataSvc.tempDir(), this.pscpFileName);

    this.pscpPathScript = path.join(this.installerDataSvc.tempDir(), 'set-pscp-path.ps1');

    this.downloads = path.normalize(path.join(__dirname,"../../.."));
  }

  static key() {
    return 'cdk';
  }

  checkForExistingInstall() {
  }

  downloadInstaller(progress, success, failure) {
    progress.setStatus('Downloading');

    let downloadSize = 869598013;

    let totalDownloads = 5;

    let downloader = new Downloader(progress, success, failure, downloadSize, totalDownloads);
    let username = this.installerDataSvc.getUsername(),
        password = this.installerDataSvc.getPassword();

    if(!fs.existsSync(path.join(this.downloads, this.boxName))) {
      let cdkBoxWriteStream = fs.createWriteStream(this.cdkBoxDownloadedFile);
      downloader.setWriteStream(cdkBoxWriteStream);
      downloader.download(this.cdkBoxUrl);
    } else {
      this.cdkBoxDownloadedFile = path.join(this.downloads, this.boxName);
      downloader.closeHandler();
    }

    if(!fs.existsSync(path.join(this.downloads, this.cdkFileName))) {
      // TODO Switch back to auth download when CDK latest is in Customer Portal
      // downloader.downloadAuth
      //   ({
      //     url: this.cdkBoxUrl,
      //     rejectUnauthorized: false
      //   }, username, password);
      let cdkWriteStream = fs.createWriteStream(this.cdkDownloadedFile);
      downloader.setWriteStream(cdkWriteStream);
      downloader.downloadAuth
      ({
        url: this.getDownloadUrl(),
        rejectUnauthorized: false
      }, username, password);
    } else {
      this.cdkDownloadedFile = path.join(this.downloads, this.cdkFileName);
      downloader.closeHandler();
    }

    if(!fs.existsSync(path.join(this.downloads, this.vagrantFileName))) {
      let vagrantFileWriteStream = fs.createWriteStream(this.vagrantDownloadedFile);
      downloader.setWriteStream(vagrantFileWriteStream);
      downloader.download(this.vagrantFileUrl);
    } else {
      this.vagrantDownloadedFile = path.join(this.downloads, this.vagrantFileName);
      downloader.closeHandler();
    }

    if(!fs.existsSync(path.join(this.downloads, this.pscpFileName))) {
      let pscpWriteStream = fs.createWriteStream(this.pscpDownloadedFile);
      downloader.setWriteStream(pscpWriteStream);
      downloader.download(this.pscpUrl);
    } else {
      this.pscpDownloadedFile = path.join(this.downloads, this.pscpFileName);
      downloader.closeHandler();
    }

    if(!fs.existsSync(path.join(this.downloads, this.ocFileName))) {
      let ocWriteStream = fs.createWriteStream(this.ocDownloadedFile);
      if(!this.ocUrl.endsWith('.zip')) {
        request(this.ocUrl,(err,rsp,body) => {
          var fname = body.match(/openshift-origin-client-tools-v\w(\.\w){1,2}-\w{1,3}-\w{8}-\w{7}-windows\.zip/)[0];
          downloader.setWriteStream(ocWriteStream);
          this.ocUrl=this.ocUrl.concat(fname);
          downloader.download(this.ocUrl);
        });
      } else {
        downloader.setWriteStream(ocWriteStream);
        downloader.download(this.ocUrl);
      }
    } else {
      this.ocDownloadedFile = path.join(this.downloads, this.ocFileName);
      downloader.closeHandler();
    }
  }

  install(progress, success, failure) {
    let vagrantInstall = this.installerDataSvc.getInstallable(VagrantInstall.key());
    if( vagrantInstall !== undefined && vagrantInstall.isInstalled() ) {
      this.postVagrantInstall(progress, success, failure);
    } else {
      progress.setStatus('Waiting for Vagrant to finish installation');
      ipcRenderer.on('installComplete', (event, arg) => {
        if (arg == 'vagrant') {
          this.postVagrantInstall(progress, success, failure);
        }
      });
    }
  }

  postVagrantInstall(progress, success, failure) {
    progress.setStatus('Installing');
    let installer = new Installer(CDKInstall.key(), progress, success, failure);

    let opts = [
      '-ExecutionPolicy',
      'ByPass',
      '-File',
      this.pscpPathScript
    ];
    let data = [
      '$newPath = "' + this.installerDataSvc.ocDir() + '";',
      '$oldPath = [Environment]::GetEnvironmentVariable("path", "User");',
      '[Environment]::SetEnvironmentVariable("Path", "$newPath;$oldPath", "User");',
      '[Environment]::Exit(0)'
    ].join('\r\n');
    let markerContent = [
      'openshift.auth.scheme=Basic',
      'openshift.auth.username=openshift-dev',
      'openshift.auth.password=<PASSWORD>',
      'vagrant.binary.path=' + path.join(this.installerDataSvc.vagrantDir(), 'bin'),
      'oc.binary.path=' + this.installerDataSvc.ocDir(),
      'rhel.subscription.username=' + this.installerDataSvc.getUsername()
    ].join('\r\n');

    installer.unzip(this.cdkDownloadedFile, this.installerDataSvc.installDir())
    .then((result) => { return installer.unzip(this.ocDownloadedFile, this.installerDataSvc.ocDir(), result); })
    .then((result) => { return installer.unzip(this.vagrantDownloadedFile, this.installerDataSvc.tempDir(), result); })
    .then((result) => { return installer.moveFile(path.join(this.installerDataSvc.tempDir(), 'openshift-vagrant-master', 'cdk-v2'), this.installerDataSvc.cdkVagrantfileDir(), result); })
    .then((result) => { return installer.moveFile(this.cdkBoxDownloadedFile, path.join(this.installerDataSvc.cdkBoxDir(), this.boxName), result); })
    .then((result) => { return installer.moveFile(this.pscpDownloadedFile, path.join(this.installerDataSvc.ocDir(), 'pscp.exe'), result); })
    .then((result) => { return installer.writeFile(this.pscpPathScript, data, result); })
    .then((result) => { return installer.writeFile(this.installerDataSvc.cdkMarker(), markerContent, result); })
    .then((result) => { return installer.execFile('powershell', opts, result); })
    .then((result) => { return this.setupVagrant(installer, result); })
    .then((result) => { return installer.succeed(result); })
    .catch((error) => { return installer.fail(error); });
  }

  createEnvironment() {
    let env = {};

    //TODO Need to get this info from VagrantInstaller rather than hard code
{'fraction_non_alphanumeric': 0.14572598758092217, 'fraction_numerical': 0.004359889021006738, 'mean_word_length': 3.796894803548796, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 30, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 136, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7278874', 'n_tokens_mistral': 4892, 'n_tokens_neox': 4777, 'n_words': 722}