#!/usr/bin/env node

const os = require('os')
const path = require('path')
const fs = require('fs')

const binaries = ['ppx', 'extract']
const aliases = { 'ppx': 'Ppx.exe', 'extract': 'Extract.exe' }

function copyFileSync(sourcePath, destPath) {
  const data = fs.readFileSync(sourcePath)
  const stat = fs.statSync(sourcePath)
  fs.writeFileSync(destPath, data)
  fs.chmodSync(destPath, stat.mode)
}

const platform = os.platform()
const arch = os.arch()

const platformDir = `platform-${platform}-${arch}`

if (!fs.existsSync(path.join(__dirname, platformDir))) {
  console.error(`res-react-intl does not support this platform: ${platform}-${arch}`)
  console.error('Supported platforms: linux-x64, linux-arm64, darwin-arm64')
  console.error('For other platforms, build from source: https://opam.ocaml.org/')
  process.exit(1)
}

for (const binary of binaries) {
  const sourcePath = path.join(__dirname, platformDir, binary)
  const destPath = path.join(__dirname, binary)
  if (fs.existsSync(destPath)) {
    fs.unlinkSync(destPath)
  }
  copyFileSync(sourcePath, destPath)
  fs.chmodSync(destPath, 0o755)

  // Also write alias (e.g. Ppx.exe) for consumers that reference the binary by that name
  const aliasName = aliases[binary]
  if (aliasName) {
    const aliasPath = path.join(__dirname, aliasName)
    if (fs.existsSync(aliasPath)) {
      fs.unlinkSync(aliasPath)
    }
    copyFileSync(sourcePath, aliasPath)
    fs.chmodSync(aliasPath, 0o755)
  }
}

console.log(`Installed ${platform}-${arch} binaries.`)
