// post-build.js
'use strict';
const fs = require('fs');

/**
 * 获取当前所在的 git commit 的 commit id
 * @returns {string} 执行成功时返回 commit id；否则返回 git_hash_error
 * https://stackoverflow.com/a/56975550/196519
 */
const git_hash = () => {
  try {
    const rev = fs.readFileSync('.git/HEAD').toString().trim().split(/.*[: ]/).slice(-1)[0];
    if (rev.indexOf('/') === -1) {
      return rev;
    } else {
      return fs.readFileSync('.git/' + rev).toString().trim();
    }
  } catch (e) {
    // eslint-disable-next-line no-console
    console.log(e);
    return 'git_hash_error';
  }
}

/**
 * 插入 build info 到 index.html 中
 */
const updateIndexHtml = () => {
  const htmlPath = 'dist/index.html';
  let html = fs.readFileSync(htmlPath).toString();
  html += '\r\n<!-- ';
  html = html + '\r\n build time:' + new Date().toUTCString() + '; ';
  // process.env.BUILD_NUMBER 是 Jenkins 执行 job 时传入的 env
  html = html + '\r\n BUILD_NUMBER:' + process.env.BUILD_NUMBER + '; ';
  html = html + '\r\n GIT_COMMIT:' + git_hash() + '; ';
  html += '\r\n -->';

  fs.writeFileSync(htmlPath, html);
  // eslint-disable-next-line no-console
  console.log(`Insert timestamp and env into index.html. -- DONE`);
}

const postBuild = () => {
  updateIndexHtml();
}

postBuild();
