#!/usr/bin/env bash set -euo pipefail usage() { echo "Usage: $0 [-o destination]" echo " Fully qualified domain name for the certificate" echo " -o Optional destination (local path or ssh://host:port/path)" echo " Supported protocols: ssh://" exit 1 } if [ $# -lt 1 ]; then usage fi if [[ "$1" == -* ]]; then usage fi FQDN="$1" shift 1 DEST="" OPTIND=1 while getopts "ho:" opt; do case "$opt" in h) usage ;; o) DEST="$OPTARG" ;; *) usage ;; esac done CERT_FILE="${FQDN}.pem" KEY_FILE="${FQDN}.key.pem" generate_cert() { echo "Generating SSL certificate for ${FQDN}..." openssl req -x509 -nodes -days 365 -newkey rsa:2048 \ -keyout "${KEY_FILE}" \ -out "${CERT_FILE}" \ -subj "/CN=${FQDN}" \ -addext "subjectAltName=DNS:${FQDN}" \ 2>/dev/null echo "Certificate generated: ${CERT_FILE}" echo "Key generated: ${KEY_FILE}" } transfer_via_ssh() { local dest="$1" local host port path dest="${dest#*://}" host="${dest%%:*}" local remainder="${dest#*:}" if [[ "$remainder" == /* ]]; then path="$remainder" port="22" else port="${remainder%%/*}" path="/${remainder#*/}" fi echo "Transferring certificates to ${host}:${port}${path}..." scp -P "${port}" "${CERT_FILE}" "${KEY_FILE}" "${host}:${path}/" echo "Certificates transferred successfully." } main() { generate_cert if [ -z "${DEST}" ]; then echo "Certificates are in the current directory (no -o destination provided)." return fi if [[ "$DEST" == ssh://* ]]; then transfer_via_ssh "${DEST#ssh://}" else if [ ! -d "${DEST}" ]; then mkdir -p "${DEST}" fi cp "${CERT_FILE}" "${KEY_FILE}" "${DEST}/" echo "Certificates copied to ${DEST}/" fi } main