#!/bin/env bash
OUTFILE=html/bundle.js

# Check Python version
pyver=$(python -V | awk '{print $2;}')
if [[ ! $pyver == 3.7.* ]]; then
	echo Python 3.7.x is required, got version $pyver
	exit 1
fi

# Transcrypt
transcrypt $@ --nomin pyRCV2.transcrypt || exit 1

# Patch next() to accept optional argument
perl -0777 -i -pe 's#function py_next \(iterator\) {#function py_next \(iterator, def = undefined\) { try { return py_next_orig \(iterator\); } catch \(exception\) { if \(def !== "undefined"\) { return def; } else { throw exception; } } } function py_next_orig \(iterator\) {#g' __target__/org.transcrypt.__runtime__.js || exit 1
# Patch sum() to accept optional argument
perl -0777 -i -pe 's#export function sum \(iterable\) {\n    let result = 0;#export function sum \(iterable, result = 0\) { for \(let item of iterable\) { result = __add__\(result, item\); } return result;#g' __target__/org.transcrypt.__runtime__.js || exit 1
# Patch sort() to use operator overloading
perl -0777 -i -pe 's#key \(a\) > key \(b\) \?#__gt__\(key \(a\), key \(b\)\) \?#g' __target__/org.transcrypt.__runtime__.js || exit 1

# Roll up
rollup __target__/pyRCV2.transcrypt.js -o $OUTFILE --name py -f iife --no-treeshake || exit 1

# Patch incorrectly generated iterator functions
#perl -0777 -i -pe "s#'__index0__'#__index0__#g" $OUTFILE || exit 1
