#!/usr/bin/env bash

# Adding a new key requires:
# * the key name must be added to ssh_keys list
# * the key and the corresponding URL must be added to the ssh_configs array

HOME=${1:-/etc/skel}
LOCAL_USER_EMAIL=cyteen@ring-zero.co.uk
KEY_SCRIPTS_DIR="/tmp/gen_ssh_keys"

mkdir -p "${KEY_SCRIPTS_DIR}"

# Define an list of SSH key names
ssh_keys=("id_rsa" "devuan_rsa" "debian_rsa" "github_rsa" "gitlab_rsa" "gitea_rsa")

# Configure ohmyzsh to look for specific keys dynamically
cat <<-FOE | tee ${KEY_SCRIPTS_DIR}/set-zstyle.sh >/dev/null
	#!/bin/bash

	mkdir -p ${HOME}/.zshrc.pre-plugins.d/001_ssh-agent
	cat <<-EOF | tee -a ${HOME}/.zshrc.pre-plugins.d/001_ssh-agent >/dev/null
	    zstyle :omz:plugins:ssh-agent identities $(printf "%s " "${ssh_keys[@]}")
	EOF
FOE

# Generate SSH keys script
cat <<-EOF | tee ${KEY_SCRIPTS_DIR}/generate-ssh-key.sh >/dev/null
	#!/bin/bash

	LOCAL_USER_EMAIL=${LOCAL_USER_EMAIL}
	HOME=${HOME}
	for key in ${ssh_keys[@]}; do
	    ssh-keygen -t rsa -b 4096 -N '' -C "\$LOCAL_USER_EMAIL" -f "\$HOME/.ssh/\$key"
	done
EOF

# Add keys to ssh-agent script
cat <<-EOF | tee ${KEY_SCRIPTS_DIR}/ssh-key-add.sh >/dev/null
	#!/bin/bash

	HOME=${HOME}
	eval "\$(ssh-agent -s)"
	for key in ${ssh_keys[@]}; do
	    ssh-add "\$HOME/.ssh/\$key"
	done
EOF

# Set permissions for SSH keys and directories script
cat <<-EOF | tee ${KEY_SCRIPTS_DIR}/ssh-key-permissions.sh >/dev/null
	#!/bin/bash

	HOME=${HOME}
	chmod 700 "\$HOME/.ssh"
	chmod 644 "\$HOME/.ssh/authorized_keys"
	chmod 644 "\$HOME/.ssh/known_hosts"
	chmod 644 "\$HOME/.ssh/config"

	for key in ${ssh_keys[@]}; do
	    chmod 600 "\$HOME/.ssh/\$key"
	    chmod 644 "\$HOME/.ssh/\${key}.pub"
	done
EOF

# Configure preferred keys for each host script
cat <<-EOF | tee ${KEY_SCRIPTS_DIR}/ssh-config.sh >/dev/null
	#!/bin/bash

	HOME=${HOME}
	declare -A ssh_configs=(
	    ["git2.ring-zero.co.uk"]="gitea_rsa"
	    ["git.ring-zero.co.uk"]="gitlab_rsa"
	    ["gitlab.com"]="gitlab_rsa"
	    ["github.com"]="github_rsa"
	    ["git.devuan.org"]="devuan_rsa"
	    ["salsa.debian.org"]="debian_rsa"
		)
	for host in "\${!ssh_configs[@]}"; do
		cat <<-FOE | sudo tee -a "\$HOME/.ssh/config" >/dev/null

				Host \$host
				User git
				Preferredauthentications publickey
				IdentityFile "\$HOME/.ssh/\${ssh_configs[\$host]}"
		FOE
	done
EOF

# Make scripts executable
# chmod +x /tmp/generate-ssh-key.sh /tmp/ssh-key-add.sh /tmp/ssh-key-permissions.sh /tmp/ssh-config.sh
chmod +x ${KEY_SCRIPTS_DIR}/*.sh

# Execute scripts
"${KEY_SCRIPTS_DIR}"/set-zstyle.sh
"${KEY_SCRIPTS_DIR}"/generate-ssh-key.sh
"${KEY_SCRIPTS_DIR}"/ssh-key-add.sh
"${KEY_SCRIPTS_DIR}"/ssh-key-permissions.sh
"${KEY_SCRIPTS_DIR}"/ssh-config.sh

# Generate system keys
ssh-keygen -A

# Generate root user keys if not present
if [ ! -f ${HOME}/.ssh/id_rsa.pub ]; then
	ssh-keygen -q -t rsa -N '' -f "${HOME}"/.ssh/id_rsa 2>/dev/null <<<y >/dev/null
	chmod 644 "${HOME}"/.ssh/id_rsa.pub
fi
