#!/usr/bin/env zsh

set -e

SCRIPT_ROOT="${${(%):-%x}:a:h}"

tmpdir="$(mktemp -d "$SCRIPT_ROOT/tmp.XXXXXX")"

virtualenv -p python3 "$tmpdir/.venv.stubgen"

python_bin_dir="$tmpdir/.venv.stubgen/bin"
python_bin="$python_bin_dir/python"

"$python_bin" -m pip install mypy setuptools

git clone git@github.com:InteractiveBrokers/tws-api.git "$tmpdir/tws-api"
all_stub_versions="$(git branch | rg '\s+([0-9]+\.[0-9]+\.[0-9]+)$' -r '$1' | sort)"
all_tws_api_versions="$(cd "$tmpdir/tws-api" && git tag | rg '^[0-9]+\.[0-9]+\.[0-9]+$' | sort)"

# find only the versions that are not in the stub_versions
versions_to_process="$(comm -23 <(echo "$all_tws_api_versions") <(echo "$all_stub_versions"))"

echo "$versions_to_process" | while read -r version; do
    (
        echo "================================================"
        echo "Processing version: $version..."

        git checkout --force master
        git checkout -b "$version"
        cd "$tmpdir/tws-api"
        git reset --hard HEAD
        git checkout --force "$version"

        cd "source/pythonclient/"
        "$python_bin" setup.py install

        ibapi_root="$("$python_bin" -c "import ibapi; import os; print(os.path.dirname(ibapi.__file__))")"
        echo "ibapi_root: $ibapi_root"
        stubgen_args=("-m" "ibapi")
        find "$ibapi_root" -maxdepth 1 -name "*.py" -not -name "_*.py" -printf "%p\n" | \
            while read -r file_path; do
                file_name="$(basename "$file_path")"
                stubgen_args+=("-m" "ibapi.${file_name%.py}")

                # patch to remove # type: ...  coz they are invalid
                # sed -i '' 's/^# type: .*//' "$file_path"
                cat "$file_path" | rg --passthru '(.*)# type:.*' -r '$1' | sponge "$file_path"
            done

        "$python_bin_dir/stubgen" --ignore-errors -o "$SCRIPT_ROOT/../src" "${stubgen_args[@]}"
        mv "$SCRIPT_ROOT/../src/ibapi" "$SCRIPT_ROOT/../src/ibapi-stubs"
        touch "$SCRIPT_ROOT/../src/ibapi-stubs/py.typed"

        cd "$SCRIPT_ROOT/.."
        git add .
        git commit -m "Add stubs for $version"

        # change the branch into tag
        git checkout master
        git tag "$version" "$version"
        git branch -D "$version"

        # build the package
        git checkout "$version"
        make build

        echo
    )
done

rm -rf "$tmpdir"
