#!/usr/bin/env bash

# klevstul :: 24.04

this_file_name=`basename "$0"`
echo "$this_file_name"

# location of ssh keys
syncdir_env_var=SYNCDIR_${HOSTNAME}
src_ssh_dir=${!syncdir_env_var}/secrets/.ssh
trg_ssh_dir=~/.ssh

echo "\$SYNCDIR_${HOSTNAME}=${!syncdir_env_var}"
echo "src_ssh_dir: ${src_ssh_dir}"

if ! [[ -d ${src_ssh_dir} ]]; then
    echo "error: non-existing directory '${src_ssh_dir}'" >&2; exit 1
fi

if ! [[ -d "$trg_ssh_dir" ]]; then
    echo "creating non-existing target dir '${trg_ssh_dir}'."
    mkdir -p ${trg_ssh_dir}
fi

if ! [[ -f ${trg_ssh_dir}/id_rsa.pub ]]; then
    echo "deploy id_rsa.pub"
    cp ${src_ssh_dir}/id_rsa.pub ${trg_ssh_dir}
else
    echo "id_rsa.pub already exist in ${trg_ssh_dir}"
fi

if ! [[ -f ${trg_ssh_dir}/id_rsa.gpg ]]; then
    echo "deploy id_rsa.gpg"
    cp ${src_ssh_dir}/id_rsa.gpg ${trg_ssh_dir}
else
    echo "id_rsa.gpg already exist in ${trg_ssh_dir}"
fi

echo "do you want to decrypt id_rsa.gpg? (y/n)"
read user_input

if [[ ${user_input} == "y" ]]; then
    echo "yes"
    echo "please, remember the hint: poq.l2"
    gpg -d ${trg_ssh_dir}/id_rsa.gpg > ${trg_ssh_dir}/id_rsa
    chmod 0600 ${trg_ssh_dir}/id_rsa        # id_rsa can not be accessible by other users
else
    echo "no worries. you can manually decrypt the file, if needed:"
    echo "gpg -d id_rsa.gpg > id_rsa"
fi

echo "${trg_ssh_dir}:"
ls -al ${trg_ssh_dir}
