#!/bin/bash

help () {
    echo "Recursively updates (fetches, fcsk's and gc's) git repos"
    echo "Usage: ${0##*/} [-[ntI]] [<start dir>] [<maxdepth>]"
    echo "Default start dir is ."
    echo "Default maxdepth is 3"
    echo " -n noparallel -- do not use gnu parallel"
    echo " -t tmux -- use tmux (needs parallel)"
    echo " -I noninteractive -- close stdin"
    exit
}

noparallel=false


tmp=`getopt hntI $*`
eval set -- "$tmp"

noparallel=
tmux=
noninteractive=
while true; do
    case $1 in
        -h) help; shift ;;
        -n) noparallel=1; shift ;;
        -t) tmux=1; shift ;;
        -I) noninteractive=1; shift ;;
        --) shift; break ;;
        *) echo "???"; exit 2 ;;
    esac
done

if [[ $tmux && $noparallel ]]; then
    echo "tmux needs parallel"
    exit 2
fi

if [[ ! $noparallel ]] && ! command -v parallel &>/dev/null; then
    echo "parallel not found"
    exit 1
fi

helper=$(mktemp)
trap "rm -f $helper" EXIT
cat >"$helper" <<'__EOF__'
if [[ -d $1 && ! -L $1/refs ]]
then
    printf "*** %s\n" "$1"
    pushd "$1/.." >/dev/null
    git fetch --all --prune
    [[ -d $1/svn ]] && {
        git svn fetch && \
        git svn rebase --local || :
    }
    git fsck
    git gc
    [[ -d $1/svn ]] && git svn gc
    popd >/dev/null
fi
__EOF__


if [[ $OSTYPE = darwin* || $OSTYPE = *bsd* ]]; then
    dofind () {
        find -x "${1:-.}" -maxdepth "${2:-3}" -name .backup -prune -o -name .bak -prune -o \( -type d -name .git -o -name \*.git \) -print
    }
elif grep -sq Ubuntu /etc/os-release; then
    dofind () {
        find "${1:-.}" -xdev -maxdepth "${2:-3}" -name .backup -prune -o -name .bak -prune -o \( -type d -name .git -o -name \*.git \) -print
    }
else
    dofind () {
        find "${1:-.}" -xdev -xautofs -maxdepth "${2:-3}" -name .backup -prune -o -name .bak -prune -o \( -type d -name .git -o -name \*.git \) -print
    }
fi

if [[ $noparallel ]]; then
    while IFS= read -r dir; do
        nice bash $helper "$dir" ${noninteractive:+</dev/null}
    done < <(dofind "$@")
else
    if command -v ionice &>/dev/null; then
        dofind "$@" | ionice -c idle nice parallel ${tmux:+--fg --tmux} --jobs 75% --eta --timeout 180 bash $helper ${noninteractive:+</dev/null}
    else
        dofind "$@" | nice parallel ${tmux:+--fg --tmux} --jobs 75% --eta --timeout 180 bash $helper ${noninteractive:+</dev/null}
    fi
fi

