// import gulp from 'gulp'
const gulp = require('gulp')
const spawnSync = require('child_process').spawnSync
const fs = require('fs')

const silentError = new Error('')
silentError.stack = ' '

gulp.task('publish', (cb) => {
  // Get semver only in this part , because in prod we dont need this  module
  const semver = require('semver')

  // We tag to promote to a production env picking the current version tag.
  const packagePath = `${process.cwd()}/package.json`
  const packageJSON = fs.readFileSync(packagePath).toString('utf-8')
  const packageLockPath = `${process.cwd()}/package-lock.json`
  const packageLockJSON = fs.readFileSync(packageJSON).toString('utf-8')
  const packageParsed = JSON.parse(packageJSON)

  const version = packageParsed.version
  const tagCmd = spawnSync(
    [`git tag v${version}`, `git push origin v${version}`].join(' && '),
    {
      stdio: 'inherit',
      shell: true
    }
  )
  if (tagCmd.status !== 0) {
    return cb(silentError)
  }

  // Now, we upload all the new builded docs , patch the version ,
  // and prepare for the next promotion ^^.
  // Save all changes before publish

  const currentVersion = packageParsed.version
  const patchedVersion = semver.inc(currentVersion, 'patch')
  fs.writeFileSync(
    packagePath,
    packageJSON.replace(
      `\"version\": \"${currentVersion}\"`,
      `\"version\": \"${patchedVersion}\"`
    )
  )

  fs.writeFileSync(
    packageLockPath,
    packageLockJSON.replace(
      `\"version\": \"${currentVersion}\"`,
      `\"version\": \"${patchedVersion}\"`
    )
  )

  const prepareForNextCmd = spawnSync(
    [
      'git add .',
      "git commit -m '[CI SKIP] update Readme.md and increase the version for the next publish'",
      'git push'
    ].join(' && '),
    {
      stdio: 'inherit',
      shell: true
    }
  )
  if (prepareForNextCmd.status !== 0) {
    return cb(silentError)
  }

  cb()
})
