#!/usr/bin/env bash

print_help() {
    cat <<- EOF
Clone and pull remote git repositories.

Usage: $0 [-fchv] <arguments>

Options:
    -f, --fetch-from <file> clone repositories listed in file.
    -c, --chdir <dir>       change working directory [default: current]
    -h, --help      print this help message and exit.
    -v, --version   print version and exit.

Example of repository list file:

https://github.com/user/repo.git    # my nice repo
https://github.com/anothr_user/repo.git

Comments is allowed. Use hash (#) sign for comments.
EOF
    exit 0
}

[[ "$@" ]] || print_help

# Transform long options to short ones
for arg in "$@"; do
  shift
  case "$arg" in
    --fetch-from) set -- "$@" "-f";;
    --chdir) set -- "$@" "-c";;
    --help) set -- "$@" "-h";;
    --version) set -- "$@" "-v";;
    *) set -- "$@" "$arg";;
  esac
done

while getopts ":f:c:hv" opt; do
    case "$opt" in
        f) fetch_from="$OPTARG";;
        c) chdir="$OPTARG";;
        h) print_help;;
        v) echo 0.1; exit 0;;
        *) echo "Unknown option $opt" >&2; exit 1;;
    esac
done

if [ "$fetch_from" ]; then
    if test -f "$fetch_from"; then
        fetch_from="$(realpath "$fetch_from")"
    else
        echo "No such file $fetch_from" >&2; exit 1
    fi
else
    echo "Missing argument for --fetch-from" >&2; exit 1
fi

if [ "$chdir" ]; then
    chdir="$(realpath "$chdir")"
else
    chdir="$PWD"
fi

if [ -d "$chdir" ]; then
    :
else
    echo "No such directory $chdir" >&2; exit 1
fi

echo -e "Fetching git repos from $fetch_from to $chdir ..."
echo -n 'Date: '; date -R
git --version

sed 's/#.*//g;/^$/d' "$fetch_from" | while read repo; do
    echo -e "\nFETCHING $repo ..."
    echo '# ---------------------------------------------------------'
    repo_dir="${repo##*/}"
    repo_dir="${repo_dir//\.git}"
    repo_dir="$(realpath "${chdir}/${repo_dir}")"
    if git -C "$chdir" clone "$repo"; then
        :
    else
        echo "ENTERING INTO $repo_dir ..."
        cd "$repo_dir" && git pull && cd - >/dev/null ||
            { echo "Cannot change dir to $OLDPWD" >&2; exit 1; }
    fi
done
