#!/bin/bash
# Clone un dépôt git au bon endroit
# Stocker un minimum de données (et donc nettoyer)
# Télécharger un minimum de données
# En cas de conflit donner raison au remote (on écrase les versions locales)

declare -A usage
declare -A varia

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

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

usage[t]="Tag of git repo"
varia[t]=tag
tag=

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 overwritten"
varia[N]=nonempty_target
nonempty_target=false

usage[K]="Remote host key file (known_hosts) for ssh connections"
varia[K]=hostkeyfile
hostkeyfile=''

usage[H]="Use real home dir"
varia[H]=use_home
use_home=false


. driglibash-args


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

if [ -n "$hostkeyfile" ] ; then
	ssh_opt="$ssh_opt -o 'UserKnownHostsFile $hostkeyfile'"
fi

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

if [ ! $use_home ] ; then
	set -a
	export HOME=/dev/null
	set +a
fi

run mkdir -p "$dst"
run cd "$dst"


if [ -d .git ] ; then

	# Compute git branch and tag
	tagref=
    if [ -n "$tag" ] ; then
        tagref="tags/$tag"
    fi

	run git fetch origin "$branch" --tags
	run git checkout --force $tagref -B "$branch"
    run git reset --hard # TODO we can keep some files?
	# 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