/**
 * Cleanup application files from sensitive information.
 * To be executed after `ubcli linkstatic` for environment where security requirements is extremely high.
 * Script:
 *  - cleanup all package.json files in /opt/unitybase/apps/{PRODUCT_NAME}/inetpub/clientRequire/ folder
 *    Only necessary information (name, version, engines, config and main sections are remains)
 *  - `version` value in package.json are forced to 100.0.1
 *  - all CHANGELOG.md files are removed
 *
 * Usage from a command line:

 ubcli hardering

 * Usage from a code:
 *
 const hardering = require('@unitybase/ubcli/hardering')
 hardering({})

 * @module hardering
 * @memberOf module:@unitybase/ubcli
 */

const options = require('@unitybase/base').options
const argv = require('@unitybase/base').argv
const fs = require('fs')
const path = require('path')

module.exports = hardering
/**
 * @param {object} cfg
 */
function hardering (cfg) {
  if (!cfg) {
    const opts = options.describe('hardering',
      'Cleanup application files from sensitive information',
      'ubcli'
    )
    cfg = opts.parseVerbose({}, true)
    if (!cfg) return
  }
  const ubCfg = argv.getServerConfiguration()
  const target = ubCfg.httpServer.inetPub

  if (!target || (typeof target !== 'string')) {
    throw new Error('"http.inetPub" value in ubConfig or is not defined')
  }
  if (!fs.existsSync(target)) {
    throw new Error(`Target folder "${target}" is not exists. May be "ubcli linkStatic" is not executed for this app`)
  }
  const resFN = '/tmp/.ubcrres.txt'
  if (fs.existsSync(resFN)) {
    fs.unlinkSync(resFN)
  }
  console.log(`Hardering '${target}' folder..`)
  // `find -L ${target} -name 'package.json' -not -path '*/node_modules/*' > ${resFN}"`
  // eslint-disable-next-line no-undef
  shellExecute('/bin/sh', `-c "find -L ${target} -name 'package.json' -not -path '*/node_modules/*' > ${resFN}"`)
  const files = fs.readFileSync(resFN, 'utf8').split('\n')
  if (!files.length) {
    throw new Error(`There is no package.json files inside "${target}"/ May be app already hardered or "ubcli linkStatic" is not executed for this app`)
  } else {
    console.log(`Processing ${files.length} package.json files..`)
  }
  for (const fn of files) {
    if (fn.trim().length === 0) continue
    const p = JSON.parse(fs.readFileSync(fn, 'utf8'))
    const newP = {
      name: p.name,
      version: '100.0.1'
    }
    ;['main', 'browser', 'config', 'engines'].forEach(k => {
      if (!p[k]) return
      newP[k] = p[k]
    })
    console.log(`  cleanup ${fn}`)
    fs.writeFileSync(fn, JSON.stringify(newP, null, 2))
    const chlFn = path.join(path.dirname(fn), 'CHANGELOG.md')
    if (fs.existsSync(chlFn)) {
      fs.unlinkSync(chlFn)
      console.log(`  remove ${chlFn}`)
    }
  }
}