#!/bin/bash

set -e

helper_url=http://uploader.xmlex.ru/uploads/2025-01-29_09-49-22_vault-ssh-helper
helper_install_path=/usr/local/bin/vault-ssh-helper

echo "Downloading vault ssh helper..."
curl -L -z $helper_install_path -o $helper_install_path $helper_url
chmod +x $helper_install_path
vault-ssh-helper version

echo 'auth sufficient pam_exec.so quiet expose_authtok log=/tmp/vaultssh.log /usr/local/bin/vault-ssh-helper -config=/etc/vault-ssh-helper.d/config.hcl' > /etc/pam.d/vault-auth
echo 'auth optional pam_unix.so use_first_pass nodelay' >> /etc/pam.d/vault-auth

echo 'ChallengeResponseAuthentication yes' > /etc/ssh/sshd_config.d/50-vault.conf
echo 'UsePAM yes' >> /etc/ssh/sshd_config.d/50-vault.conf
echo '# vault need: keyboard-interact' >> /etc/ssh/sshd_config.d/50-vault.conf
echo '#AuthenticationMethods publickey,password publickey,keyboard-interact' >> /etc/ssh/sshd_config.d/50-vault.conf

mkdir -p /etc/vault-ssh-helper.d/

echo 'vault_addr = "https://vault.inner-services.fast-system.ru/"' > /etc/vault-ssh-helper.d/config.hcl
echo 'ssh_mount_point = "ssh/prod"' >> /etc/vault-ssh-helper.d/config.hcl
echo 'tls_skip_verify = true' >> /etc/vault-ssh-helper.d/config.hcl
echo 'allowed_roles = "*"' >> /etc/vault-ssh-helper.d/config.hcl

#echo "1. Comment '@include common-auth' in /etc/pam.d/sshd"
sed -i 's/^@include common-auth/# @include common-auth/' /etc/pam.d/sshd

echo "2. Add '@include vault-auth' in /etc/pam.d/common-account"
if ! grep -Fxq "@include vault-auth" "/etc/pam.d/common-account"; then
    sed -i "1i@include vault-auth" "/etc/pam.d/common-account"
    echo "Строка '@include vault-auth' добавлена в файл /etc/pam.d/common-account"
else
    echo "Строка '@include vault-auth' уже существует в файле /etc/pam.d/common-account."
fi


echo "3. Run 'systemctl restart ssh'"
systemctl restart ssh

echo "3. Check connect"

# install-vault-ssh-heler.sh