#!/usr/bin/env python3
# coding: utf-8
# Copyright (c) 2025 Huawei Technologies Co., Ltd.
# openUBMC is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#         http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.


cat << EOF > tsa.cnf
[ req ]
default_bits = 4096
distinguished_name = req_distinguished_name
prompt = no
string_mask = utf8only
x509_extensions = extensions

[ req_distinguished_name ]
C = CN
O = Test
CN = Test Enterprise Timestamp Certificate

[ extensions ]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid, issuer
basicConstraints = critical, CA:FALSE
keyUsage = critical, nonRepudiation, digitalSignature
extendedKeyUsage = critical, timeStamping

[ tsa ]
default_tsa = tsa_config1

[ tsa_config1 ]
serial = ./serial
crypto_device = builtin
signer_digest = sha256
default_policy = 1.2.3.4.1
other_policies = 1.2.3.4.5.6, 1.2.3.4.5.7
digests = sha256, sha384, sha512
ess_cert_id_chain = no
ess_cert_id_alg = sha256
EOF

echo 03 > serial

openssl genrsa -out tsca_pri.pem 4096

openssl req -new -config tsa.cnf -out tsca.csr -key tsca_pri.pem

openssl pkcs12 -nocerts -nodes -in rootca.pfx -out rootca_pri.pem

openssl x509 -req -in tsca.csr -CA rootca.pem -CAkey rootca_pri.pem -CAcreateserial -out tsca.pem -days 3650 -extensions extensions -extfile tsa.cnf

openssl x509 -in tsca.pem -inform pem -outform der -out tsca.der

cat tsca.pem tsca_pri.pem > ts_signer.pem

rm -f rootca_pri.pem tsca.pem  tsca.csr tsca_pri.pem serial tsca.der
