#!/bin/bash

set -e

# Prompt for CSR name
read -rp "Enter the CSR name (e.g. learner): " CSR_NAME

if [[ -z "$CSR_NAME" ]]; then
  echo "Error: CSR name cannot be empty."
  exit 1
fi

KEY_FILE="${CSR_NAME}.key"
CSR_FILE="${CSR_NAME}.csr"
CSR_YAML="${CSR_NAME}-csr.yaml"
CSR_ISSUED_YAML="${CSR_NAME}-csr-issued.yaml"
CRT_FILE="${CSR_NAME}.crt"
CSR_CONFIG="${CSR_NAME}.conf"

echo "1. Generating private key..."
openssl genrsa -out "${KEY_FILE}" 2048
echo "Private key '${KEY_FILE}' generated successfully."
echo "Sleeping for 3 seconds to allow verification..."
sleep 3

echo "2. Creating CSR config file..."
cat > "${CSR_CONFIG}" <<EOF
[ req ]
default_bits       = 2048
prompt             = no
default_md         = sha256
req_extensions     = req_ext
distinguished_name = dn

[ dn ]
CN = ${CSR_NAME}

[ req_ext ]
subjectAltName = @alt_names

[ alt_names ]
DNS.1 = ${CSR_NAME}
EOF
echo "CSR config file '${CSR_CONFIG}' created."
echo "Sleeping for 3 seconds to allow verification..."
sleep 3

echo "3. Generating CSR using the config..."
openssl req -new -key "${KEY_FILE}" -out "${CSR_FILE}" -config "${CSR_CONFIG}"
echo "CSR '${CSR_FILE}' generated."
echo "Sleeping for 3 seconds to allow verification..."
sleep 3

echo "4. Base64 encoding the CSR for Kubernetes submission..."
CSR_BASE64=$(base64 -w0 < "${CSR_FILE}")
echo "CSR has been encoded in base64 format."
echo "Sleeping for 3 seconds to allow verification..."
sleep 3

echo "5. Creating Kubernetes CSR YAML manifest '${CSR_YAML}'..."
cat > "${CSR_YAML}" <<EOF
apiVersion: certificates.k8s.io/v1
kind: CertificateSigningRequest
metadata:
  name: ${CSR_NAME}
spec:
  groups:
  - system:authenticated
  request: ${CSR_BASE64}
  signerName: kubernetes.io/kube-apiserver-client
  expirationSeconds: 604800
  usages:
  - digital signature
  - key encipherment
  - client auth
EOF
echo "Kubernetes CSR manifest '${CSR_YAML}' created."
echo "Sleeping for 3 seconds to allow verification..."
sleep 3

echo "6. Applying CSR manifest to the Kubernetes cluster..."
kubectl apply -f "${CSR_YAML}"
echo "CSR resource '${CSR_NAME}' created in Kubernetes."
echo "Sleeping for 3 seconds to allow verification..."
sleep 3

echo "7. Approving the CSR '${CSR_NAME}'..."
kubectl certificate approve "${CSR_NAME}"
echo "CSR '${CSR_NAME}' approved."
echo "Sleeping for 3 seconds to allow verification..."
sleep 3

echo "8. Waiting for the certificate to be issued (max 30s)..."
for i in {1..30}; do
  CERT=$(kubectl get csr "${CSR_NAME}" -o jsonpath='{.status.certificate}' 2>/dev/null || echo "")
  if [[ -n "${CERT}" ]]; then
    echo "Certificate has been issued."
    break
  fi
  echo "Waiting for certificate issuance... (${i}/30)"
  sleep 1
done

if [[ -z "${CERT}" ]]; then
  echo "ERROR: Certificate was not issued in time."
  exit 1
fi
echo "Sleeping for 3 seconds to allow verification of certificate issuance..."
sleep 3

echo "9. Exporting the CSR resource with issued certificate to yaml file '${CSR_ISSUED_YAML}'..."
kubectl get csr "${CSR_NAME}" -o yaml > "${CSR_ISSUED_YAML}"
echo "Issued CSR YAML exported."
echo "Sleeping for 3 seconds to allow verification..."
sleep 3

echo "10. Extracting and decoding the issued certificate to '${CRT_FILE}'..."
kubectl get csr "${CSR_NAME}" -o jsonpath='{.status.certificate}' | base64 --decode > "${CRT_FILE}"
echo "Certificate saved to '${CRT_FILE}'."
echo "Sleeping for 3 seconds to allow verification..."
sleep 3

echo "All steps completed successfully!"
echo "Generated files:"
echo "  Private key        : ${KEY_FILE}"
echo "  Certificate Request: ${CSR_FILE}"
echo "  Kubernetes CSR YAML: ${CSR_YAML}"
echo "  Issued CSR YAML    : ${CSR_ISSUED_YAML}"
echo "  Issued certificate : ${CRT_FILE}"

can i chosse to name spaces ar all name spaces check if exite of name or not if yes change the name
and anther improvemnt