#!/bin/bash


declare -A usage
declare -A varia

summary="$0 [options] <repo>"

usage[b]="Branch of git repo"
varia[b]=branch
branch=master

usage[d]="Destination of clone"
varia[d]=dst
dst='.'

usage[i]="privkey used to ssh pull"
varia[i]=privkey
privkey=''

usage[N]="Clone to a Non-empty target. Existing files will be overwriten"
varia[N]=nonempty_target
nonempty_target=false


. driglibash-args


# Some SSH options
ssh_opt='ssh'
if [ -n "$privkey" ] ; then
	ssh_opt="$ssh_opt -i $privkey"
fi

repo="$1"
if [ -z "$repo" ] ; then
	die "$0: Empty repo given\n$summary"
fi

cd "$dst"

if [ -d .git ] ; then
	run git fetch origin "$branch"
	run git checkout --force -B "$branch" "origin/$branch"
    run git reset --hard
	# Preserve existing files in some cases
	if ! "$nonempty_target" ; then
		git clean -qffdx
	fi
	run git submodule update --init --recursive --force --recommend-shallow
	run git submodule foreach git fetch
	run git submodule foreach git checkout --force HEAD
	run git submodule foreach git reset --hard
	run git submodule foreach git clean -fdx
else
	clone_dst='.'

	# To override an existing dir, we need to clone elsewhere first
	if "$nonempty_target" ; then
		clone_dst="$(mktemp -d)"
	fi

    run git clone -b "$branch" --single-branch --recurse-submodules --shallow-submodules --depth 1 --config core.sshCommand="$ssh_opt" "$repo" "$clone_dst"

	# To override an existing dir, we then move everything to that dir
	if "$nonempty_target" ; then
		run mv "$clone_dst/"{*,.*} .
		run rmdir "$clone_dst"
	fi
fi