#!/bin/bash
KEYNAME="azslocal"
KEYDIR="${HOME}/.ssh"
KEY="${KEYDIR}/${KEYNAME}"
if [ -z "${1}" ]; then
    INVAL="all"
else
    INVAL=${1}
fi

if [ ! -f ${KEY} ]; then
    mkdir -p ${KEYDIR}
    chmod 700 ${KEYDIR}
    ssh-keygen -t rsa -N '' -f ${KEY}
fi
KEYTXT=$(cat ${KEY}.pub)
if [ -z "${KEYTXT}" ]; then
    exit "Не найден файл ${KEY}.pub"
    exit
fi
if [ "${INVAL}" == "all" ]; then
    WPLIST=$(getwphost --ips)
    if [ -z "$(getwphost | grep localhost)" ]; then
        WPLIST="${WPLIST} localhost"
    fi
else
    WPLIST=${INVAL}
fi

KEYDIR="/home/bukts/.ssh"
for WP in ${WPLIST}; do
    if [ "${WP}" == "localhost" -o "${WP}" == "127.0.0.1" ]; then
        echo "НАСТРОЙКА ${WP}"
        echo ${KEYTXT} > ${KEYDIR}/${KEYNAME}.pub
        cat ${KEYDIR}/${KEYNAME}.pub >> ${KEYDIR}/authorized_keys
        cat ${KEYDIR}/authorized_keys | sort | uniq > ${KEYDIR}/authorized_keys.tmp
        mv ${KEYDIR}/authorized_keys.tmp ${KEYDIR}/authorized_keys
        echo 'mkdir -p /root/.ssh;chmod 700 /root/.ssh;
            cat /home/bukts/.ssh/azslocal.pub >> /root/.ssh/authorized_keys;
            cat /root/.ssh/authorized_keys | sort | uniq > /root/.ssh/authorized_keys.tmp;
            mv /root/.ssh/authorized_keys.tmp /root/.ssh/authorized_keys' > /home/bukts/set-root-ssh-key
        chmod 755 /home/bukts/set-root-ssh-key
        echo 'sudo /home/bukts/set-root-ssh-key' > /home/bukts/bin/setrootsshkey
        chmod 755 /home/bukts/bin/setrootsshkey
    else
        echo "ПОДКЛЮЧЕНИЕ К РАБОЧЕМУ МЕСТУ ${WP}"
        sshwp ${WP} \
          "mkdir -p ${KEYDIR}; chmod 700 ${KEYDIR};
           echo ${KEYTXT} > ${KEYDIR}/${KEYNAME}.pub;
           cat ${KEYDIR}/${KEYNAME}.pub >> ${KEYDIR}/authorized_keys;
           cat ${KEYDIR}/authorized_keys | sort | uniq > ${KEYDIR}/authorized_keys.tmp;
           mv ${KEYDIR}/authorized_keys.tmp ${KEYDIR}/authorized_keys;
           echo 'mkdir -p /root/.ssh;chmod 700 /root/.ssh;
             cat ${KEYDIR}/${KEYNAME}.pub >> /root/.ssh/authorized_keys;
             cat /root/.ssh/authorized_keys | sort | uniq > /root/.ssh/authorized_keys.tmp;
             mv /root/.ssh/authorized_keys.tmp /root/.ssh/authorized_keys' > /home/bukts/set-root-ssh-key;
           chmod 755 /home/bukts/set-root-ssh-key;
           echo 'sudo /home/bukts/set-root-ssh-key' > /home/bukts/bin/setrootsshkey;
           chmod 755 /home/bukts/bin/setrootsshkey"
        echo "ПОВТОРНОЕ ПОДКЛЮЧЕНИЕ К РАБОЧЕМУ МЕСТУ ${WP} ДЛЯ РУЧНЫХ ДЕЙСТВИЙ"
        sshwp ${WP}
    fi
done
