const assert = require('assert');
const fs = require('fs');
const path = require('path');
const { runPack } = require('./_pack_helpers');
try {
  const { cwd, filename } = runPack();
  const tarPath = path.join(cwd, filename);
  if (!fs.existsSync(tarPath)) throw new Error('tarball not found: ' + tarPath);
  // inspect package/package.json within tarball using tar -xOzf
  const execSync = require('child_process').execSync;
  let pkgJsonStr;
  try {
    pkgJsonStr = execSync(`tar -xOzf ${filename} package/package.json`, { cwd, encoding: 'utf8' });
  } catch (e) {
    throw new Error('failed to extract package.json from tarball; ensure `tar` is available');
  }
  const pkg = JSON.parse(pkgJsonStr);
  assert.strictEqual(pkg.name, '@ansible/example', 'tarball package.json name mismatch');
  assert.ok(pkg.version, 'tarball package.json missing version');
  console.log('test_pack_inspect: OK');
  // cleanup: remove tarball
  try { fs.unlinkSync(tarPath); } catch (e) {}
  process.exit(0);
} catch (err) {
  console.error('test_pack_inspect: FAILED');
  console.error(err && err.message ? err.message : err);
  process.exit(1);
}
