#!/bin/bash

# Make API request and extract the IP addresses from the "hoprd_api_endpoint" field
ips=( $(curl --silent --request GET --url https://staging.discovery.rpch.tech/api/v1/node?status=READY | jq -r '.[].hoprd_api_endpoint | sub("http://"; "") | sub(":[0-9]*$"; "")') )

# Path to SSH private key for authentication
private_key_path=".ssh/id_rsa"

# Loop through the remote hosts and run the script on each one
for ip in "${ips[@]}"
do
    # Get the machine name from the SSH connection
    machine_name=$(ssh -i $private_key_path -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null root@$ip "hostname")

    # Compress the log files on the remote host
    ssh -i $private_key_path -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null root@$ip "cd \$(dirname \$(docker inspect --format='{{.LogPath}}' \$(docker ps -q -f name=hoprd))) && logs=\$(ls -t *[0-9a-f][0-9a-f][0-9a-f][0-9a-f]*-json.log* | head -n 2) && zip hoprd_logs_${machine_name}.zip \$logs"

    # Get the ZIP file name and location on the remote host
    zip_file=$(ssh -i $private_key_path -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null root@$ip "cd \$(dirname \$(docker inspect --format='{{.LogPath}}' \$(docker ps -q -f name=hoprd))) && ls -t hoprd_logs_${machine_name}.zip | head -n 1")
    zip_location=$(ssh -i $private_key_path -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null root@$ip "cd \$(dirname \$(docker inspect --format='{{.LogPath}}' \$(docker ps -q -f name=hoprd))) && pwd")

    # Copy the resulting ZIP archive to the local machine's Downloads folder
    scp -i $private_key_path -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null root@$ip:$zip_location/$zip_file ~/Downloads/${machine_name}_hoprd_logs.zip

    # Restart hoprd on the remote host
    ssh -i $private_key_path -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null root@$ip "cd /home/rpch/RPCh/apps/exit-node/ && docker compose down && docker compose up -d"

    # Delete the ZIP archive from the remote host
    ssh -i $private_key_path -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null root@$ip "rm -f ~/hoprd_logs_*.zip"
done