#!/usr/bin/env node

if (~process.argv.indexOf('--help') || ~process.argv.indexOf('-h'))
    return console.info(`Usage: ${__filename.slice(__dirname.length + 1)} [-h|--help] [--dry]`);

const isDry = ~process.argv.indexOf('--dry');

const fs = require('fs');
const config = require('../config/environment')(process.env.EMBER_ENV);

const providers = config.PREPRINTS.providers;
const hostsFileName = '/etc/hosts';
const hostIP = '127.0.0.1';
const hostsFile = fs.readFileSync(hostsFileName, {encoding: 'utf8'});
const sectionHeader = '## EMBER-PREPRINTS ##\n';
const sectionFooter = '\n## /EMBER-PREPRINTS ##';
const rgx = new RegExp(`(?:${sectionHeader})(.|\\s)*(?:${sectionFooter})`, 'm');

const maxLength = providers
    .map(provider => provider.domain)
    .reduce((a, b) => a.length > b.length ? a.length : b.length);

const lines = providers
    .map(provider => `${hostIP}\tlocal.${provider.domain}${' '.repeat(maxLength - provider.domain.length)}\t# ${provider.id}`)
    .join('\n');

const section = `${sectionHeader}${lines}${sectionFooter}`;
const resultFile = rgx.test(hostsFile) ? hostsFile.replace(rgx, section) : `${hostsFile}\n\n${section}`;

console.info(`Resulting file:\n${resultFile}`);

if (isDry)
    console.log('!!! DRY RUN, File not written !!!');
else
    fs.writeFileSync(hostsFileName, resultFile, {encoding: 'utf8'});

@@ -18,17 +18,16 @@
 de%0A%0Aif (
-~
 process.
@@ -29,29 +29,30 @@
 cess.argv.in
-dexOf
+cludes
 ('--help') %7C
@@ -53,17 +53,16 @@
 lp') %7C%7C 
-~
 process.
@@ -72,31 +72,27 @@
 v.in
-dexOf
+cludes
 ('-h'))
+ %7B
 %0A   
- return
  con
@@ -173,16 +173,39 @@
 -dry%5D%60);
+%0A    process.exit(0);%0A%7D
 %0A%0Aconst 
@@ -216,9 +216,8 @@
 y = 
-~
 proc
@@ -231,13 +231,14 @@
 v.in
-dexOf
+cludes
 ('--
@@ -350,16 +350,17 @@
 %0A%0Aconst 
+%7B
 provider
@@ -360,16 +360,17 @@
 roviders
+%7D
  = confi
@@ -384,18 +384,8 @@
 INTS
-.providers
 ;%0Aco
@@ -695,16 +695,87 @@
 %60, 'm');
+%0Aconst domainProviders = providers.filter(provider =%3E provider.domain);
 %0A%0Aconst 
@@ -786,17 +786,23 @@
 ength = 
-p
+domainP
 roviders
@@ -917,25 +917,31 @@
 nst lines = 
-p
+domainP
 roviders%0A   
@@ -1307,16 +1307,18 @@
  (isDry)
+ %7B
 %0A    con
@@ -1368,17 +1368,32 @@
 ');%0A
-else%0A    
+    process.exit(0);%0A%7D%0A%0A
 fs.w

Update add-domains script