#!/bin/bash

OPT_URL_=""         # gitweb project list to mirror
OPT_CLONE_URL_=""   # base clone url to which the repo name is appended

PROGNAME_="$(basename $0)"

usage()
{
    cat <<EOT
Usage: "$PROGNAME_" [OPTIONS] <gitweb url>

$PROGNAME_ tries to mirror all repositories from a gitweb instance

OPTIONS:
   -b         Base url for clone (default = ssh://git@<REPOSITORY>)

EOT
}

die()
{
    local msg_="$@"
    echo "Error: $msg_" >&2
    usage
    exit 1
}


###
## MAIN
###

while getopts "b:" opt; do
    case "$opt" in
        b) OPT_CLONE_URL_="$OPTARG" ;;
        h) usage; exit 0 ;;
        ?) die "unknown option \"$OPTARG\"" ;;
    esac
done
shift $(($OPTIND - 1))

OPT_URL_="$1"

[ -z "$OPT_URL_" ]          && die "need a url pointing to a gitweb installation"
[ -z "$OPT_CLONE_URL_" ]    && OPT_CLONE_URL_="ssh://git@${OPT_URL_#*//}"

curl -s "$OPT_URL_/?a=project_index" |while read i_; do
    repo_="${i_%% *}"
    repo_="${repo_%.git}"   # FIXME
    if [ -d "$repo_" ]; then
        # update
        echo "updating: $repo_"
        ( cd "$repo_" && git fetch )
    else
        # clone
        git clone "$OPT_CLONE_URL_/${repo_}.git"
    fi
done

