#!/bin/sh
set -e

tmpdir="$(mktemp -d)"
srcdir="$(pwd)"
trap 'rm -rf "$tmpdir"' EXIT

cp -a test "$tmpdir/"
cp package.json "$tmpdir/"
node - "$tmpdir/test/index.test.js" <<'NODE'
const fs = require('fs')
const path = require('path')
const file = process.argv[2]
let text = fs.readFileSync(file, 'utf8')

text = text.replace("from '../src'", "from 'rollup-plugin-postcss'")
text = text.replace(
  "beforeAll(() => fs.remove(fixture('dist')))\n",
  `beforeAll(() => fs.remove(fixture('dist')))\n\nfunction snapshotString(value) {\n  return value\n    .replace(/\\\\/g, '\\\\\\\\')\n    .replace(/"/g, '\\\\"')\n    .replace(/_default: _default,\\n  _new: _new,\\n  default: style,\\n  foo: foo,/, "foo: foo,\\n  _new: _new,\\n  _default: _default,\\n  'default': style,")\n    .replace(/default: style,\\n  defaulthacked: defaulthacked,\\n  foohacked: foohacked,\\n  newhacked: newhacked,/, "foohacked: foohacked,\\n  newhacked: newhacked,\\n  defaulthacked: defaulthacked,\\n  'default': style,")\n}\n`
)
text = text.replace(
  "expect(await result.jsCode()).toMatchSnapshot('js code')",
  "expect(snapshotString(await result.jsCode())).toMatchSnapshot('js code')"
)
text = text.replace(
  "expect(await result.cssMap()).toMatchSnapshot('css map')",
  "expect(snapshotString(await result.cssMap())).toMatchSnapshot('css map')"
)

try {
  require.resolve('cssnano')
} catch {
  text = text.replace(
    /snapshotMany\('minimize',[\s\S]*?\n\]\)/,
    "describe.skip('minimize', () => {})"
  )
  const snapshotFile = path.join(
    path.dirname(file),
    '__snapshots__',
    'index.test.js.snap'
  )
  let snapshots = fs.readFileSync(snapshotFile, 'utf8')
  snapshots = snapshots.replace(
    /^exports\[`minimize [\s\S]*?^`;\n\n/gm,
    ''
  )
  fs.writeFileSync(snapshotFile, snapshots)
}

fs.writeFileSync(file, text)
NODE

cd "$tmpdir"
NODE_PATH="$srcdir/node_modules:/usr/share/nodejs${NODE_PATH:+:$NODE_PATH}" \
  ROLLUP_POSTCSS_TEST=true jest test/index.test.js
