#!/bin/bash

. __FFOOD_INIT__
FFOOD_INIPATH="__FFOOD_INIPATH__"

ffood import core
ffood import recon

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

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

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

test -n "$hosts" || die "no valid hosts to begin with"
paths=$(iniread -s push.paths push.ini)
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
    iniread -s push.commands push.ini \
      | grep . \
      | while read cmd;
        do
            think "ssh $host -- $cmd"
            ssh -n $host -- "$cmd" > /dev/null
        done
done