#!/bin/bash

set -e

DIR=`mktemp -d`
cd $DIR

cat > package.json << EOF
{
  "name": "mjs2cjs-test",
  "version": "0.0.1",
  "type": "module",
  "exports": {
     "require": "dist/index.cjs"
  }
}
EOF

cat > index.mjs << EOF
import chalk from 'chalk';
import sliceAnsi from 'slice-ansi';

const string = 'The quick brown ' + chalk.red('fox jumped over ') +
	'the lazy ' + chalk.green('dog and then ran away with the unicorn.');

console.log(sliceAnsi(string, 20, 30));
EOF
mjs2cjs index.mjs
cd /
RES=`node $DIR/dist/index.cjs`
if [ "$RES" != "jumped ove" ]; then
	echo "Result isn't 'jumped ove' but:" >&2
	echo $RES >&2
	exit 1
fi

rm -rf $DIR/dist
cd $DIR
cat > package.json << EOF
{
  "name": "mjs2cjs-test",
  "version": "0.0.1",
  "type": "module",
  "exports": "./index.mjs"
}
EOF
pkgjs-ln chalk
pkgjs-ln slice-ansi
pkgjs-ln @rollup/plugin-node-resolve
mjs2cjs -a index.mjs
cd /
RES=`pkgjs-pjson $DIR exports require`
if [ "$RES" != "./dhnodejsBundle.cjs" ]; then
	echo "package.json is wrong:" >&2
	cat $DIR/package.json >&2
	exit 1
fi

RES=`node $DIR/dhnodejsBundle.cjs`
if [ "$RES" != "jumped ove" ]; then
	echo "Result isn't 'jumped ove' but:" >&2
	echo $RES >&2
	exit 1
fi

rm -rf $DIR
