/**
 * Post install script: create or replace the symlink .env
 * to the .env file matching the current environment
 *
 * To force a hostname, define an env variable named HOST :
 *
 *     HOST=ci node ./env/setupEnv.mjs
 *
 */
import os from 'os'
import fs from 'fs'
import { fileURLToPath } from 'node:url'
import path from 'path'

const projectDir = path.join(path.dirname(fileURLToPath(import.meta.url)), '..')

const hostname = process.env.HOSTNAME || os.hostname()

const environments = {
  site_logiciels: '.env.docker',
  'prod-v2': '.env.prod',
  'test-v2': '.env.test',
  test1: '.env.test1',
  test2: '.env.test2',
  test3: '.env.test3',
  test4: '.env.test4',
  test5: '.env.test5',
  test6: '.env.test6',
  test7: '.env.test7',
  test8: '.env.test8',
  test9: '.env.test9',
  ci: '.env.ci',
}

if (!environments.hasOwnProperty(hostname)) {
  throw new Error('Critical : unknown environment [' + hostname + ']')
}

const targetEnvFile = path.join(projectDir, 'env', environments[hostname])
const mainEnvFile = path.join(projectDir, '.env')

fs.unlink(mainEnvFile, (err) => {
  // 'ENOENT' is the error code for "no such file or directory", we ignore this one
  if (err && err.code !== 'ENOENT') {
    throw err
  }
  console.log(`${mainEnvFile} was deleted`)
})

fs.symlink(targetEnvFile, '.env', 'file', (err) => {
  if (err) {
    throw err
  }
  console.log(`Symlink created : ${mainEnvFile} -> ${targetEnvFile}`)
})
