#!/usr/bin/env bash
set -x

main() {
  find plugins/ -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | while read plugin; do
    if [[ ! -f "plugins/$plugin/go.mod" ]]; then
      continue
    fi

    pushd "plugins/$plugin" >/dev/null || return 1
    echo "====> Cloning all modules $plugin"
    go list -m -f '{{define "M"}}git clone https://{{.Path}}.git /root/go/src/{{.Path}} || true && echo {{.Version}}{{end}}{{if not .Main}}{{if not .Replace}}{{template "M" .}}{{end}}{{end}}' all >tmp-file
    bash tmp-file
    rm tmp-file

    go list -m -f '{{define "M"}}git clone https://{{.Path}}.git /usr/local/go/src/{{.Path}} || true && echo {{.Version}}{{end}}{{if not .Main}}{{if not .Replace}}{{template "M" .}}{{end}}{{end}}' all >tmp-file
    bash tmp-file
    rm tmp-file
    popd >/dev/null || return 1
  done
}

main "$@"
