#!/bin/bash

set -Eeuo pipefail

usage="Usage: $0 log_path sky-list-selectors..."
log_path=${1?"$usage"}
log_name=$(basename "$log_path")
shift

for hst in $(sky list "$@"); do (
    remote_dir="$log_name"
    remote_log="$remote_dir/$log_name.gz"
    trap "ssh '$hst' \"killall gzip; rm '/var/tmp/$remote_log'\"" SIGINT SIGTERM SIGHUP
    echo "$hst"
    mkdir -p "$hst"
    cd "$hst"
    ssh "$hst" "mkdir -p '/var/tmp/$remote_dir' && cd '/var/tmp/$remote_dir' && nice -20 cat '$log_path' | nice -20 gzip > '/var/tmp/$remote_log' || rm '/var/tmp/$remote_log'"
    sky download "/var/tmp/$remote_log" ./ "h@$hst"
    mv "$hst/$log_name.gz" ./
    rmdir "$hst"
    ssh "$hst" "rm '/var/tmp/$remote_log'"
) 2>&1 | gawk -vhst="$hst" '{printf("(%s)\t%s\n", hst, $0)}' & done

wait
