#!/bin/bash

# 检查必要工具是否安装
check_dependency() {
  if ! command -v keytool &> /dev/null; then
    echo "错误: keytool 未安装，请安装 Java JDK"
    exit 1
  fi
  if ! command -v openssl &> /dev/null; then
    echo "错误: openssl 未安装"
    exit 1
  fi
}

# 用户输入签名信息
get_signature_info() {
  read -p "密钥库文件名 (默认: android_key): " KEYSTORE_NAME
  KEYSTORE_NAME=${KEYSTORE_NAME:-android_key}
  
  read -p "别名 (默认: mykey): " KEY_ALIAS
  KEY_ALIAS=${KEY_ALIAS:-mykey}
  
  read -p "密钥库密码 (默认: android): " STORE_PASS
  STORE_PASS=${STORE_PASS:-android}
  
  read -p "密钥密码 (默认同密钥库密码): " KEY_PASS
  KEY_PASS=${KEY_PASS:-$STORE_PASS}
  
  read -p "有效期(年) (默认: 25): " VALIDITY
  VALIDITY=${VALIDITY:-25}
  
  read -p "名字与姓氏 (默认: Android Developer): " CN
  CN=${CN:-Android Developer}
  
  read -p "组织单位 (默认: Mobile Dev): " OU
  OU=${OU:-Mobile Dev}
  
  read -p "组织名称 (默认: Android Inc): " O
  O=${O:-Android Inc}
  
  read -p "城市或地区 (默认: Silicon Valley): " L
  L=${L:-Silicon Valley}
  
  read -p "州或省份 (默认: California): " ST
  ST=${ST:-California}
  
  read -p "国家代码(2字母) (默认: US): " C
  C=${C:-US}
  
  # 生成完整的DN字符串
  DN="CN=$CN, OU=$OU, O=$O, L=$L, ST=$ST, C=$C"
}

# 生成JKS密钥库
generate_jks() {
  echo "正在生成JKS密钥库..."
  keytool -genkey -v \
    -keystore "${KEYSTORE_NAME}.jks" \
    -alias "$KEY_ALIAS" \
    -keyalg RSA \
    -keysize 2048 \
    -validity $((VALIDITY * 365)) \
    -storepass "$STORE_PASS" \
    -keypass "$KEY_PASS" \
    -dname "$DN"
  
  # 导出公钥证书
  keytool -exportcert \
    -alias "$KEY_ALIAS" \
    -keystore "${KEYSTORE_NAME}.jks" \
    -storepass "$STORE_PASS" \
    -rfc \
    -file "${KEYSTORE_NAME}.cer"
}

# 生成PKCS12格式
generate_pkcs12() {
  echo "正在生成PKCS12文件..."
  keytool -importkeystore \
    -srckeystore "${KEYSTORE_NAME}.jks" \
    -destkeystore "${KEYSTORE_NAME}.p12" \
    -deststoretype PKCS12 \
    -srcstorepass "$STORE_PASS" \
    -deststorepass "$STORE_PASS" \
    -srcalias "$KEY_ALIAS" \
    -destalias "$KEY_ALIAS"
}

# 生成PEM私钥
generate_pem() {
  echo "正在生成PEM私钥..."
  openssl pkcs12 \
    -in "${KEYSTORE_NAME}.p12" \
    -nodes \
    -nocerts \
    -password pass:"$STORE_PASS" \
    -out "${KEYSTORE_NAME}.key.pem"
}

# 生成DER格式私钥
generate_der() {
  echo "正在生成DER私钥..."
  openssl rsa \
    -in "${KEYSTORE_NAME}.key.pem" \
    -outform DER \
    -out "${KEYSTORE_NAME}.key.der"
}

# 主函数
main() {
  check_dependency
  get_signature_info
  
  generate_jks
  generate_pkcs12
  generate_pem
  generate_der
  
  echo -e "\n\033[32m签名文件生成成功!\033[0m"
  echo -e "\n\033[32m请前往/www/wwwroot/panguan/QJB/KeyTool目录查看！\033[0m"
  echo "================================"
  echo "JKS 密钥库:    ${KEYSTORE_NAME}.jks"
  echo "PKCS12 文件:   ${KEYSTORE_NAME}.p12"
  echo "PEM 证书:      ${KEYSTORE_NAME}.cer"
  echo "PEM 私钥:      ${KEYSTORE_NAME}.key.pem"
  echo "DER 私钥:      ${KEYSTORE_NAME}.key.der"
  echo "================================"
  echo "别名:          $KEY_ALIAS"
  echo "有效期:        $VALIDITY 年"
}

main