#!/bin/bash

######################################################################
#   Description: 创建到存储侧签发dsware_api证书的请求文件dsware_api.csr
######################################################################
AUTH_PWD=$1
SAVE_PATH=$2
PREFIX=$3
KEY_FILE="${SAVE_PATH}/${PREFIX}.key"
CSR_FILE="${SAVE_PATH}/${PREFIX}.csr"
OPENSSL_CNF="/etc/pki/tls/openssl.cnf"


/usr/bin/expect <<-EOF
set timeout 10
spawn openssl genrsa -aes256 -out ${KEY_FILE} 3072

expect {
        "Enter pass phrase for *:" { send "${AUTH_PWD}\n"
                                     expect {
                                              "Verifying - Enter pass phrase for *:" { send "${AUTH_PWD}\n" }
                                              timeout { send_error "create dsware_api.key timeout\n"; exit 1; }
                                     }
        }
        timeout { send_error "create dsware_api.key timeout\n"; exit 1; }
}
expect eof
EOF

if [ $? -ne 0 ];then
    exit 1
fi

sleep 1

/usr/bin/expect <<-EOF
set timeout 5
spawn openssl req -new -key ${KEY_FILE} -out ${CSR_FILE} -config ${OPENSSL_CNF} -subj "/C=CN/CN=dsware_api"
expect {
        "Enter pass phrase for *:" { send "${AUTH_PWD}\n" }
        timeout { send_error "create dsware_api.csr timeout\n"; exit 1; }
}
expect eof
EOF

if [ $? -ne 0 ];then
    exit 1
fi
