#!/usr/bin/env node

const path = require('path');
const proc = require('child_process');
const startCase = require('lodash.startcase');

const baseDir = process.argv[2];

const files = proc.execFileSync(
  'find', [baseDir, '-type', 'f'], { encoding: 'utf8' },
).split('\n').filter(s => s !== '');

console.log('.API');

const links = files.map((file) => {
  const doc = file.replace(baseDir, '');
  const title = path.parse(file).name;

  return {
    xref: `* xref:${doc}[${startCase(title)}]`,
    title,
  };
});

// Case-insensitive sort based on titles (so 'token/ERC20' gets sorted as 'erc20')
const sortedLinks = links.sort(function (a, b) {
  return a.title.toLowerCase().localeCompare(b.title.toLowerCase(), undefined, { numeric: true });
});

for (const link of sortedLinks) {
  console.log(link.xref);
}

@@ -311,24 +311,175 @@
 g('.API');%0A%0A
+function getPageTitle (directory) %7B%0A  if (directory === 'metatx') %7B%0A    return 'Meta Transactions';%0A  %7D else %7B%0A    return startCase(directory);%0A  %7D%0A%7D%0A%0A
 const links 
@@ -621,24 +621,27 @@
 %7Bdoc%7D%5B$%7B
-startCas
+getPageTitl
 e(title)

Change title of meta transactions page in docs sidebar