#!/usr/bin/env node

'use strict'

const fs = require('fs')
const path = require('path')
const os = require('os')
const mnemonicHelpers = require('../lib/mnemonic-helpers')
const options = require('../lib/options-loader')()

if (!options.opts.mnemonicPath && options.opts.seedPath) {
  const seed = fs.readFileSync(options.opts.seedPath, 'utf8').trim()
  const mnemonic = mnemonicHelpers.fromSeed(seed)

  if (process.argv[2] === '--prod') {
    options.opts.mnemonicPath = path.resolve('/etc', 'lamassu', 'mnemonics', 'mnemonic.txt')
  } else {
    options.opts.mnemonicPath = path.resolve(os.homedir(), '.lamassu', 'mnemonics', 'mnemonic.txt')
  }

  if (!fs.existsSync(path.dirname(options.opts.mnemonicPath))) {
    fs.mkdirSync(path.dirname(options.opts.mnemonicPath))
  }

  if (!fs.existsSync(options.opts.mnemonicPath)) {
    fs.writeFileSync(options.opts.mnemonicPath, mnemonic, 'utf8')
  }

  fs.writeFileSync(options.path, JSON.stringify(options.opts, null, '\t'), 'utf8')
}
