#!/usr/bin/env ub

const fs = require('fs')
const path = require('path')
// argv: executable ubcli command ...params
const command = process.argv[2]

/**
 * A simple CLI for scaffolding UnityBase projects.
 * Run `npx ubcli -help` in command line (or `ubcli --help` if installed globally) for a full list of available commands
 *
 * if `-app appName` parameter specified, it's handled by `/usr/bin/ubcli` script and exports env
 * vars in the same way as systemd unit does before run ubcli.js:
 *   - export UB_APPHOME=/opt/unitybase/apps/$appName/
 *   - export UB_APPDATA=/var/opt/unitybase/$appName/
 *   - export UB_CFG="$UB_APPHOME"ubConfig.json
 *   - export UB_ENV="$UB_APPDATA"ubConfig.env
 *
 * @module @unitybase/ubcli
 */

/**
 * Show usage
 */
function showUsage () {
  const libsPath = path.join(__dirname, '..', 'lib')
  const commands = fs.readdirSync(libsPath)
  console.info('Tools for scaffolding UnityBase projects. Usage:')
  console.log('  ubcli [-app appName] command [options]\n')
  console.log('available commands:')
  const deprecated = []
  for (const cmd of commands) {
    if (cmd.endsWith('.js')) {
      let shortDoc = ' ' + cmd.replace(/\.js$/, '').padEnd(20, ' ')
      try {
        const cmdModule = require(path.join(libsPath, cmd))
        if (cmdModule.deprecated) {
          deprecated.push(cmd.replace(/\.js$/, ''))
        } else {
          if (cmdModule.shortDoc) shortDoc += ' - ' + cmdModule.shortDoc
          console.log(shortDoc)
        }
      } catch (e) {
      }
    }
  }
  if (deprecated.length) {
    console.debug('\n *deprecated commands -', deprecated.join(', '))
  }
  console.log('\n command parameters help: ubcli command -?, example: ubcli migrate -?')
}

/**
 *
 */
function ubcli () {
  if (!command || (['-?', '/?', '-help', '/help', '--help'].indexOf(command) !== -1)) {
    showUsage()
  } else {
    try {
      // eslint-disable-next-line no-unused-vars
      const resolved = require.resolve(`../lib/${command}`)
      // console.log('RESOLVED TO', resolved)
    } catch (e) {
      showUsage()
      console.error(`Invalid command "${command}". See above for possible commands`)
      return
    }
    const cmdModule = require(`../lib/${command}`)
    if (typeof cmdModule === 'function') cmdModule()
  }
}

module.exports = ubcli