#!/usr/bin/env bash
set -euo pipefail

#
# This script helps you move external dependencies from their old way of being
# tracked in Driving to their new way. Each invocation of this tool will migrate
# the specified package, complete with a git-commit at the end.
#

builtin cd "$(dirname "${BASH_SOURCE[0]}")"
builtin cd "$(git rev-parse --show-toplevel)"

package="$(basename "$1")"
build="build/$package"
external="third_party/external/$package"

[ -e "$build" ]
[ ! -e "$external" ]

git rm --force "$build/BUILD"
touch "$build/BUILD.bazel"
git mv "$build" "$external"
git add "$external/BUILD.bazel"
git mv "$external/repositories.bzl" "$external/workspace.bzl"
git mv "$external/$package.bazel" "$external/workspace.bazel"

sed \
  --in-place \
  --expression "s#${package}_repositories#workspace#g" \
  --expression "s#$build#$external#g" \
  --expression "s#$package.bazel#workspace.bazel#" \
  "$external/workspace.bzl"
git add "$external/workspace.bzl"

IFS=$'\n'
loads=(
"$(awk -v 'RS=\n\n' '1;{exit}' third_party/workspaces.bzl)"
"load(\"//$external:workspace.bzl\", ${package}_workspace = \"workspace\")"
)
loads=($(sort <<<"${loads[*]}"))
workspaces=(
"$(grep '^    ' third_party/workspaces.bzl)"
"    ${package}_workspace()"
)
workspaces=($(sort <<<"${workspaces[*]}"))
rm third_party/workspaces.bzl
for line in ${loads[@]}; do
  echo $line >> third_party/workspaces.bzl
done
echo >> third_party/workspaces.bzl
echo "def external_workspaces():" >> third_party/workspaces.bzl
for line in ${workspaces[@]}; do
  echo $line >> third_party/workspaces.bzl
done
git add third_party/workspaces.bzl

grep \
  --invert-match \
  --regexp="load(\"//$build:repositories.bzl\", \"${package}_repositories\")" \
  --regexp="${package}_repositories()" \
  WORKSPACE \
  | sed --expression '/^$/N;/^\n$/D' \
  > WORKSPACE.tmp
mv WORKSPACE.tmp WORKSPACE
git add WORKSPACE

git commit -m "Migrate $package"
