# Change date for mo than 10 days before current date and run this file to
# regenerate certificates for
set -e

SUBJ="/C=FR/ST=Ile de France"
DAYS=1460
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-server.key \
-out aws-server.csr \
-subj "$SUBJ/O=AdaCore/OU=CRM/CN=localhost/emailAddress=aws-test@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 certificate by server CA.

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

# Sign client certificate by server CA.

openssl ca -in aws-client.csr -days 10 -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
