#!/bin/bash
# deploy-tuning.sh - copies apply-tunings.sh to target hosts and runs it.
# Usage: bash deploy-tuning.sh [--no-nfs] [--apply] <host> [host...]
# Default mode is dry-run. Pass --apply to commit. Pass --no-nfs to skip NFS section.
set -uo pipefail

SCRIPT="$(cd "$(dirname "${BASH_SOURCE[0]}")/scripts" && pwd)/apply-tunings.sh"
SSH_OPTS=(-o BatchMode=yes -o ConnectTimeout=8 -o ServerAliveInterval=10 -o StrictHostKeyChecking=accept-new)
MODE=""
EXTRA_FLAGS=""

HOSTS=()
for arg in "$@"; do
    case "$arg" in
        --apply) MODE="--apply" ;;
        --dry-run) MODE="" ;;
        --no-nfs) EXTRA_FLAGS="--no-nfs" ;;
        *) HOSTS+=("$arg") ;;
    esac
done

if [ "${#HOSTS[@]}" -eq 0 ]; then
    echo "Usage: $0 <host> [host...] [--apply]"
    echo "Default: dry-run. Pass --apply to commit."
    exit 1
fi

if [ ! -r "$SCRIPT" ]; then
    echo "FATAL: $SCRIPT not found"
    exit 1
fi

for host in "${HOSTS[@]}"; do
    echo "================================================================"
    echo "[$host] deploying apply-tunings.sh (mode: ${MODE:-dry-run})"
    echo "================================================================"

    if ! ssh "${SSH_OPTS[@]}" "root@$host" 'echo ok' >/dev/null 2>&1; then
        echo "[$host] SKIP: unreachable"
        continue
    fi

    echo "[$host] uploading..."
    if ! scp "${SSH_OPTS[@]}" "$SCRIPT" "root@$host:/root/apply-tunings.sh" >/dev/null 2>&1; then
        echo "[$host] SKIP: scp failed"
        continue
    fi

    echo "[$host] running (output below)..."
    echo "----------------------------------------------------------------"
    ssh "${SSH_OPTS[@]}" "root@$host" "chmod +x /root/apply-tunings.sh && bash /root/apply-tunings.sh $MODE $EXTRA_FLAGS" 2>&1
    rc=$?
    echo "----------------------------------------------------------------"
    echo "[$host] exit code: $rc"
    echo ""
done
