/*
 * Copyright (C) 2021 StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */

import {initial, mapValues, omit, pickBy, merge, last} from 'lodash-es';
import fs from 'fs';

function accumulateFile(path) {
  const packageJson = JSON.parse(fs.readFileSync('./package.json'));
  const dependencies = merge(packageJson.dependencies, packageJson.devDependencies);

  fs.writeFileSync(path, JSON.stringify(
    mapValues(
      pickBy(
        JSON.parse(fs.readFileSync(path)),
        (value, key) => {
          const parts = key.split('@');

          return dependencies[initial(parts).join('@')] === last(parts);
        },
      ),
      value => ({
        licenseText: value.licenseFile && fs.readFileSync(value.licenseFile, 'utf8'),
        ...omit(value, 'licenseFile'),
      })
    )
  ));
}

accumulateFile('./src/assets/about/licenses.json');
