#!/bin/bash
# A quick command to connect to any of the available servers.

# Read the servers from the file into an array:
mapfile -t SERVERS < servers.txt

# Display the numbered list of server options:
echo "Please select a server:"
for i in "${!SERVERS[@]}"; do
    echo "$((i + 1)). ${SERVERS[i]}"
done

# Prompt the user for their selection
read -rp "Select a server by the number ... : " SELECTION

# Validate the selection
if [[ $SELECTION -gt 0 && $SELECTION -le ${#SERVERS[@]} ]]; then

    # Note down the selection in a variable:
    SELECTED_SERVER=${SERVERS[$((SELECTION - 1))]}

    # Ask the username and target port no. on the server::
    read -rp "Your username on the server ..... : " USER
    read -rp "The target port no. ............. : " PORT

    # Run the command:
    ssh -p "$PORT" "$USER@$SELECTED_SERVER"

    # Exit with success (assuming that the actual data sending went well):
    echo "session ended"
    exit 0

else

    # In case of a wrong server selection, exit with failure.
    echo "Invalid selection. Please run the script again."
    exit 1

fi
