
const io = require('path')
const vars_replace = require('./variables-replace')
const shell = require('shelljs')
const watch = require('watch')

module.exports = async (options, logger) => {
  let root = process.env.BITBUCKET_CLONE_DIR || process.cwd()
  let {
    source = io.join(root, '.kube'),
    destination = io.join(root, 'kube')
  } = options

  let sourceRel = source.replace(process.cwd(), '.')
  let destinationRel = destination.replace(process.cwd(), '.')

  const replace = () => {
    let vars_options = Object.assign(options, { path: destination })
    return vars_replace(vars_options, logger)
  }

  const handleChange = () => {
    shell.rm('-rf', destination)
    shell.cp('-fR', source, destination)
    return replace();
  }


  if(options.watch) {
    await handleChange()
    return new Promise((resolve, reject) =>  {
      watch.createMonitor(source, (monitor) => {
        monitor.on("created", handleChange)
        monitor.on("changed", handleChange)
        monitor.on("removed", handleChange)

        replace().then(() => {
          logger(`Watching directory ${sourceRel} for replacement in ${destinationRel}`)
          logger('Press CTRL+C to exit...');
          process.on('exit', (code) => {
            monitor.stop();
            if(code > 0)
              reject(code)
            else
              resolve()
            return;
          });
        })

      })
    })
  } else {
    return handleChange()
  }
}