#!/usr/bin/env node

const path = require("path");
const fs = require("fs");

// Mapping from Node's `process.arch` to Golang's `$GOARCH`
const ARCH_MAPPING = {
  x64: "amd64",
};

// Mapping between Node's `process.platform` to Golang's
const PLATFORM_MAPPING = {
  linux: "linux",
  darwin: "darwin",
  win32: "windows",
};

const PLATFORM_TO_BINARY_MAPPING = {
  linux: "spade-code-generator",
  darwin: "spade-code-generator",
  win32: "spade-code-generator.exe",
};

const getBinaryPath = () => path.join(__dirname, `./dist/${PLATFORM_MAPPING[process.platform]}-${ARCH_MAPPING[process.arch]}`)
const getBinaryName = () => PLATFORM_TO_BINARY_MAPPING[process.platform];

// this copies the correct platform binary into ./bin/spade-code-generator
// this binary is then pick up by npm/yarn and copied into node_modules/.bin/spade-code-generator
// todo: we could read the bin dist from package.json "bin" attribute to avoid path duplication/mismatch.
function copyPlatformBinary() {
  const binSrc = path.join(getBinaryPath(), getBinaryName())
  const binDist = path.join(__dirname, "bin")

  if (!fs.existsSync(binSrc)) {
    throw ("binary not found: " + binSrc)
  }

  if (!fs.existsSync(binDist)) {
    fs.mkdirSync(binDist)
  }

  fs.copyFileSync(binSrc, path.join(binDist, getBinaryName()));
}

try {
  copyPlatformBinary()
  process.exit(0);
} catch(err) {
  // print the error and return 0
  // we don't want to prevent yarn/npm install when spade-codegen fails to install
  console.error(err);
  process.exit(0);
}
