# Script to create certificates for the test. The expiration date of the
# certificates will happen after number of days defined in DAYS variable.

set -e

SUBJ="/C=FR/ST=Ile de France"
DAYS=3600
PKEY=ec:ecparam.pem

openssl ecparam -name prime256v1 -out ecparam.pem

# certificate request for server certificate authority

openssl req -new -newkey $PKEY -nodes -keyout CA-srv.key \
-out CA-srv.csr \
-subj "$SUBJ/O=AdaCore/OU=CA/CN=CA-Web-Server/emailAddress=ca-aws@adacore.com/"

# certificate request for client certificate authority

openssl req -new -newkey $PKEY -nodes -keyout CA-clt.key \
-out CA-clt.csr -subj \
"$SUBJ/L=Magny les Hameaux/O=AWS Team/CN=Pascal Obry/emailAddress=aws@obry.net/"

# Sign CA requests and get the self signed certificates.

openssl x509 -req -days $DAYS -in CA-srv.csr -signkey CA-srv.key -out CA-srv.crt
openssl x509 -req -days $DAYS -in CA-clt.csr -signkey CA-clt.key -out CA-clt.crt

# If we need CA certificate signed by trusted authority, we should send the
# CA-srv.csr to the trusted authority and get the signed certificate for some
# payment.

# Generate server certificate requests

openssl req -new -newkey $PKEY -nodes -keyout aws-server1.key \
-out aws-server1.csr \
-subj "$SUBJ/O=AdaCore/OU=CRM/CN=localhost/emailAddress=aws-test@adacore.com/"

openssl req -new -newkey $PKEY -nodes -keyout aws-server2.key \
-out aws-server2.csr \
-subj "$SUBJ/O=AdaCore/OU=Test/CN=localhost/emailAddress=Test-AWS@AdaCore.com/"

# Generate client certificate requests

openssl req \
-subj "$SUBJ/O=AWS Team/CN=Jean Dupont/emailAddress=jean.dupont@nowhere.com/" \
-new -newkey $PKEY -sha256 -nodes -keyout aws-client.key \
-out aws-client.csr

# Initialize a demo CA directory, see CA_default section in
# /etc/ssl/openssl.cnf.

mkdir demoCA
mkdir demoCA/newcerts
touch demoCA/index.txt
touch demoCA/index.txt.attr
echo ADAC > demoCA/serial

# Sign server certificates by server CA.

openssl ca -in aws-server1.csr -days $DAYS -cert CA-srv.crt \
 -keyfile CA-srv.key -batch -out aws-server1.crt

openssl ca -in aws-server2.csr -days $DAYS -cert CA-srv.crt \
 -keyfile CA-srv.key -batch -out aws-server2.crt

# Sign client certificate by server CA.

openssl ca -in aws-client.csr -days $DAYS -cert CA-clt.crt \
 -keyfile CA-clt.key -batch -out aws-client.crt

# concatenate client certificate with its private key.

cat aws-client.crt aws-client.key > aws-client-expired.pem
rm aws-client.crt aws-client.key

# remove certificate requests

rm CA-clt.csr CA-srv.csr aws-client.csr aws-server?.csr

# remove demo CA directory and CA private keys.

rm -fr demoCA CA-clt.key CA-srv.key
