#!/bin/bash

# Adds 'import scala.collection.Seq' so Seq means the same as it used to in
# Scala 2.12, also after upgrading to 2.13.
#
# This is not the recommended approach, but I don't want to "stop the world" now
# and fix collections.Set vs immutable.Set usage in what turns out to be 154 files!


in_dir="$1"

echo "Replacing in: $in_dir"

added_to=''
already_in=''
not_using=''

for file in $(find "$in_dir" -type f -name "*.scala"); do
    # `Seq` in use?
    if grep -qw 'Seq' "$file"; then
        # Already imported?
        alr_imp=$(egrep '^import .*(immutable|collection|mutable)\.Seq' $file)
        if [ -z "$alr_imp" ]; then

            # Insert 'import scala.collection.Seq' before the other imports.
            # Don't:
            #sed -ri '0,/^import /s/^(import .*)/import scala.collection.Seq\n\1/' "$file"
            # because \n and \1  doesn't always work with the  -ri flags,
            # there's this error:  "char 59: invalid reference \1 "
            # But with only -i, works:
            # (This line generated by ChatGPT, it works.)
            sed -i '0,/^import /s/^\(import .*\)/import scala.collection.Seq\n\1/' "$file"

            added_to=$(printf '%s\n%s' "$added_to" "$file")
            
        else
            already_in=$(printf '%s\n%s' "$already_in" "$file")
        fi
    else
        not_using=$(printf '%s\n%s' "$not_using" "$file")
    fi
done

echo "Not using Seq:"
echo "$not_using"
echo
echo "'import ...Seq' already in:"
echo "$already_in"
echo
echo "Added 'import ...Seq' to:"
echo "$added_to"
echo

