#!/usr/bin/env node
// Copyright 2021 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================

/**
 * This script generates the version_test.ts file based off of the package's
 * package.json file.
 */

import * as fs from 'fs';
import {ArgumentParser} from 'argparse';

const LICENSE = `/**
 * @license
 * Copyright ${(new Date).getFullYear()} Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */
`;

const AUTOGEN_CLAUSE = `///// DO NOT EDIT: This file is auto-generated by ` +
    `/tools/make_version_test.ts
`;

const parser = new ArgumentParser({
  description: 'This script generates the version_test file which checks that'
    + ' the package\'s version matches the version contained in the package.json',
});

parser.addArgument('package_json', {action: 'store', type: String});
parser.addArgument('version_name', {
  action: 'store',
  type: String,
});
parser.addArgument('output', {
  action: 'store',
  type: String,
});

const args = parser.parseArgs();

const package_json = fs.readFileSync(args.package_json, 'utf8');
if (! package_json) {
  throw new Error(`Failed to read package.json ${args.package_json}`);
}
const version = JSON.parse(package_json).version as string;


const versionTestContent = `${LICENSE}
${AUTOGEN_CLAUSE}
import {${args.version_name}} from './index';

describe('version', () => {
  it('version is contained', () => {
    expect(${args.version_name}).toBe('${version}');
  });
});
`;

fs.writeFileSync(args.output, versionTestContent);
