#! /bin/sh

VCS_GIT="git"
VCS_HG="hg"
VCS_SVN=""

VCS_TAR="tar"

vcs_type()
{
  if test "${VCS_GIT}" != "" -a -d "$1/.git"; then
    echo "git"
  else
    if test "${VCS_HG}" != "" -a -d "$1/.hg"; then
      echo "hg"
    else
      if test "${VCS_SVN}" != "" -a -d "$1/.svn"; then
        echo "svn"
      else
        echo "unknown"
      fi
    fi
  fi
}

vcs_clone()
{
  if test "${VCS_GIT}" = "" || ! "${VCS_GIT}" clone "$1" "$2"; then
    if test "${VCS_HG}" = "" || ! "${VCS_HG}" clone "$1" "$2"; then
      if test "${VCS_SVN}" = "" || ! "${VCS_SVN}" checkout "$1" "$2"; then
        echo "gambvcs could not clone $1"
        exit 1
      fi
    fi
  fi
}

vcs_update()
{
  case $(vcs_type "$1") in

    git)
      (cd "$1"; "${VCS_GIT}" pull) || exit 1
      ;;

    hg)
      "${VCS_HG}" pull -R "$1" -u || exit 1
      ;;

    svn)
      (cd "$1"; "${VCS_SVN}" update) || exit 1
      ;;

    *)
      exit 1
      ;;

  esac
}

vcs_copy()
{
  case $(vcs_type "$1") in

    git)
      if test "$2" = ""; then
        (cd "$1"; "${VCS_GIT}" archive HEAD) | "${VCS_TAR}" xf - -C "$3" || exit 1
      else
        (cd "$1"; "${VCS_GIT}" archive "tags/$2") | "${VCS_TAR}" xf - -C "$3" || exit 1
      fi
      ;;

    hg)
      if test "$2" = ""; then
        "${VCS_HG}" archive -R "$1" "$3" || exit 1
      else
        "${VCS_HG}" archive -R "$1" -r "$2" "$3" || exit 1
      fi
      ;;

    svn)
      if test "$2" = ""; then
        cp -R "$1/trunk/" "$3" || exit 1
      else
        cp -R "$1/tags/$2/" "$3" || exit 1
      fi
      ;;

    *)
      exit 1
      ;;

  esac
}

case "$1" in

  type)
    vcs_type "${VCS_TYPE_DIR_PARAM}"
    ;;

  clone)
    vcs_clone "${VCS_CLONE_REPO_PARAM}" "${VCS_CLONE_DIR_PARAM}"
    ;;

  update)
    vcs_update "${VCS_UPDATE_REPO_PARAM}"
    ;;

  copy)
    vcs_copy "${VCS_COPY_REPO_PARAM}" "${VCS_COPY_TAG_PARAM}" "${VCS_COPY_DIR_PARAM}"
    ;;

  *)
    echo "gambvcs unknown operation \"$1\""
    exit 1
    ;;

esac
