#!/bin/bash

# 设置变量
STORE_PASS="Admin@123\$"  # 注意：在 shell 中需要转义 $ 符号
KEY_PASS="Admin@123\$"
VALIDITY=3650
KEY_ALIAS="privateKey"
PUBLIC_ALIAS="publicCert"

# 获取项目根目录的绝对路径
PROJECT_ROOT=$(cd "$(dirname "$0")/.." && pwd)
CONF_DIR="$PROJECT_ROOT/conf"

echo "配置目录: $CONF_DIR"

# 创建配置目录
mkdir -p "$CONF_DIR"

echo "开始生成密钥库文件..."

# 生成私钥库
keytool -genkeypair \
    -keystore "$CONF_DIR/privateKeys.keystore" \
    -alias "$KEY_ALIAS" \
    -validity "$VALIDITY" \
    -keyalg RSA \
    -keysize 2048 \
    -storepass "$STORE_PASS" \
    -keypass "$KEY_PASS" \
    -dname "CN=localhost, OU=localhost, O=localhost, L=SH, ST=SH, C=CN"

if [ $? -ne 0 ]; then
    echo "生成私钥库失败"
    exit 1
fi

echo "私钥库生成成功: $CONF_DIR/privateKeys.keystore"

# 从私钥库导出证书
keytool -exportcert \
    -alias "$KEY_ALIAS" \
    -keystore "$CONF_DIR/privateKeys.keystore" \
    -storepass "$STORE_PASS" \
    -file "$CONF_DIR/certfile.cer"

if [ $? -ne 0 ]; then
    echo "导出证书失败"
    exit 1
fi

echo "证书导出成功"

# 将证书导入到公钥库
keytool -import \
    -alias "$PUBLIC_ALIAS" \
    -file "$CONF_DIR/certfile.cer" \
    -keystore "$CONF_DIR/publicCerts.keystore" \
    -storepass "$STORE_PASS" \
    -noprompt

if [ $? -ne 0 ]; then
    echo "导入公钥库失败"
    rm -f "$CONF_DIR/certfile.cer"
    exit 1
fi

echo "公钥库生成成功: $CONF_DIR/publicCerts.keystore"

# 删除临时证书文件
rm -f "$CONF_DIR/certfile.cer"

echo "==========================="
echo "密钥库文件生成完成！"
echo "项目根目录: $PROJECT_ROOT"
echo "配置目录: $CONF_DIR"
echo "私钥库: $CONF_DIR/privateKeys.keystore"
echo "公钥库: $CONF_DIR/publicCerts.keystore"
echo "==========================="

# 检查文件是否存在
if [ -f "$CONF_DIR/privateKeys.keystore" ] && [ -f "$CONF_DIR/publicCerts.keystore" ]; then
    echo "文件生成成功，请检查文件权限"
    ls -l "$CONF_DIR"/*.keystore
else
    echo "文件生成失败，请检查错误信息"
fi 