import * as path from 'path';
import * as fsExtra from 'fs-extra';
import { VersionManage } from '../utils/version';
import * as ghPages from 'gh-pages';
import repo from '../config/repo';
import { spawnSync } from 'child_process';
import * as os from 'os';

const version = new VersionManage();
const deployDirName = '.deploy';
const deployDirPath = path.resolve(__dirname, '../', deployDirName);
const dumiOutoutPath = path.resolve(__dirname, '../docs-dist');

function buildDocs(): boolean {
  const cmd = os.platform() === 'win32' ? 'npm.cmd' : 'npm';
  const result = spawnSync(cmd, ['run', 'build'], {
    stdio: 'inherit',
    cwd: path.resolve(__dirname, '../'),
  });
  if (result.error) {
    // console.error(`构建文档失败: ${result.error.message}`);
    return false;
  }
  return result.status === 0;
}

function createDeployContext() {
  const dirName = version.getLastVersion() === 'master' ? 'master' : version.getPackageVersion();
  const versionPath = path.join(deployDirPath, `./${dirName}`);
  fsExtra.ensureDirSync(versionPath);
  fsExtra.copySync(dumiOutoutPath, versionPath);
}

function removeDeployContext() {
  fsExtra.emptyDirSync(deployDirPath);
}

function getGitRepo(): string {
  return process.env.WK_DEPLOY_GIT_REPO || repo;
}

function deploy() {
  createDeployContext();
  console.log('正在上传...');
  let options = {
    repo: getGitRepo(),
    remove: version.getLastVersion(),
    branch: 'master',
    user: {
      name: 'robot',
      email: 'robot@wakedata.com',
    },
    depth: 0,
  };

  ghPages.publish(deployDirName, options, err => {
    removeDeployContext();
    if (err) {
      console.log('上传失败: ', err.message || err);
      process.exit(2);
    } else {
      console.log('上传成功');
    }
  });
}

function run() {
  version.patch();
  const buildStatus = buildDocs();
  if (!buildStatus) {
    // 回滚
    version.rollback();
    process.exit(-1);
  }

  deploy();
}

run();
