#!/usr/bin/env bash
# annex dup -- Move files like `annex move --to`, but to multiple remotes.
# vim: ts=4 sw=4 et

. lib.bash || exit

is_annex_remote() {
    [[ $1 == web ]] || git config --get "remote.$1.annex-uuid" >&/dev/null
}

cmd=${0##*/}
cmd=${cmd#annex-}

files=()
remotes=()
copyargs=()
dropargs=()
argstate=0
for arg in "$@"; do
    if [[ $arg == -J* ]]; then
        copyargs+=("$arg")
    elif (( argstate == 0 )) && [[ $arg == -- ]]; then
        argstate=1
    elif (( argstate == 0 )) && [[ $arg == --* || $arg == *[/.]* ]]; then
        argstate=1
        files+=("$arg")
    elif (( argstate == 0 )); then
        if ! is_annex_remote "$arg"; then
            die "'$arg' is not a git-annex remote"
        fi
        remotes+=("$arg")
    elif (( argstate == 1 )); then
        files+=("$arg")
    fi
done
if (( ! ${#remotes[@]} )); then
    die "no remotes specified"
fi
settitle "annex: counting files"
if [[ $cmd == store && num=`annex find "${files[@]}" | wc -l` -gt 100 ]]; then
    confirm "this will move and drop $num files; continue?" || exit
fi
if [[ $cmd == store ]] && (( ${#remotes[@]} == 1 )); then
    dest=${remotes[0]}
    log2 "moving to '$dest'"
    annex move --to "$dest" "${copyargs[@]}" "${files[@]}"
    remotes=()
fi
for dest in "${remotes[@]}"; do
    log2 "copying to '$dest'"
    annex copy --to "$dest" --not --in "$dest" "${copyargs[@]}" "${files[@]}"
    dropargs+=(--in "$dest")
done
if [[ $cmd == store ]] && (( ${#dropargs[@]} )); then
    log2 "dropping from here"
    annex drop "${dropargs[@]}" "${files[@]}"
fi
