#!/bin/sh
#***************************************************************#
# ScriptName: signcert.sh
# Author: xhy
# Create Date: 2025-02-25 21:49
# Modify Author: xhy
# Modify Date: 2025-04-13 17:33
# Version: v1
#***************************************************************#

# 配置参数
#PARENT_DOMAIN="linuxsb.com"          # 父级域名
#SUB_DOMAINS=("aaa" "bbb" "ccc")      # 子域名列表，可选配置

PARENT_DOMAIN="linuxsb.com"
SUB_DOMAINS=("gitlab" "minio")
CERT_DIR="./certs"                   # 证书存储目录
CA_NAME="myCA"                       # CA证书名称

# 创建证书目录
mkdir -p "${CERT_DIR}"
cd "${CERT_DIR}" || exit

# 生成CA证书（使用父级域名）
openssl genrsa -out "${CA_NAME}.key" 2048
openssl req -x509 -new -nodes -key "${CA_NAME}.key" \
    -subj "/CN=${PARENT_DOMAIN} Root CA" -days 3650 -out "${CA_NAME}.crt"

# 生成服务器密钥和CSR（使用父级域名作为前缀）
openssl genrsa -out "${PARENT_DOMAIN}.key" 2048
openssl req -new -key "${PARENT_DOMAIN}.key" \
    -subj "/CN=*.${PARENT_DOMAIN}" -out "${PARENT_DOMAIN}.csr"

# 生成扩展配置文件
cat > extfile.cnf << EOF
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth, clientAuth
subjectAltName = @alt_names

[alt_names]
DNS.1 = *.${PARENT_DOMAIN}          # 泛域名
DNS.2 = ${PARENT_DOMAIN}            # 主域名
EOF

# 添加具体子域名
index=3
for sub in "${SUB_DOMAINS[@]}"; do
    echo "DNS.${index} = ${sub}.${PARENT_DOMAIN}" >> extfile.cnf
    ((index++))
done

# 用CA签发服务器证书
openssl x509 -req -in "${PARENT_DOMAIN}.csr" \
    -CA "${CA_NAME}.crt" -CAkey "${CA_NAME}.key" -CAcreateserial \
    -out "${PARENT_DOMAIN}.crt" -days 3650 -extfile extfile.cnf

# 生成完整证书链文件
cat "${PARENT_DOMAIN}.crt" "${CA_NAME}.crt" > fullchain.crt

# 清理临时文件
rm -f extfile.cnf "${PARENT_DOMAIN}.csr"

echo -e "\n\n\033[32m[SUCC] >>> 证书生成完成，文件保存在 ${CERT_DIR} 目录：...\033[0m"
ls -l

echo -e "\n\n\033[32m[SUCC] >>> 证书链验证信息如下：\033[0m"
openssl verify -CAfile "${CA_NAME}.crt" "${PARENT_DOMAIN}.crt"

echo -e "\n\n\033[32m[SUCC] >>> 证书包含的域名信息如下：\033[0m"
openssl x509 -noout -text -in "${PARENT_DOMAIN}.crt" | grep -A2 "X509v3 Subject Alternative Name"
