#!/bin/bash

set -eo pipefail

if [ $# -lt 3 ]; then
    echo "Usage: $0 <hostclass> <service> <dir>"
    echo "<hostclass>: Tag of instance type to connect to (eg 'trace-statsdsink')";
    echo "<service>:   Service name whose logs to fetch (eg 'trace_statsdsink')";
    echo "<dir>:       directory to output into"
    exit 1;
fi

ips=$(aws ec2 describe-instances \
          --output text\
          --query "Reservations[*].Instances[*].PrivateIpAddress"\
          --filter "Name=tag-value,Values=$1")

n=$(echo $ips | wc -w)

echo "Found $n hosts. Fetching..."

ssh_options="-q -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o PreferredAuthentications=publickey"

for host in $ips; do
    echo "fetching $host:/var/log/jtv/$2.log to $3/$host.$2.log"
    scp $ssh_options -- "$host:/var/log/jtv/$2.log" "$3/$host.$2.log"
done

