#!/usr/bin/env bash

set -eu

containsElement() {
  element=$1
  shift
  for e in "$@"
  do
    [ "${e}" = "${element}" ] && return 0
  done
  return 1
}

update=false
if [ "${1:-}" = "--update" ]; then
  update=true
elif [ -n "${1:-}" ]; then
  echo "error: invalid argument $1" >&2
  exit 1
fi

# prefixes=("" nvim)
prefixes=""
prefixes="${prefixes} nvim"
for prefix in ${prefixes}; do
  file=~/.vim/${prefix}plugins
  target=~/.vimplugins/${prefix}bundle/start
  mkdir -p "${target}"

  if [ ! -e "${file}" ]; then
    echo "${file} doesn't exist"
    exit 1
  fi

names=()
commands=()
while read -r repo; do
  if [ -z "${repo}" ]; then
    continue
  fi

  name="${repo#*/}"
  names+=("$name")
  path="${target}/${name}"
  if [ -d "${path}" ];then
    if [ "${update}" = true ]; then
      commands+=("echo '${path}'; git -C '${path}' pull || true")
    fi
  else
    commands+=("git clone --recursive https://github.com/${repo}.git '${path}'")
  fi
done < "${file}"

if [ -n "${commands:-}" ]; then
  if command -v parallel >/dev/null 2>&1 && parallel --version >/dev/null 2>&1;then
    parallel -j0 ::: "${commands[@]}"
  elif command -v parallel >/dev/null 2>&1; then
    echo "note: install gnu-parallel instead of moreutils for better output grouping"
    parallel -- "${commands[@]}"
  else
    echo "note: install gnu-parallel to run commands in parallel"
    for cmd in "${commands[@]}"
    do
      eval "${cmd} &"
    done

    wait
  fi
fi

for dir in "${target}"/*; do
  name=$(basename "${dir}")
  if ! containsElement "${name}" "${names[@]}"; then
    echo "Removing ${dir}"
    rm -rf "${dir}"
  fi
done
done
