#!/bin/bash

. <(ffoom init)

ffoo import core
ffoo import recon

ORDER="$(eeini -p push.options.order)"

while true; do case $1 in
    -d|--debug)     FFOO_DEBUG=true;    shift;      ;;
    -v|--verbose)   FFOO_VERBOSE=true;  shift;      ;;
    -q|--quiet)     FFOO_VERBOSE=false; shift;      ;;
    -o|--order)     ORDER=$2;           shift 2;    ;;
    -h|--help)      usage;                          ;;
    "")             break                           ;;
    *)              hosts="$1"; shift;              ;;
esac done

test -n "$hosts" || hosts=$(eeini -s push.hosts | debug_pipe ini_hosts)
debug -v hosts

test -n "$hosts" || die "no valid hosts to begin with"
paths=$(eeini -s push.paths)
test -n "$paths" || die "no valid paths to begin with"

think "Probing & sorting paths"
paths=$(echo "$paths" \
        | expand_tilde \
        | filter test -e \
        | sort_paths_by_age \
        | debug_pipe ok_paths
       )
test -n "$paths" || die "no valid paths"

think "Probing hosts"
hosts=$(echo "$hosts" | filter_hosts -s | debug_pipe ok_hosts )
test -n "$hosts" || die "no valid hosts"

test "$(wc -l <<<"$paths")" == 1 && ORDER="path:host"
test "$(wc -l <<<"$hosts")" == 1 && ORDER="host:path"

think "Pushing (${ORDER/:/, then })..."

debug -v "paths:hosts"

case "$ORDER" in

    "path:host")
        for path in $paths;
        do
            for host in $hosts;
            do
                if rsync -L -r --delete $path $host:
                then
                    think $(collapse_tilde <<<"$path") sent to $host
                fi
            done
        done
    ;;

    "host:path")
        for host in $hosts;
        do
            for path in $paths;
            do
                if rsync -L -r --delete $path $host:
                then
                    think $host got $path
                fi
            done
        done
        ;;

    *)
        die "unknown push order: '$ORDER'"
        ;;
esac

for host in $hosts;
do
    eeini -s push.commands \
      | grep . \
      | while read cmd;
        do
            think "ssh $host -- $cmd"
            ssh -n $host -- "$cmd" > /dev/null
        done
done