#!/bin/bash

# set -x

check_ssh() {
    SSH_USER="${1}"
    SSH_HOST="${2}"
    SSH_PORT="${3}"
    SSH_PASSWORD="${4}"

    SSH_RESULT=$(expect -c "
        spawn ssh -p ${SSH_PORT} ${SSH_USER}@${SSH_HOST}
        expect {
            -re \".*Are you sure you want to continue connecting.*\" {
                send \"yes\n\"
                exp_continue
            }
            -re \".*password.*\" {
                send \"${SSH_PASSWORD}\n\"
                exp_continue
            }
            -re \".*@.*\" {
                send \"exit\n\"
                expect eof
            }
        }
    ")
    
    ANSWER_SUCCESS="Connection to ${SSH_HOST} closed."
    ANSWER_ERRORS=(
        "Permission denied"
        "connect to host ${SSH_HOST} port ${SSH_PORT}: No route to host"
        "connect to host ${SSH_HOST} port ${SSH_PORT}: Connection refused"
    )

    [[ $(echo "${SSH_RESULT}" | grep "${ANSWER_SUCCESS}" ) ]] && echo "Успешно подключились" && exit 0

    for ANSWER in "${ANSWER_ERRORS[@]}"
    do
        [[ $(echo "${SSH_RESULT}" | grep "${ANSWER}" ) ]] && echo "${ANSWER}" && exit 1
    done

    echo "${SSH_RESULT}"

    echo "Произошла неизвестная ошибка"
    exit 1
}

main() {
    while [[ $# -gt 0 ]]
    do
        KEY="${1}"
        VALUE="${2}"
        case "${KEY}" in
            -u)
                SSH_USER="${VALUE}"
                shift
                ;;
            -p)
                SSH_PORT="${VALUE}"
                shift
                ;;
            -h)
                SSH_HOST="${VALUE}"
                shift
                ;;
            -P)
                SSH_PASSWORD="${VALUE}"
                shift
                ;;
        esac
        shift
    done

    [ -z "${SSH_USER}" ] && echo "Не был установлен пользователь" && exit 1
    [ -z "${SSH_PORT}" ] && echo "Не был установлен порт" && exit 1
    [ -z "${SSH_HOST}" ] && echo "Не был установлен хост" && exit 1
    [ -z "${SSH_PASSWORD}" ] && echo "Не был установлен пароль" && exit 1

    check_ssh "${SSH_USER}" "${SSH_HOST}" "${SSH_PORT}" "${SSH_PASSWORD}"

    exit 0
}

main "${@}"
