#!/bin/sh
# Undo debian/bootstrap-babel7.sh: TypeScript reads the sources as they are,
# and the declarations it emits must not be truncated by the rewrites that
# only the Babel 7 parser needed.
set -e

SOURCES="packages/*/src eslint/*/src codemods/*/src"

grep -rl '</\*const\*/ ' $SOURCES 2>/dev/null \
	| xargs -r sed -i 's|</\*const\*/ |<const |g'

grep -rl '^ *//BABEL7// export type \* from' $SOURCES 2>/dev/null \
	| xargs -r sed -i 's|^\( *\)//BABEL7// export type \* from|\1export type * from|'

sed -i 's/^  \.\.\.tryLocs: TryLocs, \/\/BABEL7\/$/  ...TryLocs,/' \
	packages/babel-helpers/src/helpers/regenerator.ts

[ -s debian/json-imports.list ] || exit 0
grep -rlE "from \"[^\"]*\"" $SOURCES 2>/dev/null | xargs -r perl -i -pe '
	BEGIN {
		open my $fh, "<", "debian/json-imports.list" or die $!;
		chomp(my @s = <$fh>);
		$re = join "|", map { quotemeta } grep { length } @s;
	}
	s{(\bfrom\s*(["\x27])(?:$re)\2)(?!\s*with)(\s*;)}
	 {$1 with { type: "json" }$3}g if $re;
'
