/*
 * Copyright (C) Sapphirecode - All Rights Reserved
 * This file is part of standard which is released under MIT.
 * See file 'LICENSE' for full license details.
 * Created by Timo Hocker <timo@scode.ovh>, May 2020
 */

/* eslint-disable */

'use strict';

const fs = require ('fs');
const child_process = require ('child_process');

const pkg = JSON.parse (fs.readFileSync ('package.json', 'utf-8'));
[
  ,, pkg.version
] = process.argv;
fs.writeFileSync ('package.json', JSON.stringify (pkg, null, 2));

child_process.execSync ('yarn lint', { stdio: 'inherit' });
child_process.execSync ('yarn test', { stdio: 'inherit' });
child_process.execSync ('yarn compile', { stdio: 'inherit' });

let ok = true;

if (typeof pkg.description === 'undefined' || pkg.description === '') {
  console.log ('description undefined');
  ok = false;
}

if (typeof pkg.repository === 'undefined') {
  console.log ('repository undefined');
  ok = false;
}

function major (version) {
  return version.replace (/\.[0-9x]+$/ui, '');
}

if (fs.existsSync ('README.md')) {
  const readme = fs.readFileSync ('README.md', 'utf-8');
  const version = (/version: ([0-9x.]+)/ui).exec (readme);
  if (
    version === null
    || major (version[1]) !== major (pkg.version)
  ) {
    console.log ('readme version does not match package version');
    ok = false;
  }
}
else {
  console.log ('readme does not exist');
  ok = false;
}

if (fs.existsSync ('CHANGELOG.md')) {
  const changelog = fs.readFileSync ('CHANGELOG.md', 'utf-8');
  const cl_version = (/^## ([0-9x.]+)/mu).exec (changelog);
  if (
    cl_version === null
    || major (cl_version[1]) !== major (pkg.version)
  ) {
    console.log ('changelog is not up to date');
    ok = false;
  }
}
else {
  console.log ('changelog does not exist');
  // ok = false;   disable until all modules have a changelog
}

if (ok)
  child_process.execSync ('yarn publish --access public');
else
  process.exit (1);