#!/usr/bin/env bash

set -eu

SCRIPTS_DIR="$(cd "$(dirname "$0")" && pwd)"
BASE_DIR="$(dirname "${SCRIPTS_DIR}")"
SOURCE_DIR="${BASE_DIR}/src"
OUTPUT_DIR="${BASE_DIR}/lib"

compile_commonjs() {
  mkdir -vp "${OUTPUT_DIR}"

  babel \
    --delete-dir-on-start \
    --out-dir "${OUTPUT_DIR}/cjs" \
    --minified \
    --compact true \
    --no-comments \
    --no-highlight-code \
    --env-name production \
    --source-root "${SOURCE_DIR}" \
    --out-file-extension .js \
    '**/index.mjs'

  echo '{"type":"commonjs"}' > "${OUTPUT_DIR}/cjs/package.json"
}

compile_module() {
  mkdir -vp "${OUTPUT_DIR}"

  babel \
    --delete-dir-on-start \
    --out-dir "${OUTPUT_DIR}/esm" \
    --minified \
    --compact true \
    --no-babelrc \
    --no-comments \
    --no-highlight-code \
    --env-name production \
    --source-root "${SOURCE_DIR}" \
    --out-file-extension .mjs \
    '**/index.mjs'

  echo '{"type":"module"}' > "${OUTPUT_DIR}/esm/package.json"
}

compile() {
  compile_commonjs "$@"
  compile_module "$@"
}

compile "$@"
