#!/bin/sh

DIR="$1"
SOURCE="$(pkgjs-pjson $DIR 'source')"
if [ "$2" != "" ]
then
    INDEX="$2"
else
    INDEX="$SOURCE"
fi

EXTERNAL="path-to-regexp,delegate-it,typed-query-selector,focus-options-polyfill"
if [ "$DIR" = "." ]
then
    RPATH="."
elif [ "$DIR" = "plugin" ]
then
    RPATH=".."
    EXTERNAL="$EXTERNAL,swup"
else
    RPATH=".."
    EXTERNAL="$EXTERNAL,swup,@swup/plugin"
fi

MODULES="-p node-resolve -p babel -p commonjs -p typescript -p json -p terser"
# Globals are taken from outputOptions generated by microbundle
GLOBALS0="dns:dns,fs:fs,path:path,url:url"
GLOBALS1="$GLOBALS0,path-to-regexp:pathToRegexp,delegate-it:delegateIt,typed-query-selector:typedQuerySelector,focus-options-polyfill:focusOptionsPolyfill,swup:swup,@swup/plugin:swupPlugin"

set -x
cd "$DIR"
rollup $MODULES -e $EXTERNAL -g $GLOBALS1 -f cjs $INDEX -o $(pkgjs-pjson . main) -m
rollup $MODULES -e $EXTERNAL -g $GLOBALS1 -f es $INDEX -o $(pkgjs-pjson . module) -m
rollup -c $RPATH/rollup.modern.mjs $MODULES -e $EXTERNAL -g $GLOBALS1 -f es $INDEX -o $(pkgjs-pjson . exports . import) -m
rollup $MODULES -e none -g $GLOBALS0 -f umd $SOURCE -o $(pkgjs-pjson . unpkg) -m -n $(pkgjs-pjson . amdName)

