#!/bin/bash

if [ $# -eq 0 ]; then

  srcDir=$(
    readlink -e "${HOME}/packageSources"
  )

  [ -d "${srcDir}" ] || exit 0

  lockFile="${srcDir}/.lock"
  if [ -s "${lockFile}" ] && kill -0 "$(cat "${lockFile}")"; then
    exit
  fi
  echo $$ >"${lockFile}"

  find "${srcDir}" \
    -type d \
    -exec sh -c 'test -f "{}/HEAD"' \; \
    -printf 'git: %p\n' \
    -prune , \
    -type d \
    -exec sh -c 'test -d "{}/.svn"' \; \
    -printf 'svn: %p\n' \
    -prune \
  | parallel -j 0 -l 1 "$0"

  rm -f "${lockFile}"

elif [ $# -eq 1 ]; then

  case "${1%%: *}" in
    'git')
      git -C "${1#*: }" fetch --all -p \
      || rm -rf --one-file-system "${1#*: }"
    ;;
    'svn')
      cd "${1#*: }"
      svn update \
      || rm -rf --one-file-system "${1#*: }"
    ;;
    *)
      >&2 printf '%s: unknown VCS "%s"\n' "$0" "${1%%: *}"
      exit 1
    ;;
  esac

else

  >&2 printf '%s: too many arguments\n' "$0"
  exit 1

fi