#!/usr/bin/env node

/**
 * Tmplify prototype.
 */

'use strict'

process.chdir(`${__dirname}/..`)

const path = require('path')
const fs = require('fs')
const { runTasks } = require('ape-tasking')
const tmplconv = require('tmplconv')

const scff = require('../lib')

const demo = path.dirname(require.resolve('apeman-demo-mock/package.json'))
const demoPkg = require('apeman-demo-mock/package.json')

runTasks('tmplify', [
  () => tmplconv.tmplify(demo, 'asset/tmpl', {
    clean: true,
    mode: '444',
    pattern: [
      '**/*.*',
      '.*',
      'src/.*.json',
      '*/.*.bud',
      '*/.*.hbs'
    ],
    ignore: [
      'node_modules/**/*.*',
      'dist/**/*.*',
      '.DS_Store',
      '.svg'
    ],
    data: {
      'github_repository': 'apeman-demo-labo/apeman-demo-mock',
      'package_name': demoPkg.name,
      'package_description': demoPkg.description,
      'author_name': demoPkg.author.name,
      'author_email': demoPkg.author.email,
      'author_url': demoPkg.author.url
    },
    prefix: scff.prefix,
    suffix: scff.suffix
  }),
  () => tmplconv.tmplify(`${__dirname}/..`, 'asset/tmpl', {
    pattern: [
      '.gitignore'
    ],
    prefix: scff.prefix,
    suffix: scff.suffix
  }),
  function (callback) {
    let filename = require.resolve('../asset/tmpl/package.json.tmpl')
    let str = fs.readFileSync(filename).toString()
    let pkg = JSON.parse(str)
    fs.chmodSync(filename, '644')
    fs.writeFileSync(filename, JSON.stringify({
      name: pkg.name,
      version: '1.0.0',
      description: pkg.description,
      main: pkg.main,
      scripts: pkg.scripts,
      repository: pkg.repository.url.split(/\//g).slice(-1).join('/').replace(/\.git$/, ''),
      keywords: pkg.keywords,
      author: pkg.author,
      license: pkg.license,
      bugs: pkg.bugs,
      homepage: pkg.homepage,
      dependencies: pkg.dependencies,
      devDependencies: pkg.devDependencies,
      engines: pkg.engines
    }, null, 2))
    fs.chmodSync(filename, '444')
    callback(null)
  }
], true)
