const fs = require('fs');
const path = require('path');
const debug = require('debug');

const envPath = path.resolve(__dirname, '../../.env');
require('dotenv').config({ path: envPath });

const { createRedirects } = require('./createRedirects');

const log = debug('fcc:tools:ensure-env');
const {
  HOME_LOCATION: home,
  API_LOCATION: api,
  FORUM_LOCATION: forum,
  FORUM_PROXY_LOCATION: forumProxy,
  LOCALE: locale
} = process.env;

const locations = {
  homeLocation: home,
  apiLocation: api,
  forumLocation: forum,
  forumProxyLocation: forumProxy
};


const apiPath = path.resolve(__dirname, '../../api-server');
const clientPath = path.resolve(__dirname, '../../client');
const clientStaticPath = path.resolve(clientPath, 'static');
const globalConfigPath = path.resolve(__dirname, '../../config');
const env = Object.assign(locations, {locale});

const redirects = createRedirects({ api, home, forum, forumProxy });

fs.writeFile(`${clientStaticPath}/_redirects`, redirects, function(err) {
  if (err) {
    log('Error');
    console.error(err);
  }
  log('_redirects written');
});

fs.access(`${apiPath}/server/resources/pathMigration.json`, err => {
  if (err) {
    log('creating pathMigration');
    return fs.writeFileSync(
      `${apiPath}/server/resources/pathMigration.json`,
      '{}'
    );
  }
  log('pathMigration present');
  return null;
});

fs.writeFileSync(`${clientPath}/config/env.json`, JSON.stringify(env));
fs.writeFileSync(`${globalConfigPath}/env.json`, JSON.stringify(env));

@@ -414,16 +414,38 @@
 : locale
+,%0A  NODE_ENV: NODE_ENV
 %0A%7D = pro
@@ -872,24 +872,59 @@
 %7Blocale%7D);%0A%0A
+if (NODE_ENV === 'production') %7B%0A  
 const redire
@@ -976,25 +976,26 @@
 umProxy %7D);%0A
-%0A
+  
 fs.writeFile
@@ -1054,24 +1054,26 @@
 on(err) %7B%0A  
+ 
+ 
 if (err) %7B%0A 
@@ -1063,32 +1063,34 @@
 %0A    if (err) %7B%0A
+  
     log('Error')
@@ -1095,16 +1095,18 @@
 ');%0A    
+ 
+ 
 console.
@@ -1117,20 +1117,24 @@
 r(err);%0A
+  
   %7D%0A
+  
   log('_
@@ -1154,19 +1154,92 @@
 tten');%0A
+  
 %7D);
+%0A%7D else %7B%0A  log(%60ignoring creation of redirect file in $%7BNODE_ENV%7D%60);%0A%7D
 %0A%0Afs.acc

remove redirect build on dev