#!/bin/bash

set -o pipefail
set -o errexit

function error() {
    echo "$@" >&2
    exit 1
}

# Each arg in the query string e.g /ttyd?arg=192.168.125.101
# positionally map to the script invocation arg positions.
# There should be at least one arg which is the destination IP
# of the device to ssh into.
destination="$1"

# Validate inputs
if [[ -z "$destination" ]]; then
    error "Invalid usage"
fi

echo "Connecting to ${destination}"
# Prompt user for username
read -rp "Username: " username
if [[ -z "$username" ]]; then
    error "No username provided"
fi

# SSH and filter out specific warning messages
IGNORE_MSG='^Warning\: Permanently added .*? to the list of known hosts\.'
ssh \
    -o "StrictHostKeyChecking=no" \
    -o UserKnownHostsFile=/dev/null \
    -- \
    "$username"@"$destination" 2> >(stdbuf -i0 -o0 -e0 -- grep -Ev "$IGNORE_MSG" >&2)
